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(runtime): preserve transport bindings through catalog enrichment
zszz3022cb0a8ffec
diff --git a/apps/desktop/electron/main/models-dev-catalog.ts b/apps/desktop/electron/main/models-dev-catalog.tsindex fbf42f28c..a8a6b310f 100644--- a/apps/desktop/electron/main/models-dev-catalog.ts+++ b/apps/desktop/electron/main/models-dev-catalog.ts@@ -32,7 +32,7 @@ import type {ThinkingProtocol,ModelBinding,} from "@pi-desktop/shared";-import { genericModelConfig, modelConfigWithBinding, type ModelConfig } from "@pi-desktop/agent-runtime";+import { genericModelConfig, modelConfigWithBinding, transcriptConfigFromPi, type ModelConfig } from "@pi-desktop/agent-runtime";import { resolveBindingLimits } from "@pi-desktop/shared";export const MODELS_DEV_API_URL = "https://models.dev/api.json";@@ -1424,6 +1424,16 @@ export class ModelsDevCatalog {const thinking = this.anthropicThinkingFor(input.modelId);if (thinking) baseline = { ...baseline, ...thinking };}+ // Pi owns wire capabilities, independently of models.dev's limits/prices.+ // Use the original published record, never an account/relay projection.+ const key = input.vendorKey?.trim().toLowerCase();+ const vendor = (key ? PI_VENDOR_ALIASES[key] ?? key : undefined) ?? this.providerKeyForRow(input);+ const transport = vendor ? this.operationModels.getModel(vendor, input.modelId) : undefined;+ if (transport) {+ const transcript = transcriptConfigFromPi(transport);+ baseline = { ...baseline, transcriptBinding: transcript.transcriptBinding,+ compat: { ...baseline.compat, ...transcript.compat } };+ }if (!binding) return baseline;const limits = resolveBindingLimits(baseline, binding);return modelConfigWithBinding(limits.catalogConfig, limits.binding);diff --git a/apps/desktop/test/models-dev-catalog.test.mjs b/apps/desktop/test/models-dev-catalog.test.mjsindex cdfc969a1..7d79bf3e8 100644--- a/apps/desktop/test/models-dev-catalog.test.mjs+++ b/apps/desktop/test/models-dev-catalog.test.mjs@@ -4,11 +4,15 @@ import { tmpdir } from "node:os";import { join } from "node:path";import test from "node:test";import { fileURLToPath } from "node:url";+import { createModels, InMemoryModelsStore } from "@earendil-works/pi-ai";+import { builtinProviders } from "@earendil-works/pi-ai/providers/all";+import { buildProviderModel } from "../../../packages/agent-runtime/dist/provider-binding.js";import {apiStyleForAdapter,bindingForCustomModelInfo,catalogModelIdsMatch,modelIdsMatch,+ resolveApiStyle,} from "@pi-desktop/shared";import {MODELS_DEV_API_URL,@@ -103,6 +107,43 @@ async function loadFixtureCatalog(t, fixture = catalogFixture) {return catalog;}+test("published metadata retains exact Pi transcript transport bindings through runtime launch", async (t) => {+ const pi = createModels({ modelsStore: new InMemoryModelsStore(),+ authContext: { env: async () => undefined, fileExists: async () => false } });+ for (const provider of builtinProviders()) pi.setProvider(provider);+ for (const [vendorKey, modelId] of [+ ["deepseek", "deepseek-flash"], ["anthropic", "claude-opus-5-5"],+ ["openai", "gpt-6.1-sol"], ["openai-codex", "gpt-6.1-sol"],+ ]) {+ const original = pi.getModel(vendorKey, modelId);+ assert.ok(original, `${vendorKey}/${modelId}`);+ const catalog = await loadFixtureCatalog(t, { [vendorKey]: {+ name: vendorKey, api: original.baseUrl, models: { [modelId]: {+ id: modelId, limit: { context: 543_210, output: 40_000 }, cost: { input: 1.25, output: 2.5 },+ } },+ } });+ const target = { providerId: "account", vendorKey, modelId, baseUrl: original.baseUrl,+ apiStyle: resolveApiStyle(original.api) };+ const config = catalog.modelConfigFor(target);+ assert.equal(config.source, "models.dev");+ assert.equal(config.contextWindow, 543_210);+ assert.equal(config.maxTokens, 40_000);+ assert.equal(config.cost.input, 1.25);+ assert.deepEqual(config.transcriptBinding, { modelId, api: original.api, baseUrl: original.baseUrl });+ const provider = { ...target, id: "account", name: "Fixture", apiKey: "", authKind: "none",+ supportsReasoning: false, supportedThinkingLevels: ["off"], modelConfig: config };+ const wire = buildProviderModel(provider);+ assert.equal(wire.compat.supportsMidConvoSystemMessages, true, vendorKey);+ assert.equal(wire.compat.supportsMidConvoToolChanges, original.compat?.supportsMidConvoToolChanges === true);+ assert.equal(wire.compat.supportsAdditionalTools, original.compat?.supportsAdditionalTools === true);+ const relay = { ...target, baseUrl: "https://relay.invalid/v1" };+ assert.equal(buildProviderModel({ ...provider, ...relay, modelConfig: catalog.modelConfigFor(relay) })+ .compat.supportsMidConvoSystemMessages, false);+ assert.equal(buildProviderModel({ ...provider, modelId: `${modelId}-alias` })+ .compat.supportsMidConvoSystemMessages, false);+ }+});+test("the bundled models.dev OpenAI record supplies the selected model limits", async () => {const catalogPath = fileURLToPath(new URL("../resources/models.dev/api.json", import.meta.url));const catalog = new ModelsDevCatalog({ catalogPath });diff --git a/docs/adr/chronological-system-transcript.md b/docs/adr/chronological-system-transcript.mdindex 74884ee9f..c1a484003 100644--- a/docs/adr/chronological-system-transcript.md+++ b/docs/adr/chronological-system-transcript.md@@ -38,6 +38,13 @@ Accept transcript capability opt-ins only when that identity matches the actualrequest route. Let Pi adapt the request for partial or absent support; neverpersist an adapter's folded projection.+The current models.dev catalog remains authoritative for published limits,+prices and modalities. Independently copy only the five transcript transport+flags and their original binding from Pi's exact published model. Do not derive+transport support from a models.dev metadata match or an account endpoint+override. Both Pi and models.dev metadata projections can carry that binding;+unverified routes and generic records retain the conservative fallback.+The existing Pi 0.99.1 dependency patch adds the missing mid-conversation systemcapability to its `deepseek-flash` catalog entry. Authorized official-endpointexperiments confirmed both preserved cache reuse and effective updateddiff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.mdindex db1a2ee59..44506236b 100644--- a/docs/spec/03-runtime/02-agent-runtime.md+++ b/docs/spec/03-runtime/02-agent-runtime.md@@ -1308,6 +1308,11 @@ and redefinitions use the adapter's supported fallback. Model switching neverrewrites the canonical journal. Cache savings depend on the actual provider;unsupported routes may still rebuild the request prefix.+Published model limits, prices and modalities remain owned by models.dev. Its+runtime projection separately carries Pi's exact published transcript capability+flags and original binding. An enriched metadata source does not grant native+support by itself, and account overrides never replace that original binding.+The pinned Pi patch declares mid-conversation system support for`deepseek-flash` on its published `openai-completions` binding at`https://api.deepseek.com`. Skill changes on this binding append system updatesdiff --git a/packages/agent-runtime/src/model-capabilities.ts b/packages/agent-runtime/src/model-capabilities.tsindex 2c7f3cd58..43e54643c 100644--- a/packages/agent-runtime/src/model-capabilities.ts+++ b/packages/agent-runtime/src/model-capabilities.ts@@ -7,6 +7,7 @@ import {type ModelModality,} from "@pi-desktop/shared";import type { ModelConfig, ThinkingCapabilitySet } from "./thinking-level.js";+export { transcriptConfigFromPi } from "./transcript-compat.js";export {agentThinkingLevel,diff --git a/packages/agent-runtime/src/provider-binding.test.ts b/packages/agent-runtime/src/provider-binding.test.tsindex bc4036443..ad755e70a 100644--- a/packages/agent-runtime/src/provider-binding.test.ts+++ b/packages/agent-runtime/src/provider-binding.test.ts@@ -254,12 +254,9 @@ describe("Anthropic runtime endpoint", () => {.result();expect(result.stopReason).toBe("error");- expect(- Object.hasOwn(model.compat ?? {}, "supportsMidConvoSystemMessages"),- ).toBe(false);- expect(- Object.hasOwn(model.compat ?? {}, "supportsMidConvoToolChanges"),- ).toBe(false);+ expect(model.compat).toMatchObject({+ supportsMidConvoSystemMessages: false, supportsMidConvoToolChanges: false,+ });expect(request?.headers.get("anthropic-beta") ?? "").not.toMatch(/mid-conversation-tool-changes|inline-tools/,);diff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.tsindex 9318de1cb..689bab439 100644--- a/packages/agent-runtime/src/runtime.test.ts+++ b/packages/agent-runtime/src/runtime.test.ts@@ -2213,11 +2213,10 @@ describe("DesktopAgentRuntime deferred tool catalog", () => {expect(agent.state.tools.some((tool: any) => tool.name === "BrowserPreview")).toBe(true,);- // Tool deltas append new declarations; catalog order is not semantic.- const byName = (a: { name: string }, b: { name: string }) => a.name.localeCompare(b.name);- expect([...getCurrentTools(agent.state.messages)].sort(byName)).toEqual(- agent.state.tools.map(toToolDeclaration).sort(byName),- );+ // Reset retains executability; Pi declares it at the next dispatch, not+ // while this test calls preparation helpers outside the agent loop.+ expect(getCurrentTools(agent.state.messages).some((tool) => tool.name === "BrowserPreview")).toBe(false);+ await runtime.dispose();});});diff --git a/packages/agent-runtime/src/system-transcript-journal.test.ts b/packages/agent-runtime/src/system-transcript-journal.test.tsindex 22b9816a3..3fc43d2ee 100644--- a/packages/agent-runtime/src/system-transcript-journal.test.ts+++ b/packages/agent-runtime/src/system-transcript-journal.test.ts@@ -80,6 +80,16 @@ describe("model system journal", () => {expect(checkpoint?.toolsAdded).toEqual(initial.toolsAdded);});+ it("recognizes a restored checkpoint with text blocks without adding durable rows", async () => {+ const blocks: SystemMessage = { ...initial, content: [{ type: "text", text: "Extension instructions" }] };+ const checkpoint = systemTranscriptCheckpoint([blocks, user])!;+ const journal = new SystemTranscriptJournal();+ journal.rememberCheckpoint(JSON.stringify(checkpoint));+ const append = vi.fn();+ await journal.persist(JSON.parse(JSON.stringify([checkpoint, user])), [], append);+ expect(append).not.toHaveBeenCalled();+ });+it.each([null, {}, { ...initial, timestamp: -1 }, { ...initial, toolsAdded: [{ name: "Read", parameters: "bad" }] }])("rejects malformed saved state", (value) => {expect(() => readSystemMessage(value)).toThrow("Invalid persisted model system message");});diff --git a/packages/agent-runtime/src/system-transcript-runtime.test.ts b/packages/agent-runtime/src/system-transcript-runtime.test.tsindex f48e132dd..15ced3662 100644--- a/packages/agent-runtime/src/system-transcript-runtime.test.ts+++ b/packages/agent-runtime/src/system-transcript-runtime.test.ts@@ -86,6 +86,9 @@ describe("system state through the Desktop user path", () => {const activation = after.findIndex((message) => message.role === "toolResult" && message.toolName === "ToolSearch");expect(after.slice(activation + 1)).toContainEqual(expect.objectContaining({ role: "system", toolsAdded: expect.arrayContaining([expect.objectContaining({ name: "BrowserPreview" })]) }));expect(f.rows.filter((row) => row.modelSystem)).toHaveLength(2);+ await f.prompt("same-runtime-user");+ expect(getCurrentTools(f.requests[2]).some((tool) => tool.name === "BrowserPreview")).toBe(true);+ expect(f.rows.filter((row) => row.modelSystem)).toHaveLength(2);const restored = fixture(structuredClone(f.rows));try {await restored.prompt("user-2");diff --git a/packages/agent-runtime/src/system-transcript.test.ts b/packages/agent-runtime/src/system-transcript.test.tsindex 8e994a499..3d4ec5c1d 100644--- a/packages/agent-runtime/src/system-transcript.test.ts+++ b/packages/agent-runtime/src/system-transcript.test.ts@@ -19,6 +19,7 @@ import {replaceSystemPrompt,systemTranscriptCheckpoint,systemPromptContent,+ removeTrailingAssistantMessages,} from "./system-transcript.js";const read: Tool = { name: "Read", description: "Read text", parameters: Type.Object({ path: Type.String() }) };@@ -50,6 +51,15 @@ function estimateContextTokens(messages: AgentMessage[]) {afterEach(() => vi.restoreAllMocks());describe("system transcript helpers", () => {+ it("removes failed trailing responses across cleanup deltas without changing system state", () => {+ const messages = [initial, user, assistant, delta, { ...assistant, timestamp: 3_000 }];+ const cleaned = removeTrailingAssistantMessages(messages);+ expect(cleaned).toEqual([initial, user, delta]);+ expect(getCurrentTools(cleaned)).toEqual(getCurrentTools(messages));+ expect(messages).toHaveLength(5);+ expect(removeTrailingAssistantMessages([user, assistant])).toEqual([user]);+ expect(removeTrailingAssistantMessages([assistant, user, delta])).toEqual([assistant, user, delta]);+ });it("updates only the changed skill entry and preserves unrelated sections", () => {const previous: AgentMessage[] = [{role: "system", content: "", timestamp: 1,diff --git a/packages/agent-runtime/src/system-transcript.ts b/packages/agent-runtime/src/system-transcript.tsindex a5bac9363..f3e347033 100644--- a/packages/agent-runtime/src/system-transcript.ts+++ b/packages/agent-runtime/src/system-transcript.ts@@ -106,8 +106,12 @@ export function rebuildSystemTranscript(/** Fold state only at an explicit compaction boundary, with semantic time. */export function systemTranscriptCheckpoint(messages: readonly AgentMessage[]): SystemMessage | undefined {- const checkpoint = currentSystemMessage(messages);- if (!checkpoint?.sections || !(CONTEXT_BUDGET_SECTION in checkpoint.sections)) return checkpoint;+ const current = currentSystemMessage(messages);+ if (!current) return undefined;+ // Use the journal's durable shape, including extension-provided text blocks.+ const checkpoint: SystemMessage = { ...current, content: contentText(current.content),+ ...(current.toolsAdded ? { toolsAdded: current.toolsAdded.map(toToolDeclaration) } : {}) };+ if (!checkpoint.sections || !(CONTEXT_BUDGET_SECTION in checkpoint.sections)) return checkpoint;const { [CONTEXT_BUDGET_SECTION]: _expired, ...sections } = checkpoint.sections;return { ...checkpoint, sections };}diff --git a/packages/agent-runtime/src/transcript-compat.test.ts b/packages/agent-runtime/src/transcript-compat.test.tsindex 86fb4c2c6..6e3df7ced 100644--- a/packages/agent-runtime/src/transcript-compat.test.ts+++ b/packages/agent-runtime/src/transcript-compat.test.ts@@ -14,6 +14,10 @@ const provider: RuntimeProviderConfig = {};describe("transcript compatibility binding", () => {+ it("keeps Pi transport capabilities when models.dev owns published metadata", () => {+ expect(buildProviderModel({ ...provider, modelConfig: { ...provider.modelConfig!, source: "models.dev" } }).compat)+ .toMatchObject({ supportsMidConvoSystemMessages: true });+ });it("keeps instruction and tool capabilities independent on the exact binding", () => {expect(buildProviderModel(provider).compat).toMatchObject({ supportsMidConvoSystemMessages: true, supportsMidConvoToolAdditions: false });expect(buildProviderModel({ ...provider, baseUrl: `${baseUrl}/` }).compat).toMatchObject({ supportsMidConvoSystemMessages: true });diff --git a/packages/agent-runtime/src/transcript-compat.ts b/packages/agent-runtime/src/transcript-compat.tsindex 365e2f6da..887e40687 100644--- a/packages/agent-runtime/src/transcript-compat.ts+++ b/packages/agent-runtime/src/transcript-compat.ts@@ -1,10 +1,21 @@import type { ModelConfig } from "./thinking-level.js";+import type { Api, Model } from "@earendil-works/pi-ai";const capabilities = ["supportsMidConvoSystemMessages", "supportsMidConvoToolAdditions","supportsMidConvoToolChanges", "supportsAdditionalTools", "supportsToolSearch",] as const;+/** Transport capabilities only; published limits and prices keep their owner. */+export function transcriptConfigFromPi(model: Model<Api>): Pick<ModelConfig, "transcriptBinding" | "compat"> {+ return {+ transcriptBinding: { modelId: model.id, api: model.api, baseUrl: model.baseUrl },+ compat: Object.fromEntries(capabilities.map((key) => [key,+ model.compat !== undefined && key in model.compat && Reflect.get(model.compat, key) === true,+ ])),+ };+}+function endpoint(value: string): string | undefined {try {const url = new URL(value);@@ -21,7 +32,7 @@ export function transcriptCompat(): Record<(typeof capabilities)[number], boolean> {const binding = catalog?.transcriptBinding;const address = endpoint(baseUrl);- const verified = catalog?.source === "pi" && binding?.modelId === modelId &&+ const verified = (catalog?.source === "pi" || catalog?.source === "models.dev") && binding?.modelId === modelId &&binding.api === api && address !== undefined && endpoint(binding.baseUrl) === address;return Object.fromEntries(capabilities.map((key) => [key, verified && catalog?.compat?.[key] === true])) asRecord<(typeof capabilities)[number], boolean>;