Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
feat(plugins): add OAuth provider callbacks
vastsa7934897bf0f0
diff --git a/apps/desktop/electron/main/index.ts b/apps/desktop/electron/main/index.tsindex 92591a840..c66cdec99 100644--- a/apps/desktop/electron/main/index.ts+++ b/apps/desktop/electron/main/index.ts@@ -284,6 +284,7 @@ const vendorOAuth = new VendorOAuth({openExternal: async (url) => {await safeOpenExternal(url);},+ getPluginOAuthBridge: () => pluginServices.plugins,log: (level, message, data) => logger.app("provider", level, message, { data }),onAccountModels: (id, models) => modelsDevCatalog.setAccountModels(id, models),onAccountRemoved: (id) => modelsDevCatalog.deleteAccount(id),diff --git a/apps/desktop/electron/main/oauth.ts b/apps/desktop/electron/main/oauth.tsindex bd8c38968..02bdf3110 100644--- a/apps/desktop/electron/main/oauth.ts+++ b/apps/desktop/electron/main/oauth.ts@@ -32,12 +32,19 @@ import type {MutableModels,Provider,} from "@earendil-works/pi-ai";+import type {+ PluginProviderOAuthCredential,+ PluginProviderOAuthEvent,+ PluginProviderOAuthPrompt,+ PluginProviderOAuthRequest,+} from "@pi-desktop/plugin-sdk";import { registerBunOAuthFlows } from "@earendil-works/pi-ai/bun-oauth";import { builtinModels } from "@earendil-works/pi-ai/providers/all";import {capabilitiesFromModelConfig,genericModelConfig,installProviderHeadersFetch,+ modelConfigWithBinding,runWithProviderHeaders,type ModelConfig,type VendorModelBinding,@@ -132,15 +139,41 @@ export type HostCall = <T = unknown>(/** The slice of a provider row this module reads; the rest stays in index.ts. */export type OAuthProviderRow = {id: string;+ name?: string;vendorKey?: string;+ ownerPluginId?: string;authKind?: string;hasOauth?: boolean;oauthAccountLabel?: string;headers?: Record<string, string>;baseUrl?: string;+ apiStyle?: string;+ models?: ModelBinding[];+ enabled?: boolean;defaultModelId?: string;};+export type PluginOAuthProvider = {+ pluginId: string;+ runtimeId: string;+ contributionId: string;+ providerId: string;+ name: string;+ loginLabel?: string;+ isSubscription: boolean;+};++export type PluginOAuthBridge = {+ listOAuthProviders: () => PluginOAuthProvider[];+ invokeProviderOAuth: (+ pluginId: string,+ contributionId: string,+ request: PluginProviderOAuthRequest,+ signal?: AbortSignal,+ expectedRuntimeId?: string,+ ) => Promise<unknown>;+};+/** A model ID offered by a signed-in account and its required wire identity. */export type OAuthModelOption = {modelId: string;@@ -155,6 +188,8 @@ export type VendorOAuthDeps = {emit: (event: OAuthLoginEvent) => void;/** Open the vendor's consent page; rejects when no browser could be launched. */openExternal: (url: string) => Promise<void>;+ /** Loaded plugin OAuth providers and their isolated callback hooks. */+ getPluginOAuthBridge?: () => PluginOAuthBridge | undefined;log?: (level: "info" | "warn" | "error",message: string,@@ -215,6 +250,20 @@ type LoginSession = {finished?: Promise<void>;};+type PluginLoginSession = {+ loginId: string;+ vendorId: string;+ providerId: string;+ pluginId: string;+ contributionId: string;+ runtimeId: string;+ prompts: Map<string, PendingPrompt>;+ controller: AbortController;+ tail: Promise<void>;+ cancelled: boolean;+ finished?: Promise<void>;+};+function promptRequest(promptId: string,prompt: AuthPrompt,@@ -235,9 +284,100 @@ function promptRequest(};}+function clippedText(value: unknown, maxLength: number): string {+ return typeof value === "string" ? value.trim().slice(0, maxLength) : "";+}++function isHttpUrl(value: unknown): value is string {+ if (typeof value !== "string" || value.length > 4_096) return false;+ try {+ const url = new URL(value);+ return (url.protocol === "https:" || url.protocol === "http:") && !url.username && !url.password;+ } catch {+ return false;+ }+}++function normalizePluginCredential(raw: unknown): PluginProviderOAuthCredential {+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {+ throw new Error("plugin OAuth credential must be an object");+ }+ const value = raw as Record<string, unknown>;+ const accessToken = value.accessToken;+ if (+ typeof accessToken !== "string" ||+ !accessToken.trim() ||+ Buffer.byteLength(accessToken, "utf8") > 16 * 1024+ ) {+ throw new Error("plugin OAuth credential has an invalid accessToken");+ }+ const result: PluginProviderOAuthCredential = { accessToken };+ if (value.refreshToken !== undefined) {+ if (typeof value.refreshToken !== "string" || Buffer.byteLength(value.refreshToken, "utf8") > 16 * 1024) {+ throw new Error("plugin OAuth credential has an invalid refreshToken");+ }+ result.refreshToken = value.refreshToken;+ }+ if (value.expiresAt !== undefined) {+ if (+ typeof value.expiresAt !== "number" ||+ !Number.isSafeInteger(value.expiresAt) ||+ value.expiresAt <= 0+ ) {+ throw new Error("plugin OAuth credential has an invalid expiresAt");+ }+ result.expiresAt = value.expiresAt;+ }+ if (value.accountLabel !== undefined) {+ if (typeof value.accountLabel !== "string" || value.accountLabel.length > 256) {+ throw new Error("plugin OAuth credential has an invalid accountLabel");+ }+ result.accountLabel = value.accountLabel.trim();+ }+ if (value.headers !== undefined) {+ if (!value.headers || typeof value.headers !== "object" || Array.isArray(value.headers)) {+ throw new Error("plugin OAuth credential headers must be an object");+ }+ const entries = Object.entries(value.headers as Record<string, unknown>);+ if (entries.length > 32) throw new Error("plugin OAuth credential has too many headers");+ const headers: Record<string, string> = {};+ const seenHeaderNames = new Set<string>();+ const blocked = new Set([+ "authorization",+ "proxy-authorization",+ "host",+ "cookie",+ "set-cookie",+ "content-length",+ "transfer-encoding",+ "connection",+ "proxy-connection",+ ]);+ for (const [name, headerValue] of entries) {+ const normalizedName = name.toLowerCase();+ if (+ !/^[A-Za-z0-9-]{1,128}$/.test(name) ||+ blocked.has(normalizedName) ||+ seenHeaderNames.has(normalizedName) ||+ typeof headerValue !== "string" ||+ Buffer.byteLength(headerValue, "utf8") > 4_096 ||+ /[\r\n\0]/.test(headerValue)+ ) {+ throw new Error("plugin OAuth credential has an invalid header");+ }+ seenHeaderNames.add(normalizedName);+ headers[name] = headerValue;+ }+ result.headers = headers;+ }+ return result;+}+export class VendorOAuth {private readonly deps: VendorOAuthDeps;private readonly logins = new Map<string, LoginSession>();+ private readonly pluginLogins = new Map<string, PluginLoginSession>();+ private readonly pluginRefreshControllers = new Map<string, AbortController>();/** One pi-ai collection and credential store per local OAuth account row. */private readonly accountModels = new Map<string, AccountModels>();/** Successful and failed account model lists, so launch does not refetch per model. */@@ -259,7 +399,7 @@ export class VendorOAuth {async listVendors(): Promise<OAuthVendor[]> {const models = await this.ensureCatalogModels();const rows = await this.rows();- return models+ const vendors = models.getProviders().filter((provider) => provider.auth.oauth).map((provider) => {@@ -268,6 +408,7 @@ export class VendorOAuth {.filter((candidate) =>candidate.authKind === OAUTH_AUTH_KIND &&+ !candidate.ownerPluginId &&candidate.vendorKey === provider.id,).map((row) => ({@@ -283,6 +424,30 @@ export class VendorOAuth {accounts,};});+ const pluginBridge = this.deps.getPluginOAuthBridge?.();+ if (!pluginBridge) return vendors;+ for (const provider of pluginBridge.listOAuthProviders()) {+ const row = rows.find(+ (candidate) =>+ candidate.id === provider.providerId &&+ candidate.ownerPluginId === provider.pluginId &&+ candidate.authKind === OAUTH_AUTH_KIND,+ );+ if (!row) continue;+ const credential = row.hasOauth ? await this.readPluginCredential(row.id) : undefined;+ vendors.push({+ vendorId: row.id,+ name: provider.name,+ loginLabel: provider.loginLabel,+ isSubscription: provider.isSubscription,+ accounts: [{+ providerId: row.id,+ accountLabel: credential?.accountLabel || undefined,+ connected: row.hasOauth === true,+ }],+ });+ }+ return vendors;}/**@@ -291,6 +456,20 @@ export class VendorOAuth {* accounts instead of silently replacing the first one.*/async start(vendorId: string): Promise<OAuthStartResult> {+ const pluginProvider = this.deps+ .getPluginOAuthBridge?.()+ ?.listOAuthProviders()+ .find((provider) => provider.providerId === vendorId);+ if (pluginProvider) {+ const row = (await this.rows()).find(+ (candidate) =>+ candidate.id === vendorId &&+ candidate.ownerPluginId === pluginProvider.pluginId &&+ candidate.authKind === OAUTH_AUTH_KIND,+ );+ if (!row) throw new Error(`unknown plugin OAuth provider: ${vendorId}`);+ return this.startPluginLogin(pluginProvider);+ }const models = await this.ensureCatalogModels();const provider = models.getProvider(vendorId);if (!provider?.auth.oauth) {@@ -332,14 +511,38 @@ export class VendorOAuth {return { loginId: session.loginId };}+ private startPluginLogin(provider: PluginOAuthProvider): OAuthStartResult {+ const superseded = [...this.pluginLogins.values()].filter(+ (running) => running.providerId === provider.providerId,+ );+ for (const running of superseded) this.cancelPluginLogin(running);+ const session: PluginLoginSession = {+ loginId: this.nextId(),+ vendorId: provider.providerId,+ providerId: provider.providerId,+ pluginId: provider.pluginId,+ contributionId: provider.contributionId,+ runtimeId: provider.runtimeId,+ prompts: new Map(),+ controller: new AbortController(),+ tail: Promise.resolve(),+ cancelled: false,+ };+ this.pluginLogins.set(session.loginId, session);+ session.finished = this.runPluginLogin(session);+ return { loginId: session.loginId };+ }+/** Answer a prompt. An absent value cancels the prompt and the login. */respond(input: OAuthRespondInput): boolean {const session = this.logins.get(input.loginId);- const pending = session?.prompts.get(input.promptId);- if (!session || !pending) return false;+ const pluginSession = this.pluginLogins.get(input.loginId);+ const pending = session?.prompts.get(input.promptId) ?? pluginSession?.prompts.get(input.promptId);+ if ((!session && !pluginSession) || !pending) return false;if (input.value === undefined) {pending.reject(new Error("login cancelled"));- session.controller.abort();+ if (session) session.controller.abort();+ if (pluginSession) this.cancelPluginLogin(pluginSession);} else {pending.resolve(input.value);}@@ -349,11 +552,135 @@ export class VendorOAuth {/** Abort a login: stops the local callback server or device-code polling. */cancel(loginId: string): boolean {const session = this.logins.get(loginId);- if (!session) return false;- session.controller.abort();+ if (session) {+ session.controller.abort();+ return true;+ }+ const pluginSession = this.pluginLogins.get(loginId);+ if (!pluginSession) return false;+ this.cancelPluginLogin(pluginSession);return true;}+ /** Plugin callbacks can ask the same Host-rendered question as native OAuth flows. */+ promptPluginOAuth(+ pluginId: string,+ loginId: string,+ input: PluginProviderOAuthPrompt,+ ): Promise<string> {+ const session = this.pluginLogins.get(loginId);+ if (!session || session.pluginId !== pluginId || session.cancelled) {+ return Promise.reject(new Error("provider OAuth login is no longer active"));+ }+ if (+ !input ||+ typeof input !== "object" ||+ !["text", "secret", "select", "manual_code"].includes(input.type) ||+ typeof input.message !== "string" ||+ !input.message.trim() ||+ input.message.length > 2_000+ ) {+ return Promise.reject(new Error("provider OAuth prompt is invalid"));+ }+ if (input.type === "select" && (!Array.isArray(input.options) || input.options.length === 0 || input.options.length > 32)) {+ return Promise.reject(new Error("provider OAuth select prompt requires 1 to 32 options"));+ }+ const options = input.type === "select"+ ? (input.options ?? []).flatMap((option) =>+ option && typeof option.id === "string" && typeof option.label === "string"+ ? [{+ id: option.id.slice(0, 128),+ label: option.label.slice(0, 256),+ ...(typeof option.description === "string"+ ? { description: option.description.slice(0, 512) }+ : {}),+ }]+ : [],+ )+ : undefined;+ if (input.type === "select" && options?.length === 0) {+ return Promise.reject(new Error("provider OAuth select prompt options are invalid"));+ }+ const promptId = this.nextId();+ return new Promise((resolve, reject) => {+ const settle = () => session.prompts.delete(promptId);+ session.prompts.set(promptId, {+ resolve: (value) => { settle(); resolve(value); },+ reject: (error) => { settle(); reject(error); },+ });+ const request: OAuthPromptRequest = {+ promptId,+ type: input.type,+ message: input.message.trim(),+ ...(typeof input.placeholder === "string" && input.placeholder.length <= 512+ ? { placeholder: input.placeholder }+ : {}),+ ...(options ? { options } : {}),+ };+ this.pushPluginEvent(session, { kind: "prompt", request });+ });+ }++ /** Relay only bounded, non-secret progress to the renderer. */+ async notifyPluginOAuth(+ pluginId: string,+ loginId: string,+ event: PluginProviderOAuthEvent,+ ): Promise<void> {+ const session = this.pluginLogins.get(loginId);+ if (!session || session.pluginId !== pluginId || session.cancelled) {+ throw new Error("provider OAuth login is no longer active");+ }+ if (event.kind === "authUrl") {+ if (!isHttpUrl(event.url)) throw new Error("provider OAuth URL must use HTTP or HTTPS");+ const url = event.url.slice(0, 4_096);+ session.tail = session.tail.then(async () => {+ const opened = await this.deps.openExternal(url).then(() => true, () => false);+ this.deps.emit({+ loginId,+ vendorId: session.vendorId,+ kind: "authUrl",+ url,+ instructions: clippedText(event.instructions, 2_000),+ opened,+ });+ });+ await session.tail;+ return;+ }+ if (event.kind === "deviceCode") {+ if (!isHttpUrl(event.verificationUri)) throw new Error("verificationUri must use HTTP or HTTPS");+ this.pushPluginEvent(session, {+ kind: "deviceCode",+ userCode: clippedText(event.userCode, 256),+ verificationUri: event.verificationUri.slice(0, 4_096),+ ...(Number.isFinite(event.intervalSeconds) ? { intervalSeconds: event.intervalSeconds } : {}),+ ...(Number.isFinite(event.expiresInSeconds) ? { expiresInSeconds: event.expiresInSeconds } : {}),+ });+ await session.tail;+ return;+ }+ if (event.kind === "info") {+ this.pushPluginEvent(session, {+ kind: "info",+ message: clippedText(event.message, 2_000),+ ...(Array.isArray(event.links)+ ? {+ links: event.links.slice(0, 4).flatMap((link) =>+ isHttpUrl(link?.url)+ ? [{ url: link.url.slice(0, 4_096), ...(typeof link.label === "string" ? { label: link.label.slice(0, 128) } : {}) }]+ : [],+ ),+ }+ : {}),+ });+ await session.tail;+ return;+ }+ this.pushPluginEvent(session, { kind: "progress", message: clippedText(event.message, 2_000) });+ await session.tail;+ }+/*** Delete one account's provider row and its provider-scoped OAuth secret.* Host-core owns the atomic cleanup of the row and both secret references.@@ -363,6 +690,20 @@ export class VendorOAuth {if (!row || row.authKind !== OAUTH_AUTH_KIND) {throw new Error(`unknown vendor account provider: ${providerId}`);}+ if (row.ownerPluginId) {+ this.pluginRefreshControllers.get(providerId)?.abort(new Error("provider sign-out requested"));+ const running = [...this.pluginLogins.values()].find(+ (session) => session.providerId === providerId,+ );+ if (running) this.cancelPluginLogin(running);+ await this.serialize(providerId, () =>+ this.deps.call("secrets.delete", {+ secretRef: secretRefForProviderOauth(providerId),+ }),+ );+ this.clearAccountModels(providerId);+ return;+ }const running = [...this.logins.values()].find((session) => session.providerId === providerId,);@@ -383,6 +724,10 @@ export class VendorOAuth {* short-lived access token, headers and per-credential baseUrl.*/async resolveAuth(providerId: string): Promise<ModelAuth> {+ const row = (await this.rows()).find((candidate) => candidate.id === providerId);+ if (row?.ownerPluginId && row.authKind === OAUTH_AUTH_KIND) {+ return this.resolvePluginAuth(row);+ }return this.withRowHeaders(providerId, async () => {const account = await this.accountForProvider(providerId);if (!account) throw new Error(`vendor account not signed in: ${providerId}`);@@ -400,6 +745,16 @@ export class VendorOAuth {* be read. Radius keeps its gateway refresh and does not get a second probe.*/async listModels(providerId: string): Promise<OAuthModelOption[]> {+ const row = (await this.rows()).find((candidate) => candidate.id === providerId);+ if (row?.ownerPluginId && row.authKind === OAUTH_AUTH_KIND) {+ if (!row.baseUrl) return [];+ const baseUrl = row.baseUrl;+ return (row.models ?? []).map((model) => ({+ modelId: model.id,+ apiStyle: row.apiStyle ?? "chat_completions",+ baseUrl,+ }));+ }return this.withRowHeaders(providerId, async () => {const account = await this.accountForProvider(providerId);if (!account) throw new Error(`unknown vendor account provider: ${providerId}`);@@ -431,6 +786,38 @@ export class VendorOAuth {providerId: string,modelId: string,): Promise<VendorModelBinding | undefined> {+ const row = (await this.rows()).find((candidate) => candidate.id === providerId);+ if (row?.ownerPluginId && row.authKind === OAUTH_AUTH_KIND) {+ const declared = row.models?.find((model) => model.id === modelId);+ if (!declared || !row.baseUrl) return undefined;+ const option: OAuthModelOption = {+ modelId: declared.id,+ apiStyle: row.apiStyle ?? "chat_completions",+ baseUrl: row.baseUrl,+ };+ const published = await this.deps.modelConfigFor?.({+ providerId: row.id,+ vendorKey: row.vendorKey ?? "custom",+ option,+ }).catch(() => undefined);+ const baseline = withMappedThinkingLevels(+ published ?? genericModelConfig(option.modelId, option.baseUrl),+ );+ const model = modelConfigWithBinding(baseline, {+ ...declared,+ contextWindow: declared.contextWindow > 0 ? declared.contextWindow : baseline.contextWindow,+ maxTokens: declared.maxTokens > 0 ? declared.maxTokens : baseline.maxTokens,+ });+ const modelConfig = declared.thinkingLevels.length > 0+ ? withMappedThinkingLevels(model)+ : { ...model, reasoning: false, supportedThinkingLevels: [] };+ return {+ apiStyle: option.apiStyle,+ baseUrl: option.baseUrl,+ modelConfig,+ ...capabilitiesFromModelConfig(modelConfig),+ };+ }return this.withRowHeaders(providerId, () =>this.bindingForUnscoped(providerId, modelId),);@@ -600,6 +987,221 @@ export class VendorOAuth {}}+ private async runPluginLogin(session: PluginLoginSession): Promise<void> {+ try {+ const bridge = this.deps.getPluginOAuthBridge?.();+ if (!bridge) throw new Error("provider OAuth is unavailable");+ const raw = await bridge.invokeProviderOAuth(+ session.pluginId,+ session.contributionId,+ {+ operation: "login",+ providerId: session.contributionId,+ loginId: session.loginId,+ },+ session.controller.signal,+ session.runtimeId,+ );+ if (session.cancelled) throw new Error("login cancelled");+ const credential = normalizePluginCredential(raw);+ await this.serialize(session.providerId, async () => {+ const row = (await this.rows()).find((candidate) => candidate.id === session.providerId);+ const currentProvider = bridge.listOAuthProviders().find(+ (candidate) => candidate.providerId === session.providerId,+ );+ if (+ session.cancelled ||+ currentProvider?.runtimeId !== session.runtimeId ||+ row?.ownerPluginId !== session.pluginId ||+ row.authKind !== OAUTH_AUTH_KIND ||+ row.enabled === false+ ) {+ throw new Error("plugin provider changed during OAuth sign-in");+ }+ await this.writePluginCredential(session.providerId, credential);+ const savedRow = (await this.rows()).find((candidate) => candidate.id === session.providerId);+ const savedProvider = this.deps.getPluginOAuthBridge?.()+ ?.listOAuthProviders()+ .find((candidate) => candidate.providerId === session.providerId);+ if (+ savedRow?.ownerPluginId !== session.pluginId ||+ savedRow.authKind !== OAUTH_AUTH_KIND ||+ savedRow.enabled === false ||+ savedProvider?.runtimeId !== session.runtimeId+ ) {+ await this.deps.call("secrets.delete", {+ secretRef: secretRefForProviderOauth(session.providerId),+ });+ throw new Error("plugin provider changed during OAuth sign-in");+ }+ });+ this.invalidateAccountModels(session.providerId);+ this.pushPluginEvent(session, {+ kind: "done",+ providerId: session.providerId,+ accountLabel: credential.accountLabel,+ });+ } catch {+ if (session.cancelled) {+ this.pushPluginEvent(session, { kind: "cancelled" });+ } else {+ // Callback errors are plugin-controlled and may contain token material.+ // Keep the user-facing diagnostic useful without reflecting the error.+ this.pushPluginEvent(session, {+ kind: "error",+ code: "PLUGIN_OAUTH_FAILED",+ message: "",+ });+ this.log("warn", "plugin provider OAuth sign-in failed", {+ pluginId: session.pluginId,+ providerId: session.providerId,+ });+ }+ } finally {+ for (const pending of session.prompts.values()) {+ pending.reject(new Error("login finished"));+ }+ await session.tail;+ this.pluginLogins.delete(session.loginId);+ }+ }++ private cancelPluginLogin(session: PluginLoginSession): void {+ if (session.cancelled) return;+ session.cancelled = true;+ session.controller.abort(new Error("login cancelled"));+ for (const pending of session.prompts.values()) {+ pending.reject(new Error("login cancelled"));+ }+ }++ private pushPluginEvent(+ session: PluginLoginSession,+ event: OAuthEventBody,+ ): void {+ session.tail = session.tail.then(() => {+ if (session.cancelled && event.kind !== "cancelled") return;+ this.deps.emit({+ ...event,+ loginId: session.loginId,+ vendorId: session.vendorId,+ } as OAuthLoginEvent);+ });+ }++ private async resolvePluginAuth(row: OAuthProviderRow): Promise<ModelAuth> {+ if (!row.ownerPluginId || !row.hasOauth) {+ throw new Error(`plugin provider account not signed in: ${row.id}`);+ }+ const credential = await this.serialize(row.id, async () => {+ let current = await this.readPluginCredential(row.id);+ if (!current) throw new Error(`plugin provider account not signed in: ${row.id}`);+ if (current.expiresAt !== undefined && current.expiresAt <= Date.now() + 30_000) {+ if (!current.refreshToken) throw new Error(`plugin provider credential expired: ${row.id}`);+ const provider = this.deps.getPluginOAuthBridge?.()+ ?.listOAuthProviders()+ .find((candidate) => candidate.providerId === row.id);+ const bridge = this.deps.getPluginOAuthBridge?.();+ if (!provider || !bridge) throw new Error(`plugin provider OAuth is unavailable: ${row.id}`);+ const refreshController = new AbortController();+ this.pluginRefreshControllers.set(row.id, refreshController);+ let rawRefreshed: unknown;+ try {+ rawRefreshed = await bridge.invokeProviderOAuth(+ provider.pluginId,+ provider.contributionId,+ {+ operation: "refresh",+ providerId: provider.contributionId,+ credential: current,+ },+ refreshController.signal,+ provider.runtimeId,+ );+ } finally {+ if (this.pluginRefreshControllers.get(row.id) === refreshController) {+ this.pluginRefreshControllers.delete(row.id);+ }+ }+ const refreshed = normalizePluginCredential(rawRefreshed);+ current = {+ ...refreshed,+ ...(refreshed.refreshToken ? {} : { refreshToken: current.refreshToken }),+ ...(refreshed.accountLabel ? {} : current.accountLabel ? { accountLabel: current.accountLabel } : {}),+ ...(refreshed.headers ? {} : current.headers ? { headers: current.headers } : {}),+ };+ const latest = (await this.rows()).find((candidate) => candidate.id === row.id);+ if (+ !latest ||+ latest.ownerPluginId !== row.ownerPluginId ||+ latest.authKind !== OAUTH_AUTH_KIND ||+ latest.enabled === false+ ) {+ throw new Error(`plugin provider changed during OAuth refresh: ${row.id}`);+ }+ await this.writePluginCredential(row.id, current);+ const savedRow = (await this.rows()).find((candidate) => candidate.id === row.id);+ const savedProvider = this.deps.getPluginOAuthBridge?.()+ ?.listOAuthProviders()+ .find((candidate) => candidate.providerId === row.id);+ if (+ !savedRow ||+ savedRow.ownerPluginId !== row.ownerPluginId ||+ savedRow.authKind !== OAUTH_AUTH_KIND ||+ savedRow.enabled === false ||+ savedProvider?.runtimeId !== provider.runtimeId+ ) {+ await this.deps.call("secrets.delete", {+ secretRef: secretRefForProviderOauth(row.id),+ });+ throw new Error(`plugin provider changed during OAuth refresh: ${row.id}`);+ }+ }+ return current;+ });+ return {+ apiKey: credential.accessToken,+ ...(credential.headers ? { headers: credential.headers } : {}),+ };+ }++ private async readPluginCredential(+ providerId: string,+ ): Promise<PluginProviderOAuthCredential | undefined> {+ const { value } = await this.deps.call<{ value?: string | null }>(+ "secrets.getForRuntime",+ { secretRef: secretRefForProviderOauth(providerId) },+ );+ if (!value) return undefined;+ try {+ return normalizePluginCredential(JSON.parse(value));+ } catch {+ this.log("warn", "stored plugin provider credential is not readable", { providerId });+ return undefined;+ }+ }++ private async writePluginCredential(+ providerId: string,+ credential: PluginProviderOAuthCredential,+ ): Promise<void> {+ await this.deps.call("secrets.set", {+ secretRef: secretRefForProviderOauth(providerId),+ value: JSON.stringify(credential),+ });+ }++ private clearAccountModels(providerId: string): void {+ this.invalidateAccountModels(providerId);+ this.deps.onAccountRemoved?.(providerId);+ }++ private invalidateAccountModels(providerId: string): void {+ this.accountModels.delete(providerId);+ this.liveModelCache.delete(providerId);+ this.liveModelLoads.delete(providerId);+ }+/** Point the row at a usable model now that the catalog can be read. */private async completeRow(session: LoginSession,diff --git a/apps/desktop/electron/main/plugin-host-process.mjs b/apps/desktop/electron/main/plugin-host-process.mjsindex 717c4e70b..9919b2dcd 100644--- a/apps/desktop/electron/main/plugin-host-process.mjs+++ b/apps/desktop/electron/main/plugin-host-process.mjs@@ -151,6 +151,9 @@ function normalizeBytes(value) {const commands = new Map();const tools = new Map();const speechHandles = new Map();+// Parent initiated OAuth callbacks can outlive the UI prompt. Their own+// cancellation signal lets the plugin stop polling or clean up local state.+const parentCallControllers = new Map();// Resident services declared in the manifest. The broker decides when they run;// this map only holds the callables and whether they are currently up.const services = new Map();@@ -249,6 +252,12 @@ function buildApi() {project: {create: (input) => call("project.create", [input ?? {}]),},+ providers: {+ oauth: {+ prompt: (loginId, input) => call("providers.oauth.prompt", [loginId, input]),+ notify: (loginId, event) => call("providers.oauth.notify", [loginId, event]),+ },+ },workspace: {get: () => call("workspace.get"),},@@ -494,11 +503,19 @@ async function handleInit(message) {globalThis.pi = buildApi();pluginModule = await loadPluginModule(entry);+ const oauthProviders = Array.isArray(manifest?.contributes?.providers)+ ? manifest.contributes.providers.filter((provider) => provider?.authKind === "oauth")+ : [];+ if (oauthProviders.length > 0 && typeof pluginModule?.onProviderOAuth !== "function") {+ const error = new Error("OAuth providers require an onProviderOAuth hook");+ error.code = "PLUGIN_INVALID";+ throw error;+ }if (pluginModule?.onLoad) await pluginModule.onLoad();return { pluginId };}-async function handleParentCall(method, payload, invocationId) {+async function handleParentCall(method, payload, invocationId, callId) {switch (method) {case "panel.invoke": {const invoke = pluginModule?.onPanelInvoke;@@ -509,6 +526,26 @@ async function handleParentCall(method, payload, invocationId) {}return invoke(String(payload?.channel ?? ""), payload?.payload ?? {});}+ case "provider.oauth": {+ const handle = pluginModule?.onProviderOAuth;+ if (typeof handle !== "function") {+ const error = new Error("plugin does not expose provider OAuth operations");+ error.code = "UNSUPPORTED";+ throw error;+ }+ if (typeof callId !== "string" || !callId || parentCallControllers.has(callId)) {+ const error = new Error("provider OAuth requires a unique parent call ID");+ error.code = "INVALID_ARGUMENT";+ throw error;+ }+ const controller = new AbortController();+ parentCallControllers.set(callId, controller);+ try {+ return await handle(payload ?? {}, { signal: controller.signal });+ } finally {+ parentCallControllers.delete(callId);+ }+ }case "command.run": {const run = commands.get(String(payload?.id ?? ""));if (!run) {@@ -604,6 +641,10 @@ async function handleParentCall(method, payload, invocationId) {}case "lifecycle.unload": {for (const id of invocations.keys()) cancelInvocation(id, "Plugin unloaded");+ for (const [id, controller] of parentCallControllers) {+ controller.abort(toolAbortedError("Plugin unloaded"));+ parentCallControllers.delete(id);+ }// Best effort: a throwing onUnload must not block teardown.try {if (pluginModule?.onUnload) await pluginModule.onUnload();@@ -637,6 +678,12 @@ onHostMessage((message) => {return;}if (message.t === "cancel") {+ if (typeof message.callId === "string") {+ const controller = parentCallControllers.get(message.callId);+ if (controller && !controller.signal.aborted) {+ controller.abort(toolAbortedError(String(message.reason ?? "Plugin call cancelled")));+ }+ }cancelInvocation(message.invocationId, String(message.reason ?? ""));return;}@@ -657,7 +704,7 @@ onHostMessage((message) => {return;}if (message.t === "call") {- void invocationContext.run(undefined, () => handleParentCall(message.method, message.payload, message.invocationId))+ void invocationContext.run(undefined, () => handleParentCall(message.method, message.payload, message.invocationId, message.id)).then((value) => send({ t: "res", id: message.id, ok: true, value: value ?? null })).catch((error) =>send({diff --git a/apps/desktop/electron/main/plugin-runtime.ts b/apps/desktop/electron/main/plugin-runtime.tsindex 070abb297..5891e468c 100644--- a/apps/desktop/electron/main/plugin-runtime.ts+++ b/apps/desktop/electron/main/plugin-runtime.ts@@ -61,6 +61,10 @@ import {type PluginNativeNotificationResult,type PluginNotificationPermission,type PluginNetEgressGrant,+ type PluginProviderOAuthEvent,+ type PluginProviderOAuthPrompt,+ type PluginProviderOAuthRequest,+ type PluginProviderContrib,type PluginServiceContrib,type PluginSettingContrib,type PluginSkillContrib,@@ -330,6 +334,18 @@ export type PluginHostServices = {input: PluginNativeNotificationInput,) => Promise<PluginNativeNotificationResult>;openExternal: (url: string) => Promise<void>;+ /** Host-rendered prompts for an active provider OAuth login. */+ providerOAuthPrompt?: (+ pluginId: string,+ loginId: string,+ input: PluginProviderOAuthPrompt,+ ) => Promise<string>;+ /** Host-rendered, non-secret progress for an active provider OAuth login. */+ providerOAuthNotify?: (+ pluginId: string,+ loginId: string,+ event: PluginProviderOAuthEvent,+ ) => Promise<void>;/** Open one already-authorized file with the OS-associated application. */openPath: (fullPath: string) => Promise<void>;/** Reveal one already-authorized file in the OS file manager. */@@ -470,6 +486,16 @@ export type PluginHostServices = {};};+export type PluginOAuthProvider = {+ pluginId: string;+ runtimeId: string;+ contributionId: string;+ providerId: string;+ name: string;+ loginLabel?: string;+ isSubscription: boolean;+};+/** Host APIs a plugin process may reach. Anything else does not exist (spec 04 §2). */const HOST_API_ALLOWLIST = new Set(["app.getVersion",@@ -549,6 +575,8 @@ const HOST_API_ALLOWLIST = new Set(["session.delete","usage.listTurns","agent.complete",+ "providers.oauth.prompt",+ "providers.oauth.notify","keyboard.registerGlobalShortcut","keyboard.unregisterGlobalShortcut","keyboard.listGlobalShortcuts",@@ -574,6 +602,8 @@ const PLUGIN_TOOL_TIMEOUT_MS = 110_000;export const PLUGIN_COMPLETE_TIMEOUT_MS = 90_000;/** Fixed panel operations are user-facing and must not hang the renderer. */const PLUGIN_PANEL_TIMEOUT_MS = 30_000;+/** OAuth login may wait for browser or device approval by the user. */+const PLUGIN_PROVIDER_OAUTH_TIMEOUT_MS = 5 * 60_000;const PANEL_SKILL_CHANNELS = new Set(["skill.list","skill.read",@@ -721,6 +751,7 @@ type PendingCall = {type LoadedPlugin = {manifest: PluginManifest;+ runtimeId: string;path: string;development: boolean;permissions: Set<string>;@@ -1592,6 +1623,94 @@ export class PluginRuntime {return this.loaded.get(pluginId);}+ /** OAuth provider entries exposed to the Host's provider sign-in surface. */+ listOAuthProviders(): PluginOAuthProvider[] {+ const result: PluginOAuthProvider[] = [];+ for (const loaded of this.loaded.values()) {+ if (!loaded.permissions.has("provider.oauth")) continue;+ const providers = (loaded.manifest.contributes?.providers ?? []) as PluginProviderContrib[];+ for (const provider of providers) {+ if (provider.authKind !== "oauth") continue;+ result.push({+ pluginId: loaded.manifest.id,+ runtimeId: loaded.runtimeId,+ contributionId: provider.id,+ providerId: `plugin:${loaded.manifest.id}:${provider.id}`,+ name: provider.name,+ loginLabel: provider.oauth?.loginLabel,+ isSubscription: provider.oauth?.isSubscription === true,+ });+ }+ }+ return result;+ }++ /** Invoke a declared provider's OAuth hook after rechecking its grant and owner. */+ async invokeProviderOAuth(+ pluginId: string,+ contributionId: string,+ request: PluginProviderOAuthRequest,+ signal?: AbortSignal,+ expectedRuntimeId?: string,+ ): Promise<unknown> {+ const loaded = this.loaded.get(pluginId);+ if (!loaded || loaded.disposing) {+ throw apiError("NOT_FOUND", `plugin not loaded: ${pluginId}`);+ }+ if (expectedRuntimeId && loaded.runtimeId !== expectedRuntimeId) {+ throw apiError("PLUGIN_UNLOADED", "provider OAuth plugin runtime changed");+ }+ this.assertPermission(loaded, "provider.oauth");+ const providers = (loaded.manifest.contributes?.providers ?? []) as PluginProviderContrib[];+ const provider = providers.find((entry) => entry.id === contributionId);+ if (!provider || provider.authKind !== "oauth") {+ throw apiError("PERMISSION_DENIED", "provider OAuth contribution is not declared");+ }+ if (request.providerId !== contributionId) {+ throw apiError("INVALID_ARGUMENT", "provider OAuth contribution does not match");+ }+ try {+ const value = await this.sendToChild(+ loaded,+ { t: "call", method: "provider.oauth", payload: request },+ PLUGIN_PROVIDER_OAUTH_TIMEOUT_MS,+ signal,+ );+ if (this.loaded.get(pluginId) !== loaded || loaded.disposing) {+ throw apiError("PLUGIN_UNLOADED", "provider OAuth plugin runtime changed");+ }+ let bytes = 0;+ try {+ bytes = Buffer.byteLength(JSON.stringify(value ?? null), "utf8");+ } catch {+ throw apiError("INVALID_ARGUMENT", "provider OAuth result must be JSON serializable");+ }+ if (bytes > 64 * 1024) {+ throw apiError("LIMIT_EXCEEDED", "provider OAuth result exceeds 64 KiB");+ }+ this.services.audit?.({+ pluginId,+ api: "provider.oauth",+ operation: request.operation,+ providerId: contributionId,+ ok: true,+ ts: Date.now(),+ });+ return value;+ } catch (error) {+ this.services.audit?.({+ pluginId,+ api: "provider.oauth",+ operation: request.operation,+ providerId: contributionId,+ ok: false,+ errorCode: (error as { code?: string } | null | undefined)?.code ?? "PLUGIN_OAUTH_FAILED",+ ts: Date.now(),+ });+ throw error;+ }+ }+/*** Read a persisted declared variable without exposing the plugin's private* settings record. Host-rendered scenic destinations use this only after@@ -1802,6 +1921,7 @@ export class PluginRuntime {const loaded: LoadedPlugin = {manifest,+ runtimeId: randomUUID(),path: pluginPath,development: options.development ?? this.devPlugins.has(manifest.id),permissions: granted,@@ -2269,9 +2389,11 @@ export class PluginRuntime {const id = `h${loaded.nextCallId++}`;return new Promise((resolvePromise, rejectPromise) => {const cancelChild = (error: Error) => {- if (typeof message.invocationId !== "string") return;+ const cancellation = typeof message.invocationId === "string"+ ? { invocationId: message.invocationId }+ : { callId: id };try {- child.postMessage({ t: "cancel", invocationId: message.invocationId, reason: error.message });+ child.postMessage({ t: "cancel", ...cancellation, reason: error.message });} catch {// The process may already be gone; the host still revokes the call.}@@ -2753,6 +2875,38 @@ export class PluginRuntime {}return this.services.project.create(loaded.manifest.id, { path: path.trim() });}+ case "providers.oauth.prompt": {+ this.assertPermission(loaded, "provider.oauth");+ this.assertHasOAuthProvider(loaded);+ const loginId = args[0];+ const input = args[1];+ if (typeof loginId !== "string" || !loginId || !input || typeof input !== "object") {+ throw apiError("INVALID_ARGUMENT", "provider OAuth prompt requires a loginId and request");+ }+ if (!this.services.providerOAuthPrompt) {+ throw apiError("UNSUPPORTED", "provider OAuth prompts are unavailable in this host");+ }+ this.services.audit?.({ pluginId, api, ok: true, ts: Date.now(), kind: "prompt" });+ return this.services.providerOAuthPrompt(pluginId, loginId, input as PluginProviderOAuthPrompt);+ }+ case "providers.oauth.notify": {+ this.assertPermission(loaded, "provider.oauth");+ this.assertHasOAuthProvider(loaded);+ const loginId = args[0];+ const event = args[1];+ if (typeof loginId !== "string" || !loginId || !event || typeof event !== "object") {+ throw apiError("INVALID_ARGUMENT", "provider OAuth notification requires a loginId and event");+ }+ if (!this.services.providerOAuthNotify) {+ throw apiError("UNSUPPORTED", "provider OAuth notifications are unavailable in this host");+ }+ const kind = (event as { kind?: unknown }).kind;+ if (!new Set(["info", "authUrl", "deviceCode", "progress"]).has(String(kind))) {+ throw apiError("INVALID_ARGUMENT", "unsupported provider OAuth event");+ }+ this.services.audit?.({ pluginId, api, ok: true, ts: Date.now(), kind });+ return this.services.providerOAuthNotify(pluginId, loginId, event as PluginProviderOAuthEvent);+ }case "session.list": {this.assertPermission(loaded, "session.read.own");const input = normalizePluginSessionInput(args[0] ?? {}, "other");@@ -4264,6 +4418,13 @@ export class PluginRuntime {}}+ private assertHasOAuthProvider(loaded: LoadedPlugin): void {+ const providers = (loaded.manifest.contributes?.providers ?? []) as PluginProviderContrib[];+ if (!providers.some((provider) => provider.authKind === "oauth")) {+ throw apiError("PERMISSION_DENIED", "provider OAuth requires a declared OAuth provider");+ }+ }+private sessionSource(loaded: LoadedPlugin,rawSource: unknown,diff --git a/apps/desktop/electron/main/services/plugin-services.ts b/apps/desktop/electron/main/services/plugin-services.tsindex 57768d288..16211557d 100644--- a/apps/desktop/electron/main/services/plugin-services.ts+++ b/apps/desktop/electron/main/services/plugin-services.ts@@ -202,6 +202,10 @@ export function createPluginServices({const plugins: PluginRuntime = new PluginRuntime({pluginShortcuts,pluginSockets,+ providerOAuthPrompt: (pluginId, loginId, input) =>+ vendorOAuth.promptPluginOAuth(pluginId, loginId, input),+ providerOAuthNotify: (pluginId, loginId, event) =>+ vendorOAuth.notifyPluginOAuth(pluginId, loginId, event),getWorkspacePath: () => {// Filled after host boots; temporary stub until services rebinding.return null;diff --git a/apps/desktop/src/components/settings/OAuthLoginDialog.tsx b/apps/desktop/src/components/settings/OAuthLoginDialog.tsxindex 983990b15..2d1865155 100644--- a/apps/desktop/src/components/settings/OAuthLoginDialog.tsx+++ b/apps/desktop/src/components/settings/OAuthLoginDialog.tsx@@ -89,7 +89,11 @@ export function OAuthLoginDialog({break;case "error":setPrompt(null);- setError(event.message);+ setError(+ event.code === "PLUGIN_OAUTH_FAILED"+ ? t("settings.pluginOauthFailed")+ : event.message,+ );break;case "cancelled":if (settled.current) break;@@ -98,7 +102,7 @@ export function OAuthLoginDialog({break;}});- }, [session]);+ }, [session, t]);const cancel = useCallback(async () => {if (closing) return;diff --git a/apps/desktop/src/components/settings/ServiceList.tsx b/apps/desktop/src/components/settings/ServiceList.tsxindex 300b3641c..847b82010 100644--- a/apps/desktop/src/components/settings/ServiceList.tsx+++ b/apps/desktop/src/components/settings/ServiceList.tsx@@ -73,9 +73,10 @@ export function ServiceList({const menuItems = (provider: ProviderPublic): CapabilityMenuItem[] => {const kind = serviceRowKind(provider);+ const pluginOAuth = kind === "account" && !!provider.ownerPluginId;const items: CapabilityMenuItem[] = [];// A plugin owns its row's fields and lifetime; only its key is the user's.- if (kind !== "plugin") {+ if (kind !== "plugin" && !pluginOAuth) {items.push({key: "edit",label: t(kind === "account" ? "settings.editVendorAccount" : "settings.editProvider"),@@ -123,7 +124,9 @@ export function ServiceList({key: "remove",label: isArmed? t("settings.capabilityRemoveConfirm")- : t(kind === "account" ? "settings.vendorRemoveAccount" : "settings.delete"),+ : t(pluginOAuth+ ? "settings.vendorSignOut"+ : kind === "account" ? "settings.vendorRemoveAccount" : "settings.delete"),icon: <IconTrash size={14} />,danger: true,onSelect: () => {@@ -145,7 +148,9 @@ export function ServiceList({const kind = serviceRowKind(provider);const rowBusy = reorder.saving || isRowBusy(provider.id);const onOpen =- kind !== "plugin"+ kind === "account" && provider.ownerPluginId+ ? undefined+ : kind !== "plugin"? () => onEdit(provider): provider.authKind === "api_key"? () => toggleKeyEntry(provider)diff --git a/apps/desktop/src/components/settings/service-row-status.ts b/apps/desktop/src/components/settings/service-row-status.tsindex 09e3ed0f3..e07441472 100644--- a/apps/desktop/src/components/settings/service-row-status.ts+++ b/apps/desktop/src/components/settings/service-row-status.ts@@ -81,7 +81,7 @@ export function serviceRowBadges(if (!provider.enabled) {badges.push({ key: "disabled", label: t("settings.providerDisabledBadge"), tone: "neutral" });}- if (kind === "plugin") {+ if (kind === "plugin" || provider.ownerPluginId) {badges.push({key: "plugin",label: t("settings.pluginProviderBadge"),diff --git a/apps/desktop/src/components/settings/useVendorAccounts.ts b/apps/desktop/src/components/settings/useVendorAccounts.tsindex f0f21d182..35daf793d 100644--- a/apps/desktop/src/components/settings/useVendorAccounts.ts+++ b/apps/desktop/src/components/settings/useVendorAccounts.ts@@ -189,9 +189,14 @@ export function useVendorAccounts() {useAppStore.setState({ settings: nextSettings });}await Promise.all([loadVendors(), refreshProviders()]);- showToast(t("settings.vendorAccountRemoved", { vendor: vendorName }), {+ showToast(+ provider.ownerPluginId+ ? t("settings.vendorSignedOut", { vendor: vendorName })+ : t("settings.vendorAccountRemoved", { vendor: vendorName }),+ {variant: "success",- });+ },+ );} catch (error) {showToast(error instanceof Error ? error.message : String(error), {variant: "error",diff --git a/apps/desktop/src/features/plugins/model.ts b/apps/desktop/src/features/plugins/model.tsindex d2ec8deed..1ffc6c92a 100644--- a/apps/desktop/src/features/plugins/model.ts+++ b/apps/desktop/src/features/plugins/model.ts@@ -49,6 +49,8 @@ export const PERMISSION_RISK: Record<string, RiskTier> = {"agent.extension": "high",// Its code runs in the app's own document, so the grant is the boundary."renderer.extension": "high",+ // The isolated plugin callback can read its own encrypted OAuth credentials.+ "provider.oauth": "high","desktop.control": "high","session.read": "high","browser.cdp": "high",diff --git a/apps/desktop/test/plugin-provider-oauth.test.mjs b/apps/desktop/test/plugin-provider-oauth.test.mjsnew file mode 100644index 000000000..3386e9ef4--- /dev/null+++ b/apps/desktop/test/plugin-provider-oauth.test.mjs@@ -0,0 +1,217 @@+import assert from "node:assert/strict";+import test from "node:test";+import { fork } from "node:child_process";+import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { register } from "node:module";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { fileURLToPath, pathToFileURL } from "node:url";++const here = dirname(fileURLToPath(import.meta.url));+const desktopRoot = join(here, "..");+const hostProcessEntry = join(desktopRoot, "electron/main/plugin-host-process.mjs");++register(pathToFileURL(join(here, "helpers/ts-import-hooks.mjs")));+const { PluginRuntime } = await import("../electron/main/plugin-runtime.ts");++function forkPluginProcess({ entry }) {+ const child = fork(entry, [], { stdio: ["ignore", "pipe", "pipe", "ipc"] });+ return {+ postMessage: (message) => {+ if (child.connected) child.send(message);+ },+ onMessage: (handler) => child.on("message", handler),+ onExit: (handler) => child.on("exit", (code) => handler(code ?? 0)),+ kill: () => child.kill(),+ };+}++function createRuntime(t, services = {}) {+ const runtime = new PluginRuntime({+ hostEntry: hostProcessEntry,+ spawnProcess: forkPluginProcess,+ ...services,+ });+ t.after(async () => {+ for (const loaded of runtime.listLoaded()) await runtime.unload(loaded.manifest.id);+ });+ return runtime;+}++function writePlugin(t, { id, main }) {+ const dir = mkdtempSync(join(tmpdir(), "pi-plugin-oauth-"));+ t.after(() => rmSync(dir, { recursive: true, force: true }));+ writeFileSync(join(dir, "manifest.json"), JSON.stringify({+ schemaVersion: 1,+ id,+ name: `Plugin ${id}`,+ version: "0.1.0",+ main: "main.js",+ permissions: ["provider.register", "provider.oauth"],+ contributes: {+ providers: [{+ id: "gateway",+ name: "Fixture Gateway",+ authKind: "oauth",+ baseUrl: "https://api.example.test/v1",+ oauth: { loginLabel: "Sign in to Fixture Gateway" },+ models: [{ id: "fixture-model" }],+ }],+ },+ }), "utf8");+ writeFileSync(join(dir, "main.js"), typeof main === "function" ? main(dir) : main, "utf8");+ return dir;+}++function deferred() {+ let resolve;+ let reject;+ const promise = new Promise((resolvePromise, rejectPromise) => {+ resolve = resolvePromise;+ reject = rejectPromise;+ });+ return { promise, resolve, reject };+}++async function nextUntil(predicate, message) {+ for (let attempt = 0; attempt < 200; attempt++) {+ if (predicate()) return;+ await new Promise((resolve) => setImmediate(resolve));+ }+ throw new Error(message);+}++test("OAuth provider hooks cross the plugin process and use permission-gated host prompts", async (t) => {+ const audits = [];+ const notices = [];+ const promptSeen = deferred();+ const promptAnswer = deferred();+ const runtime = createRuntime(t, {+ audit: (entry) => audits.push(entry),+ providerOAuthNotify: async (pluginId, loginId, event) => {+ notices.push({ pluginId, loginId, event });+ },+ providerOAuthPrompt: async (pluginId, loginId, input) => {+ promptSeen.resolve({ pluginId, loginId, input });+ return promptAnswer.promise;+ },+ });+ const main = `module.exports = {+ onProviderOAuth: async (request) => {+ await pi.providers.oauth.notify(request.loginId, {+ kind: "deviceCode",+ userCode: "ABCD-EFGH",+ verificationUri: "https://auth.example.test/device",+ });+ const code = await pi.providers.oauth.prompt(request.loginId, {+ type: "secret",+ message: "Enter the device code",+ });+ return {+ accessToken: "fixture-access-token",+ refreshToken: "fixture-refresh-token",+ accountLabel: code,+ };+ },+ };\n`;+ const dir = writePlugin(t, { id: "demo.oauth", main });+ await runtime.loadFromPath(dir, ["provider.register", "provider.oauth"]);++ const [provider] = runtime.listOAuthProviders();+ assert.equal(provider.pluginId, "demo.oauth");+ assert.equal(provider.providerId, "plugin:demo.oauth:gateway");+ assert.ok(provider.runtimeId);++ const callback = runtime.invokeProviderOAuth("demo.oauth", "gateway", {+ operation: "login",+ providerId: "gateway",+ loginId: "login-fixture",+ }, undefined, provider.runtimeId);+ await nextUntil(() => notices.length > 0, "plugin did not notify the host");+ assert.deepEqual(notices, [{+ pluginId: "demo.oauth",+ loginId: "login-fixture",+ event: {+ kind: "deviceCode",+ userCode: "ABCD-EFGH",+ verificationUri: "https://auth.example.test/device",+ },+ }]);+ const prompt = await promptSeen.promise;+ assert.deepEqual(prompt, {+ pluginId: "demo.oauth",+ loginId: "login-fixture",+ input: { type: "secret", message: "Enter the device code" },+ });+ promptAnswer.resolve("[email protected]");++ const credential = await callback;+ assert.equal(credential.accessToken, "fixture-access-token");+ assert.equal(credential.refreshToken, "fixture-refresh-token");+ assert.equal(credential.accountLabel, "[email protected]");+ assert.ok(audits.some((entry) => entry.api === "provider.oauth" && entry.ok === true));+ assert.equal(JSON.stringify(audits).includes("fixture-access-token"), false);++ const deniedDir = writePlugin(t, {+ id: "demo.oauth.denied",+ main: "module.exports = { onProviderOAuth: async () => ({ accessToken: 'nope' }) };\n",+ });+ await runtime.loadFromPath(deniedDir, ["provider.register"]);+ assert.deepEqual(runtime.listOAuthProviders().map((entry) => entry.pluginId), ["demo.oauth"]);+ await assert.rejects(+ runtime.invokeProviderOAuth("demo.oauth.denied", "gateway", {+ operation: "login",+ providerId: "gateway",+ loginId: "denied-login",+ }),+ (error) => error.code === "PERMISSION_DENIED",+ );+});++test("unloading a plugin aborts its in-flight OAuth callback context", async (t) => {+ const progress = [];+ const started = deferred();+ const runtime = createRuntime(t, {+ providerOAuthNotify: async (_pluginId, _loginId, event) => {+ progress.push(event.message);+ if (event.message === "started") started.resolve();+ },+ });+ const dir = writePlugin(t, {+ id: "demo.oauth.cancel",+ main: (pluginPath) => `const { writeFileSync } = require("node:fs");+const abortMarker = ${JSON.stringify(join(pluginPath, "oauth-aborted"))};+module.exports = {+ onProviderOAuth: async (request, { signal }) => {+ const cancelled = new Promise((resolve) => {+ signal.addEventListener("abort", () => {+ writeFileSync(abortMarker, "aborted");+ resolve({ accessToken: "late-token" });+ }, { once: true });+ });+ await pi.providers.oauth.notify(request.loginId, { kind: "progress", message: "started" });+ return cancelled;+ },+ };\n`,+ });+ await runtime.loadFromPath(dir, ["provider.register", "provider.oauth"]);+ const [provider] = runtime.listOAuthProviders();+ const callback = runtime.invokeProviderOAuth("demo.oauth.cancel", "gateway", {+ operation: "login",+ providerId: "gateway",+ loginId: "cancel-login",+ }, undefined, provider.runtimeId);+ await started.promise;+ const unloading = runtime.unload("demo.oauth.cancel");+ await assert.rejects(callback, (error) => error.code === "PLUGIN_UNLOADED");+ await unloading;+ assert.equal(existsSync(join(dir, "oauth-aborted")), true, "the child callback sees its abort signal");+ assert.deepEqual(progress, ["started"]);+});++test("an OAuth manifest without its callback fails closed at plugin load", async (t) => {+ const runtime = createRuntime(t);+ const dir = writePlugin(t, { id: "demo.oauth.no-hook", main: "module.exports = {};\n" });+ await assert.rejects(runtime.loadFromPath(dir, ["provider.register", "provider.oauth"]), /OAuth providers require an onProviderOAuth hook/);+ assert.deepEqual(runtime.listOAuthProviders(), []);+});diff --git a/apps/desktop/test/vendor-oauth-login.test.mjs b/apps/desktop/test/vendor-oauth-login.test.mjsindex 2a67ec5a1..7ff62944c 100644--- a/apps/desktop/test/vendor-oauth-login.test.mjs+++ b/apps/desktop/test/vendor-oauth-login.test.mjs@@ -189,6 +189,7 @@ function harness(options = {}) {return options.createModels ? options.createModels(store) : fakeModels(store, options);},modelConfigFor: options.modelConfigFor,+ getPluginOAuthBridge: options.getPluginOAuthBridge,onAccountModels: options.onAccountModels,onAccountRemoved: options.onAccountRemoved,log: options.log,@@ -308,6 +309,209 @@ test("a completed login stores the credential and configures the row", async ()]);});+test("plugin OAuth uses host login slots, encrypted credentials, refresh, and sign-out", async () => {+ const provider = {+ pluginId: "test.clinepress",+ runtimeId: "runtime-1",+ contributionId: "clinepress",+ providerId: "plugin:test.clinepress:clinepress",+ name: "ClinePress",+ loginLabel: "Sign in with ClinePress",+ isSubscription: false,+ };+ const invoked = [];+ let oauth;+ const bridge = {+ listOAuthProviders: () => [provider],+ invokeProviderOAuth: async (pluginId, contributionId, request, signal, expectedRuntimeId) => {+ invoked.push({ pluginId, contributionId, request, signal, expectedRuntimeId });+ assert.equal(pluginId, provider.pluginId);+ assert.equal(contributionId, provider.contributionId);+ assert.equal(expectedRuntimeId, provider.runtimeId);+ if (request.operation === "login") {+ await oauth.notifyPluginOAuth(pluginId, request.loginId, {+ kind: "deviceCode",+ userCode: "ABCD-EFGH",+ verificationUri: "https://auth.example.com/device",+ });+ const code = await oauth.promptPluginOAuth(pluginId, request.loginId, {+ type: "secret",+ message: "Enter the device code",+ });+ return {+ accessToken: `access-${code}`,+ refreshToken: "refresh-plugin-token",+ expiresAt: Date.now() + 60_000,+ accountLabel: "[email protected]",+ };+ }+ assert.equal(request.operation, "refresh");+ assert.equal(request.credential.refreshToken, "refresh-plugin-token");+ assert.equal(signal.aborted, false);+ return {+ accessToken: "refreshed-plugin-access",+ expiresAt: Date.now() + 3_600_000,+ };+ },+ };+ const removed = [];+ const h = harness({+ getPluginOAuthBridge: () => bridge,+ onAccountRemoved: (providerId) => removed.push(providerId),+ });+ oauth = h.oauth;+ h.host.providers.set(provider.providerId, {+ id: provider.providerId,+ name: provider.name,+ vendorKey: "custom",+ ownerPluginId: provider.pluginId,+ authKind: "oauth",+ baseUrl: "https://api.example.com/v1",+ apiStyle: "chat_completions",+ models: [{ id: "cline-model", contextWindow: 128_000, maxTokens: 8_192, thinkingLevels: [] }],+ enabled: true,+ });++ const unconnected = await oauth.listVendors();+ const vendor = unconnected.find((entry) => entry.vendorId === provider.providerId);+ assert.equal(vendor.name, "ClinePress");+ assert.equal(vendor.accounts[0].connected, false);++ const { loginId } = await oauth.start(provider.providerId);+ const device = await waitFor(h.events, "deviceCode");+ assert.equal(device.userCode, "ABCD-EFGH");+ const prompt = await waitFor(h.events, "prompt");+ assert.equal(prompt.request.message, "Enter the device code");+ assert.equal(oauth.respond({ loginId, promptId: prompt.request.promptId, value: "123456" }), true);+ const done = await waitFor(h.events, "done");+ assert.equal(done.accountLabel, "[email protected]");++ const secretRef = secretRefForProviderOauth(provider.providerId);+ const stored = JSON.parse(h.host.secrets.get(secretRef));+ assert.equal(stored.accessToken, "access-123456");+ assert.equal(stored.refreshToken, "refresh-plugin-token");+ assert.equal(stored.accountLabel, "[email protected]");+ assert.equal(await oauth.resolveAuth(provider.providerId).then((auth) => auth.apiKey), "access-123456");+ assert.deepEqual(await oauth.listModels(provider.providerId), [{+ modelId: "cline-model",+ apiStyle: "chat_completions",+ baseUrl: "https://api.example.com/v1",+ }]);+ const binding = await oauth.bindingFor(provider.providerId, "cline-model");+ assert.equal(binding.baseUrl, "https://api.example.com/v1");+ assert.equal(binding.modelConfig.name, "cline-model");++ stored.expiresAt = Date.now() - 1;+ h.host.secrets.set(secretRef, JSON.stringify(stored));+ assert.deepEqual(await oauth.resolveAuth(provider.providerId), {+ apiKey: "refreshed-plugin-access",+ });+ assert.equal(invoked.filter((entry) => entry.request.operation === "refresh").length, 1);+ assert.equal(+ JSON.parse(h.host.secrets.get(secretRef)).refreshToken,+ "refresh-plugin-token",+ "an omitted refresh token keeps the current refresh token",+ );++ const connected = (await oauth.listVendors()).find((entry) => entry.vendorId === provider.providerId);+ assert.equal(connected.accounts[0].connected, true);+ assert.equal(connected.accounts[0].accountLabel, "[email protected]");+ await oauth.deleteAccount(provider.providerId);+ assert.equal(h.host.secrets.has(secretRef), false);+ assert.equal(h.host.providers.has(provider.providerId), true, "sign-out keeps the manifest-owned provider row");+ assert.deepEqual(removed, [provider.providerId]);+});++test("cancelling plugin OAuth aborts its callback and rejects an active host prompt", async () => {+ const provider = {+ pluginId: "test.cancel-oauth",+ runtimeId: "runtime-1",+ contributionId: "cancel",+ providerId: "plugin:test.cancel-oauth:cancel",+ name: "Cancel OAuth",+ isSubscription: false,+ };+ let oauth;+ let callbackSignal;+ const bridge = {+ listOAuthProviders: () => [provider],+ invokeProviderOAuth: async (pluginId, contributionId, request, signal) => {+ callbackSignal = signal;+ return oauth.promptPluginOAuth(pluginId, request.loginId, {+ type: "manual_code",+ message: "Paste the callback code",+ });+ },+ };+ const h = harness({ getPluginOAuthBridge: () => bridge });+ oauth = h.oauth;+ h.host.providers.set(provider.providerId, {+ id: provider.providerId,+ name: provider.name,+ ownerPluginId: provider.pluginId,+ authKind: "oauth",+ baseUrl: "https://api.example.com/v1",+ enabled: true,+ });++ const { loginId } = await oauth.start(provider.providerId);+ await waitFor(h.events, "prompt");+ assert.equal(oauth.cancel(loginId), true);+ await waitFor(h.events, "cancelled");+ assert.equal(callbackSignal.aborted, true);+ assert.equal(h.host.secrets.has(secretRefForProviderOauth(provider.providerId)), false);+});++test("signing out aborts an in-flight plugin token refresh before clearing its secret", async () => {+ const provider = {+ pluginId: "test.refresh-cancel",+ runtimeId: "runtime-1",+ contributionId: "refresh-cancel",+ providerId: "plugin:test.refresh-cancel:refresh-cancel",+ name: "Refresh cancellation",+ isSubscription: false,+ };+ let refreshSignal;+ let markRefreshStarted;+ const refreshStarted = new Promise((resolve) => {+ markRefreshStarted = resolve;+ });+ const bridge = {+ listOAuthProviders: () => [provider],+ invokeProviderOAuth: async (_pluginId, _contributionId, request, signal) => {+ assert.equal(request.operation, "refresh");+ refreshSignal = signal;+ markRefreshStarted();+ return new Promise((_resolve, reject) => {+ signal.addEventListener("abort", () => reject(signal.reason), { once: true });+ });+ },+ };+ const h = harness({ getPluginOAuthBridge: () => bridge });+ h.host.providers.set(provider.providerId, {+ id: provider.providerId,+ name: provider.name,+ ownerPluginId: provider.pluginId,+ authKind: "oauth",+ baseUrl: "https://api.example.com/v1",+ enabled: true,+ });+ const secretRef = secretRefForProviderOauth(provider.providerId);+ h.host.secrets.set(secretRef, JSON.stringify({+ accessToken: "expired-access",+ refreshToken: "refresh-token",+ expiresAt: Date.now() - 1,+ }));++ const auth = h.oauth.resolveAuth(provider.providerId);+ await refreshStarted;+ await h.oauth.deleteAccount(provider.providerId);+ await assert.rejects(auth, /provider sign-out requested/);+ assert.equal(refreshSignal.aborted, true);+ assert.equal(h.host.secrets.has(secretRef), false);+ assert.equal(h.host.providers.has(provider.providerId), true);+});+test("the pi-ai 1.0 Anthropic copy-code flow uses the select and manual-code bridge", async () => {const requests = [];const previousFetch = globalThis.fetch;diff --git a/crates/host-core/src/plugins/providers.rs b/crates/host-core/src/plugins/providers.rsindex 6e562f727..f42465373 100644--- a/crates/host-core/src/plugins/providers.rs+++ b/crates/host-core/src/plugins/providers.rs@@ -29,11 +29,8 @@ const PLUGIN_API_STYLES: [&str; 7] = ["pi_messages",];-/// Auth kinds a manifest may declare today. `oauth` is deliberately absent: a-/// plugin OAuth broker needs a Host-owned login flow that does not exist yet,-/// so a declaration that asks for one is refused instead of materializing a-/// row nobody can sign in to.-const PLUGIN_AUTH_KINDS: [&str; 2] = ["api_key", "none"];+/// Auth kinds a manifest may declare.+const PLUGIN_AUTH_KINDS: [&str; 3] = ["api_key", "none", "oauth"];pub(crate) fn is_known_api_style(value: &str) -> bool {PLUGIN_API_STYLES.contains(&value)@@ -306,8 +303,8 @@ pub(crate) fn sync_plugin_providers(.map(|binding| binding.id).collect::<Vec<_>>();providers::forget_cached_models(db, &row_id, &removed_models)?;- // The merge replaces only the model bindings: headers and the OAuth- // account label a login flow wrote are not this function's to drop.+ // The merge replaces only model bindings; headers and OAuth metadata+ // are not this declaration's to drop.let config = providers::config_with_model_bindings(existing_config.as_deref().unwrap_or("{}"),&models,@@ -327,6 +324,13 @@ pub(crate) fn sync_plugin_providers(}None};+ if provider.auth_kind != "oauth" {+ let oauth_ref = crate::secrets::secret_ref_for_provider_oauth(&row_id);+ secrets.delete(&oauth_ref)?;+ db.conn()+ .prepare_cached("DELETE FROM secrets_meta WHERE secret_ref = ?1")?+ .execute(params![oauth_ref])?;+ }// The public projection derives the default from the first binding, so// the declared order is the plugin's choice of default.let default_model_id = models.first().map(|model| model.id.clone());diff --git a/crates/host-core/src/plugins/providers/tests.rs b/crates/host-core/src/plugins/providers/tests.rsindex f7563a88f..0ff625476 100644--- a/crates/host-core/src/plugins/providers/tests.rs+++ b/crates/host-core/src/plugins/providers/tests.rs@@ -531,26 +531,28 @@ fn the_declaration_shape_is_validated() {);assert!(read_manifest_err(&root).contains("declares model m twice"));- // OAuth needs the Host-owned login flow, which does not exist yet.+ // OAuth declarations require an explicit OAuth capability grant.write_plugin(&root,declaration_manifest(json!([{ "id": "demo", "name": "Demo", "authKind": "oauth",- "models": [{ "id": "m" }] }]),- permissions,+ "baseUrl": "https://api.example.com/v1", "models": [{ "id": "m" }] }]),+ permissions.clone(),),);- assert!(read_manifest_err(&root).contains("unsupported authKind oauth"));+ assert!(read_manifest_err(&root).contains("require the provider.oauth permission"));write_plugin(&root,declaration_manifest(json!([{ "id": "demo", "name": "Demo", "authKind": "oauth",- "oauth": { "label": "Demo" }, "models": [{ "id": "m" }] }]),- json!(["provider.register"]),+ "baseUrl": "https://api.example.com/v1",+ "oauth": { "loginLabel": "Continue in browser", "isSubscription": true },+ "models": [{ "id": "m" }] }]),+ json!(["provider.register", "provider.oauth"]),),);- assert!(read_manifest_err(&root).contains("not supported in this release"));+ assert!(PluginManager::read_manifest(&root).is_ok());}/// A row id already in use by something other than this plugin cannot arisediff --git a/crates/host-core/src/plugins/validation.rs b/crates/host-core/src/plugins/validation.rsindex 225b2fcc7..d95520c58 100644--- a/crates/host-core/src/plugins/validation.rs+++ b/crates/host-core/src/plugins/validation.rs@@ -257,14 +257,6 @@ pub(crate) fn validate_contributions(root: &Path, manifest: &PluginManifest) ->bail!("PLUGIN_INVALID: provider {id} has unsupported apiStyle {style}");}}- // `oauth` declarations arrive with the Host-owned plugin login- // flow. Until it exists, a manifest that asks for one is refused- // rather than turned into a row nobody can sign in to.- if obj.get("oauth").is_some() {- bail!(- "PLUGIN_INVALID: provider {id} declares oauth; plugin OAuth providers are not supported in this release"- );- }let auth_kind = obj.get("authKind").and_then(Value::as_str)@@ -272,6 +264,44 @@ pub(crate) fn validate_contributions(root: &Path, manifest: &PluginManifest) ->if !is_known_auth_kind(auth_kind) {bail!("PLUGIN_INVALID: provider {id} has unsupported authKind {auth_kind}");}+ if auth_kind == "oauth" {+ require_permission(manifest, "provider.oauth", "OAuth providers")?;+ if obj.get("baseUrl").and_then(Value::as_str).is_none() {+ bail!("PLUGIN_INVALID: provider {id} requires baseUrl for OAuth");+ }+ }+ if let Some(oauth) = obj.get("oauth") {+ if auth_kind != "oauth" {+ bail!("PLUGIN_INVALID: provider {id} oauth metadata requires authKind oauth");+ }+ let oauth = oauth.as_object().ok_or_else(|| {+ anyhow!("PLUGIN_INVALID: provider {id} oauth must be an object")+ })?;+ if let Some(field) = oauth+ .keys()+ .find(|key| key.as_str() != "loginLabel" && key.as_str() != "isSubscription")+ {+ bail!("PLUGIN_INVALID: provider {id} oauth has unsupported field {field}");+ }+ if let Some(login_label) = oauth.get("loginLabel") {+ if login_label+ .as_str()+ .map(str::trim)+ .filter(|value| !value.is_empty() && value.encode_utf16().count() <= 128)+ .is_none()+ {+ bail!(+ "PLUGIN_INVALID: provider {id} oauth.loginLabel must be a non-empty string of at most 128 characters"+ );+ }+ }+ if oauth+ .get("isSubscription")+ .is_some_and(|value| !value.is_boolean())+ {+ bail!("PLUGIN_INVALID: provider {id} oauth.isSubscription must be a boolean");+ }+ }if let Some(base_url) = obj.get("baseUrl").and_then(Value::as_str) {// The runtime reaches this endpoint, so a declaration may only// name an absolute http(s) URL.@@ -396,7 +426,9 @@ pub(crate) fn validate_contributions(root: &Path, manifest: &PluginManifest) ->anyhow!("PLUGIN_INVALID: theme {id} asset missing: {raw}")})?;if !asset_path.starts_with(&package_root) {- bail!("PLUGIN_INVALID: theme {id} asset {raw} resolves outside the plugin package");+ bail!(+ "PLUGIN_INVALID: theme {id} asset {raw} resolves outside the plugin package"+ );}asset_path};diff --git a/docs/adr/0259-plugin-declared-providers.md b/docs/adr/0259-plugin-declared-providers.mdindex 51c3adf5e..4db5a43ee 100644--- a/docs/adr/0259-plugin-declared-providers.md+++ b/docs/adr/0259-plugin-declared-providers.md@@ -39,9 +39,11 @@ Ownership is the part that needs a decision: a provider row is no longer onlyapiStyle, models). Values the declaration does not own — stored headers andthe OAuth account label — are preserved across a refresh.5. Credentials stay in the Host secret store under the same refs as any provider:- `secret:provider:<id>:api_key` and `secret:provider:<id>:oauth`. The plugin- neither holds nor exports the credential, and the row is an ordinary runtime- row for model resolution, discovery, and connection tests.+ `secret:provider:<id>:api_key` and `secret:provider:<id>:oauth`. API-key+ credentials are never handed to the plugin. OAuth credentials are accessible+ only through the plugin's own `onProviderOAuth` callback with the separate+ high-risk `provider.oauth` grant (ADR 0320). The row remains an ordinary+ runtime row for model resolution, discovery, and connection tests.6. The user path refuses a plugin-owned row. `providers.update` and`providers.delete` fail with a `PROVIDER_OWNED_BY_PLUGIN` error, because themanifest declaration would overwrite a user edit on the next load and only the@@ -58,13 +60,13 @@ Ownership is the part that needs a decision: a provider row is no longer only`plugins.uninstall`, and once at host startup for every registered plugin. Aprovider sync failure is logged as a warning; it never changes pluginenablement.-10. OAuth is staged, not shipped: an `oauth` block or `authKind: "oauth"` is- refused at manifest validation (`plugin OAuth providers are not supported in- this release` / `unsupported authKind oauth`), because the Host has no plugin- OAuth login flow. The `provider.oauth` permission and a Host-owned login flow- are future work and are not available today.-11. The plugin SDK mirrors the same authoring-time rules, requires the same- permission, and derives the `providers` capability token for the plugin row.+10. OAuth contributions use the host-owned account UI and callback protocol in+ ADR 0320. Each declaration has one encrypted OAuth credential at a time;+ sign-out clears it while the manifest-owned row remains. Multi-account+ provider rows are not part of this contract.+11. The plugin SDK mirrors the same authoring-time rules, requires+ `provider.oauth` for OAuth declarations, and derives the `providers`+ capability token for the plugin row.## Consequences@@ -79,9 +81,10 @@ Ownership is the part that needs a decision: a provider row is no longer onlydevelopment-plugin limit for v1.1 bound that exposure.- A credential is only as durable as the declaration: dropping an entry from themanifest, or uninstalling the plugin, deletes the stored key or token.-- The plugin-side surface is deliberately narrow (no OAuth, no plugin-owned- headers, no user editing), so a row cannot become a writable side channel- around the provider config schema.+- The plugin-side surface is deliberately narrow: OAuth code runs only in the+ isolated plugin process for its own provider, while host-owned UI and secret+ storage retain account and renderer ownership. The manifest still owns the+ provider row and users cannot edit it.- The v15→v16 session-collaboration step now stamps its own version `16` insteadof the latest schema constant, so a v15 file can walk v15→v16→v17 in onelaunch.diff --git a/docs/adr/0320-plugin-oauth-provider-callbacks.md b/docs/adr/0320-plugin-oauth-provider-callbacks.mdnew file mode 100644index 000000000..09f939595--- /dev/null+++ b/docs/adr/0320-plugin-oauth-provider-callbacks.md@@ -0,0 +1,96 @@+# ADR 0320: Host-owned OAuth lifecycle for plugin providers++- Status: Accepted for implementation+- Date: 2026-10-06+- Decision: D647+- Related: ADR 0008, ADR 0095, ADR 0259, `07-plugins/02-plugin-manifest-schema.md`, `07-plugins/03-plugin-api.md`, `07-plugins/04-plugin-security.md`, `07-plugins/13-plugin-permissions-matrix.md`, `03-runtime/14-secrets-storage.md`++## Context++ADR 0259 gives plugins manifest-owned provider rows, but its first version+supports only API keys and no-auth providers. Some providers can only be used+through OAuth. The host already owns provider account UI, encrypted secrets,+request authentication, and cancellation; allowing a plugin to add a provider+must not move those responsibilities into its panel or into Electron main.++OAuth also creates a new permission boundary: the plugin that implements an+OAuth protocol must handle its own access and refresh tokens. A general secret+API would expose unrelated credentials and create a second secret owner.++## Decision++1. Add `authKind: "oauth"` and bounded `oauth` display metadata to+ `contributes.providers`. Such a contribution requires `provider.register`,+ `provider.oauth`, an absolute HTTP(S) `baseUrl`, and an `onProviderOAuth`+ export from the plugin main module. The callback runs in the existing+ isolated plugin process (ADR 0008), never in Electron main.+2. The Host owns the sign-in surface and lifecycle. Vendor accounts lists the+ loaded plugin provider, the host renders prompts and progress, and the host+ opens an authorization URL after validating it. The plugin uses+ `pi.providers.oauth.prompt` and `.notify` only during its active login.+3. `onProviderOAuth` handles `login` and `refresh`, and receives an abort signal+ for cancellation, plugin unload, and timeout. Login returns a credential;+ refresh receives and returns only the credential for the same declared+ contribution. No general secret read API is added.+4. Electron main stores the credential under the existing encrypted+ `secret:provider:<providerRowId>:oauth` reference and serializes refreshes by+ provider row. The Host validates token, header, and result sizes. Renderer+ events contain only login UI state and a non-secret account label. The+ Agent Runtime receives only the access token through the normal per-request+ auth resolver; the refresh token remains in Electron main and the Host+ secret store.+5. `provider.oauth` is a separate high-risk permission from `provider.register`+ and `net.fetch`. Host-mediated callback egress still requires `net.fetch` and+ `manifest.net.domains`. Plugin entry code is not an OS sandbox, so granting+ `provider.oauth` means trusting the plugin code with that provider's+ credential.+6. One credential is stored per provider contribution. Sign out clears the+ OAuth secret but leaves the manifest-owned row. Multi-account plugin+ providers would need separately owned account rows and are not part of this+ contract. Plugin-owned rows and secrets remain excluded from portable+ configuration capture.+7. Existing `api_key` and `none` provider contributions keep their behavior;+ old plugins receive no OAuth grant by default. Missing permissions or a+ missing callback fail closed without changing an existing plugin's+ enablement or other provider rows.++## Consequences++- A plugin can integrate an OAuth-only provider into the native provider and+ model selection paths without adding a second provider registry.+- The trusted callback sees its own access and refresh tokens. That exposure is+ explicit in the high-risk permission review and is not mitigated by encrypted+ storage once a token is delivered to the callback.+- Host-owned prompts, secret storage, refresh serialization, renderer projection,+ and request-auth delivery remain under their existing owners.+- Each contribution has one account at a time. Supporting multiple accounts+ requires a future account identity and row-lifecycle design.+- The OAuth callback is plugin-authored code and remains subject to the plugin+ process trust boundary documented in the security specification.++## Alternatives considered++### Give plugins a general secret-store API++Rejected: it would expose unrelated provider credentials, require a new+secret-reference authorization model, and let a plugin become a second secret+owner. The callback can access only its own declared provider credential.++### Run plugin OAuth code inside Electron main++Rejected: loading third-party OAuth libraries into Electron main would break+the existing process boundary and put arbitrary plugin code beside renderer,+window, and host-process capabilities. The callback remains in the plugin's+existing isolated process.++### Store OAuth tokens in plugin-private storage++Rejected: the Host could not serialize refreshes, clear credentials on sign-out+or provider removal, report a connected account without reading plugin data, or+keep the runtime auth resolver authoritative.++### Create one provider row per plugin OAuth account++Deferred: it changes provider identity, manifest reconciliation, default-model+selection, and uninstall cleanup. The initial contract keeps the manifest row+stable and stores one account credential beneath it.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 15a643506..c09ca3e35 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -361,3 +361,4 @@ Each ADR includes:| retained-browser-pages-per-tab | [Retain a host-owned browser page per resource tab](retained-browser-pages-per-tab.md) | Accepted || 0318 | [Publish native Linux arm64 artifacts](0318-linux-arm64-release-lane.md) | Accepted (D638) || 0319 | [Inline external imports in owning Settings destinations](0319-settings-inline-imports.md) | Accepted (D645) |+| 0320 | [Host-owned OAuth lifecycle for plugin providers](0320-plugin-oauth-provider-callbacks.md) | Accepted for implementation (D647; amends ADR 0259) |diff --git a/docs/plugin-development.md b/docs/plugin-development.mdindex 38527666a..92f8afd15 100644--- a/docs/plugin-development.md+++ b/docs/plugin-development.md@@ -16,6 +16,7 @@ A plugin can contribute one or more of these capabilities:| Floating widget | A transparent, frameless companion window — a round orb, not a rectangle | `ui.panel` permission, `"ui": { "shape": "widget" }`, `window.pluginBridge` || Work panel view | An interface docked in the app's right work panel | `contributes.views`, `ui.view` permission, `window.pluginBridge` || Agent tool | A function the Agent can call | `contributes.agentTools`, `pi.agent.registerTool` |+| OAuth provider | A provider row with host-owned sign-in and encrypted credentials | `contributes.providers`, `provider.oauth`, `onProviderOAuth` || One-shot completion | A host-owned completion against the user's models | `pi.models.list`, `pi.session.getLlmContext`, `pi.agent.complete` || Skill | Instructions loaded by the Agent on demand | `contributes.skills`, `agent.prompt.inject` permission || Theme | Design-token overrides | `contributes.themes`, `ui.theme` permission |@@ -190,6 +191,15 @@ promptly.Only `onLoad` and `onUnload` are fired today. Other lifecycle names in themanifest are reserved for the planned full lifecycle.+`onProviderOAuth` is a separate operation callback for OAuth provider+contributions, not a lifecycle hook. It handles login and refresh only for its+own declared provider. The host stores its returned credential encrypted and+passes only the access token to model requests; the callback can also use+`pi.providers.oauth.prompt` and `.notify` for host-rendered login steps. The+permission `provider.oauth` is high risk, and token egress still requires+`net.fetch` plus the manifest's network domains. See the provider OAuth section+in the [Plugin API](spec/07-plugins/03-plugin-api.md).+### `renderer/index.html`PI-Desktop hosts the panel in a frameless window on every platform. The hostdiff --git a/docs/spec/03-runtime/12-provider-config-schema.md b/docs/spec/03-runtime/12-provider-config-schema.mdindex b51ce2dbb..f367d5dd7 100644--- a/docs/spec/03-runtime/12-provider-config-schema.md+++ b/docs/spec/03-runtime/12-provider-config-schema.md@@ -196,6 +196,15 @@ non-secret `accountLabel`, and a `connected` flag. The custom-provider dialogdoes not edit or delete OAuth rows; the Vendor accounts card calls`providers.delete` for the selected row.+Plugin-owned OAuth rows use the same `authKind` and encrypted secret reference,+but keep the manifest-owned row id `plugin:<pluginId>:<declaredId>`. The+`provider.oauth` callback handles login and refresh for that row, and one+credential is stored per declared provider contribution. Signing out deletes+only its OAuth secret; the provider row remains until the plugin is disabled,+uninstalled, or removes the declaration. Plugin-owned rows and their secrets+are excluded from portable configuration capture because the plugin manifest+recreates the row on the destination host.+`models` is the provider's selected model binding array. Each binding owns itscontext/output limits and explicit thinking configuration. Published cataloglevels seed a newly selected known model, but the binding may enable anydiff --git a/docs/spec/03-runtime/14-secrets-storage.md b/docs/spec/03-runtime/14-secrets-storage.mdindex 5212ffcc4..adb73ca39 100644--- a/docs/spec/03-runtime/14-secrets-storage.md+++ b/docs/spec/03-runtime/14-secrets-storage.md@@ -153,6 +153,18 @@ generic manual-code prompt with the flow's PKCE state; both paths persist thecredential through the same provider-scoped Host secret store. The choice doesnot expose refresh tokens or change the account/auth ownership boundary.+Plugin-owned OAuth rows use the same encrypted+`secret:provider:<providerId>:oauth` reference. The host invokes the owning+plugin's `onProviderOAuth` callback for login and refresh only after checking+the `provider.oauth` grant and declared contribution. The callback can read+that provider's own credential; it receives an abort signal for cancellation,+plugin unload, or timeout. The host validates and bounds callback results,+serializes refresh per provider row, and passes only the access token through+the normal per-request auth resolver. The refresh token never reaches the+renderer or Agent Runtime. One credential is stored per manifest contribution;+sign out clears that secret without deleting the provider row. Plugin-owned+provider rows are omitted from portable configuration and credential capture.+Request auth flows one way only:1. The launch payload for an `authKind: "oauth"` row carries `apiKey: ""`.diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex f5a699460..dca79aee1 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -15789,22 +15789,28 @@ plugin-form fixtures in an isolated temporary directory at runtime.acceptance remains outstanding. Required post-integration suites: `test:e2e`,`test:e2e:subagents`, `test:e2e:subagent-models`.-#### E2E-PLUGIN-declared-provider-appears-in-the-native-provider-list: A plugin-declared provider is a Host-owned row with thinking controls--- **Preconditions**: An installed local plugin declares one provider in- `contributes.providers` with the `provider.register` permission, one model,- a fixture `baseUrl`, `thinkingLevels: ["off", "low", "high"]`, and- `defaultThinkingLevel: "high"`; a key is stored once through Settings.+#### E2E-PLUGIN-declared-provider-appears-in-the-native-provider-list: Plugin providers use Host-owned rows, permissions, and OAuth sign-in++- **Preconditions**: An installed local plugin declares one API-key provider+ with `provider.register` and one OAuth provider with both `provider.register`+ and `provider.oauth`. Both use a fixture `baseUrl` and one model; the API-key+ model has `thinkingLevels: ["off", "low", "high"]` and+ `defaultThinkingLevel: "high"`. Its `onProviderOAuth` callback uses only a+ local OAuth fixture and host-rendered `pi.providers.oauth` interactions.- **Steps**: 1) Enable the plugin and open Settings → Providers. 2) Inspectthe model binding and Composer thinking selector, then select the row as thesession model and run a turn. 3) Change the session thinking level and run asecond turn. 4) Try to edit the provider, then delete it, through the user- path. 5) Disable the plugin, inspect the list and stored credential, and- re-enable it. 6) Uninstall the plugin; reinstall and enable it, then remove- the declaration from its manifest and reload. 7) Load a manifest that- declares providers without `provider.register`. 8) Load a manifest that- declares an `oauth` block and `authKind: "oauth"`. 9) Load manifests whose- model uses a non-array `thinkingLevels`, a non-string entry, or a non-string+ path. 5) Open Vendor accounts, sign in to the plugin OAuth provider using its+ host-rendered prompt/device-code step, then select that provider and run a+ turn. 6) Expire the fixture access token and run another turn to exercise the+ plugin refresh callback. 7) Cancel a second login and confirm the callback's+ abort signal fires; sign out and then disable/re-enable the plugin. 8)+ Uninstall the plugin; reinstall and enable it, then remove the declaration+ from its manifest and reload. 9) Load manifests that omit `provider.register`+ or `provider.oauth`, have OAuth metadata without `authKind: "oauth"`, or+ lack the `onProviderOAuth` module export. 10) Load manifests whose model uses a+ non-array `thinkingLevels`, a non-string entry, or a non-string`defaultThinkingLevel`.- **Expected**: Step 1 shows one row in the native provider list with`ownerPluginId` set to the plugin and the row id@@ -15814,17 +15820,21 @@ plugin-form fixtures in an isolated temporary directory at runtime.starts the session at `high`; the turn uses that choice. Step 3 persists anduses the changed session level without changing the provider declaration.Step 4 refuses both actions with an error whose message begins- `PROVIDER_OWNED_BY_PLUGIN` and leaves the row unchanged. Step 5 keeps the- row and sets `enabled = 0` while `secret:provider:<id>:api_key` stays stored,- so re-enabling restores the credential and thinking binding. Step 6 deletes- the row and both credential refs (`:api_key` and `:oauth`) in both orders —- uninstall, and a manifest that no longer declares the provider. Steps 7 and- 8 fail manifest validation as `PLUGIN_INVALID` — the missing-permission- message and `plugin OAuth providers are not supported in this release` /- `unsupported authKind oauth` — and neither failure changes plugin enablement.- Step 9 rejects each malformed thinking-level field with `PLUGIN_INVALID` and- leaves plugin enablement unchanged.+ `PROVIDER_OWNED_BY_PLUGIN` and leaves the row unchanged. Step 5 completes+ login through the native OAuth dialog and stores one encrypted credential+ under `secret:provider:<plugin-row-id>:oauth`; the renderer sees only status+ and the non-secret account label. Step 6 invokes the refresh callback with+ the plugin's own credential, but only the new access token reaches the Agent+ Runtime; refresh tokens stay in Electron main and the Host secret store. Step+ 7 stops the callback on cancellation, clears the OAuth secret on sign-out,+ keeps both manifest-owned rows across disable/enable, and restores sign-in+ status only for credentials that remain stored. Step 8 removes both rows and+ their credential refs when uninstalled or undeclared. Step 9 fails closed:+ missing permissions fail manifest validation, and a missing callback fails+ plugin load without exposing a sign-in action. Step 10 rejects malformed+ thinking-level fields with `PLUGIN_INVALID` and leaves enablement unchanged.- **Specs linked**: `07-plugins/02-plugin-manifest-schema.md` §4, §5.4, §7;+ `07-plugins/03-plugin-api.md` (provider OAuth); `07-plugins/04-plugin-security.md`;`07-plugins/13-plugin-permissions-matrix.md`; `03-runtime/04-data-storage.md`§4.3, §7; `03-runtime/11-provider-model-system.md` §6.2;`03-runtime/12-provider-config-schema.md` §2, §9;@@ -15833,12 +15843,11 @@ plugin-form fixtures in an isolated temporary directory at runtime.G (plugins), Security, Quality- **Milestone**: Post-MVP (R7 v1)- **Status**: Partially automated (`pnpm test:e2e:trusted-extensions`): the- declared row materializing as `plugin:<pluginId>:<declaredId>` in the native- provider list with its `ownerPluginId`, endpoint, models, and thinking- binding passes. Ownership refusal (`PROVIDER_OWNED_BY_PLUGIN`),- disable/enable, undeclare and uninstall cleanup, and the manifest refusals- are covered by host-core unit tests; the renderer's read-only row and- thinking-selector presentation remain additional validation.+ API-key declared row materializing with its endpoint, models, and thinking+ binding passes. Ownership refusal, disable/enable, cleanup, and manifest+ validation are covered by host-core checks. OAuth callback, prompt, token+ refresh, cancellation, sign-out, permission presentation, and the renderer's+ provider/account interaction require task-candidate E2E coverage.#### E2E-CHAT-disclosure-toggle-keeps-reading-positiondiff --git a/docs/spec/07-plugins/02-plugin-manifest-schema.md b/docs/spec/07-plugins/02-plugin-manifest-schema.mdindex d3c832c45..d7e1d6aa4 100644--- a/docs/spec/07-plugins/02-plugin-manifest-schema.md+++ b/docs/spec/07-plugins/02-plugin-manifest-schema.md@@ -145,7 +145,7 @@ type PluginContributes = {agentTools?: PluginAgentToolContrib[];skills?: Array<string | PluginSkillContrib>; // relative paths, or metadata overridesagentExtensions?: string[]; // ExtensionAPI modules run in the agent sidecar; needs `agent.extension` (spec 16)- providers?: PluginProviderContrib[]; // Host-owned provider rows; needs `provider.register` (spec 13)+providers?: PluginProviderContrib[]; // Host-owned provider rows; needs `provider.register`; OAuth also needs `provider.oauth` (spec 13)settings?: PluginSettingContrib[];themes?: PluginThemeContrib[];scenicThemes?: PluginScenicThemesContrib;@@ -281,7 +281,8 @@ type PluginProviderContrib = {vendorKey?: string; // models.dev vendor key, default `custom`baseUrl?: string; // absolute http(s) URLapiStyle?: PluginProviderApiStyle; // wire style, default `chat_completions`- authKind?: "api_key" | "none"; // default `api_key`; `oauth` is refused for now+ authKind?: "api_key" | "none" | "oauth"; // default `api_key`+ oauth?: { loginLabel?: string; isSubscription?: boolean }; // only with `authKind: "oauth"`models: PluginProviderModelContrib[]; // 1..64 entries};@@ -332,6 +333,7 @@ type PluginPermission =| "agent.tool.register"| "agent.prompt.inject"| "provider.register"+ | "provider.oauth"| "net.fetch"| "net.anyHost"| "shell.openExternal"@@ -457,7 +459,11 @@ as rows in the native provider list, owned by the plugin ([ADR 0259](../../adr/0- `baseUrl` is optional, but must be an absolute `http(s)` URL- `apiStyle` is optional and defaults to `chat_completions`; the accepted valuesare the provider-config styles except `auto`-- `authKind` is optional, either `api_key` (default) or `none`+- `authKind` is optional: `api_key` (default), `none`, or `oauth`+- OAuth providers require `baseUrl`, the `provider.oauth` permission, and an+ `onProviderOAuth` module export. Optional `oauth.loginLabel` is a+ non-empty string of at most 128 characters; `oauth.isSubscription` is a+ boolean. The host stores one encrypted credential per provider contribution.- `models` requires 1..64 entries with unique ids of 1..256 characters`thinkingLevels` is optional. The Host trims entries, drops unknown canonical@@ -473,10 +479,17 @@ fields; disabling the plugin keeps the rows and turns them off, while dropping adeclaration or uninstalling the plugin deletes the row with its storedcredentials.-`oauth` is **not supported yet**: the Host has no plugin OAuth login flow, so an-`oauth` block or `authKind: "oauth"` fails manifest validation. The planned-`provider.oauth` permission and Host-owned login flow are future work, not-available behavior.+OAuth contributions use the host-owned vendor-account UI. `onProviderOAuth`+handles `login` and `refresh`; `pi.providers.oauth.prompt` and `.notify` provide+host-rendered interaction. The callback can read only the credential for its+own provider contribution and only when `provider.oauth` is granted. Its model+requests receive the access token through the ordinary Host auth resolver; the+refresh token never enters the renderer or Agent Runtime. Egress still requires+`net.fetch` and the declared network domains when the callback uses the Host+network API. Plugin entry code is not an OS sandbox and can use raw Node APIs;+grant the permission only to code you trust. See+[03-plugin-api.md](03-plugin-api.md) and+[13-plugin-permissions-matrix.md](13-plugin-permissions-matrix.md).## 6. activationEvents (optional)@@ -514,7 +527,7 @@ MVP may implement only:valid patterns (§5.1)12. A contribution that needs a permission fails validation when the permissionis missing: `themes` → `ui.theme`, `views` → `ui.view`, `providers` →- `provider.register`, stdio servers → `mcp.server.local`, remote+ `provider.register`, OAuth providers → `provider.oauth`, stdio servers → `mcp.server.local`, remoteservers → `mcp.server.remote`, `services` → `background.service`,`bus.publish` → `bus.publish`, `bus.subscribe` → `bus.subscribe`.`skills` is the exception — it predates the permission gate, so a manifestdiff --git a/docs/spec/07-plugins/03-plugin-api.md b/docs/spec/07-plugins/03-plugin-api.mdindex f5ace650a..045ad2820 100644--- a/docs/spec/07-plugins/03-plugin-api.md+++ b/docs/spec/07-plugins/03-plugin-api.md@@ -341,6 +341,71 @@ Only enabled, authenticated provider rows are returned (API key, OAuth, orso a picker page can populate itself. When the host transport is unavailable,the call returns an empty list instead of warning (D080).+### provider OAuth (requires `provider.oauth`)++An OAuth provider contribution needs both `provider.register` and+`provider.oauth`, a `baseUrl`, and an `onProviderOAuth` export from the plugin's+main module. The host invokes the hook only for a declared contribution:++```ts+type PluginProviderOAuthRequest = {+ operation: "login" | "refresh"+ providerId: string // plugin-local contribution id+ loginId?: string // login only; pass to prompt/notify+ credential?: PluginProviderOAuthCredential // refresh only; this provider's credential+}++type PluginProviderOAuthCredential = {+ accessToken: string+ refreshToken?: string+ expiresAt?: number // Unix epoch milliseconds+ accountLabel?: string+ headers?: Record<string, string>+}++type PluginProviderOAuthContext = { signal: AbortSignal }++onProviderOAuth(request, { signal }): Promise<PluginProviderOAuthCredential>+```++During login, return the credential after the user authorizes it. During+refresh, the host passes the current credential to the same callback; return the+updated credential. The host encrypts it under the provider row's OAuth secret+reference and serializes refreshes. A callback can access only its own+contribution's credential. The host sends the resolved access token to the+Agent Runtime per request; refresh tokens never reach the renderer or Agent+Runtime. One account is stored for each provider contribution; sign out clears+that credential while the manifest-owned provider row remains.++The plugin can use host-owned login UI without opening its own window:++```ts+if (!request.loginId) throw new Error("loginId is required for sign-in")+const loginId = request.loginId++await pi.providers.oauth.notify(loginId, {+ kind: "deviceCode",+ userCode,+ verificationUri,+ intervalSeconds,+ expiresInSeconds,+})++const code = await pi.providers.oauth.prompt(loginId, {+ type: "secret",+ message: "Enter the verification code",+})+```++`prompt` supports `text`, `secret`, `select`, and `manual_code`. `notify`+supports non-secret `info`, `authUrl`, `deviceCode`, and `progress` events; the+host opens valid HTTP(S) authorization URLs and reports whether the browser+opened. The callback context signal is aborted when the user cancels, the plugin+unloads, or the host call times out. OAuth token requests still require+`net.fetch` and the manifest's `net.domains` when they use the host network API.+This permission does not grant a general host secret API. Plugin entry code is+not an OS sandbox and can use raw Node APIs, so grant it only to code you trust.+### session (requires `session.read`)```tspi.session.getLlmContext(): Promise<PluginLlmContext>@@ -1118,6 +1183,7 @@ Any of the following calls must be logged for audit:- models.list (returned row count)- session.getLlmContext (session id, message count, truncated flag — never transcript text)- agent.complete (model key, sizes, usage — never prompt or completion text)+- provider.oauth (plugin id, declared provider id, operation, result/error code — never credential contents)Log fields:- pluginId@@ -1146,6 +1212,7 @@ The desktop plugin runtime now implements the MVP host API surface used by local- `agent.registerTool` / `unregisterTool` / `agent.complete`- `speech.registerAdapter` / `unregisterAdapter` (`speech.adapter.register`)- `models.list`, `session.getLlmContext`+- `onProviderOAuth` and `pi.providers.oauth.prompt` / `notify` (`provider.oauth`)- `clipboard.*`, `shell.openExternal`, `net.fetch`- `browser.*` (guest CDP; `browser.cdp`)- `services.register` / `unregister`, `bus.publish` / `subscribe`, `events.on` / `off`diff --git a/docs/spec/07-plugins/04-plugin-security.md b/docs/spec/07-plugins/04-plugin-security.mdindex df25d67e8..4b7f96526 100644--- a/docs/spec/07-plugins/04-plugin-security.md+++ b/docs/spec/07-plugins/04-plugin-security.md@@ -30,9 +30,11 @@ Main risks:### Must1. Plugin UI is isolated from the host UI DOM2. Plugins cannot directly require host modules-3. The secret store is not open to plugins. Host-owned completions+3. The secret store is not open to general plugin APIs. Host-owned completions(`agent.complete`) resolve credentials in Electron main and never pass keys,- refresh tokens, or `ModelAuth` to the plugin process+ refresh tokens, or `ModelAuth` to the plugin process. The high-risk+ `provider.oauth` callback is the narrow exception: it can read only the+ encrypted OAuth credential for its own declared provider contribution4. The plugin-private data directory is separate from the host core library5. Session transcripts from `session.getLlmContext` are a bounded projection ofthe in-flight tool session only (D336 / D019)@@ -153,7 +155,8 @@ Plugins can access:Plugins cannot access:- Other plugins' data-- Host secrets+- Host secrets through a general-purpose API; `provider.oauth` grants access+ only to the callback's own declared provider credential- The host's full session database (unless a controlled API exists in the future)## 5.1 Inter-plugin message bus@@ -175,6 +178,21 @@ The bus is the only channel between two plugins, and it is deliberately narrow:Treat a topic as public within the app: any plugin that can declare a matchingpattern and hold `bus.subscribe` will see it. Do not put secrets on the bus.+### Provider OAuth credential boundary++`provider.oauth` is a separate high-risk grant from `provider.register` and+`net.fetch`. It lets `onProviderOAuth` handle login and refresh for a provider+declared by the same plugin. The host encrypts each credential in its secret+store and never sends the refresh token to the renderer or Agent Runtime. The+plugin callback can read that credential because it implements the provider's+OAuth protocol; it cannot read another provider's secret or call a general+secret API. Requests made through the host network API still require+`net.fetch` and `manifest.net.domains`. Plugin entry code is not an OS sandbox+and can use raw Node APIs, so a plugin with this grant must be code the user+trusts. The callback receives an abort signal when login is cancelled, the+plugin unloads, or the host call times out. Sign out clears the credential and+leaves the manifest-owned provider row in place.+## 6. Path safety`fs.read` / `fs.write` / `fs.delete` say whether a plugin may touch files;diff --git a/docs/spec/07-plugins/05-plugin-lifecycle.md b/docs/spec/07-plugins/05-plugin-lifecycle.mdindex e447388a0..b994fc32e 100644--- a/docs/spec/07-plugins/05-plugin-lifecycle.md+++ b/docs/spec/07-plugins/05-plugin-lifecycle.md@@ -43,6 +43,11 @@ discovered**Implemented today:** the runtime (`apps/desktop/electron/main/plugin-runtime.ts`) invokes `onLoad` (when a plugin is loaded on load/enable) and `onUnload` (dispatched into the plugin process on unload/disable/reload/app quit, 5s budget — 1.5s on quit — then the process is stopped); unloading tears down the plugin's registered commands and tools. The other hooks below are declared in the API but not yet fired.+`onProviderOAuth` is a provider operation callback, not a lifecycle hook. The+host invokes it only for an enabled plugin's declared OAuth provider during+user sign-in or token refresh; it receives an abort signal for cancellation,+unload, and timeout.+**Planned:** once the full lifecycle lands, hooks fire in this order:1. `onInstall` (once, only after a successful install)diff --git a/docs/spec/07-plugins/13-plugin-permissions-matrix.md b/docs/spec/07-plugins/13-plugin-permissions-matrix.mdindex e88bc719c..110bae9e0 100644--- a/docs/spec/07-plugins/13-plugin-permissions-matrix.md+++ b/docs/spec/07-plugins/13-plugin-permissions-matrix.md@@ -24,7 +24,8 @@ Provide a permission–capability–risk–default-policy reference table for re| `agent.tool.register` | high | Register an agent tool | Confirm at install | Tool execution is audited separately || `agent.prompt.inject` | high | Inject a system prompt; activates `contributes.skills` | Deny by default / strong confirmation | Easily leads to behavior hijacking || `agent.extension` | high | Run `contributes.agentExtensions` modules inside the agent process | Explicit confirmation; local imports and development plugins only in v1.1 | Same access as the agent's own tools; the plugin sandbox does not apply (spec 16) |-| `provider.register` | high | `contributes.providers` become rows in the native provider list, owned by the plugin and refreshed from the manifest on load | Explicit confirmation; local imports and development plugins only in v1.1, matching `agent.extension` | The user path refuses the row (`PROVIDER_OWNED_BY_PLUGIN`); credentials stay in the Host secret store under the usual provider refs; `oauth` declarations are not enabled yet |+| `provider.register` | high | `contributes.providers` become rows in the native provider list, owned by the plugin and refreshed from the manifest on load | Explicit confirmation; local imports and development plugins only in v1.1, matching `agent.extension` | The user path refuses edits to the row (`PROVIDER_OWNED_BY_PLUGIN`); API-key credentials stay in the Host secret store under the usual provider refs |+| `provider.oauth` | high | `onProviderOAuth`; host-rendered `pi.providers.oauth.prompt` / `notify` for a declared OAuth provider | Explicit confirmation | Required with `provider.register` for `authKind: "oauth"`. The callback can read and refresh only that contribution's encrypted credential. The Host keeps refresh tokens out of the renderer and Agent Runtime. Host-mediated callback egress still needs `net.fetch` and `manifest.net.domains`; plugin entry code itself is not an OS sandbox. One account is stored per provider contribution; sign out clears it || `net.fetch` | high | `net.fetch` | Deny by default | Confined to `manifest.net.domains`; an empty or malformed list means no egress (§2A) || `net.websocket` | high | `pi.net.websocket.connect` / `send` / `close` (host-owned sockets; at most 4 per plugin, 1 MiB frames) | Deny by default | Confined to `manifest.net.domains` like `net.fetch`; a refused host never reaches the transport, and every socket is closed when the plugin unloads, is disabled, or crashes || `net.anyHost` | high | Any host-owned egress path (`net.fetch`, `net.websocket`, panel session, remote HTTP MCP) | Confirm at install | Lifts the `manifest.net.domains` allowlist for user-typed endpoints (self-hosted servers); cloud metadata endpoints stay refused; nothing prompts at request time |diff --git a/docs/spec/08-meta/decisions-log.md b/docs/spec/08-meta/decisions-log.mdindex a778c08f9..2849ee120 100644--- a/docs/spec/08-meta/decisions-log.md+++ b/docs/spec/08-meta/decisions-log.md@@ -5469,11 +5469,7 @@ not an unreviewed upstream registry passthrough.## 2026-09-15 — Plugin-declared providers are Host-owned rows (D427)-**A plugin may declare `contributes.providers`, and the Host materializes each entry as a provider row in the native Settings → Provider list, owned by that plugin (`providers.owner_plugin_id`, schema v17; row id `plugin:<pluginId>:<declaredId>`). The declaration is re-read on every load and is authoritative for its own fields, so a dropped entry is deleted together with both credential references; `providers.update` / `providers.delete` refuse a plugin-owned row with `PROVIDER_OWNED_BY_PLUGIN`. A non-empty declaration needs the new high-risk `provider.register` permission, and an `oauth` block or `authKind: "oauth"` is refused until a Host-owned login flow exists. See ADR 0259, `07-plugins/02-plugin-manifest-schema.md` §5.4, `07-plugins/13-plugin-permissions-matrix.md`, `03-runtime/04-data-storage.md` §4.3/§7, and E2E-PLUGIN-declared-provider-appears-in-the-native-provider-list.**--It deliberately does not include plugin OAuth: the `provider.oauth` permission-and a Host-owned plugin login flow are future work, so a declared provider has no-OAuth login, token refresh, or account label today.+**A plugin may declare `contributes.providers`, and the Host materializes each entry as a provider row in the native Settings → Provider list, owned by that plugin (`providers.owner_plugin_id`, schema v17; row id `plugin:<pluginId>:<declaredId>`). The declaration is re-read on every load and is authoritative for its own fields, so a dropped entry is deleted together with both credential references; `providers.update` / `providers.delete` refuse a plugin-owned row with `PROVIDER_OWNED_BY_PLUGIN`. A non-empty declaration needs the new high-risk `provider.register` permission. D427 initially excluded OAuth; D647 amends it with a Host-owned login flow and separate high-risk `provider.oauth` grant. See ADR 0259, ADR 0320, `07-plugins/02-plugin-manifest-schema.md` §5.4, `07-plugins/13-plugin-permissions-matrix.md`, `03-runtime/04-data-storage.md` §4.3/§7, and E2E-PLUGIN-declared-provider-appears-in-the-native-provider-list.**## 2026-09-15 — Side chats materialize on first Send (#421)@@ -7486,3 +7482,22 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.- Covered by `apps/desktop/test/home-project-name.test.mjs`, which renders thereal surface against the real store. See `04-ux/01-ui-ia.md`,`04-ux/08-component-spec.md`, and E2E-256.++## 2026-10-06 — Plugin providers can own OAuth sign-in through a scoped callback (D647)++- D647 amends ADR 0259: a plugin provider may declare `authKind: "oauth"` when+ it has `provider.register`, the separate high-risk `provider.oauth` grant, and+ an `onProviderOAuth` callback. The Host owns the login UI, encrypted+ `secret:provider:<rowId>:oauth` storage, refresh serialization, and the+ per-request auth resolver. The callback can read only its own provider's+ OAuth credential; the Agent Runtime receives only an access token and the+ renderer receives no tokens. `pi.providers.oauth.prompt` and `.notify` provide+ bounded host-rendered login interaction. Host-mediated network calls still+ need `net.fetch` and declared domains; plugin entry code remains outside an+ OS sandbox. One credential is stored per declared provider row, and sign-out+ clears it without deleting the manifest-owned row. Plugin-owned provider rows+ and credentials remain out of portable configuration capture.+- Covered by the updated plugin manifest/provider validation contracts and the+ provider OAuth scenario in E2E-PLUGIN-declared-provider-appears-in-the-native-provider-list.+ See ADR 0320, the plugin OAuth API and permission specs, and+ `03-runtime/14-secrets-storage.md`.diff --git a/docs/zh-CN/spec/07-plugins/02-plugin-manifest-schema.md b/docs/zh-CN/spec/07-plugins/02-plugin-manifest-schema.mdindex c1c6b7f7f..633c5e58b 100644--- a/docs/zh-CN/spec/07-plugins/02-plugin-manifest-schema.md+++ b/docs/zh-CN/spec/07-plugins/02-plugin-manifest-schema.md@@ -397,7 +397,10 @@ type PluginNetDomains = string[]; // "api.example.com" 或 "*.example.com"- `baseUrl` 可选,但必须是绝对 `http(s)` URL- `apiStyle` 可选,默认 `chat_completions`;可取值是 provider 配置中除 `auto`以外的风格-- `authKind` 可选,为 `api_key`(默认)或 `none`+- `authKind` 可选,为 `api_key`(默认)、`none` 或 `oauth`+- OAuth provider 需要 `provider.register` 和独立高风险权限 `provider.oauth`,还需要+ 绝对 HTTP(S) `baseUrl` 及插件主模块导出的 `onProviderOAuth`;`oauth` 元数据可设置+ `loginLabel` 和 `isSubscription`- `models` 要求 1..64 条,id 唯一且长度为 1..256非空的 `contributes.providers` 需要高风险权限 `provider.register`@@ -405,9 +408,11 @@ type PluginNetDomains = string[]; // "api.example.com" 或 "*.example.com"声明会在每次插件加载时重新读取,并对其自身字段具有权威;禁用插件会保留这些行并将其关闭,而删除声明或卸载插件会连同已存凭据一起删除该行。-`oauth` **暂不支持**:宿主还没有插件 OAuth 登录流程,因此 `oauth` 块或-`authKind: \"oauth\"` 会在清单元数据校验阶段被拒绝。计划中的 `provider.oauth`-权限与宿主自有的登录流程属于未来工作,当前不可用。+OAuth 登录使用宿主自有的账号界面和加密凭据存储。宿主通过+`pi.providers.oauth.prompt` / `notify` 显示登录提示和进度;OAuth 回调只收到该插件+自身 provider 的凭据。刷新令牌保留在 Electron 主进程与宿主密钥库内,Agent Runtime+只接收请求所需的访问令牌。每个 provider 声明目前只支持一个账号;宿主插件进程不是+操作系统沙箱,因此授予 `provider.oauth` 表示信任该插件处理此 provider 的凭据。## 6. activationEvents(可选)示例:diff --git a/docs/zh-CN/spec/07-plugins/03-plugin-api.md b/docs/zh-CN/spec/07-plugins/03-plugin-api.mdindex 160355ff9..f60b8bc3a 100644--- a/docs/zh-CN/spec/07-plugins/03-plugin-api.md+++ b/docs/zh-CN/spec/07-plugins/03-plugin-api.md@@ -283,6 +283,66 @@ type PluginModelInfo = {只返回已启用且已认证的 provider 行(API key、OAuth 或 `authKind: "none"`)。不含密钥。`models.list` 也是面板桥通道,选择器页面可以自行填充。宿主传输不可用时返回空列表,不记警告(D080)。+### provider OAuth(需要 `provider.oauth`)++OAuth provider 声明需要同时拥有 `provider.register` 和 `provider.oauth`、设置+`baseUrl`,并由插件主模块导出 `onProviderOAuth`。宿主只会为 manifest 中声明的+provider 调用该回调:++```ts+type PluginProviderOAuthRequest = {+ operation: "login" | "refresh"+ providerId: string // 插件本地 provider 声明 id+ loginId?: string // 仅登录时提供;传给 prompt/notify+ credential?: PluginProviderOAuthCredential // 仅刷新时提供;属于该 provider 的凭据+}++type PluginProviderOAuthCredential = {+ accessToken: string+ refreshToken?: string+ expiresAt?: number // Unix epoch 毫秒+ accountLabel?: string+ headers?: Record<string, string>+}++type PluginProviderOAuthContext = { signal: AbortSignal }++onProviderOAuth(request, { signal }): Promise<PluginProviderOAuthCredential>+```++登录时,用户授权后回调返回凭据。刷新时,宿主把当前凭据传给同一回调,回调返回更新后+的凭据。宿主把凭据加密存于 provider 行对应的 OAuth secret 引用下,并串行执行刷新。+回调只能访问自己的 provider 声明凭据。宿主按请求向 Agent Runtime 传递解析后的访问令牌;+刷新令牌不会发给渲染进程或 Agent Runtime。每个 provider 声明只保存一个账号;退出登录会+清除凭据,但保留 manifest 所有的 provider 行。++插件可以使用宿主提供的登录界面,不必自行打开窗口:++```ts+if (!request.loginId) throw new Error("loginId is required for sign-in")+const loginId = request.loginId++await pi.providers.oauth.notify(loginId, {+ kind: "deviceCode",+ userCode,+ verificationUri,+ intervalSeconds,+ expiresInSeconds,+})++const code = await pi.providers.oauth.prompt(loginId, {+ type: "secret",+ message: "Enter the verification code",+})+```++`prompt` 支持 `text`、`secret`、`select` 和 `manual_code`。`notify` 支持非敏感的+`info`、`authUrl`、`deviceCode` 和 `progress` 事件;宿主会打开经过校验的 HTTP(S) 授权+链接,并报告浏览器是否成功打开。用户取消、插件卸载或宿主调用超时都会中止回调上下文+的 signal。使用宿主网络 API 请求 OAuth token 时,仍需 `net.fetch` 和+`manifest.net.domains`。该权限不提供通用宿主密钥 API。插件入口代码并非操作系统沙箱,+仍可使用原生 Node API,因此只应向可信代码授予该权限。+### session(需要 `session.read`)```tspi.session.getLlmContext(): Promise<PluginLlmContext>@@ -886,6 +946,7 @@ window.pluginBridge.on(event, handler)- models.list(返回行数)- session.getLlmContext(会话 id、消息数、truncated 标志 —— 不含转录文本)- agent.complete(模型 key、体积、usage —— 不含提示或补全文本)+- provider.oauth(插件 id、声明的 provider id、操作、结果/错误码——绝不记录凭据内容)日志字段:- 插件ID@@ -915,6 +976,7 @@ window.pluginBridge.on(event, handler)- `speech.registerAdapter` / `unregisterAdapter`(`speech.adapter.register`)- `models.list`、`session.getLlmContext`+- `onProviderOAuth` 和 `pi.providers.oauth.prompt` / `notify`(`provider.oauth`)- `clipboard.*`、`shell.openExternal`、`net.fetch`- `browser.*`(访客页 CDP;`browser.cdp`)- `services.register` / `unregister`、`bus.publish` / `subscribe`、`events.on` / `off`diff --git a/docs/zh-CN/spec/07-plugins/13-plugin-permissions-matrix.md b/docs/zh-CN/spec/07-plugins/13-plugin-permissions-matrix.mdindex b4f474f85..a40b66767 100644--- a/docs/zh-CN/spec/07-plugins/13-plugin-permissions-matrix.md+++ b/docs/zh-CN/spec/07-plugins/13-plugin-permissions-matrix.md@@ -27,7 +27,8 @@| `agent.tool.register` | 高 | 注册代理工具 | 安装时确认 | 工具执行情况单独审核 || `agent.prompt.inject` | 高 | 注入系统提示符;激活 `contributes.skills` | 默认拒绝/强确认 | 容易导致行为劫持 || `agent.extension` | 高 | 在 agent 进程内运行 `contributes.agentExtensions` 模块 | 显式确认;v1.1 仅限本地导入和开发插件 | 与 agent 自身工具同等权限;插件沙箱不适用(规格 16) |-| `provider.register` | 高 | `contributes.providers` 成为原生 Provider 列表中的行,归插件所有并在每次加载时按 manifest 刷新 | 显式确认;v1.1 仅限本地导入和开发插件,与 `agent.extension` 一致 | 用户路径拒绝该行(`PROVIDER_OWNED_BY_PLUGIN`);凭据仍存放在 Host secret store 的常规 provider 引用下;暂不启用 `oauth` 声明 |+| `provider.register` | 高 | `contributes.providers` 成为原生 Provider 列表中的行,归插件所有并在每次加载时按 manifest 刷新 | 显式确认;v1.1 仅限本地导入和开发插件,与 `agent.extension` 一致 | 用户路径拒绝编辑该行(`PROVIDER_OWNED_BY_PLUGIN`);API key 凭据仍存放在 Host secret store 的常规 provider 引用下 |+| `provider.oauth` | 高 | 已声明 OAuth provider 的 `onProviderOAuth`;宿主渲染的 `pi.providers.oauth.prompt` / `notify` | 显式确认 | `authKind: "oauth"` 需要与 `provider.register` 一起授予。回调只能读取和刷新该 provider 声明自己的加密凭据。Host 会把刷新令牌隔离在渲染进程与 Agent Runtime 之外。宿主代发的网络请求仍需 `net.fetch` 和 `manifest.net.domains`;插件入口代码本身不是操作系统沙箱。每个 provider 声明只保存一个账号;退出登录会清除凭据 || `net.fetch` | 高 | `net.fetch` | 默认拒绝 | 限定在 `manifest.net.domains` 之内;列表为空或非法即完全不放行出网(§2A) || `net.websocket` | 高 | `pi.net.websocket.connect` / `send` / `close`(套接字由宿主持有;每个插件最多 4 个,帧封顶 1 MiB) | 默认拒绝 | 与 `net.fetch` 一样被限制在 `manifest.net.domains` 之内;被拒绝的主机永远到不了传输层,插件卸载、被禁用或崩溃时每个套接字都会被关闭 || `net.anyHost` | 高 | 主机掌握的所有出网路径(`net.fetch`、`net.websocket`、面板 session、远程 HTTP MCP) | 安装时确认 | 对用户自填端点(自建服务器等)解除 `manifest.net.domains` 白名单;云元数据端点始终拒绝;请求时不再弹窗 |diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.tsindex 5e5cedde7..7ca6403e9 100644--- a/packages/i18n/src/locales/de/index.ts+++ b/packages/i18n/src/locales/de/index.ts@@ -1451,6 +1451,9 @@ sklm: {"vendorAccountUpdated": "Lieferantenkonto aktualisiert","vendorRemoveAccount": "Konto entfernen","vendorAccountRemoved": "{{vendor}}-Konto entfernt",+ "vendorSignOut": "Abmelden",+ "vendorSignedOut": "Von {{vendor}} abgemeldet",+ "pluginOauthFailed": "Das Plugin konnte die Anbieteranmeldung nicht abschließen.","vendorLoginStarting": "Anmeldung wird gestartet…","vendorBrowserOpened": "Beenden Sie die Anmeldung in Ihrem Browser und kehren Sie dann zu diesem Fenster zurück.","vendorBrowserFailed": "Ihr Browser wurde nicht geöffnet – kopieren Sie den Link und öffnen Sie ihn selbst.",@@ -2191,6 +2194,7 @@ sklm: {"agent.extension": "Code im Agenten ausführen","renderer.extension": "Oberfläche in Chat-Slots zeichnen","provider.register": "Anbieter zur Modellliste hinzufügen",+ "provider.oauth": "Bei einem Anbieter per OAuth anmelden","desktop.control": "Desktop steuern","models.list": "Authentifizierte Modelle auflisten","session.read": "Aktuelle an das Modell gesendete Konversation lesen",@@ -2230,6 +2234,7 @@ sklm: {"renderer.extension": "Lädt das Renderer-Modul dieses Plugins in das App-Fenster, um UI-Slot-Komponenten zu zeichnen (Nachrichten-Aktionsleisten, Antwort-Anhänge, Tool-Karten, Codeblock-Renderer, Eingabebereich). Das Modul läuft im selben Dokument wie PI-Desktop. Aktiviere nur Code, dem du vertraust.","agent.extension": "Führt ExtensionAPI-Module im Agentenprozess mit denselben Rechten wie die Tools des Agenten aus. Aktivieren Sie nur Code, dem Sie vertrauen.","provider.register": "Fügt die Anbieter, die dieses Plugin definiert, zur Anbieterliste in den Einstellungen hinzu. Das Plugin liefert den Endpunkt und die Modelle; Ihr API-Schlüssel bleibt in PI-Desktop.",+ "provider.oauth": "Erlaubt diesem Plugin die OAuth-Anmeldung und Token-Aktualisierung für seinen Anbieter. PI-Desktop verschlüsselt die Tokens, aber der vertrauenswürdige Callback kann sie lesen. Vom Host vermittelte Netzwerkzugriffe benötigen weiterhin net.fetch und deklarierte Domains; der Plugin-Prozess ist keine Betriebssystem-Sandbox. Nur vertrauenswürdigem Code gewähren.","desktop.control": "Erlaubt den Aufruf des geprüften PI-Desktop-Katalogs; destruktive Vorgänge benötigen weiterhin confirm=true, und das MCP-Bearer-Token wird nicht offengelegt.","models.list": "Kann sehen, für welche Modelle Sie sich angemeldet haben. Es erhält keine Schlüssel.","session.read": "Kann die Konversation lesen, an der der aktuelle Tool-Aufruf arbeitet, einschließlich der Tool-Ergebnisse.",diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.tsindex fff8171ff..e4b6a1584 100644--- a/packages/i18n/src/locales/en/index.ts+++ b/packages/i18n/src/locales/en/index.ts@@ -1472,6 +1472,9 @@ sklm: {vendorAccountUpdated: "Vendor account updated",vendorRemoveAccount: "Remove account",vendorAccountRemoved: "{{vendor}} account removed",+ vendorSignOut: "Sign out",+ vendorSignedOut: "Signed out of {{vendor}}",+ pluginOauthFailed: "The plugin could not complete provider sign-in.",vendorLoginStarting: "Starting sign-in…",vendorBrowserOpened:"Finish signing in in your browser, then come back to this window.",@@ -2215,6 +2218,7 @@ importConfirm: "Imported extensions run inside the agent process with the same a"agent.extension": "Run code inside the agent","renderer.extension": "Draw UI in chat slots","provider.register": "Add providers to the model list",+ "provider.oauth": "Sign in to a provider with OAuth","desktop.control": "Control the desktop","models.list": "List authenticated models","session.read": "Read the current conversation sent to the model",@@ -2264,6 +2268,8 @@ importConfirm: "Imported extensions run inside the agent process with the same a"Loads this plugin's renderer module into the app window to draw UI slot components (message action bars, entry extras, tool cards, code-block renderers, composer controls). The module runs in the same document as PI-Desktop. Enable only code you trust.","provider.register":"Adds the providers this plugin defines to Settings' provider list. The plugin supplies the endpoint and models; your API key stays in PI-Desktop.",+ "provider.oauth":+ "Lets this plugin run OAuth login and refresh for its declared provider. PI-Desktop encrypts the tokens, but the trusted callback can read them. Host-mediated network access still requires net.fetch and declared domains; plugin entry code is not an OS sandbox, so grant this only to code you trust.","desktop.control":"Lets the plugin invoke the reviewed PI-Desktop control catalog. Destructive operations still require confirm=true; the MCP bearer token is never exposed.","models.list": "Can see which models you have signed in for. It does not receive keys.",diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.tsindex 88ecbd6c8..118a3d565 100644--- a/packages/i18n/src/locales/es/index.ts+++ b/packages/i18n/src/locales/es/index.ts@@ -1451,6 +1451,9 @@ sklm: {"vendorAccountUpdated": "Cuenta de proveedor actualizada","vendorRemoveAccount": "Eliminar cuenta","vendorAccountRemoved": "{{vendor}} cuenta eliminada",+ "vendorSignOut": "Cerrar sesión",+ "vendorSignedOut": "Sesión cerrada en {{vendor}}",+ "pluginOauthFailed": "El complemento no pudo completar el inicio de sesión del proveedor.","vendorLoginStarting": "Iniciando inicio de sesión...","vendorBrowserOpened": "Termine de iniciar sesión en su navegador y luego regrese a esta ventana.","vendorBrowserFailed": "Su navegador no se abrió; copie el enlace y ábralo usted mismo.",@@ -2191,6 +2194,7 @@ sklm: {"agent.extension": "Ejecutar código dentro del agente","renderer.extension": "Dibujar interfaz en los slots del chat","provider.register": "Agregar proveedores a la lista de modelos",+ "provider.oauth": "Iniciar sesión con OAuth en un proveedor","desktop.control": "Controlar el escritorio","models.list": "Listar modelos autenticados","session.read": "Leer la conversación actual enviada al modelo",@@ -2230,6 +2234,7 @@ sklm: {"agent.extension": "Ejecuta módulos ExtensionAPI dentro del proceso del agente con el mismo acceso que sus propias herramientas. Activa solo código en el que confíes.","renderer.extension": "Carga el módulo de renderizado de este complemento en la ventana de la app para dibujar componentes en los slots de la interfaz (barras de acción de mensajes, extras de respuesta, tarjetas de herramientas, renderizadores de bloques de código, controles del compositor). El módulo se ejecuta en el mismo documento que PI-Desktop. Activa solo código de confianza.","provider.register": "Agregue los proveedores que define este complemento a la lista de proveedores de Configuración. El complemento aporta el punto final y los modelos; su clave API permanece en PI-Desktop.",+ "provider.oauth": "Permite que este complemento inicie sesión y renueve tokens para su proveedor declarado. PI-Desktop cifra los tokens, pero la devolución de llamada de confianza puede leerlos. El acceso a la red mediado por el host requiere net.fetch y dominios declarados; el proceso del complemento no es una zona aislada del sistema operativo. Concédelo solo a código de confianza.","desktop.control": "Permite invocar el catálogo de control de PI-Desktop revisado; las operaciones destructivas siguen requiriendo confirm=true y el token bearer de MCP no se expone.","models.list": "Puede ver en qué modelos se ha registrado. No recibe llaves.","session.read": "Puede leer la conversación en la que está operando la llamada de herramienta actual, incluidos los resultados de la herramienta.",diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.tsindex e7296977c..231bc2c6c 100644--- a/packages/i18n/src/locales/fr/index.ts+++ b/packages/i18n/src/locales/fr/index.ts@@ -1451,6 +1451,9 @@ sklm: {"vendorAccountUpdated": "Compte fournisseur mis à jour","vendorRemoveAccount": "Supprimer le compte","vendorAccountRemoved": "{{vendor}} compte supprimé",+ "vendorSignOut": "Se déconnecter",+ "vendorSignedOut": "Déconnexion de {{vendor}}",+ "pluginOauthFailed": "Le plugin n’a pas pu terminer la connexion au fournisseur.","vendorLoginStarting": "Début de la connexion…","vendorBrowserOpened": "Terminez la connexion dans votre navigateur, puis revenez à cette fenêtre.","vendorBrowserFailed": "Votre navigateur ne s'est pas ouvert : copiez le lien et ouvrez-le vous-même.",@@ -2191,6 +2194,7 @@ sklm: {"agent.extension": "Exécuter du code dans l'agent","renderer.extension": "Dessiner l'interface dans les emplacements du chat","provider.register": "Ajouter des fournisseurs à la liste de modèles",+ "provider.oauth": "Se connecter à un fournisseur avec OAuth","desktop.control": "Contrôler le bureau","models.list": "Liste des modèles authentifiés","session.read": "Lire la conversation en cours envoyée au modèle",@@ -2230,6 +2234,7 @@ sklm: {"agent.extension": "Exécute des modules ExtensionAPI dans le processus de l'agent avec le même accès que ses propres outils. N'activez que du code auquel vous faites confiance.","renderer.extension": "Charge le module de rendu de ce plugin dans la fenêtre de l'app pour dessiner des composants d'interface (barres d'actions des messages, extras de réponse, cartes d'outils, rendus de blocs de code, contrôles du composeur). Le module s'exécute dans le même document que PI-Desktop. N'activez que du code de confiance.","provider.register": "Ajoute les fournisseurs définis par ce plugin à la liste des fournisseurs des Paramètres. Le plugin fournit le point de terminaison et les modèles ; votre clé API reste dans PI-Desktop.",+ "provider.oauth": "Autorise ce plugin à se connecter et à renouveler les jetons de son fournisseur déclaré. PI-Desktop chiffre les jetons, mais le rappel de confiance peut les lire. L'accès réseau médié par l'hôte nécessite net.fetch et des domaines déclarés ; le processus du plugin n'est pas une sandbox système. À accorder uniquement à du code fiable.","desktop.control": "Permet d'appeler le catalogue PI-Desktop contrôlé ; les opérations destructrices exigent toujours confirm=true et le bearer token MCP n'est pas exposé.","models.list": "Peut voir pour quels modèles vous vous êtes connecté. Il ne reçoit pas de clés.","session.read": "Peut lire la conversation sur laquelle l'appel d'outil actuel fonctionne, y compris les résultats de l'outil.",diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.tsindex 46df6c31a..8ab395069 100644--- a/packages/i18n/src/locales/ko/index.ts+++ b/packages/i18n/src/locales/ko/index.ts@@ -1465,6 +1465,9 @@ sklm: {vendorAccountUpdated: "벤더 계정 업데이트됨",vendorRemoveAccount: "계정 제거",vendorAccountRemoved: "{{vendor}} 계정 제거됨",+ vendorSignOut: "로그아웃",+ vendorSignedOut: "{{vendor}}에서 로그아웃됨",+ pluginOauthFailed: "플러그인이 공급자 로그인을 완료하지 못했습니다.",vendorLoginStarting: "로그인 시작 중…",vendorBrowserOpened:"브라우저에서 로그인을 완료한 후 이 창으로 돌아오세요.",@@ -2207,6 +2210,7 @@ importConfirm: "가져온 확장은 에이전트 프로세스 안에서 에이"agent.extension": "에이전트 안에서 코드 실행","renderer.extension": "채팅 슬롯에 UI 그리기","provider.register": "모델 목록에 프로바이더 추가",+ "provider.oauth": "OAuth로 프로바이더 로그인","desktop.control": "데스크톱 제어","models.list": "인증된 모델 목록 표시","session.read": "모델에 전송되는 현재 대화 읽기",@@ -2254,6 +2258,8 @@ importConfirm: "가져온 확장은 에이전트 프로세스 안에서 에이"renderer.extension": "이 플러그인의 렌더러 모듈을 앱 창에 로드하여 메시지 작업 표시줄, 응답 추가 영역, 도구 카드, 코드 블록 렌더러, 작성기 컨트롤 등 UI 슬롯 구성 요소를 그립니다. 모듈은 PI-Desktop과 같은 문서에서 실행됩니다. 신뢰하는 코드만 활성화하세요.","provider.register":"이 플러그인이 정의한 프로바이더를 설정의 프로바이더 목록에 추가합니다. 플러그인은 엔드포인트와 모델을 제공하며, API 키는 PI-Desktop에 남습니다.",+ "provider.oauth":+ "이 플러그인이 선언된 프로바이더의 OAuth 로그인과 토큰 갱신을 수행하도록 허용합니다. PI-Desktop은 토큰을 암호화하지만 신뢰하는 콜백은 토큰을 읽을 수 있습니다. 호스트가 중개하는 네트워크 접근에는 net.fetch와 선언된 도메인이 필요하며, 플러그인 프로세스는 운영체제 샌드박스가 아닙니다. 신뢰하는 코드에만 허용하세요.","desktop.control":"플러그인이 검토된 PI-Desktop 제어 카탈로그를 호출할 수 있습니다. 파괴적 작업에는 여전히 confirm=true가 필요하며 MCP bearer token은 노출되지 않습니다.","models.list": "로그인한 모델을 볼 수 있지만 키는 받지 않습니다.",diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.tsindex 4e1e0050c..4610a8b34 100644--- a/packages/i18n/src/locales/pt-BR/index.ts+++ b/packages/i18n/src/locales/pt-BR/index.ts@@ -1415,6 +1415,9 @@ export const ptBR = {vendorAccountUpdated: "Conta de provedor atualizada",vendorRemoveAccount: "Excluir conta",vendorAccountRemoved: "Conta do {{vendor}} removida",+ vendorSignOut: "Sair",+ vendorSignedOut: "Você saiu de {{vendor}}",+ pluginOauthFailed: "O plugin não conseguiu concluir o login no provedor.",vendorLoginStarting: "Iniciando login…",vendorBrowserOpened: "Navegador aberto para autenticação.",vendorBrowserFailed: "O seu navegador não abriu — copie o link e abra-o manualmente.",@@ -2142,6 +2145,7 @@ export const ptBR = {"agent.extension": "Executar código dentro do agente","renderer.extension": "Desenhar interface nos slots do chat","provider.register": "Adicionar provedores à lista de modelos",+ "provider.oauth": "Entrar em um provedor com OAuth","desktop.control": "Controlar a área de trabalho","models.list": "Listar modelos autenticados","session.read": "Ler a conversa atual enviada ao modelo",@@ -2182,6 +2186,7 @@ export const ptBR = {"renderer.extension":"Carrega o módulo de renderização deste plugin na janela do aplicativo para desenhar componentes de slot (barras de ações de mensagens, extras de entrada, cartões de ferramentas, renderizadores de blocos de código, controles do compositor). O módulo é executado no mesmo documento do PI-Desktop. Ative somente código em que você confia.","provider.register": "Adiciona os provedores que este plugin define à lista de provedores em Configurações. O plugin fornece o endpoint e os modelos; sua chave de API permanece no PI-Desktop.",+ "provider.oauth": "Permite que este plugin faça login e renove tokens para o provedor declarado. O PI-Desktop criptografa os tokens, mas o callback confiável pode lê-los. O acesso à rede mediado pelo host ainda exige net.fetch e domínios declarados; o processo do plugin não é um sandbox do sistema operacional. Conceda apenas a código confiável.","desktop.control": "Permite que o plugin invoque o catálogo de controle revisado do PI-Desktop. Operações destrutivas ainda exigem confirm=true; o token bearer do MCP nunca é exposto.","models.list": "Pode ver em quais modelos você está conectado. Não recebe suas chaves de API.","session.read": "Pode ler a conversa em que a chamada de ferramenta atual está sendo executada, incluindo os resultados das ferramentas.",diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.tsindex 9e289f0d3..d6eaae50c 100644--- a/packages/i18n/src/locales/tr/index.ts+++ b/packages/i18n/src/locales/tr/index.ts@@ -1455,6 +1455,9 @@ sklm: {vendorAccountUpdated: "Satıcı hesabı güncellendi",vendorRemoveAccount: "Hesabı kaldır",vendorAccountRemoved: "{{vendor}} hesabı kaldırıldı",+ vendorSignOut: "Oturumu kapat",+ vendorSignedOut: "{{vendor}} oturumu kapatıldı",+ pluginOauthFailed: "Eklenti sağlayıcı oturum açma işlemini tamamlayamadı.",vendorLoginStarting: "Oturum açılıyor…",vendorBrowserOpened:"Tarayıcınızda oturum açmayı bitirin, sonra bu pencereye dönün.",@@ -2197,6 +2200,7 @@ importConfirm: "İçe aktarılan uzantılar ajan sürecinde, ajanın kendi araç"agent.extension": "Ajanın içinde kod çalıştır","renderer.extension": "Sohbet yuvalarında arayüz çiz","provider.register": "Model listesine servis ekle",+ "provider.oauth": "Bir serviste OAuth ile oturum aç","desktop.control": "Masaüstünü kontrol et","models.list": "Kimliği doğrulanmış modelleri listele","session.read": "Modele gönderilen geçerli konuşmayı oku",@@ -2244,6 +2248,8 @@ importConfirm: "İçe aktarılan uzantılar ajan sürecinde, ajanın kendi araç"renderer.extension": "Bu eklentinin işleyici modülünü uygulama penceresine yükler; mesaj eylem çubukları, yanıt ek alanları, araç kartları, kod bloğu işleyicileri ve besteleyici kontrolleri gibi arayüz yuvası bileşenleri çizer. Modül PI-Desktop ile aynı belgede çalışır. Yalnızca güvendiğiniz kodu etkinleştirin.","provider.register":"Bu eklentinin tanımladığı servisleri Ayarlar’daki servis listesine ekler. Uç noktayı ve modelleri eklenti sağlar; API anahtarınız PI-Desktop’ta kalır.",+ "provider.oauth":+ "Eklentinin, tanımladığı sağlayıcı için OAuth ile oturum açmasını ve token yenilemesini sağlar. PI-Desktop tokenları şifreler, ancak güvenilen geri çağrı bunları okuyabilir. Host üzerinden yapılan ağ erişimi için net.fetch ve tanımlı etki alanları gerekir; eklenti süreci işletim sistemi korumalı alanı değildir. Yalnızca güvendiğiniz koda verin.","desktop.control":"Eklentinin incelenmiş PI-Desktop denetim kataloğunu çağırmasını sağlar. Yıkıcı işlemler yine confirm=true gerektirir; MCP bearer token eklentiye verilmez.","models.list": "Oturum açtığınız modelleri görebilir. Anahtar almaz.",diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.tsindex 4592e6edd..a78bd2ef9 100644--- a/packages/i18n/src/locales/zh-CN/index.ts+++ b/packages/i18n/src/locales/zh-CN/index.ts@@ -1438,6 +1438,9 @@ sklm: {vendorAccountUpdated: "厂商账户已更新",vendorRemoveAccount: "移除账户",vendorAccountRemoved: "{{vendor}} 账户已移除",+ vendorSignOut: "退出登录",+ vendorSignedOut: "已退出 {{vendor}}",+ pluginOauthFailed: "插件未能完成厂商登录。",vendorLoginStarting: "正在开始登录…",vendorBrowserOpened: "请在浏览器中完成登录,然后回到此窗口。",vendorBrowserFailed: "浏览器未能打开——请复制链接自行打开。",@@ -2176,6 +2179,7 @@ sklm: {"agent.extension": "在 agent 内运行代码","renderer.extension": "在聊天插槽绘制界面","provider.register": "将服务添加到模型列表",+ "provider.oauth": "通过 OAuth 登录 Provider","desktop.control": "控制桌面操作","models.list": "列出已登录的模型","session.read": "读取当前发给模型的对话",@@ -2216,6 +2220,7 @@ sklm: {"agent.extension": "在 agent 进程内运行 ExtensionAPI 模块,拥有与 agent 自身工具相同的权限。只启用你信任的代码。","renderer.extension": "把该插件的渲染模块加载进应用窗口,在消息操作栏、回复追加区、工具卡、代码块、输入区等插槽绘制界面。模块与 PI-Desktop 同文档运行,只启用你信任的代码。","provider.register": "把此插件定义的服务添加到设置的服务列表。接口地址和模型由插件提供,API 密钥则留在 PI-Desktop 中。",+ "provider.oauth": "允许插件为自己声明的 Provider 执行 OAuth 登录和令牌刷新。PI-Desktop 会加密令牌,但受信任的回调可以读取令牌。宿主代理的网络访问仍需 net.fetch 和域名白名单;插件进程并非操作系统沙箱,只应授予可信代码。","desktop.control":"允许插件调用经过审查的 PI-Desktop 操作目录;破坏性操作仍需 confirm=true,插件永远拿不到 MCP bearer token。","models.list": "可以看到你已登录的模型,但拿不到密钥。",diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.tsindex 89f35eca0..e89e8a776 100644--- a/packages/i18n/src/locales/zh-TW/index.ts+++ b/packages/i18n/src/locales/zh-TW/index.ts@@ -1438,6 +1438,9 @@ sklm: {vendorAccountUpdated: "廠商賬戶已更新",vendorRemoveAccount: "移除賬戶",vendorAccountRemoved: "{{vendor}} 賬戶已移除",+ vendorSignOut: "登出",+ vendorSignedOut: "已登出 {{vendor}}",+ pluginOauthFailed: "外掛未能完成供應商登入。",vendorLoginStarting: "正在開始登入…",vendorBrowserOpened: "請在瀏覽器中完成登入,然後回到此視窗。",vendorBrowserFailed: "瀏覽器未能開啟——請複製連結自行開啟。",@@ -2176,6 +2179,7 @@ sklm: {"agent.extension": "在 agent 內執行程式碼","renderer.extension": "在聊天插槽繪製介面","provider.register": "將服務新增到模型列表",+ "provider.oauth": "透過 OAuth 登入 Provider","desktop.control": "控制桌面操作","models.list": "列出已登入的模型","session.read": "讀取當前發給模型的對話",@@ -2216,6 +2220,7 @@ sklm: {"agent.extension": "在 agent 程序內執行 ExtensionAPI 模組,擁有與 agent 自身工具相同的權限。只啟用你信任的程式碼。","renderer.extension": "把該外掛的渲染模組載入應用視窗,在訊息操作列、回覆追加區、工具卡、程式碼區塊、輸入區等插槽繪製介面。模組與 PI-Desktop 同文件執行,只啟用你信任的程式碼。","provider.register": "把此外掛定義的服務新增到設定的服務列表。介面地址和模型由外掛提供,API 金鑰則留在 PI-Desktop 中。",+ "provider.oauth": "允許外掛為自己宣告的 Provider 執行 OAuth 登入與權杖更新。PI-Desktop 會加密權杖,但受信任的回呼可以讀取權杖。主機代理的網路存取仍須 net.fetch 與網域白名單;外掛程序並非作業系統沙箱,只應授予可信任的程式碼。","desktop.control": "允許外掛呼叫經過審查的 PI-Desktop 操作目錄;破壞性操作仍需 confirm=true,外掛永遠拿不到 MCP bearer token。","models.list": "可以看到你已登入的模型,但拿不到金鑰。","session.read": "可以讀取當前這次工具呼叫所在會話發給模型的對話,包括工具結果。",diff --git a/packages/plugin-sdk/src/index.test.ts b/packages/plugin-sdk/src/index.test.tsindex f0330bd74..9fdf8282a 100644--- a/packages/plugin-sdk/src/index.test.ts+++ b/packages/plugin-sdk/src/index.test.ts@@ -871,15 +871,32 @@ describe("contributes.providers", () => {).toMatch(/defaultThinkingLevel must be a string/);});- it("rejects oauth, which needs a Host-owned login flow", () => {+ it("requires provider.oauth and accepts a declared OAuth provider", () => {+ const oauthProvider: PluginProviderContrib = {+ ...provider,+ authKind: "oauth",+ oauth: { loginLabel: "Continue in browser", isSubscription: true },+ };+ expect(+ validateManifest({+ ...base,+ permissions: ["provider.register"],+ contributes: { providers: [oauthProvider] },+ }).error,+ ).toMatch(/OAuth providers require the provider.oauth permission/);expect(- validateContributions({ providers: [{ ...provider, authKind: "oauth" as never }] }),- ).toMatch(/unsupported authKind oauth/);+ validateManifest({+ ...base,+ permissions: ["provider.register", "provider.oauth"],+ contributes: { providers: [oauthProvider] },+ }).ok,+ ).toBe(true);expect(validateContributions({- providers: [{ ...provider, oauth: { label: "Demo" } } as never],+ providers: [{ ...oauthProvider, oauth: { label: "Demo" } } as never],}),- ).toMatch(/not supported in this release/);+ ).toMatch(/oauth has unsupported field label/);+ expect(PLUGIN_PERMISSIONS).toContain("provider.oauth");});it("requires a name", () => {diff --git a/packages/plugin-sdk/src/index.ts b/packages/plugin-sdk/src/index.tsindex 7cd4ebe60..4a577a299 100644--- a/packages/plugin-sdk/src/index.ts+++ b/packages/plugin-sdk/src/index.ts@@ -466,15 +466,64 @@ export const PLUGIN_PROVIDER_API_STYLES = [export type PluginProviderApiStyle = (typeof PLUGIN_PROVIDER_API_STYLES)[number];/**- * Credential a contributed provider accepts. Absent means `api_key`. `oauth`- * is deliberately absent: a plugin OAuth provider needs a Host-owned login- * flow that does not exist yet, so a declaration asking for one is refused- * instead of materializing a row nobody can sign in to.+ * Credential a contributed provider accepts. Absent means `api_key`.*/-export const PLUGIN_PROVIDER_AUTH_KINDS = ["api_key", "none"] as const;+export const PLUGIN_PROVIDER_AUTH_KINDS = ["api_key", "none", "oauth"] as const;export type PluginProviderAuthKind = (typeof PLUGIN_PROVIDER_AUTH_KINDS)[number];+/** Host-rendered sign-in metadata for an OAuth provider contribution. */+export type PluginProviderOAuthContrib = {+ loginLabel?: string;+ isSubscription?: boolean;+};++/** Secret state stored encrypted by the Host and passed only to the plugin callback. */+export type PluginProviderOAuthCredential = {+ accessToken: string;+ refreshToken?: string;+ /** Unix epoch milliseconds. Omit when the access token does not expire. */+ expiresAt?: number;+ accountLabel?: string;+ headers?: Record<string, string>;+};++export type PluginProviderOAuthPrompt = {+ type: "text" | "secret" | "select" | "manual_code";+ message: string;+ placeholder?: string;+ options?: Array<{ id: string; label: string; description?: string }>;+};++/** Non-secret progress the Host may show during a plugin-owned OAuth flow. */+export type PluginProviderOAuthEvent =+ | { kind: "info"; message: string; links?: Array<{ url: string; label?: string }> }+ | { kind: "authUrl"; url: string; instructions?: string }+ | {+ kind: "deviceCode";+ userCode: string;+ verificationUri: string;+ intervalSeconds?: number;+ expiresInSeconds?: number;+ }+ | { kind: "progress"; message: string };++export type PluginProviderOAuthRequest = {+ operation: "login" | "refresh";+ /** Plugin-local provider contribution id. */+ providerId: string;+ /** Present during login; use it for Host-rendered prompts and progress. */+ loginId?: string;+ /** Present during refresh; never sent to the renderer or Agent Runtime. */+ credential?: PluginProviderOAuthCredential;+};++/** Runtime context for a provider OAuth callback. */+export type PluginProviderOAuthContext = {+ /** Aborted when the user cancels sign-in, the plugin unloads, or the call times out. */+ signal: AbortSignal;+};+/** Upper bound on `contributes.providers` entries one plugin may declare. */export const MAX_PLUGIN_PROVIDERS_PER_PLUGIN = 8;@@ -507,10 +556,10 @@ export type PluginProviderModelContrib = {};/**- * One provider a plugin adds to Settings' provider list. The plugin supplies- * the endpoint and model catalog; the user's API key stays in the host and is- * never handed to the plugin. The row appears as `plugin:<pluginId>:<id>` and- * is read-only in Settings.+ * One provider a plugin adds to Settings' provider list. The row appears as+ * `plugin:<pluginId>:<id>` and is read-only in Settings. API-key credentials+ * stay in the Host; OAuth callbacks can access only this provider's own OAuth+ * credential under the `provider.oauth` permission.*/export type PluginProviderContrib = {/** Plugin-local id matching [a-zA-Z][a-zA-Z0-9_-]{0,63}, unique per plugin. */@@ -523,6 +572,8 @@ export type PluginProviderContrib = {baseUrl?: string;apiStyle?: PluginProviderApiStyle;authKind?: PluginProviderAuthKind;+ /** OAuth sign-in metadata; valid only when `authKind` is `oauth`. */+ oauth?: PluginProviderOAuthContrib;/** 1..64 models with unique ids. */models: PluginProviderModelContrib[];};@@ -1062,6 +1113,13 @@ export type PluginHostApi = {project: {create: (input: { path: string }) => Promise<PluginProjectRecord>;};+ /** Host-rendered interaction surface for a declared OAuth provider. */+ providers: {+ oauth: {+ prompt: (loginId: string, input: PluginProviderOAuthPrompt) => Promise<string>;+ notify: (loginId: string, event: PluginProviderOAuthEvent) => Promise<void>;+ };+ };workspace: {get: () => Promise<{ path: string; name: string } | null>;};@@ -1270,6 +1328,11 @@ export type PluginHostApi = {export type PluginModule = {onLoad?: () => Promise<void> | void;onUnload?: () => Promise<void> | void;+ /** Performs OAuth login or refresh for one `contributes.providers` entry. */+ onProviderOAuth?: (+ request: PluginProviderOAuthRequest,+ context: PluginProviderOAuthContext,+ ) => Promise<PluginProviderOAuthCredential> | PluginProviderOAuthCredential;/** Optional fixed-channel operations for an isolated plugin panel. */onPanelInvoke?: (channel: string, payload: unknown) => Promise<unknown> | unknown;/**@@ -1307,6 +1370,7 @@ export const PLUGIN_PERMISSIONS = [// renderer itself. One umbrella permission, like `agent.extension`."renderer.extension","provider.register",+ "provider.oauth","desktop.control","models.list","project.create",@@ -1430,6 +1494,13 @@ export function validateManifest(raw: unknown): {) {return { ok: false, error: "contributes.providers requires the provider.register permission" };}+ if (+ !contributesError &&+ (m.contributes?.providers ?? []).some((provider) => provider?.authKind === "oauth") &&+ !(m.permissions ?? []).includes("provider.oauth")+ ) {+ return { ok: false, error: "OAuth providers require the provider.oauth permission" };+ }if (!contributesError &&m.contributes?.windowAppearance !== undefined &&@@ -1681,11 +1752,38 @@ export function validateContributions(return `provider "${provider.id}" has unsupported authKind ${provider.authKind}`;}}- // A Host-owned plugin login flow does not exist yet, so a declaration that- // asks for one is refused rather than turned into a row nobody can sign in- // to.- if ((provider as { oauth?: unknown }).oauth !== undefined) {- return `provider "${provider.id}" declares oauth; plugin OAuth providers are not supported in this release`;+ const oauth = (provider as { oauth?: unknown }).oauth;+ if (oauth !== undefined) {+ if (provider.authKind !== "oauth") {+ return `provider "${provider.id}" oauth metadata requires authKind "oauth"`;+ }+ if (!oauth || typeof oauth !== "object" || Array.isArray(oauth)) {+ return `provider "${provider.id}" oauth must be an object`;+ }+ const oauthMetadata = oauth as { loginLabel?: unknown; isSubscription?: unknown };+ const unsupportedOAuthField = Object.keys(oauthMetadata).find(+ (key) => key !== "loginLabel" && key !== "isSubscription",+ );+ if (unsupportedOAuthField) {+ return `provider "${provider.id}" oauth has unsupported field ${unsupportedOAuthField}`;+ }+ if (+ oauthMetadata.loginLabel !== undefined &&+ (typeof oauthMetadata.loginLabel !== "string" ||+ !oauthMetadata.loginLabel.trim() ||+ oauthMetadata.loginLabel.length > 128)+ ) {+ return `provider "${provider.id}" oauth.loginLabel must be a non-empty string of at most 128 characters`;+ }+ if (+ oauthMetadata.isSubscription !== undefined &&+ typeof oauthMetadata.isSubscription !== "boolean"+ ) {+ return `provider "${provider.id}" oauth.isSubscription must be a boolean`;+ }+ }+ if (provider.authKind === "oauth" && !provider.baseUrl) {+ return `provider "${provider.id}" requires baseUrl for OAuth`;}if (!Array.isArray(provider.models)) {return `provider "${provider.id}" requires models`;diff --git a/packages/shared/src/types/providers.ts b/packages/shared/src/types/providers.tsindex d96ee76d2..d0c0ecf9f 100644--- a/packages/shared/src/types/providers.ts+++ b/packages/shared/src/types/providers.ts@@ -165,7 +165,7 @@ export type OAuthLoginEvent = {/** The flow resolved a prompt on its own — e.g. the callback beat the paste box. */| { kind: "promptCancelled"; promptId: string }| { kind: "done"; providerId: string; accountLabel?: string }- | { kind: "error"; message: string }+ | { kind: "error"; message: string; code?: "PLUGIN_OAUTH_FAILED" }| { kind: "cancelled" });