Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
Merge upstream/main into feat/fast-mode-1657
zszz3933a560b9828
diff --cc apps/desktop/electron/main/runtime/session-launch.tsindex 0b82b13da,3461c2e70..9c0210c27--- a/apps/desktop/electron/main/runtime/session-launch.ts+++ b/apps/desktop/electron/main/runtime/session-launch.ts@@@ -706,9 -706,6 +706,9 @@@ export function createSessionLaunchRunt...(overrides.turnId ? { turnId: overrides.turnId } : {}),thinkingLevel,infiniteProviderRetry: settings.infiniteProviderRetry === true,+ // The session `/fast` switch only reaches a model the user allowed it- // for in model settings (ADR 0332).++ // for in model settings (ADR 0334).+ fastMode: session.fastMode === true && storedModel?.fastModeAllowed === true,...(jevApiKey ? { jevApiKey } : {}),commandShell,scratchDir: join(dataDir, "scratch", sessionId),diff --cc apps/desktop/src/components/settings/ModelSelectionPanes.tsxindex 8b0192d9a,668a838b2..d1b742c71--- a/apps/desktop/src/components/settings/ModelSelectionPanes.tsx+++ b/apps/desktop/src/components/settings/ModelSelectionPanes.tsx@@@ -308,14 -307,6 +308,14 @@@ export function ModelSelectionPanes(// Use the same published endpoint routing as the runtime. A disabled control// means this connection is not integrated, not that the vendor cannot search.const nativeWebSearchWireCapable = nativeWebSearchSupportedOn(apiStyle, lookupContext?.baseUrl);+ // Fast mode rides the Responses `service_tier` field; the hint names what- // the priority tier costs on this wire (ADR 0332).++ // the priority tier costs on this wire (ADR 0334).+ const fastModeBilling = fastModeBillingOn(apiStyle);+ const fastModeHint = fastModeBilling === "subscription"+ ? "settings.fastModeAllowedSubscriptionHint"+ : fastModeBilling === "usage"+ ? "settings.fastModeAllowedUsageHint"+ : "settings.fastModeAllowedUnsupported";/*** The chosen list narrows with the discovered list's rule plus the binding'sdiff --cc apps/desktop/src/features/chat/composer/ComposerModelPicker.tsxindex d9e943198,05a89f815..28e0a6956--- a/apps/desktop/src/features/chat/composer/ComposerModelPicker.tsx+++ b/apps/desktop/src/features/chat/composer/ComposerModelPicker.tsx@@@ -15,8 -15,6 +15,8 @@@ export type ComposerModelPickerProps =modelLabel: string;thinkingLabel: string;thinkingLevel: string;- /** The selected model asks for OpenAI's priority tier (ADR 0332). */++ /** The selected model asks for OpenAI's priority tier (ADR 0334). */+ fastMode?: boolean;selectedProviderId?: string;selectedModelId?: string;controlsBlocked: boolean;diff --cc apps/desktop/src/features/chat/composer/ComposerToolbar.tsxindex 526ab6400,2b04f19f8..b2e3a80bf--- a/apps/desktop/src/features/chat/composer/ComposerToolbar.tsx+++ b/apps/desktop/src/features/chat/composer/ComposerToolbar.tsx@@@ -51,8 -51,6 +51,8 @@@ export type ComposerToolbarProps =modelMenu: ModelMenuController;modelLabel: string;thinkingLabel: string;- /** The selected model asks for OpenAI's priority tier (ADR 0332). */++ /** The selected model asks for OpenAI's priority tier (ADR 0334). */+ modelFastMode?: boolean;contextUsage: ContextUsage | null;value: string;modelReady: boolean;diff --cc apps/desktop/src/lib/fast-mode-command.tsindex 6fefb5763,000000000..00dedec65mode 100644,000000..100644--- a/apps/desktop/src/lib/fast-mode-command.ts+++ b/apps/desktop/src/lib/fast-mode-command.ts@@@ -1,78 -1,0 +1,78 @@@+import i18n from "i18next";+import { fastModeBillingOn, type ProviderPublic } from "@pi-desktop/shared";+import { useAppStore } from "../stores/app-store";+import { sameComposerModelId } from "./composer-models";+import { isRemoteSession } from "./remote-session-safety";+import { inheritedSessionModelBinding } from "./session-model";++/**- * The `/fast` builtin (ADR 0332): a per-session switch for OpenAI's priority++ * The `/fast` builtin (ADR 0334): a per-session switch for OpenAI's priority+ * service tier. Model settings decide which models may use it.+ */++type FastModeProvider = Pick<ProviderPublic, "apiStyle" | "models"> | undefined | null;++function fastModeAllowed(provider: FastModeProvider, modelId: string | undefined): boolean {+ return !!modelId && provider?.models.some(+ (binding) => sameComposerModelId(binding.id, modelId) && binding.fastModeAllowed === true,+ ) === true;+}++/** Whether the Composer should mark the selected model as running in Fast mode. */+export function sessionFastModeActive(+ provider: FastModeProvider,+ modelId: string | undefined,+ target: { fastMode?: boolean } | null | undefined,+): boolean {+ return target?.fastMode === true && !!fastModeBillingOn(provider?.apiStyle) &&+ fastModeAllowed(provider, modelId);+}++export async function toggleSessionFastMode(): Promise<void> {+ const store = useAppStore.getState();+ const activeSession = store.sessions.find((session) => session.id === store.activeSessionId);+ if (store.activeSessionId && !activeSession) return;+ if (activeSession && isRemoteSession(activeSession)) {+ store.showToast(i18n.t("chat.fastModeRemote"), { variant: "warning" });+ return;+ }+ const target = activeSession ?? store.draftConfiguration;+ const enabled = target?.fastMode !== true;+ const selected = inheritedSessionModelBinding({+ draft: target,+ settings: store.settings,+ providers: store.providers,+ recentModels: store.recentModels,+ });+ const provider = store.providers.find((candidate) => candidate.id === selected.providerId);+ const billing = fastModeBillingOn(provider?.apiStyle);+ // Without a configured model the switch does nothing, so `/fast` only+ // points to the setting; a stale stored switch stays inert at launch.+ if (!billing) {+ store.showToast(i18n.t("chat.fastModeUnsupported"), { variant: "warning" });+ return;+ }+ if (!fastModeAllowed(provider, selected.modelId)) {+ store.showToast(i18n.t("chat.fastModeNotAllowed"), { variant: "warning" });+ return;+ }++ if (activeSession) {+ await store.configureActiveSession({+ mode: activeSession.mode,+ providerId: activeSession.providerId,+ modelId: activeSession.modelId,+ thinkingLevel: activeSession.thinkingLevel,+ fastMode: enabled,+ });+ // A pending plan review or a read-only session leaves the switch as is.+ const after = useAppStore.getState().sessions.find((session) => session.id === activeSession.id);+ if ((after?.fastMode === true) !== enabled) return;+ } else {+ useAppStore.setState((state) => ({+ draftConfiguration: { ...state.draftConfiguration, fastMode: enabled },+ }));+ }+ const message = !enabled ? "chat.fastModeOff" : billing === "usage" ? "chat.fastModeOnUsage" : "chat.fastModeOn";+ store.showToast(i18n.t(message), { variant: "info" });+}diff --cc apps/desktop/src/stores/app-state.tsindex 3319a148b,21b76b5b9..7ce14a12c--- a/apps/desktop/src/stores/app-state.ts+++ b/apps/desktop/src/stores/app-state.ts@@@ -114,8 -111,6 +114,8 @@@ export type DraftSessionConfigurationproviderId?: string;modelId?: string;permissionMode?: PermissionMode;- /** Session `/fast` switch carried into the created session (ADR 0332). */++ /** Session `/fast` switch carried into the created session (ADR 0334). */+ fastMode?: boolean;};diff --cc apps/desktop/test/fast-mode-command.test.mjsindex 63bd460f4,000000000..09753c77amode 100644,000000..100644--- a/apps/desktop/test/fast-mode-command.test.mjs+++ b/apps/desktop/test/fast-mode-command.test.mjs@@@ -1,155 -1,0 +1,155 @@@+import i18n from "i18next";+import { en } from "@pi-desktop/i18n";+import assert from "node:assert/strict";+import { register } from "node:module";+import test from "node:test";+register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));+const { useAppStore, materializeDraftSession } = await import("../src/stores/app-store.ts");+const { api } = await import("../src/lib/api.ts");+const { runPaletteCommand } = await import("../src/lib/commands.ts");+const { sessionFastModeActive } = await import("../src/lib/fast-mode-command.ts");+- // ADR 0332: `/fast` is a per-session switch, and model settings decide which++// ADR 0334: `/fast` is a per-session switch, and model settings decide which+// models may use it.++await i18n.init({ lng: "en", keySeparator: false, resources: { en: { translation: flatten(en) } } });++function flatten(catalog, prefix = "", out = {}) {+ for (const [key, value] of Object.entries(catalog)) {+ if (value && typeof value === "object") flatten(value, `${prefix}${key}.`, out);+ else out[`${prefix}${key}`] = value;+ }+ return out;+}++const codex = {+ id: "codex", name: "ChatGPT", enabled: true, hasSecret: true, authKind: "oauth", apiStyle: "openai_codex_responses",+ models: [{ id: "gpt-codex", fastModeAllowed: true }, { id: "gpt-mini" }],+};+const relay = {+ id: "relay", name: "Relay", enabled: true, hasSecret: true, authKind: "api_key", apiStyle: "responses",+ models: [{ id: "gpt-relay", fastModeAllowed: true }],+};+const completions = {+ id: "completions", name: "Gateway", enabled: true, hasSecret: true, authKind: "api_key", apiStyle: "chat_completions",+ models: [{ id: "chat", fastModeAllowed: true }],+};+const session = (provider, modelId, extra = {}) => ({+ id: "s1", title: "Task", messageCount: 0, mode: "agent", thinkingLevel: "medium", permissionMode: "inherit",+ providerId: provider.id, modelId, createdAt: "2026-01-01T00:00:00Z", updatedAt: "2026-01-01T00:00:00Z", ...extra,+});++function setup(t, state) {+ const toasts = [];+ const configures = [];+ const creates = [];+ t.mock.method(api, "configureSession", async (id, config) => {+ configures.push(config);+ return { session: { ...useAppStore.getState().sessions.find((item) => item.id === id), ...config, id } };+ });+ t.mock.method(api, "createSession", async (config) => {+ creates.push(config);+ return { session: { ...config, id: "created", title: "New task", messageCount: 0, messages: [] } };+ });+ useAppStore.setState({+ providers: [codex, relay, completions],+ sessions: [],+ activeSessionId: null,+ runningSessions: {},+ pendingPlans: {},+ recentModels: [],+ draftConfiguration: null,+ workspace: null,+ settings: { defaultProviderId: codex.id, defaultModelId: "gpt-codex", defaultMode: "agent" },+ showToast: (message, options) => { toasts.push({ message, variant: options?.variant }); },+ ...state,+ });+ return { toasts, configures, creates };+}++test("/fast toggles an allowed subscription model's session through session.configure", async (t) => {+ const { toasts, configures } = setup(t, { sessions: [session(codex, "gpt-codex")], activeSessionId: "s1" });+ await runPaletteCommand("builtin.session.fast");+ assert.equal(configures.length, 1);+ assert.equal(configures[0].fastMode, true);+ assert.equal(configures[0].thinkingLevel, "medium", "other selections are resent unchanged");+ assert.equal(useAppStore.getState().sessions[0].fastMode, true);+ assert.equal(toasts[0].message, en.chat.fastModeOn);++ await runPaletteCommand("builtin.session.fast");+ assert.equal(configures[1].fastMode, false);+ assert.equal(useAppStore.getState().sessions[0].fastMode, false);+ assert.equal(toasts[1].message, en.chat.fastModeOff);+});++test("/fast on a per-token Responses model warns about the price", async (t) => {+ const { toasts, configures } = setup(t, { sessions: [session(relay, "gpt-relay")], activeSessionId: "s1" });+ await runPaletteCommand("builtin.session.fast");+ assert.equal(configures[0].fastMode, true);+ assert.equal(toasts[0].message, en.chat.fastModeOnUsage);+});++test("/fast refuses a model the user has not allowed, and a wire without the tier", async (t) => {+ const notAllowed = setup(t, { sessions: [session(codex, "gpt-mini")], activeSessionId: "s1" });+ await runPaletteCommand("builtin.session.fast");+ assert.equal(notAllowed.configures.length, 0);+ assert.deepEqual(notAllowed.toasts, [{ message: en.chat.fastModeNotAllowed, variant: "warning" }]);++ const unsupported = setup(t, { sessions: [session(completions, "chat")], activeSessionId: "s1" });+ await runPaletteCommand("builtin.session.fast");+ assert.equal(unsupported.configures.length, 0);+ assert.deepEqual(unsupported.toasts, [{ message: en.chat.fastModeUnsupported, variant: "warning" }]);+});++test("/fast points to model settings instead of toggling a stale switch on an unconfigured model", async (t) => {+ const { configures, toasts } = setup(t, {+ sessions: [session(codex, "gpt-mini", { fastMode: true })],+ activeSessionId: "s1",+ });+ await runPaletteCommand("builtin.session.fast");+ assert.equal(configures.length, 0);+ assert.deepEqual(toasts, [{ message: en.chat.fastModeNotAllowed, variant: "warning" }]);+});++test("/fast refuses remote sessions", async (t) => {+ const { configures, toasts } = setup(t, {+ sessions: [session(codex, "gpt-codex", { id: "remote:host:s1", source: "remote" })],+ activeSessionId: "remote:host:s1",+ });+ await runPaletteCommand("builtin.session.fast");+ assert.equal(configures.length, 0);+ assert.equal(toasts[0].message, en.chat.fastModeRemote);+});++test("/fast on the new-task draft carries the switch into the created session", async (t) => {+ const { configures, creates } = setup(t, {});+ await runPaletteCommand("builtin.session.fast");+ assert.equal(configures.length, 0);+ assert.deepEqual(useAppStore.getState().draftConfiguration, { fastMode: true });++ // Choosing a model on the draft keeps the switch.+ await useAppStore.getState().configureActiveSession({+ mode: "agent", providerId: codex.id, modelId: "gpt-codex", thinkingLevel: "high",+ });+ assert.equal(useAppStore.getState().draftConfiguration.fastMode, true);++ await materializeDraftSession();+ assert.equal(creates.length, 1);+ assert.equal(creates[0].fastMode, true);+ assert.equal(creates[0].thinkingLevel, "high");+});++test("a draft without /fast creates a session on the default tier and default thinking", async (t) => {+ const { creates } = setup(t, {});+ await materializeDraftSession();+ assert.equal(creates.length, 1);+ assert.equal("fastMode" in creates[0], false);+});++test("the Composer marks Fast only when the switch is on for an allowed model", () => {+ assert.equal(sessionFastModeActive(codex, "gpt-codex", { fastMode: true }), true);+ assert.equal(sessionFastModeActive(codex, "gpt-codex", { fastMode: false }), false);+ assert.equal(sessionFastModeActive(codex, "gpt-mini", { fastMode: true }), false);+ assert.equal(sessionFastModeActive(completions, "chat", { fastMode: true }), false);+ assert.equal(sessionFastModeActive(undefined, undefined, { fastMode: true }), false);+});diff --cc apps/desktop/test/fast-mode-session-launch.test.mjsindex 139955ffb,000000000..c5c4d7dd8mode 100644,000000..100644--- a/apps/desktop/test/fast-mode-session-launch.test.mjs+++ b/apps/desktop/test/fast-mode-session-launch.test.mjs@@@ -1,89 -1,0 +1,89 @@@+import assert from "node:assert/strict";+import { createRequire } from "node:module";+import { mkdtemp, rm } from "node:fs/promises";+import { join } from "node:path";+import test from "node:test";+import { pathToFileURL } from "node:url";+import { repositoryRoot } from "../../../scripts/e2e/boot.mjs";++const root = repositoryRoot();+const { build } = createRequire(join(root, "packages/agent-runtime/package.json"))("esbuild");+- test("session launch sends Fast mode only for a model the user allowed it on (ADR 0332)", async () => {++test("session launch sends Fast mode only for a model the user allowed it on (ADR 0334)", async () => {+ const temp = await mkdtemp(join(root, "apps/desktop/.fast-mode-launch-test-"));+ const priorHome = process.env.HOME;+ process.env.HOME = temp;+ try {+ const bundle = join(temp, "session-launch.mjs");+ await build({+ entryPoints: [join(root, "apps/desktop/electron/main/runtime/session-launch.ts")],+ outfile: bundle,+ bundle: true,+ platform: "node",+ format: "esm",+ packages: "external",+ nodePaths: [join(root, "apps/desktop/node_modules")],+ });+ const { createSessionLaunchRuntime } = await import(pathToFileURL(bundle).href);+ const provider = {+ id: "openai-provider",+ name: "OpenAI",+ authKind: "none",+ apiStyle: "responses",+ baseUrl: "http://127.0.0.1:11434/v1",+ enabled: true,+ defaultModelId: "allowed-model",+ models: [],+ };+ const allowed = new Set(["allowed-model"]);+ const host = {+ isAvailable: () => true,+ async call(method) {+ if (method === "commandShells.list") {+ const shell = { id: "bash", label: "Bash", dialect: "posix", available: true, isDefault: true };+ return { configuredId: "bash", effective: shell, fallback: false, choices: [shell] };+ }+ if (method === "providers.list") return { providers: [provider] };+ if (method === "providers.getSecret") return { value: "" };+ if (method === "skills.disabledBuiltins") return { disabled: [] };+ if (method === "skills.active") return { skills: [] };+ if (method === "mcp.active") return { servers: [] };+ if (method === "agents.active") return { subagents: [] };+ if (method === "agents.disabledBuiltins") return { disabled: [] };+ throw new Error("Unexpected fixture Host method: " + method);+ },+ };+ const launchRuntime = createSessionLaunchRuntime({+ runtimeState: { host, sidecar: { setVendorAuthBindings() {} }, agentHostBridge: null },+ logger: { app() {} },+ userMcp: { setRecords() {}, async toolsForProject() { return []; } },+ plugins: { getTools: () => [], getSkills: () => [], listLoaded: () => [], getAgentExtensions: () => [] },+ sessionProjects: new Map(),+ dataDir: temp,+ vendorOAuth: { async bindingFor() { return undefined; } },+ modelsDevCatalog: { async ensureLoaded() {}, configureAccount() {}, findModel() { return undefined; } },+ getWorkspacePath: () => null,+ pluginActiveInProject: () => true,+ bindingForModel: (_provider, modelId) =>+ allowed.has(modelId) ? { id: modelId, fastModeAllowed: true } : { id: modelId },+ effectiveSubagentModelConfig: () => ({ modelConfig: undefined, capabilities: {} }),+ normalizeThinkingLevel: () => "off",+ });+ const launch = async (modelId, fastMode) => {+ const { sidecarParams } = await launchRuntime.resolveAgentRuntimeLaunch(+ "session-fixture",+ { providerId: provider.id, modelId, ...(fastMode === undefined ? {} : { fastMode }) },+ { defaultProviderId: provider.id, defaultModelId: modelId, defaultMode: "agent" },+ );+ return sidecarParams.fastMode;+ };++ assert.equal(await launch("allowed-model", true), true);+ assert.equal(await launch("allowed-model", false), false);+ assert.equal(await launch("allowed-model", undefined), false);+ assert.equal(await launch("other-model", true), false);+ } finally {+ process.env.HOME = priorHome;+ await rm(temp, { recursive: true, force: true });+ }+});diff --cc apps/desktop/test/model-advanced-capabilities.test.mjsindex fb2ab6284,8e1010564..670aa7ef7--- a/apps/desktop/test/model-advanced-capabilities.test.mjs+++ b/apps/desktop/test/model-advanced-capabilities.test.mjs@@@ -285,15 -285,3 +285,15 @@@ test("the offered default and the save/resolveBindingDefaultThinkingLevel\(\s*binding\.defaultThinkingLevel,\s*sortThinkingLevels\(next\),/,);});++test("model settings let the user allow Fast mode per model on Responses wires", () => {- // ADR 0332: the opt-in lives on the binding; `/fast` is the per-session switch.++ // ADR 0334: the opt-in lives on the binding; `/fast` is the per-session switch.+ assert.match(pickerSource, /const fastModeBilling = fastModeBillingOn\(apiStyle\);/);+ assert.match(pickerSource, /checked=\{binding\.fastModeAllowed === true\}/);+ assert.match(pickerSource, /disabled=\{!fastModeBilling\}/);+ assert.match(pickerSource, /fastModeAllowed: event\.target\.checked \|\| undefined/);+ // Plan limits and per-token billing are different costs, so the hint differs.+ assert.match(pickerSource, /"settings\.fastModeAllowedSubscriptionHint"/);+ assert.match(pickerSource, /"settings\.fastModeAllowedUsageHint"/);+ assert.match(pickerSource, /"settings\.fastModeAllowedUnsupported"/);+});diff --cc crates/host-core/src/db/session_fast_mode_migration.rsindex e24503e6f,000000000..5e942819amode 100644,000000..100644--- a/crates/host-core/src/db/session_fast_mode_migration.rs+++ b/crates/host-core/src/db/session_fast_mode_migration.rs@@@ -1,33 -1,0 +1,33 @@@+use super::{create_migration_backup, Connection, Context, Path, Result};+use rusqlite::Transaction;+- /// v25 stores the per-session `/fast` switch (ADR 0332). Every existing++/// v25 stores the per-session `/fast` switch (ADR 0334). Every existing+/// session keeps the default service tier.+fn migrate_v24_to_v25_tx(tx: &Transaction<'_>) -> Result<()> {+ let has_fast_mode: bool = tx.query_row(+ "SELECT EXISTS(SELECT 1 FROM pragma_table_info('sessions') WHERE name = 'fast_mode')",+ [],+ |row| row.get(0),+ )?;+ if !has_fast_mode {+ tx.execute_batch(+ "ALTER TABLE sessions ADD COLUMN fast_mode INTEGER NOT NULL DEFAULT 0+ CHECK (fast_mode IN (0, 1));",+ )?;+ }+ tx.pragma_update(None, "user_version", 25i64)?;+ Ok(())+}++pub(crate) fn migrate_v24_to_v25(conn: &Connection, path: &Path) -> Result<()> {+ let backup = create_migration_backup(conn, path, 24)?;+ let tx = conn.unchecked_transaction()?;+ migrate_v24_to_v25_tx(&tx)?;+ tx.commit().with_context(|| {+ format!(+ "commit schema v24 to v25 migration; backup {} remains",+ backup.display()+ )+ })?;+ Ok(())+}diff --cc crates/host-core/src/db/tests.rsindex bcfb8e1ad,8f5ed4f1e..bfe00d106--- a/crates/host-core/src/db/tests.rs+++ b/crates/host-core/src/db/tests.rs@@@ -294,43 -294,6 +294,43 @@@ fn worktree_registry_enforces_one_row_p/// `sessions` stamps nor the `session_todo` table, so the upgrade must add/// both, keep the v20 rows, leave a readable pre-migration backup, and stay/// idempotent when a fixture downgrades the same file in place.- /// v25 adds the per-session `/fast` column (ADR 0332). Existing sessions keep++/// v25 adds the per-session `/fast` column (ADR 0334). Existing sessions keep+/// their configuration, default to the normal tier, and a backup remains.+#[test]+fn v24_database_gains_session_fast_mode_defaulting_off() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("pi.sqlite");+ let session_id = {+ let db = Database::open(&path).unwrap();+ let session = crate::sessions::create_session_with_thinking(+ &db,+ Some("Kept".into()),+ None,+ None,+ None,+ None,+ Some("high".into()),+ )+ .unwrap();+ db.conn()+ .execute_batch("ALTER TABLE sessions DROP COLUMN fast_mode;")+ .unwrap();+ db.conn().pragma_update(None, "user_version", 24).unwrap();+ session.id+ };++ let db = Database::open(&path).unwrap();+ assert_eq!(schema_version(db.conn()), SCHEMA_VERSION);+ assert!(migration_backup_path(&path, 24).exists());+ let summary = crate::sessions::get_session(&db, &session_id)+ .unwrap()+ .unwrap()+ .summary;+ assert_eq!(summary.title, "Kept");+ assert_eq!(summary.thinking_level, "high");+ assert!(!summary.fast_mode);+}+#[test]fn v20_database_migrates_the_session_checklist_with_a_backup() {let dir = tempfile::tempdir().unwrap();diff --cc crates/host-core/src/providers/model.rsindex fa980ae3f,40f590012..97a4e3c83--- a/crates/host-core/src/providers/model.rs+++ b/crates/host-core/src/providers/model.rs@@@ -170,10 -170,6 +170,10 @@@ pub struct ModelBinding/// default because models.dev does not publish hosted-tool capability.#[serde(default, skip_serializing_if = "Option::is_none")]pub native_web_search: Option<bool>,+ /// Opt-in that lets the session `/fast` switch request OpenAI's priority- /// service tier for this model (ADR 0332). None/false keeps the default.++ /// service tier for this model (ADR 0334). None/false keeps the default.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub fast_mode_allowed: Option<bool>,}#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]diff --cc crates/host-core/src/rpc/mod.rsindex 10bb144b1,4f86af66b..ef77cdad3--- a/crates/host-core/src/rpc/mod.rs+++ b/crates/host-core/src/rpc/mod.rs@@@ -719,20 -719,6 +719,20 @@@ fn plugin_session_rpc_err(error: impl Trpc_err(rpc_code, message, &code)}- /// Optional session `/fast` switch (ADR 0332). Absent or null leaves the++/// Optional session `/fast` switch (ADR 0334). Absent or null leaves the+/// stored value; anything but a boolean is rejected rather than coerced.+fn fast_mode_param(params: &Value) -> Result<Option<bool>, JsonRpcError> {+ match params.get("fastMode") {+ None | Some(Value::Null) => Ok(None),+ Some(Value::Bool(value)) => Ok(Some(*value)),+ Some(_) => Err(rpc_err(+ 1002,+ "fastMode must be a boolean",+ "INVALID_PARAMS",+ )),+ }+}+/// Parse the optional session thinking selector at the RPC boundary. A/// missing/null value keeps the backwards-compatible default; present values/// must be strings from the host's allowlist rather than being silently@@@ -6700,58 -6682,6 +6700,58 @@@ mod tests);}- /// ADR 0332: `fastMode` is an optional boolean on create and configure;++ /// ADR 0334: `fastMode` is an optional boolean on create and configure;+ /// an absent value keeps the stored switch and a non-boolean is rejected.+ #[tokio::test]+ async fn session_fast_mode_rpc_is_optional_boolean_and_preserved() {+ let data_dir = tempfile::tempdir().unwrap();+ let mut app_state = AppState::open(data_dir.path()).unwrap();+ app_state.handshook = true;+ let state = Arc::new(Mutex::new(app_state));+ let (tx, _rx) = mpsc::unbounded_channel();+ let call = |method: &'static str, params: Value| {+ handle_request(state.clone(), method, params, tx.clone())+ };++ let legacy = call("session.create", json!({ "mode": "agent" }))+ .await+ .unwrap();+ assert_eq!(legacy["session"]["fastMode"], false);+ let created = call(+ "session.create",+ json!({ "mode": "agent", "fastMode": true }),+ )+ .await+ .unwrap();+ assert_eq!(created["session"]["fastMode"], true);+ let id = created["session"]["id"].as_str().unwrap().to_string();++ let kept = call(+ "session.configure",+ json!({ "id": id, "mode": "plan", "thinkingLevel": "high" }),+ )+ .await+ .unwrap();+ assert_eq!(kept["session"]["fastMode"], true);+ let off = call(+ "session.configure",+ json!({ "id": id, "mode": "agent", "fastMode": false }),+ )+ .await+ .unwrap();+ assert_eq!(off["session"]["fastMode"], false);++ for method in ["session.create", "session.configure"] {+ let error = call(+ method,+ json!({ "id": id, "mode": "agent", "fastMode": "yes" }),+ )+ .await+ .unwrap_err();+ assert_eq!(error.data.unwrap()["errorCode"], "INVALID_PARAMS");+ }+ }+#[tokio::test]async fn session_create_rpc_inherits_optional_permission_mode() {let data_dir = tempfile::tempdir().unwrap();diff --cc crates/host-core/src/rpc/scheduled_rpc.rsindex f86ca943a,7e043f47a..979cb72e6--- a/crates/host-core/src/rpc/scheduled_rpc.rs+++ b/crates/host-core/src/rpc/scheduled_rpc.rs@@@ -192,8 -192,6 +192,8 @@@ fn handle_with_workspace_policy.permission_mode.clone().or_else(|| automatic.then(|| "ask".into())),- // Unattended runs keep the default tier (ADR 0332).++ // Unattended runs keep the default tier (ADR 0334).+ fast_mode: false,};let uses_task_execution_settings = task.permission_mode.is_some()|| task.thinking_level.is_some()diff --cc crates/host-core/src/session_collaboration/mod.rsindex dac851691,50077ead6..25c71e708--- a/crates/host-core/src/session_collaboration/mod.rs+++ b/crates/host-core/src/session_collaboration/mod.rs@@@ -167,8 -167,6 +167,8 @@@ fn spawn(db: &Database, input: &Value)project_path: parent.summary.project_path,thinking_level: Some(parent.summary.thinking_level),permission_mode: Some(parent.summary.permission_mode),- // Delegated workers keep the default tier (ADR 0332).++ // Delegated workers keep the default tier (ADR 0334).+ fast_mode: false,},)?;db.conn().execute("INSERT INTO session_collaboration_links(session_id,created_by_session_id,plugin_id,created_at) VALUES(?1,?2,?3,?4)",params![created.id,source,plugin,now_ms()])?;diff --cc crates/host-core/src/sessions.rsindex 57f63bc55,fd7a3650d..2557f271f--- a/crates/host-core/src/sessions.rs+++ b/crates/host-core/src/sessions.rs@@@ -128,10 -128,6 +128,10 @@@ pub struct SessionSummarypub thinking_level: String,#[serde(default = "default_permission_mode")]pub permission_mode: String,- /// The `/fast` switch for this session's main turns (ADR 0332). Requests++ /// The `/fast` switch for this session's main turns (ADR 0334). Requests+ /// use the priority tier only when the model binding also allows it.+ #[serde(default)]+ pub fast_mode: bool,pub updated_at: String,pub created_at: String,/// True when this session is the transcript owned by a scheduled-task run.@@@ -1371,8 -1375,6 +1381,8 @@@ pub struct SessionCreateOptionspub project_path: Option<String>,pub thinking_level: Option<String>,pub permission_mode: Option<String>,- /// The `/fast` switch (ADR 0332); false keeps the default service tier.++ /// The `/fast` switch (ADR 0334); false keeps the default service tier.+ pub fast_mode: bool,}pub fn create_session_with_thinking(@@@ -1883,31 -1879,6 +1893,31 @@@ pub fn configure_session_with_thinkingmodel_id: Option<&str>,thinking_level: Option<&str>,permission_mode: Option<&str>,+) -> Result<Option<SessionSummary>> {+ configure_session_with_fast_mode(+ db,+ id,+ mode,+ provider_id,+ model_id,+ thinking_level,+ permission_mode,+ None,+ )+}++/// Full configurator. Every `None` preserves the persisted value, including- /// the `/fast` switch (ADR 0332).++/// the `/fast` switch (ADR 0334).+#[allow(clippy::too_many_arguments)]+pub fn configure_session_with_fast_mode(+ db: &Database,+ id: &str,+ mode: &str,+ provider_id: Option<&str>,+ model_id: Option<&str>,+ thinking_level: Option<&str>,+ permission_mode: Option<&str>,+ fast_mode: Option<bool>,) -> Result<Option<SessionSummary>> {if !(is_valid_mode(mode) || mode == "chat") {return Err(anyhow!("mode must be plan or agent"));@@@ -4787,76 -4769,6 +4810,76 @@@ mod testsassert_eq!(omitted.thinking_level, "omit");}- /// ADR 0332: `/fast` is stored per session, survives configures that do++ /// ADR 0334: `/fast` is stored per session, survives configures that do+ /// not mention it, and is copied by a fork.+ #[test]+ fn session_fast_mode_is_persisted_preserved_and_forked() {+ let db = test_db();+ let session = create_session(&db, None, None, None, None, None).unwrap();+ assert!(!session.fast_mode);++ let set = |enabled: Option<bool>, mode: &str| {+ configure_session_with_fast_mode(+ &db,+ &session.id,+ mode,+ None,+ None,+ None,+ None,+ enabled,+ )+ .unwrap()+ .unwrap()+ };+ assert!(set(Some(true), "agent").fast_mode);+ assert!(set(None, "plan").fast_mode);+ let kept = configure_session(&db, &session.id, "agent", None, None)+ .unwrap()+ .unwrap();+ assert!(kept.fast_mode);+ assert!(+ get_session(&db, &session.id)+ .unwrap()+ .unwrap()+ .summary+ .fast_mode+ );++ let ForkSessionResult::Created(fork) =+ fork_session_through(&db, &session.id, None, None).unwrap()+ else {+ panic!("expected fork");+ };+ assert!(fork.summary.fast_mode);+ assert!(+ get_session(&db, &fork.summary.id)+ .unwrap()+ .unwrap()+ .summary+ .fast_mode+ );++ assert!(!set(Some(false), "agent").fast_mode);++ let created = create_session_with_options(+ &db,+ SessionCreateOptions {+ fast_mode: true,+ ..Default::default()+ },+ )+ .unwrap();+ assert!(created.fast_mode);+ assert!(+ get_session(&db, &created.id)+ .unwrap()+ .unwrap()+ .summary+ .fast_mode+ );+ }+#[test]fn create_session_permission_mode_is_optional_and_validated() {let db = test_db();diff --cc docs/adr/0334-openai-fast-mode.mdindex 074215f20,000000000..f9a177d2amode 100644,000000..100644--- a/docs/adr/0334-openai-fast-mode.md+++ b/docs/adr/0334-openai-fast-mode.md@@@ -1,72 -1,0 +1,72 @@@- # ADR 0332: OpenAI Fast mode as a per-session switch gated by model settings++# ADR 0334: OpenAI Fast mode as a per-session switch gated by model settings++- Status: Accepted+- Date: 2026-10-17+- Deciders: PI-Desktop maintainers+- Related: [ADR 0329](0329-session-worktree-isolation.md) ·+ [03-runtime/11-provider-model-system](../spec/03-runtime/11-provider-model-system.md) ·+ [04-ux/04-builtin-commands](../spec/04-ux/04-builtin-commands.md) ·+ issue #1657 · E2E-FAST-MODE++## Context++OpenAI serves a faster priority tier that Codex CLI and the OpenAI API call+Fast mode. On the wire it is the Responses body field `service_tier:+"priority"`; the Codex backend rejects `"fast"`. The tier costs more: a ChatGPT+subscription spends its plan limits faster, and the OpenAI API bills a higher+per-token price. PI-Desktop never asked for a tier. pi-ai's Responses and+Codex adapters already accept `serviceTier` and price the tier the response+reports, but `streamSimple` dropped the option while building its base options.++The cost is a decision about one conversation, while whether an endpoint+honors the field is something only the user knows for a relay. Issue #1657 asks+for the subscription speed-up; maintainers asked that capability be configured+in model settings.++## Decision++1. **Model settings own capability.** `ModelBinding.fastModeAllowed` is an+ opt-in, stored in the existing provider `config_json` like+ `nativeWebSearch`, so it needs no migration. The checkbox is enabled only+ for Responses wires (`openai_codex_responses`, `responses`), including+ relays; its hint names the cost on that wire.+2. **`/fast` owns the session switch.** A new builtin `builtin.session.fast`+ (`/fast`) toggles a persisted `sessions.fast_mode` column (schema v25,+ additive, v24 backup). `session.create` and `session.configure` accept an+ optional boolean `fastMode`; omission keeps the stored value. Forks copy it;+ scheduled runs and delegated workers start off. A draft carries it into the+ session its first prompt creates. Remote sessions refuse it.+3. **`/fast` only works on a configured model.** When the selected model's+ wire cannot carry the tier or the model is not allowed, `/fast` stores+ nothing and points to Settings → Models → Advanced, in either direction. A+ stale stored switch on such a model is inert because launch also requires+ the opt-in.+4. **The launcher resolves; the runtime only stamps the wire.** Session launch+ sends `fastMode: true` to the sidecar only when the session switch is on and+ the user's stored binding allows it. The runtime passes pi-ai's native+ `serviceTier: "priority"` on main turns whose resolved wire is+ `openai-codex-responses` or `openai-responses`; the existing pi-ai patch+ forwards `serviceTier` through `streamSimple`, so the adapters also apply+ their own tier pricing. Subagents, compaction, and one-shot plugin requests+ build their own options and keep the default tier.++## Alternatives++- **Per-model switch only (no session state).** Avoids a migration, but turns+ a per-conversation cost into a global one: enabling Fast for one task speeds+ up and costs every conversation on that model.+- **Hard-coded capability rule (official OpenAI host only).** Removes a+ setting, but excludes relays the user knows support the field and hides the+ decision in code.+- **Generic request-parameter injection with presets.** More flexible, but an+ arbitrary body-field channel needs its own validation and permission story,+ which is larger than this need.++## Consequences++- Schema v25 adds one column; older apps opening a v25 database refuse it as+ newer, the existing downgrade behavior.+- The capability can be wrong for a relay that ignores or rebills the field;+ the settings hint states that risk, and the user owns the opt-in.+- The Composer model chip shows a Fast mark while the switch is on for an+ allowed model, so the cost is visible at send time.diff --cc docs/adr/README.mdindex 922f4a80c,eba1586a0..e7bebd327--- a/docs/adr/README.md+++ b/docs/adr/README.md@@@ -377,7 -378,7 +378,8 @@@ Each ADR includes| 0329 | [Isolate parallel sessions of one project in git worktrees](0329-session-worktree-isolation.md) | Accepted (Windows E2E pending) || 0330 | [Open scoped HTML files in the work-panel Browser from plugins](0330-open-html-files-in-work-panel-browser-from-plugins.md) | Accepted || 0331 | [Plugin session follow and host-owned work-panel reveal](0331-plugin-session-follow-and-work-panel-reveal.md) | Accepted |- | 0332 | [OpenAI Fast mode as a per-session switch gated by model settings](0332-openai-fast-mode.md) | Accepted |+ | 0333 | [A plugin-owned suggestion in the Composer placeholder](0333-plugin-composer-suggestion.md) | Accepted |++| 0334 | [OpenAI Fast mode as a per-session switch gated by model settings](0334-openai-fast-mode.md) | Accepted || plugin-fetch-redirect-policy | [Host-enforced plugin fetch redirect policy](plugin-fetch-redirect-policy.md) | Accepted (implementation candidate for #1475) || local-agent-remote-workspace-tools | [Local Agent and model requests for remote workspaces](local-agent-remote-workspace-tools.md) | Accepted for implementation |diff --cc docs/project/unreleased.mdindex 69b504767,da447d18c..5699e1462--- a/docs/project/unreleased.md+++ b/docs/project/unreleased.md@@@ -1,7 -1,6 +1,11 @@@# Unreleased changes+- Add OpenAI Fast mode (#1657). Allow it per model in Settings → Models for a+ ChatGPT subscription or an OpenAI Responses connection, then type `/fast` to+ turn it on for the current conversation. Requests ask for the priority+ service tier, which replies faster and spends plan limits faster or bills+ more per token; the Composer model chip shows a Fast mark while it is on.+ - Upgrade the Pi agent, model adapters, native-session SDK, and MCP client from+ 1.1.0 to 1.3.0. Preserve Desktop compatibility patches, omit foreign-model+ thinking from replay, reject malformed final tool JSON before execution, and+ expose the user-run discriminator to trusted extension startup handlers.diff --cc docs/spec/02-architecture/06-pi-runtime-dependency-boundary.mdindex c53fb0243,26645a2f7..728aa4dca--- a/docs/spec/02-architecture/06-pi-runtime-dependency-boundary.md+++ b/docs/spec/02-architecture/06-pi-runtime-dependency-boundary.md@@@ -19,8 -19,7 +19,8 @@@ in `docs/project/pi-130-adoption.md`prompt-template expansion, and session-context projection.- `@earendil-works/pi-ai` supplies provider transports, auth, message types,request retries, and token estimation. Hosted-search request and estimation- behavior remains covered by PI-Desktop's pi-ai patch and contract tests.+ behavior, and forwarding `serviceTier` through `streamSimple` for Fast mode- (ADR 0332), remain covered by PI-Desktop's pi-ai patch and contract tests.++ (ADR 0334), remain covered by PI-Desktop's pi-ai patch and contract tests.- Rust `host-core` remains the sole owner of SQLite and authoritative durablesession state. The Node sidecar asks it to persist checkpoints and tooloutcomes through the existing RPC contract.diff --cc docs/spec/03-runtime/01-ipc-protocol.mdindex 29d19104f,8eea0bc40..2cfcffc69--- a/docs/spec/03-runtime/01-ipc-protocol.md+++ b/docs/spec/03-runtime/01-ipc-protocol.md@@@ -188,8 -188,6 +188,8 @@@ type SessionConfigureRequest =providerId?: string;modelId?: string;thinkingLevel: SessionThinkingLevel;- /** Session `/fast` switch (ADR 0332); omitted keeps the stored value. */++ /** Session `/fast` switch (ADR 0334); omitted keeps the stored value. */+ fastMode?: boolean;};```diff --cc docs/spec/03-runtime/04-data-storage.mdindex b0b740862,3d7cc6472..839eb5b0a--- a/docs/spec/03-runtime/04-data-storage.md+++ b/docs/spec/03-runtime/04-data-storage.md@@@ -585,8 -594,6 +594,8 @@@ CREATE TABLE sessions'high', 'xhigh', 'max', 'omit')),permission_mode TEXT NOT NULL DEFAULT 'inherit' -- D115: inherit follows settingsCHECK (permission_mode IN ('inherit', 'ask', 'accept-edits', 'auto')),- fast_mode INTEGER NOT NULL DEFAULT 0 -- ADR 0332: session /fast switch++ fast_mode INTEGER NOT NULL DEFAULT 0 -- ADR 0334: session /fast switch+ CHECK (fast_mode IN (0, 1)),source TEXT, -- import origin: claude-code | codex | opencode | pideleted_at INTEGER, -- plugin trash marker; null means activepinned INTEGER NOT NULL DEFAULT 0,@@@ -1621,13 -1628,6 +1630,13 @@@ truncating at a guessed position- **Schema v23 is additive.** It adds `sessions.title_source` and classifiesexisting placeholder titles as `default`; every other existing title ispreserved and classified as `manual`. The migration keeps a v22 backup.+- **Schema v24 is additive.** It adds the `worktrees` registry and+ `projects.worktree_setup_command` for isolated sessions (ADR 0329). The+ migration keeps a v23 backup.- - **Schema v25 is additive.** It adds `sessions.fast_mode` (ADR 0332), the++- **Schema v25 is additive.** It adds `sessions.fast_mode` (ADR 0334), the+ session `/fast` switch, defaulting to `0` for every existing session. Forks+ copy it; scheduled runs and delegated workers start at `0`. The migration+ keeps a v24 backup.- **Schema v14 is additive.** It adds nullable `sessions.deleted_at`, thepartial deletion index, and `session_import_origins`. Existing sessions stayactive and have no origin rows. The migration runs in the same guardeddiff --cc docs/spec/03-runtime/06-host-rpc-protocol.mdindex c103419bb,e03cfbd78..264f7868a--- a/docs/spec/03-runtime/06-host-rpc-protocol.md+++ b/docs/spec/03-runtime/06-host-rpc-protocol.md@@@ -296,8 -296,6 +296,8 @@@ to later refresh and inference; the ven`inheritPermissionFromSessionId`; when present, the host copies the existingsession's persisted permission mode atomically, while omission preserves theexisting `inherit` default. Missing/null thinking level defaults to `off`.- Optional boolean `fastMode` (ADR 0332) stores the session `/fast` switch;++ Optional boolean `fastMode` (ADR 0334) stores the session `/fast` switch;+ missing/null means `false` and a non-boolean returns `INVALID_PARAMS`.Optional `isolated: true` (ADR 0329) also requires `projectPath` and givesthe new session its own git worktree before it returns; if the worktreecannot be created the session is deleted again and the call fails with a@@@ -354,9 -352,7 +354,9 @@@- `session.configure` — atomically persists `mode`, `providerId`, `modelId`,and optional `thinkingLevel` (`off|minimal|low|medium|high|xhigh|max|omit`)for the next pi turn; omitting/null- `thinkingLevel` preserves the current value; invalid modes or levels return+ `thinkingLevel` preserves the current value; optional boolean `fastMode`- (ADR 0332) follows the same rule, and a non-boolean is `INVALID_PARAMS`;++ (ADR 0334) follows the same rule, and a non-boolean is `INVALID_PARAMS`;+ invalid modes or levels return`INVALID_PARAMS`; mode is `plan | goal | agent` and changing any sessionconfiguration is allowed only while idle and without a pending/queued/runningPlan or Goal recorddiff --cc docs/spec/03-runtime/11-provider-model-system.mdindex dbf505947,87c439b1c..cb91f276f--- a/docs/spec/03-runtime/11-provider-model-system.md+++ b/docs/spec/03-runtime/11-provider-model-system.md@@@ -351,7 -351,6 +351,7 @@@ type ModelBinding =defaultThinkingLevel: SessionThinkingLevel | nullthinkingProtocol?: "legacy" | "adaptive"availableForSubagents?: boolean // opt-in for AI-driven delegation- fastModeAllowed?: boolean // opt-in for the session /fast switch (ADR 0332)++ fastModeAllowed?: boolean // opt-in for the session /fast switch (ADR 0334)}type SelectedModelRef = {@@@ -384,17 -383,6 +384,17 @@@ array remain future work. A legacy provmaterialized as one fallback binding on host read and upgraded to `models` onthe next provider write.- `ModelBinding.fastModeAllowed` (boolean, default false, ADR 0332): lets the++`ModelBinding.fastModeAllowed` (boolean, default false, ADR 0334): lets the+session `/fast` switch request OpenAI's priority service tier+(`service_tier: "priority"`) for this model. Model settings enable the checkbox+only for Responses wires: `openai_codex_responses` (ChatGPT subscription; the+tier spends plan limits faster) and `responses` (billed per token at the tier's+higher price; a relay may ignore or rebill the field). The launcher sends+`fastMode: true` to the sidecar only when the session switch is on and the+stored binding allows it; the runtime adds the field to main-turn requests whose+resolved wire is `openai-codex-responses` or `openai-responses`. Subagents,+compaction, and one-shot requests keep the default tier.+`ModelBinding.availableForSubagents` (boolean, default false): opt-in flag thatmakes the model available for AI-driven subagent delegation. When enabled, themodel appears in the delegation catalog injected into the parent agent's systemdiff --cc docs/spec/04-ux/04-builtin-commands.mdindex 05c462326,2617e5fc2..b58613906--- a/docs/spec/04-ux/04-builtin-commands.md+++ b/docs/spec/04-ux/04-builtin-commands.md@@@ -27,7 -27,6 +27,7 @@@ builtin command contracts| `builtin.mode.agent` | Switch to Agent | mode, agent | Session | low | set the idle session mode to Agent || `builtin.mode.plan` | Switch to Plan | mode, plan, planning | Session | low | set the idle session mode to Plan || `builtin.mode.goal` | Switch to Goal | mode, goal, objective, autonomous | Session | low | set the idle session mode to Goal |- | `builtin.session.fast` | Toggle Fast mode | fast, speed, priority, service tier | Session | medium | toggle the session's OpenAI priority service tier (ADR 0332) |++| `builtin.session.fast` | Toggle Fast mode | fast, speed, priority, service tier | Session | medium | toggle the session's OpenAI priority service tier (ADR 0334) |## 4. Visibility and execution rules@@@ -45,15 -44,6 +45,15 @@@Agent/Plan/Goal chip. They update an idle session immediately. With no activesession, they update the persisted default for the next session; a runningsession or pending approval is not changed.+- `Toggle Fast mode` flips the session's persisted `fastMode` through the same- configuration path (ADR 0332). With no active session it records the switch on++ configuration path (ADR 0334). With no active session it records the switch on+ the new-task draft, and the created session starts with it. The selected+ model must allow Fast mode in Settings → Models → Advanced on a Responses+ wire (Codex subscription or OpenAI Responses); otherwise, in either+ direction, a warning toast points to that setting and nothing is stored. A+ stored switch on an unconfigured model has no effect at launch. Remote+ sessions refuse it. The risk is medium because the priority tier+ spends plan limits faster or bills more per token.- `SubmitPlan` and `SubmitGoal` are model tools, not palette commands. There isno Chat mode or request-changes alias.- The former app/project/settings/plugin/log commands remain available throughdiff --cc docs/spec/06-delivery/04-e2e-test-plan.mdindex a5192c175,ced0b4975..eb7391050--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@@ -18218,33 -18423,53 +18423,84 @@@ host-created files. The full app's file`apps/desktop/test/main-wiring-contract.test.mjs`; the interactive Electronscenario remains a manual validation run.+### E2E-FAST-MODE: `/fast` asks for the priority tier only on an allowed model++- **Preconditions**: A ChatGPT subscription (Codex) account and a Responses+ API-key provider, each with two configured models. No real provider is+ required for the automated path; the manual path uses a capturing local+ endpoint or the user's authorized account.+- **Steps**:+ 1. In Settings → Models, check **Fast mode** on one model of each provider.+ Confirm the checkbox is disabled on a Chat Completions provider.+ 2. Start a new task on the allowed Codex model, type `/fast`, send a prompt.+ 3. Send `/fast` again, then send another prompt.+ 4. Switch the session to the model without the opt-in and send `/fast`.+ 5. Fork the session while Fast is on; restart the app and reopen both.+- **Expected**: Step 1 persists `fastModeAllowed` on the binding only. Step 2+ shows the Fast mark on the model chip and the request body carries+ `service_tier: "priority"`; a Responses API-key model shows the per-token+ price toast instead. Step 3 clears the mark and the field. Step 4 refuses+ with the model-settings hint and stores nothing. Step 5 keeps the switch on+ the fork and across restart. Subagent and compaction requests never carry+ the field. Remote sessions refuse `/fast`.+- **Specs linked**: `03-runtime/11-provider-model-system.md`,+ `03-runtime/04-data-storage.md` (v25), `04-ux/04-builtin-commands.md`,- ADR 0332, issue #1657.++ ADR 0334, issue #1657.+- **Status**: Automated coverage: `apps/desktop/test/fast-mode-command.test.mjs`+ (draft → created session, toggle, refusals, remote, chip),+ `apps/desktop/test/fast-mode-session-launch.test.mjs` (launch resolution),+ `packages/agent-runtime/src/fast-mode.test.ts` (request body through the real+ pi-ai Responses and Completions adapters), host-core migration, RPC and fork+ tests. The full settings → `/fast` → captured request path is a manual+ validation scenario.+++ ### E2E-PROVIDER-optional-client-certificate++ - **Preconditions:** The locked Electron 43 runtime, built workspace packages,+ and an isolated profile. Only a local HTTPS fixture and local proxy are used;+ trust is confined to the test process/session and fixture certificate.+ - **Steps:** Run `node scripts/e2e-provider-client-certificate.mjs`. Confirm the+ original `net.fetch` aborts before HTTP. Probe the model list and connection+ through the real metadata service; repeat with an invalid fixture key and an+ authenticated custom HTTP proxy. Return a cross-origin redirect, then cancel+ a pending response.+ - **Expected:** Valid credentials return the fixture model; invalid credentials+ reach HTTP 401. The retry follows the proxy route, sends no client identity,+ refuses cross-origin redirects and aborts with the original signal.+ - **Security coverage:** `provider-https-metadata.test.mjs` additionally checks+ mandatory client authentication, untrusted server certificates, hostname+ mismatch, compressed responses, and late-tunnel cleanup. The metadata policy+ tests reject fallback on other TLS/network errors or HTTP failures.+ - **Specs linked:** `03-runtime/07-process-model.md`,+ ADR `provider-metadata-client-certificate-retry`, issue #1676.+ - **Acceptance:** Recovery without an Electron major upgrade, TLS verification+ bypass, direct proxy bypass, or change to persisted provider bindings.+ - **Milestone:** Maintenance.+ - **Status:** Automated fixture; record the tested head/base and execution+ result in the delivery report.++ #### E2E-1175: A plugin suggestion rides in the Composer placeholder and is taken with Tab++ - **Preconditions**: A plugin that declares `composer.suggest` is installed,+ enabled, and granted the permission, and it offers one line on+ `session:turnEnded` after its own completion.+ - **Steps:** 1) Run an Agent turn in a session and let it complete while that+ session is on screen and its Composer is empty. 2) Observe the placeholder+ layer. 3) Press Tab. 4) Repeat, then press Esc. 5) Repeat, then type one+ character. 6) Repeat, then switch session before the offer arrives.+ - **Expected**: The suggestion appears in the placeholder layer of an empty+ draft, brighter than the shell placeholder and on one line with an ellipsis,+ with a `Tab` / `Esc` hint and one polite announcement. Tab writes the exact+ text into the draft with the caret at the end and the input focused, keeping+ any staged attachment; Esc drops it; a first character drops it; a missed+ offer answers `{ shown: false, reason }` and shows nothing. No transcript row,+ toast, or overlay appears, and the plugin's call is audited.+ - **Specs linked**: `07-plugins/03-plugin-api.md`,+ `07-plugins/13-plugin-permissions-matrix.md`, ADR 0333.+ - **Acceptance**: A (Composer entry path), Security (permission-gated, never+ sent by the plugin).+ - **Milestone**: M6++ - **Status**: Unit/source-contract-covered by+ `composer-suggestion-state.test.mjs`, `composer-suggestion-relay.test.mjs`,+ and `plugin-composer-suggestion.test.mjs`; the rendered journey remains a+ manual/Electron check when this surface changes.diff --cc docs/zh-CN/spec/02-architecture/06-pi-runtime-dependency-boundary.mdindex f79163d03,006c7af22..c1247addb--- a/docs/zh-CN/spec/02-architecture/06-pi-runtime-dependency-boundary.md+++ b/docs/zh-CN/spec/02-architecture/06-pi-runtime-dependency-boundary.md@@@ -12,8 -12,7 +12,8 @@@ JavaScript 包。上游包演进时,�- `@earendil-works/pi-agent-core` 提供 Agent 循环,以及稳定的 agent、event、tool类型。Agent Runtime 自行维护桌面专用的上下文投影、压缩和 prompt 模板展开。- `@earendil-works/pi-ai` 提供提供商传输、认证、消息类型、请求重试和 token 估算。- Hosted search 请求与估算行为继续由 PI-Desktop 的 pi-ai 补丁和契约测试覆盖。+ Hosted search 请求与估算行为,以及为 Fast 模式让 `streamSimple` 转发 `serviceTier`- (ADR 0332),继续由 PI-Desktop 的 pi-ai 补丁和契约测试覆盖。++ (ADR 0334),继续由 PI-Desktop 的 pi-ai 补丁和契约测试覆盖。- Rust `host-core` 仍然是 SQLite 和权威持久会话状态的唯一所有者。Node sidecar通过现有 RPC 契约请求持久化检查点和工具结果。- `@earendil-works/pi-coding-agent` 是过渡期依赖。生产代码仅在原生 Pi 会话续接及diff --cc docs/zh-CN/spec/03-runtime/01-ipc-protocol.mdindex b3a25113a,a2bf727ed..d2070919a--- a/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md+++ b/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md@@@ -158,8 -158,6 +158,8 @@@ type SessionConfigureRequest =providerId?: string;modelId?: string;thinkingLevel: SessionThinkingLevel;- /** Session `/fast` switch (ADR 0332); omitted keeps the stored value. */++ /** Session `/fast` switch (ADR 0334); omitted keeps the stored value. */+ fastMode?: boolean;};```diff --cc docs/zh-CN/spec/03-runtime/04-data-storage.mdindex 33c9c1711,60132669b..9ffa481c0--- a/docs/zh-CN/spec/03-runtime/04-data-storage.md+++ b/docs/zh-CN/spec/03-runtime/04-data-storage.md@@@ -362,8 -362,6 +362,8 @@@ CREATE TABLE sessions'high', 'xhigh', 'max', 'omit')),permission_mode TEXT NOT NULL DEFAULT 'inherit' -- D115: inherit follows settingsCHECK (permission_mode IN ('inherit', 'ask', 'accept-edits', 'auto')),- fast_mode INTEGER NOT NULL DEFAULT 0 -- ADR 0332: session /fast switch++ fast_mode INTEGER NOT NULL DEFAULT 0 -- ADR 0334: session /fast switch+ CHECK (fast_mode IN (0, 1)),source TEXT, -- import origin: claude-code | codex | opencode | pideleted_at INTEGER, -- plugin trash marker; null means activepinned INTEGER NOT NULL DEFAULT 0,@@@ -1186,11 -1184,6 +1186,11 @@@ outbox 排空。渲染器侧的停止�`default`;其余现有标题保持原样并归类为 `manual`。迁移前保留 v22 备份。v15→v16 会话协作步骤现在写入 `16`(它自己的版本)而不是最新的架构常量,因此 v15 文件可以在一次启动中走完两个步骤。+- **架构 v24 是增量的。** 它为隔离会话增加 `worktrees` 登记表和+ `projects.worktree_setup_command`(ADR 0329)。迁移前保留 v23 备份。- - **架构 v25 是增量的。** 它增加 `sessions.fast_mode`(ADR 0332),即会话的 `/fast`++- **架构 v25 是增量的。** 它增加 `sessions.fast_mode`(ADR 0334),即会话的 `/fast`+ 开关,所有已有会话默认为 `0`。fork 会复制该值;定时任务运行和委托子会话从 `0` 开始。+ 迁移前保留 v24 备份。- **架构 v7 首先到达 v8,然后使用受保护的路径。** v7→v8迁移之后是相同的受保护的 v8→v15 迁移;架构-v9 和schema-v10 数据库采用相同的受保护路径并接收精确的可读数据diff --cc docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.mdindex fa7897617,b47139846..1635cd00f--- a/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md+++ b/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md@@@ -226,8 -226,7 +226,8 @@@ type ToolBudgetHealth =### 会议- `session.list`- `session.create` — 接受可选的 `thinkingLevel`; missing/null 默认值- 至 `off`。可选布尔值 `fastMode`(ADR 0332)保存会话的 `/fast` 开关;缺省/null 表示-至 `off`。可选的 `isolated: true`(ADR 0329)同时要求 `projectPath`,并在返回前为新会话++至 `off`。可选布尔值 `fastMode`(ADR 0334)保存会话的 `/fast` 开关;缺省/null 表示+`false`,非布尔值返回 `INVALID_PARAMS`。可选的 `isolated: true`(ADR 0329)同时要求 `projectPath`,并在返回前为新会话创建专属 git worktree;无法创建时会话会被删除,调用以 `WORKTREE_*` 错误(§7)失败。- `session.fork` — accepts `sessionId`, an optional caller-provided display`title`, and optional `throughMessageId`; creates@@@ -253,8 -252,7 +253,8 @@@并且不更新 `updated_at`、转录内容或消息数。- `session.configure` — 以原子方式持久保存 `mode`、`providerId`、`modelId`,以及可选的 `thinkingLevel` 用于下一个 pi 回合; omitting/null- `thinkingLevel` 保留当前值;可选布尔值 `fastMode`(ADR 0332)遵循同一规则,- `thinkingLevel` 保留当前值;返回无效模式或级别++ `thinkingLevel` 保留当前值;可选布尔值 `fastMode`(ADR 0334)遵循同一规则,+ 非布尔值返回 `INVALID_PARAMS`;返回无效模式或级别`INVALID_PARAMS`;模式为 `plan | goal | agent` 并更改任何会话仅在空闲且没有 pending/queued/running 时才允许配置Plan 或 Goal 记录diff --cc docs/zh-CN/spec/03-runtime/11-provider-model-system.mdindex b97b73211,31ea7fd85..01706470e--- a/docs/zh-CN/spec/03-runtime/11-provider-model-system.md+++ b/docs/zh-CN/spec/03-runtime/11-provider-model-system.md@@@ -295,7 -295,6 +295,7 @@@ type ModelBinding =thinkingLevels: ThinkingLevel[]defaultThinkingLevel: SessionThinkingLevel | nullavailableForSubagents?: boolean // opt-in for AI-driven delegation- fastModeAllowed?: boolean // opt-in for the session /fast switch (ADR 0332)++ fastModeAllowed?: boolean // opt-in for the session /fast switch (ADR 0334)}type SelectedModelRef = {@@@ -324,14 -323,6 +324,14 @@@ type ThinkingLevel后续工作。只有 `defaultModelId` 的旧版提供商,在主机读取时会被具体化为一条回退 binding,并在下一次提供商写入时升级为 `models`。- `ModelBinding.fastModeAllowed`(布尔值,默认 false,ADR 0332):允许会话的 `/fast`++`ModelBinding.fastModeAllowed`(布尔值,默认 false,ADR 0334):允许会话的 `/fast`+开关为该模型请求 OpenAI 优先服务档位(`service_tier: "priority"`)。模型设置只在+Responses 协议上启用该勾选框:`openai_codex_responses`(ChatGPT 订阅,优先档位会更快+消耗订阅额度)和 `responses`(按优先档位更高的 token 单价计费;中转服务可能忽略或+另行计费)。只有当会话开关打开且保存的 binding 允许时,启动器才向 sidecar 发送+`fastMode: true`;运行时只在解析后的协议为 `openai-codex-responses` 或+`openai-responses` 的主回合请求中加入该字段。子代理、压缩和一次性请求保持默认档位。+`ModelBinding.availableForSubagents`(布尔值,默认 false):这是一个选择加入的标志,让该模型可用于 AI 驱动的子代理委托。启用后,该模型会出现在注入父agent 系统提示的委托目录中。父 agent 随后就能通过 Task 工具的 `model` 参数diff --cc docs/zh-CN/spec/04-ux/04-builtin-commands.mdindex 1403d9266,331ee02c8..0a44692b9--- a/docs/zh-CN/spec/04-ux/04-builtin-commands.md+++ b/docs/zh-CN/spec/04-ux/04-builtin-commands.md@@@ -26,7 -26,6 +26,7 @@@ builtin.<domain>.<action| `builtin.mode.agent` | 切换到 Agent | mode、agent | Session | 低 | 将空闲会话模式设为 Agent || `builtin.mode.plan` | 切换到 Plan | mode、plan、planning | Session | 低 | 将空闲会话模式设为 Plan || `builtin.mode.goal` | 切换到 Goal | mode、goal、objective、autonomous | Session | 低 | 将空闲会话模式设为 Goal |- | `builtin.session.fast` | 切换 Fast 模式 | fast、speed、priority、service tier | Session | 中 | 切换会话的 OpenAI 优先服务档位(ADR 0332) |++| `builtin.session.fast` | 切换 Fast 模式 | fast、speed、priority、service tier | Session | 中 | 切换会话的 OpenAI 优先服务档位(ADR 0334) |## 4. 可见性与执行规则@@@ -39,12 -38,6 +39,12 @@@- 模式命令使用与 Composer Agent/Plan/Goal 芯片相同的活动会话配置路径,立即更新空闲会话。没有活动会话时,它们更新下一个会话使用的持久化默认值;正在运行的会话或待审批会话不会被修改。- - `Toggle Fast mode` 通过同一条配置路径翻转会话持久化的 `fastMode`(ADR 0332)。++- `Toggle Fast mode` 通过同一条配置路径翻转会话持久化的 `fastMode`(ADR 0334)。+ 没有活动会话时,它记录在新任务草稿上,创建出的会话会带上该开关。所选模型必须在+ 「设置 → 模型 → 高级」中允许 Fast 模式,且走 Responses 协议(Codex 订阅或 OpenAI+ Responses);否则无论开启还是关闭,都只弹出警告指向该设置,不保存任何状态。未配置+ 模型上残留的开关在启动时不生效。远程会话拒绝该命令。风险为中,+ 因为优先档位会更快消耗订阅额度,或按更高的 token 单价计费。- `SubmitPlan` 和 `SubmitGoal` 是模型工具,不是命令面板命令。没有 Chat 模式或request-changes 别名。- 原有的应用、项目、设置、插件和日志操作(仍适用时)通过各自的专用界面提供,diff --cc docs/zh-CN/spec/06-delivery/04-e2e-test-plan.mdindex 492b10952,d6b118154..8af097099--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md@@@ -9765,21 -9872,3 +9872,21 @@@ host-created files. The full app's file- **关联规格**:`04-ux/01-ui-ia.md` §3.2、`04-ux/06-settings-ia.md`(常规 → 侧边栏卡片)。- **验收**:项目折叠时仍能回答“这里是否有正在运行的工作”,且两种提示可从持久化设置独立控制。- **状态**:草稿。现有 `apps/desktop/test/sidebar-project-runs.test.mjs` 覆盖数量分类、总开关与子开关门控、两种渲染入口,以及主题令牌和减少动态效果保证;它不覆盖设置 API 缺省值规范化或完整交互,相关场景仍需在可用环境手动验证。++### E2E-FAST-MODE:`/fast` 只在允许的模型上请求优先档位++- **前置条件**:一个 ChatGPT 订阅(Codex)账号和一个 Responses API key 提供商,各配置两个模型。+ 自动化路径不需要真实提供商;手动路径使用可捕获请求的本地端点或用户授权的账号。+- **步骤**:+ 1. 在「设置 → 模型」中为每个提供商的一个模型勾选 **Fast 模式**;确认 Chat Completions 提供商上该勾选框不可用。+ 2. 在允许的 Codex 模型上新建任务,输入 `/fast`,发送一条提示。+ 3. 再次发送 `/fast`,然后再发送一条提示。+ 4. 把会话切换到未允许的模型,发送 `/fast`。+ 5. 在 Fast 开启时 fork 会话;重启应用后重新打开两个会话。+- **预期**:第 1 步只在 binding 上保存 `fastModeAllowed`。第 2 步模型芯片显示 Fast 标识,请求体带有+ `service_tier: "priority"`;Responses API key 模型改为提示按 token 计费的价格。第 3 步清除标识和该字段。+ 第 4 步给出模型设置提示并拒绝,不保存任何状态。第 5 步 fork 和重启后开关保持开启。子代理和压缩请求+ 从不携带该字段。远程会话拒绝 `/fast`。+- **关联规格**:`03-runtime/11-provider-model-system.md`、`03-runtime/04-data-storage.md`(v25)、- `04-ux/04-builtin-commands.md`、ADR 0332、issue #1657。++ `04-ux/04-builtin-commands.md`、ADR 0334、issue #1657。+- **状态**:自动化覆盖见英文版。完整的设置 → `/fast` → 捕获请求路径为手动验证场景。diff --cc packages/agent-runtime/src/fast-mode.tsindex 4b45d5812,000000000..28ace6890mode 100644,000000..100644--- a/packages/agent-runtime/src/fast-mode.ts+++ b/packages/agent-runtime/src/fast-mode.ts@@@ -1,17 -1,0 +1,17 @@@+/**- * OpenAI Fast mode (ADR 0332). The launcher has already combined the session++ * OpenAI Fast mode (ADR 0334). The launcher has already combined the session+ * `/fast` switch with the model binding's opt-in; pi-ai's Responses adapters+ * send `serviceTier` as `service_tier` and price the tier the response reports.+ */++import type { SimpleStreamOptions } from "@earendil-works/pi-ai";+import { FAST_MODE_SERVICE_TIER, fastModeSupportedOn } from "@pi-desktop/shared";++/** Ask for the priority tier on a wire that carries it; other wires keep their options. */+export function withFastModeOptions(+ options: SimpleStreamOptions,+ api: string,+ fastMode: boolean,+): SimpleStreamOptions {+ return fastMode && fastModeSupportedOn(api) ? { ...options, serviceTier: FAST_MODE_SERVICE_TIER } : options;+}diff --cc packages/agent-runtime/src/runtime.tsindex cc40c6c27,7249de152..0fd2ccabd--- a/packages/agent-runtime/src/runtime.ts+++ b/packages/agent-runtime/src/runtime.ts@@@ -979,11 -978,6 +979,11 @@@ export type AgentRuntimeOptions =thinkingLevel: SessionThinkingLevel;/** Persisted opt-in for retrying transient provider failures until success. */infiniteProviderRetry?: boolean;+ /**+ * Fast mode for main turns, already resolved by the launcher from the- * session `/fast` switch and the model binding's opt-in (ADR 0332).++ * session `/fast` switch and the model binding's opt-in (ADR 0334).+ */+ fastMode?: boolean;/** TypeSafe Jev credential, resolved by Electron main only when enabled. */jevApiKey?: string;systemPrompt?: string;diff --cc packages/agent-runtime/src/sidecar.tsindex 9ed694ee0,1fdcd50f2..98e0441b5--- a/packages/agent-runtime/src/sidecar.ts+++ b/packages/agent-runtime/src/sidecar.ts@@@ -106,8 -111,6 +111,8 @@@ type RuntimeParams =turnId?: string;thinkingLevel?: SessionThinkingLevel;infiniteProviderRetry?: boolean;- /** Session `/fast` switch AND the model's opt-in, resolved by main (ADR 0332). */++ /** Session `/fast` switch AND the model's opt-in, resolved by main (ADR 0334). */+ fastMode?: boolean;/** Opt-in TypeSafe classifier credential resolved by Electron main. */jevApiKey?: string;provider: RuntimeProviderConfig;diff --cc packages/shared/src/fast-mode.tsindex d6d4078ac,000000000..a31940397mode 100644,000000..100644--- a/packages/shared/src/fast-mode.ts+++ b/packages/shared/src/fast-mode.ts@@@ -1,26 -1,0 +1,26 @@@+/**- * OpenAI Fast mode (ADR 0332): the Responses body field++ * OpenAI Fast mode (ADR 0334): the Responses body field+ * `service_tier: "priority"`. A request asks for it only when the model+ * binding's `fastModeAllowed` and the session `/fast` switch are both on.+ */+export const FAST_MODE_SERVICE_TIER = "priority";++/** `subscription` spends ChatGPT plan limits; `usage` is billed per token. */+export type FastModeBilling = "subscription" | "usage";++/** Stored apiStyle and resolved wire spellings of the wires that carry the tier. */+const FAST_MODE_BILLING: Record<string, FastModeBilling> = {+ openai_codex_responses: "subscription",+ "openai-codex-responses": "subscription",+ responses: "usage",+ "openai-responses": "usage",+};++/** How the tier is paid for on this apiStyle or wire, or undefined when it cannot carry it. */+export function fastModeBillingOn(api: string | undefined | null): FastModeBilling | undefined {+ return FAST_MODE_BILLING[(api ?? "").trim().toLowerCase()];+}++export function fastModeSupportedOn(api: string | undefined | null): boolean {+ return fastModeBillingOn(api) !== undefined;+}diff --cc packages/shared/src/types/models.tsindex 856c94cc8,47d436f6b..edd3a98f3--- a/packages/shared/src/types/models.ts+++ b/packages/shared/src/types/models.ts@@@ -254,12 -254,6 +254,12 @@@ export type ModelBinding =* knowledge of the endpoint is the only source.*/nativeWebSearch?: boolean;+ /**+ * Opt-in that lets the session `/fast` switch ask OpenAI for the priority- * service tier on this model (ADR 0332). Absent/false keeps the default++ * service tier on this model (ADR 0334). Absent/false keeps the default+ * tier; only Responses wires carry it (`fastModeSupportedOn`).+ */+ fastModeAllowed?: boolean;};export const MODEL_MODALITIES = ["text", "image", "audio", "video", "pdf"] as const;diff --cc packages/shared/src/types/sessions.tsindex 69ff8a78d,a76795597..83b139b57--- a/packages/shared/src/types/sessions.ts+++ b/packages/shared/src/types/sessions.ts@@@ -57,12 -57,6 +57,12 @@@ export type SessionSummary =thinkingLevel: SessionThinkingLevel;/** Per-session permission mode; `inherit` follows the global default (D115). */permissionMode: PermissionMode;+ /**- * Session `/fast` switch (ADR 0332). Requests use the priority tier only++ * Session `/fast` switch (ADR 0334). Requests use the priority tier only+ * when the selected model also allows it. Older hosts and remote sessions+ * omit it, meaning off.+ */+ fastMode?: boolean;/** Effective capability for this session's exact provider/model pair. */supportsReasoning?: boolean;/** Effective image-input capability for this session's exact model. */diff --cc patches/@[email protected]index caeea4f84,1e34fd3db..d1f6b484f--- a/patches/@[email protected]+++ b/patches/@[email protected]@@@ -745,7 -753,7 +753,7 @@@ index 2ab985c7d..c48a104d7 10064const samplingParams = resolveSamplingParams(model, reasoningEffort ?? "off", options?.samplingParams);if (samplingParams) {diff --git a/dist/api/simple-options.js b/dist/api/simple-options.js- index 4e36f35..fd9225e 100644-index 4e36f350e..c817c2e4a 100644++index 4e36f350e..fd9225e5e 100644--- a/dist/api/simple-options.js+++ b/dist/api/simple-options.js@@ -5,7 +5,7 @@ const MIN_MAX_TOKENS = 1;@@@ -757,16 -765,8 +765,16 @@@return Math.min(maxTokens, Math.max(MIN_MAX_TOKENS, available));}export function resolveSamplingParams(model, thinkingLevel, requestParams) {+@@ -30,6 +30,7 @@ export function buildBaseOptions(model, context, options, apiKey) {+ sessionId: options?.sessionId,+ headers: options?.headers,+ onPayload: options?.onPayload,++ serviceTier: options?.serviceTier,+ onResponse: options?.onResponse,+ onProviderStreamEvent: options?.onProviderStreamEvent,+ timeoutMs: options?.timeoutMs,diff --git a/dist/auth/oauth/anthropic.js b/dist/auth/oauth/anthropic.js- index 0823512..713d38a 100644+ index 0823512eb..713d38af6 100644--- a/dist/auth/oauth/anthropic.js+++ b/dist/auth/oauth/anthropic.js@@ -4,6 +4,7 @@@@@ -955,21 -981,12 +989,21 @@@ index 1443bb592..5fc062577 10064-{"openai-completions":{"chat:deepseek-flash":{"id":"deepseek-flash","name":"DeepSeek V4.1 Flash","api":"openai-completions","baseUrl":"https://api.deepseek.com","provider":"deepseek","reasoning":true,"thinkingLevelMap":{"minimal":null,"low":"low","medium":null,"high":"high","max":"max"},"input":["text","image"],"cost":{"input":0.3,"output":1.2,"cacheRead":0.006,"cacheWrite":0},"contextWindow":1000000,"maxTokens":384000,"compat":{"supportsStore":false,"supportsDeveloperRole":false,"maxTokensField":"max_tokens","requiresReasoningContentOnAssistantMessages":true,"thinkingFormat":"deepseek","supportsStrictMode":true},"inputLimits":{"images":{"resize":{"maxWidth":2000,"maxHeight":2000,"maxBytes":4718592,"jpegQuality":80}}},"type":"chat"},"chat:deepseek-v4-pro":{"id":"deepseek-v4-pro","name":"DeepSeek V4 Pro","api":"openai-completions","baseUrl":"https://api.deepseek.com","provider":"deepseek","reasoning":true,"input":["text"],"cost":{"input":1.32,"output":3.96,"cacheRead":0.044,"cacheWrite":0},"contextWindow":1000000,"maxTokens":384000,"compat":{"supportsStore":false,"supportsDeveloperRole":false,"maxTokensField":"max_tokens","requiresReasoningContentOnAssistantMessages":true,"thinkingFormat":"deepseek","supportsStrictMode":true,"supportsMidConvoSystemMessages":true},"thinkingLevelMap":{"minimal":null,"low":null,"medium":null,"high":"high","max":"max"},"type":"chat"}}}+{"openai-completions":{"chat:deepseek-flash":{"id":"deepseek-flash","name":"DeepSeek V4.1 Flash","api":"openai-completions","baseUrl":"https://api.deepseek.com","provider":"deepseek","reasoning":true,"thinkingLevelMap":{"minimal":null,"low":"low","medium":null,"high":"high","max":"max"},"input":["text","image"],"cost":{"input":0.3,"output":1.2,"cacheRead":0.006,"cacheWrite":0},"contextWindow":1000000,"maxTokens":384000,"compat":{"supportsStore":false,"supportsDeveloperRole":false,"maxTokensField":"max_tokens","requiresReasoningContentOnAssistantMessages":true,"thinkingFormat":"deepseek","supportsStrictMode":true,"supportsMidConvoSystemMessages":true},"inputLimits":{"images":{"resize":{"maxWidth":2000,"maxHeight":2000,"maxBytes":4718592,"jpegQuality":80}}},"type":"chat"},"chat:deepseek-v4-pro":{"id":"deepseek-v4-pro","name":"DeepSeek V4 Pro","api":"openai-completions","baseUrl":"https://api.deepseek.com","provider":"deepseek","reasoning":true,"input":["text"],"cost":{"input":1.32,"output":3.96,"cacheRead":0.044,"cacheWrite":0},"contextWindow":1000000,"maxTokens":384000,"compat":{"supportsStore":false,"supportsDeveloperRole":false,"maxTokensField":"max_tokens","requiresReasoningContentOnAssistantMessages":true,"thinkingFormat":"deepseek","supportsStrictMode":true,"supportsMidConvoSystemMessages":true},"thinkingLevelMap":{"minimal":null,"low":null,"medium":null,"high":"high","max":"max"},"type":"chat"}}}diff --git a/dist/types.d.ts b/dist/types.d.ts- index b01603b..432fbf7 100644-index 022faa196..efed3b8b0 100644++index 022faa196..6295215ae 100644--- a/dist/types.d.ts+++ b/dist/types.d.ts- @@ -251,6 +251,8 @@ export interface SimpleStreamOptions extends StreamOptions {-@@ -276,6 +276,30 @@ export interface ToolCall {++@@ -234,6 +234,8 @@ export interface SimpleStreamOptions extends StreamOptions {+ };+ /** Custom token budgets for thinking levels (token-based providers only) */+ thinkingBudgets?: ThinkingBudgets;++ /** OpenAI Responses service tier; adapters without the field ignore it. */++ serviceTier?: "auto" | "default" | "flex" | "scale" | "priority";+ }+ export type StreamFunction<TApi extends Api = Api, TOptions extends StreamOptions = StreamOptions> = (model: Model<TApi>, context: TranscriptContext, options?: TOptions) => AssistantMessageEventStream;+ export type ImagesFunction<TOptions extends ImagesOptions = ImagesOptions> = (model: ImageModel<ImageApi>, context: ImagesContext, options?: TOptions) => Promise<AssistantImages>;- @@ -288,6 +290,30 @@ export interface ToolCall {- /** OpenAI Responses namespace for calls to dynamically loaded or namespaced tools. */- namespace?: string;++@@ -276,6 +278,30 @@ export interface ToolCall {+ */+ argumentsError?: string;}+export interface HostedSearchCitation {+ url: string;@@@ -998,7 -1015,7 +1032,7 @@@export interface Usage {input: number;output: number;- @@ -373,7 +399,7 @@ export interface UserMessage {-@@ -361,7 +385,7 @@ export interface UserMessage {++@@ -361,7 +387,7 @@ export interface UserMessage {}export interface AssistantMessage {role: "assistant";@@@ -1007,7 -1024,7 +1041,7 @@@api: Api;provider: ProviderId;model: string;- @@ -388,6 +414,8 @@ export interface AssistantMessage {-@@ -376,6 +400,8 @@ export interface AssistantMessage {++@@ -376,6 +402,8 @@ export interface AssistantMessage {stopReason: StopReason;deferred?: DeferredHandle;errorMessage?: string;@@@ -1016,7 -1033,7 +1050,7 @@@rawStopReason?: string;/*** Provider indication of whether the model explicitly ended its turn.- @@ -623,6 +651,10 @@ export type AssistantMessageEvent = {-@@ -611,6 +637,10 @@ export type AssistantMessageEvent = {++@@ -611,6 +639,10 @@ export type AssistantMessageEvent = {contentIndex: number;toolCall: ToolCall;partial: AssistantMessage;@@@ -1027,20 -1044,7 +1061,7 @@@} | {type: "done";reason: Extract<StopReason, "stop" | "length" | "toolUse" | "deferred">;- @@ -657,6 +689,12 @@ export interface OpenAICompletionsCompat {- requiresThinkingAsText?: boolean;- /** Whether all replayed assistant messages must include an empty reasoning_content field when reasoning is enabled. Default: auto-detected from URL. */- requiresReasoningContentOnAssistantMessages?: boolean;- + /**- + * Whether a replayed assistant message that carries no reasoning must send a documented- + * non-empty placeholder instead of an empty string. Some relays reject the empty echo.- + * Default: false; only an explicit model.compat opt-in enables it.- + */- + requiresNonEmptyReasoningReplay?: boolean;- /** Format for reasoning/thinking parameter. "openai" uses reasoning_effort, "openrouter" uses reasoning: { effort }, "deepseek" uses thinking: { type } plus reasoning_effort when supported, "together" uses reasoning: { enabled } plus reasoning_effort when supported, "baseten" uses configurable chat_template_args plus reasoning_effort when supported, "zai" uses thinking: { type }, "qwen" uses top-level enable_thinking: boolean, "qwen-chat-template" uses chat_template_kwargs.enable_thinking and preserve_thinking, "chat-template" uses configurable chat_template_kwargs, "string-thinking" uses top-level thinking: string, and "ant-ling" uses reasoning: { effort } only when the mapped effort is non-null. Default: "openai". */- thinkingFormat?: "openai" | "openrouter" | "deepseek" | "together" | "baseten" | "zai" | "qwen" | "chat-template" | "qwen-chat-template" | "string-thinking" | "ant-ling";- /** Kwargs to send as `chat_template_kwargs` when `thinkingFormat` is `chat-template`. Use `{ "$var": "thinking.enabled" }`, `{ "$var": "thinking.effort" }`, or `{ "$var": "thinking.budget" }` for pi-controlled thinking values. */- @@ -935,6 +973,8 @@ export interface Model<TApi extends Api> extends BaseModel<TApi> {-@@ -642,6 +672,8 @@ export interface Model<TApi extends Api> extends BaseModel<TApi> {++@@ -642,6 +674,8 @@ export interface Model<TApi extends Api> extends BaseModel<TApi> {*/type?: "chat";reasoning: boolean;diff --cc pnpm-lock.yamlindex 43bcc8d0e,d777c5d91..7acea6996--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@@ -205,9 -205,9 +205,9 @@@ overridesvite@5: '>=6.4.3 <7'patchedDependencies:- '@earendil-works/[email protected]': a2c96619d0f9a1d643a6c6a555ba6a7fb533147336c181f7d3b7f847be33a6eb- '@earendil-works/[email protected]': f4ef44e75753e4d966c253f28d09a55924c26bb8a79bde1628ee66b2d8039b0b- '@earendil-works/[email protected]': 73b8776451352deeaa307306b1aaa3a22e2c2cfd6e06c802fcd390409912f60a+ '@earendil-works/[email protected]': afe17754a8c323f4010e051c96a66314ce96c1745a235c3efb5970cfea91a9b0- '@earendil-works/[email protected]': 14ebd53075a2fbd0e5f101c88253e555d9e79a21c1e399f7c0e7b652c498dd12++ '@earendil-works/[email protected]': 001c2e942031c87b1f04d433679d07acacc8aa901b5c16fff73937ae8037e1de+ '@earendil-works/[email protected]': 5cb7070ec8e1695932e9968afa6828b36beb1face77418739d5cd01b2a07c371importers:@@@ -233,11 -233,11 +233,11 @@@version: 0.2.2devDependencies:'@earendil-works/pi-ai':- specifier: 1.1.0- version: 1.1.0(patch_hash=f4ef44e75753e4d966c253f28d09a55924c26bb8a79bde1628ee66b2d8039b0b)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])+ specifier: 1.3.0- version: 1.3.0(patch_hash=14ebd53075a2fbd0e5f101c88253e555d9e79a21c1e399f7c0e7b652c498dd12)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])++ version: 1.3.0(patch_hash=001c2e942031c87b1f04d433679d07acacc8aa901b5c16fff73937ae8037e1de)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])'@earendil-works/pi-mcp':- specifier: 1.1.0- version: 1.1.0+ specifier: 1.3.0+ version: 1.3.0'@pi-desktop/agent-host':specifier: workspace:*version: link:../../packages/agent-host@@@ -425,14 -425,14 +425,14 @@@packages/agent-runtime:dependencies:'@earendil-works/pi-agent-core':- specifier: 1.1.0- version: 1.1.0(patch_hash=a2c96619d0f9a1d643a6c6a555ba6a7fb533147336c181f7d3b7f847be33a6eb)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])+ specifier: 1.3.0+ version: 1.3.0(patch_hash=afe17754a8c323f4010e051c96a66314ce96c1745a235c3efb5970cfea91a9b0)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])'@earendil-works/pi-ai':- specifier: 1.1.0- version: 1.1.0(patch_hash=f4ef44e75753e4d966c253f28d09a55924c26bb8a79bde1628ee66b2d8039b0b)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])+ specifier: 1.3.0- version: 1.3.0(patch_hash=14ebd53075a2fbd0e5f101c88253e555d9e79a21c1e399f7c0e7b652c498dd12)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])++ version: 1.3.0(patch_hash=001c2e942031c87b1f04d433679d07acacc8aa901b5c16fff73937ae8037e1de)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])'@earendil-works/pi-coding-agent':- specifier: 1.1.0- version: 1.1.0(patch_hash=73b8776451352deeaa307306b1aaa3a22e2c2cfd6e06c802fcd390409912f60a)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])+ specifier: 1.3.0+ version: 1.3.0(patch_hash=5cb7070ec8e1695932e9968afa6828b36beb1face77418739d5cd01b2a07c371)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])'@pi-desktop/shared':specifier: workspace:*version: link:../shared@@@ -5229,13 -5064,9 +5064,9 @@@ snapshotstransitivePeerDependencies:- '@algolia/client-search'- '@earendil-works/[email protected]':- dependencies:- esbuild: 0.28.2-- '@earendil-works/[email protected](patch_hash=a2c96619d0f9a1d643a6c6a555ba6a7fb533147336c181f7d3b7f847be33a6eb)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])':+ '@earendil-works/[email protected](patch_hash=afe17754a8c323f4010e051c96a66314ce96c1745a235c3efb5970cfea91a9b0)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])':dependencies:- '@earendil-works/pi-ai': 1.1.0(patch_hash=f4ef44e75753e4d966c253f28d09a55924c26bb8a79bde1628ee66b2d8039b0b)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])- '@earendil-works/pi-ai': 1.3.0(patch_hash=14ebd53075a2fbd0e5f101c88253e555d9e79a21c1e399f7c0e7b652c498dd12)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])++ '@earendil-works/pi-ai': 1.3.0(patch_hash=001c2e942031c87b1f04d433679d07acacc8aa901b5c16fff73937ae8037e1de)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])typebox: 1.3.27transitivePeerDependencies:- '@aws-sdk/credential-provider-node'@@@ -5250,7 -5081,7 +5081,7 @@@- ws- zod- '@earendil-works/[email protected](patch_hash=f4ef44e75753e4d966c253f28d09a55924c26bb8a79bde1628ee66b2d8039b0b)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])':- '@earendil-works/[email protected](patch_hash=14ebd53075a2fbd0e5f101c88253e555d9e79a21c1e399f7c0e7b652c498dd12)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])':++ '@earendil-works/[email protected](patch_hash=001c2e942031c87b1f04d433679d07acacc8aa901b5c16fff73937ae8037e1de)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])':dependencies:'@anthropic-ai/sdk': 0.129.0([email protected])'@aws-sdk/client-bedrock-runtime': 3.1127.0@@@ -5275,7 -5106,7 +5106,7 @@@- ws- zod- '@earendil-works/[email protected](patch_hash=f4ef44e75753e4d966c253f28d09a55924c26bb8a79bde1628ee66b2d8039b0b)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])':- '@earendil-works/[email protected](patch_hash=14ebd53075a2fbd0e5f101c88253e555d9e79a21c1e399f7c0e7b652c498dd12)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])':++ '@earendil-works/[email protected](patch_hash=001c2e942031c87b1f04d433679d07acacc8aa901b5c16fff73937ae8037e1de)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])':dependencies:'@anthropic-ai/sdk': 0.129.0([email protected])'@aws-sdk/client-bedrock-runtime': 3.1127.0@@@ -5304,14 -5135,13 +5135,13 @@@dependencies:quickjs-wasi: 3.6.2- '@earendil-works/[email protected](patch_hash=73b8776451352deeaa307306b1aaa3a22e2c2cfd6e06c802fcd390409912f60a)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])':+ '@earendil-works/[email protected](patch_hash=5cb7070ec8e1695932e9968afa6828b36beb1face77418739d5cd01b2a07c371)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])':dependencies:- '@earendil-works/chord': 1.1.0- '@earendil-works/pi-agent-core': 1.1.0(patch_hash=a2c96619d0f9a1d643a6c6a555ba6a7fb533147336c181f7d3b7f847be33a6eb)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])- '@earendil-works/pi-ai': 1.1.0(patch_hash=f4ef44e75753e4d966c253f28d09a55924c26bb8a79bde1628ee66b2d8039b0b)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])- '@earendil-works/pi-codemode': 1.1.0- '@earendil-works/pi-mcp': 1.1.0- '@earendil-works/pi-tui': 1.1.0+ '@earendil-works/pi-agent-core': 1.3.0(patch_hash=afe17754a8c323f4010e051c96a66314ce96c1745a235c3efb5970cfea91a9b0)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])- '@earendil-works/pi-ai': 1.3.0(patch_hash=14ebd53075a2fbd0e5f101c88253e555d9e79a21c1e399f7c0e7b652c498dd12)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])++ '@earendil-works/pi-ai': 1.3.0(patch_hash=001c2e942031c87b1f04d433679d07acacc8aa901b5c16fff73937ae8037e1de)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])+ '@earendil-works/pi-codemode': 1.3.0+ '@earendil-works/pi-mcp': 1.3.0+ '@earendil-works/pi-tui': 1.3.0'@silvia-odwyer/photon-node': 0.3.4brace-expansion: 5.0.12chalk: 6.0.0