Skip to content

armgit / Orkas

Public Imported from GitHub
0

Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.

Expand connector authorization and model compatibility

BlueSkyID6660eeef6b95570
diff --git a/bin/local-api-auth.cjs b/bin/local-api-auth.cjs
index e7f94a90..f6ab05df 100644
--- a/bin/local-api-auth.cjs
+++ b/bin/local-api-auth.cjs
@@ -586,8 +586,8 @@ async function authorizeEtsy(env) {
async function authorizeMercadoLibre(env) {
const { client_id: clientId, client_secret: clientSecret, redirect_uri: redirectUri } = env.credentials;
- const userId = String(env.metadata.user_id || '');
- if (!clientId || !clientSecret || !redirectUri || !/^[1-9][0-9]{0,18}$/.test(userId)) {
+ const expectedUserId = String(env.metadata.user_id || '');
+ if (!clientId || !clientSecret || !redirectUri || (expectedUserId && !/^[1-9][0-9]{0,18}$/.test(expectedUserId))) {
throw new Error('incomplete Mercado Libre authorization input');
}
const { code, verifier } = await authorizationCode(env);
@@ -598,14 +598,22 @@ async function authorizeMercadoLibre(env) {
if (!token.access_token || !token.refresh_token || !token.user_id) {
throw new Error('Mercado Libre token exchange returned incomplete credentials');
}
- if (String(token.user_id) !== userId) throw new Error('Mercado Libre authorization returned a different seller');
+ const userId = String(token.user_id);
+ if (!/^[1-9][0-9]{0,18}$/.test(userId)
+ || (typeof token.user_id !== 'string' && !Number.isSafeInteger(token.user_id))) {
+ throw new Error('Mercado Libre authorization returned an invalid seller');
+ }
+ if (expectedUserId && userId !== expectedUserId) throw new Error('Mercado Libre authorization returned a different seller');
const missing = missingScopes(token.scope, MERCADO_LIBRE_SCOPES);
if (missing.length) throw new Error(`Mercado Libre authorization is missing required scopes: ${missing.join(', ')}`);
const identity = await readJson(await fetch('https://api.mercadolibre.com/users/me', {
headers: { authorization: `Bearer ${token.access_token}`, accept: 'application/json' },
redirect: 'error', signal: AbortSignal.timeout(60_000),
}), 'Mercado Libre seller verification');
- if (String(identity.id || '') !== userId) throw new Error('Mercado Libre authorization returned a different seller');
+ if (String(identity.id || '') !== userId
+ || (typeof identity.id !== 'string' && !Number.isSafeInteger(identity.id))) {
+ throw new Error('Mercado Libre authorization returned a different seller');
+ }
return {
provider: 'mercado_libre', client_id: clientId, client_secret: clientSecret,
redirect_uri: redirectUri, access_token: token.access_token, refresh_token: token.refresh_token,
diff --git a/bin/marketplace-seller-api.cjs b/bin/marketplace-seller-api.cjs
index b97a0b9e..cf44fae3 100644
--- a/bin/marketplace-seller-api.cjs
+++ b/bin/marketplace-seller-api.cjs
@@ -36,7 +36,7 @@ function shopeeNumber(value, zero = false) {
return result;
}
-function validateSetup(provider, metadata, credentials) {
+function validateSetup(provider, metadata, credentials, discoverShop = false) {
if (!isSellerProvider(provider)) throw new Error('Unsupported seller provider');
if (provider === 'shopee') {
shopeeNumber(metadata.shop_id);
@@ -47,7 +47,8 @@ function validateSetup(provider, metadata, credentials) {
if (typeof credentials.partner_key !== 'string' || credentials.partner_key.length < 8) throw new Error('Invalid Shopee Partner Key');
} else {
// Seller Center shop codes may be alphanumeric; the API shop ID is resolved after consent.
- if (!/^[A-Za-z0-9_-]{3,64}$/.test(metadata.shop_id || '') || !['us', 'row'].includes(metadata.region)) {
+ if ((!(discoverShop && !metadata.shop_id) && !/^[A-Za-z0-9_-]{3,64}$/.test(metadata.shop_id || ''))
+ || !['us', 'row'].includes(metadata.region)) {
throw new Error('Invalid TikTok Shop code or authorization region');
}
numericId(credentials.service_id);
@@ -85,7 +86,7 @@ function apiBase(provider, metadata) {
}
function authorizeUrl(provider, metadata, credentials, state, redirectUri) {
- validateSetup(provider, metadata, credentials);
+ validateSetup(provider, metadata, credentials, true);
let url;
if (provider === 'shopee') {
const suffix = metadata.region === 'cn' ? 'cn' : metadata.region === 'br' ? 'com.br' : 'com';
@@ -228,12 +229,38 @@ async function shopIdentity(config, fetchImpl) {
return { shop_id: shop.id, shop_name: shop.name, shop_region: shop.region, shop_cipher: shop.cipher };
}
-async function authorize(provider, metadata, credentials, code, fetchImpl) {
- validateSetup(provider, metadata, credentials);
- const config = { provider, metadata, credentials };
+async function authorize(provider, metadata, credentials, code, fetchImpl, selectShop) {
+ validateSetup(provider, metadata, credentials, true);
+ const config = { provider, metadata: { ...metadata }, credentials };
config.credentials = tokensFrom(provider, await tokenRequest(config, code, false, fetchImpl), { provider, ...credentials });
- const identity = await shopIdentity(config, fetchImpl);
- config.credentials.identity = { ...identity, binding_shop_id: metadata.shop_id, region: metadata.region,
+ let identity;
+ if (provider === 'tiktok_shop' && !metadata.shop_id) {
+ const data = await tikTokRequest(config, '/authorization/202309/shops', {}, undefined, config.credentials.access_token, fetchImpl, false);
+ if (!Array.isArray(data.shops) || !data.shops.length || data.shops.length > 100) {
+ throw failure('No authorized shops are available.', 'seller_shop_mismatch');
+ }
+ // Validate identities before offering a choice; never select the first matching row.
+ const ids = new Set();
+ for (const shop of data.shops) {
+ if (!shop || typeof shop !== 'object') throw failure('Invalid authorized shop.', 'seller_shop_mismatch');
+ numericId(shop.id);
+ if (ids.has(shop.id) || typeof shop.region !== 'string' || !/^[A-Z]{2}$/.test(shop.region)
+ || typeof shop.cipher !== 'string' || !shop.cipher || typeof shop.name !== 'string' || !shop.name) {
+ throw failure('Invalid authorized shop.', 'seller_shop_mismatch');
+ }
+ ids.add(shop.id);
+ }
+ const shops = data.shops.filter(shop => (metadata.region === 'us') === (shop.region === 'US'));
+ if (!shops.length || typeof selectShop !== 'function') throw failure('Select an authorized shop in this market.', 'seller_shop_mismatch');
+ const selectedId = await selectShop(shops.map(shop => ({ id: shop.id, label: `${shop.name.slice(0, 120)} (${shop.id})` })));
+ const shop = shops.find(candidate => candidate.id === selectedId);
+ if (!shop) throw failure('The selected shop is not authorized.', 'seller_shop_mismatch');
+ config.metadata.shop_id = shop.id;
+ identity = { shop_id: shop.id, shop_name: shop.name, shop_region: shop.region, shop_cipher: shop.cipher };
+ } else {
+ identity = await shopIdentity(config, fetchImpl);
+ }
+ config.credentials.identity = { ...identity, binding_shop_id: config.metadata.shop_id, region: metadata.region,
...(provider === 'shopee' ? { environment: metadata.environment } : {}) };
return config.credentials;
}
diff --git a/resources/connectors/setup/mercado-libre-global-selling.md b/resources/connectors/setup/mercado-libre-global-selling.md
index 5431c560..6cf270f7 100644
--- a/resources/connectors/setup/mercado-libre-global-selling.md
+++ b/resources/connectors/setup/mercado-libre-global-selling.md
@@ -1,4 +1,4 @@
-<!-- setup-guide: {"auth_modes":["local_api"],"provider":"mercado_libre","catalog_reviewed_at":"2026-09-08","sources":[]} -->
+<!-- setup-guide: {"auth_modes":["local_api"],"provider":"mercado_libre","catalog_reviewed_at":"2026-09-23","sources":[]} -->
# mercado-libre-global-selling
## Entry
@@ -8,7 +8,7 @@ Global Selling → Developer Center → My applications.
Inspect the KYC-approved owner app; enable the required access and PKCE and set the supplied callback. Continue through the owner authorization, not a collaborator/operator account.
## Credentials
-Use [[field:user_id]], [[field:client_id]] and [[field:client_secret]]; owner CBT identity is not a child-marketplace Seller ID.
+Use [[field:client_id]] and [[field:client_secret]]. Leave [[field:user_id]] blank to confirm the verified owner after authorization. An optional known owner ID restricts the connection; a child-marketplace Seller ID is not the owner. Reconnecting without an ID retains the existing account binding.
## Verify
Read the authorized owner identity and compare the binding before checking business data.
diff --git a/resources/connectors/setup/tiktok-shop.md b/resources/connectors/setup/tiktok-shop.md
index f3d6c77b..1a9c683a 100644
--- a/resources/connectors/setup/tiktok-shop.md
+++ b/resources/connectors/setup/tiktok-shop.md
@@ -1,4 +1,4 @@
-<!-- setup-guide: {"auth_modes":["local_api"],"provider":"tiktok_shop","catalog_reviewed_at":"2026-09-08","sources":[]} -->
+<!-- setup-guide: {"auth_modes":["local_api"],"provider":"tiktok_shop","catalog_reviewed_at":"2026-09-23","sources":[]} -->
# tiktok-shop
## Entry
@@ -8,7 +8,7 @@ TikTok Shop Partner Center, App & Service; match [[field:region]] to the shop.
Inspect the approved seller Custom App and required seller permissions. Locate its authorization link/service before connecting; content-app developer credentials are a different integration.
## Credentials
-Use [[field:shop_id]], [[field:service_id]], [[field:app_key]] and [[field:app_secret]] from the seller app and shop.
+Use [[field:service_id]], [[field:app_key]] and [[field:app_secret]] from the seller app. Leave [[field:shop_id]] blank to choose an authorized shop in the selected market after login. An optional known shop code or ID restricts the connection. Reconnecting without an ID retains the existing shop binding.
## Verify
Read the authorized seller/shop identity. If seller-development access is absent, identify the account-manager approval dependency before asking for credentials.
diff --git a/resources/connectors/setup/woocommerce.md b/resources/connectors/setup/woocommerce.md
index dac0391a..05b2fbd6 100644
--- a/resources/connectors/setup/woocommerce.md
+++ b/resources/connectors/setup/woocommerce.md
@@ -1,14 +1,14 @@
-<!-- setup-guide: {"auth_modes":["local_api"],"provider":"woocommerce","catalog_reviewed_at":"2026-09-08","sources":[]} -->
+<!-- setup-guide: {"auth_modes":["local_api"],"provider":"woocommerce","catalog_reviewed_at":"2026-09-23","sources":["https://developer.woocommerce.com/docs/apis/rest-api/authentication/"]} -->
# woocommerce
## Entry
-The target WordPress store admin → WooCommerce → Settings → Advanced → REST API.
+Enter the target store root in [[field:store_url]] and connect. Orkas opens that store's WooCommerce authorization page; no separate provider application is needed.
## Configure
-Inspect or prepare a key for a store user with the required capabilities and Read/Write access. Preserve the one-time secret in the protected form; no separate provider OAuth app is needed.
+Sign in as a store user with the required capabilities and approve Read/Write access for Orkas. WooCommerce generates the keys and sends them through the short-lived Orkas relay; the desktop verifies the store before saving the keys encrypted locally.
## Credentials
-Use [[field:store_url]], [[field:consumer_key]] and [[field:consumer_secret]]; the URL is the store root, not an API endpoint.
+Leave [[field:consumer_key]] and [[field:consumer_secret]] empty for browser authorization. Existing Read/Write keys can still be entered together in the protected form. Keep any WordPress subdirectory in the store URL; do not enter an API endpoint.
## Verify
-Read a bounded product list. On failure, check store URL, HTTPS reachability, key permissions and the issuing user before regenerating keys.
+Read a bounded product list. On failure, check the store URL, HTTPS reachability and the authorizing user's permissions. Keys can be revoked under WooCommerce → Settings → Advanced → REST API.
diff --git a/src/core-agent/src/providers/google-native-search.ts b/src/core-agent/src/providers/google-native-search.ts
index 7e1a140d..582edc9a 100644
--- a/src/core-agent/src/providers/google-native-search.ts
+++ b/src/core-agent/src/providers/google-native-search.ts
@@ -5,8 +5,9 @@
*/
import { FunctionCallingConfigMode, GoogleGenAI, type GenerateContentParameters, type Part, type ThinkingLevel } from '@google/genai';
import { convertMessages, convertTools, mapStopReason, resolveGoogleThinkingLevel } from '@earendil-works/pi-ai/api/google-shared';
+import { normalizeContext } from '@earendil-works/pi-ai/utils/transcript';
import { sanitizeSurrogates } from '@earendil-works/pi-ai/utils/sanitize-unicode';
-import type { Model, Api, Context, AssistantMessage, AssistantMessageEvent } from '@earendil-works/pi-ai/compat';
+import type { Model, Api, Context, AssistantMessage, AssistantMessageEvent, JsonObject } from '@earendil-works/pi-ai/compat';
import type { GoogleNativeReplay } from '../shared/types.js';
export type GoogleReplayMessage = AssistantMessage & { googleNativeReplay?: GoogleNativeReplay };
@@ -39,11 +40,11 @@ export function hasGoogleNativeReplay(context: Context, model: Model<Api>): bool
}
function contentsWithReplay(model: GoogleModel, context: Context) {
- const contents = convertMessages(model, context);
+ const contents = convertMessages(model, normalizeContext(context));
const assistants = context.messages.filter(m => m.role === 'assistant');
// The canonical serializer may omit empty assistant messages. Mirror that
// selection through its exported converter instead of indexing raw history.
- const rendered = assistants.filter(m => convertMessages(model, { messages: [m] }).some(c => c.role === 'model'));
+ const rendered = assistants.filter(m => convertMessages(model, normalizeContext({ messages: [m] })).some(c => c.role === 'model'));
const nativeModels = contents.filter(c => c.role === 'model');
if (nativeModels.length !== rendered.length) throw new Error('Google history projection mismatch');
const originalIds = new Map<string, string>();
@@ -147,7 +148,7 @@ export async function* streamGoogleNativeSearch(modelInput: Model<Api>, context:
// one would break the signed native context circulated next round.
if (!call.id || !call.name || callIds.has(call.id)) throw new Error('Invalid Google function call');
callIds.add(call.id);
- const toolCall = { type: 'toolCall' as const, id: call.id, name: call.name, arguments: call.args ?? {},
+ const toolCall = { type: 'toolCall' as const, id: call.id, name: call.name, arguments: (call.args ?? {}) as JsonObject,
...(part.thoughtSignature ? { thoughtSignature: part.thoughtSignature } : {}) };
const contentIndex = output.content.length;
output.content.push(toolCall);
diff --git a/src/core-agent/src/providers/pi-provider.ts b/src/core-agent/src/providers/pi-provider.ts
index 3d41a396..8ceaa8c2 100644
--- a/src/core-agent/src/providers/pi-provider.ts
+++ b/src/core-agent/src/providers/pi-provider.ts
@@ -12,6 +12,7 @@ import {
completeSimple as piCompleteSimple,
streamSimple as piStreamSimple,
Type,
+ getEnvApiKey,
} from "@earendil-works/pi-ai/compat";
import {
getBuiltinModel,
@@ -25,6 +26,7 @@ import type {
AssistantMessage as PiAssistantMessage,
Tool as PiTool,
KnownProvider,
+ JsonObject,
} from "@earendil-works/pi-ai/compat";
import * as crypto from "node:crypto";
@@ -48,12 +50,16 @@ import {
isStorageFullError,
} from "../shared/errors.js";
import { createLogger } from "../shared/logger.js";
-import { providerCredentialFailure } from "../shared/provider-error-facts.js";
+import { providerCredentialFailure, providerErrorFacts } from "../shared/provider-error-facts.js";
import type { CompletionParams, CompletionResult, LLMProvider, ToolDefinition } from "./base.js";
+import { createResponsesStatusDiagnostics } from './responses-status-diagnostics.js';
import { createRequestDiagnostics, type ProviderFailureSource } from "./request-diagnostics.js";
+import { createProviderErrorCapture } from "./provider-error-capture.js";
import { ToolInputDiagnostics } from "./tool-input-diagnostics.js";
+import { replayOrigin, projectReplay, compatibleReplay, replayMessageSource, projectResponsesItemIds, needsDeepSeekToolReasoning, projectDeepSeekToolReasoning } from "./replay-compatibility.js";
+
const log = createLogger("pi-provider");
// Core-agent favors stable HTTP event streams over WebSocket optimizations.
@@ -160,13 +166,13 @@ function cacheSafeSessionId(s: string | undefined): string | undefined {
// ─── Type conversion helpers ──────────────────────────────────────────────
-type RuntimePiContext = PiContext & { hostMessageIndexes: number[] };
+type RuntimePiContext = PiContext & { hostMessageIndexes: number[]; foreignResponsesCalls: boolean[] };
/** pi-ai serializer rules mirrored by `restoreHostMessageRoles` (portable user
* ordering in `transform-messages`, one image trailer per contiguous tool-result
* batch in `openai-completions`). Bump only after re-checking those rules against
* the new release; `providers.test.ts` pins the installed package to this value. */
-export const MIRRORED_PI_AI_SERIALIZER_VERSION = "0.85.1";
+export const MIRRORED_PI_AI_SERIALIZER_VERSION = "0.99.1";
/** pi-ai's portable history has no developer role. Responses has one, so
* restore explicitly typed host messages at the native serialization boundary.
@@ -237,35 +243,35 @@ function buildPiContext(
messages: Message[],
systemPrompt?: string,
tools?: ToolDefinition[],
- /**
- * Current model being called. Used to stamp each replayed assistant
- * message with `api`/`provider`/`model` matching the active model so
- * pi-ai's `transformMessages` evaluates `isSameModel === true` and
- * preserves thinking blocks (with their `thinkingSignature`) intact.
- *
- * Why this matters: pi-ai's transformMessages downgrades a thinking
- * block to a plain text block whenever it judges the source model
- * differs from the current one — that path skips the reasoner-specific
- * field (`reasoning_content` / `signature`) altogether, which causes
- * DeepSeek V4 Pro to 400 with a misleading "reasoning_content in the
- * thinking mode must be passed back" error. Stamping the current model
- * here keeps the thinking block whole and lets pi-ai's openai-completions
- * converter set `assistantMsg.reasoning_content` correctly.
- *
- * Caveat: Orkas doesn't persist per-message provenance in the session
- * jsonl, so this assumes the entire conversation was generated by one
- * model. If the user mid-chat switches to a different provider whose
- * thinking signatures are incompatible (Anthropic encrypted thinking →
- * OpenAI o-series), pi-ai's safety downgrade was the right behavior;
- * we accept that mid-chat switch may produce a turn the new model
- * rejects. Per-message stamping is the proper long-term fix.
- */
- model?: { api: string; provider: string; id: string; compat?: Model<Api>["compat"] },
+ /** Target adapter identity; private state is projected per source block. */
+ model?: { api: string; provider: string; id: string; baseUrl?: string; compat?: Model<Api>["compat"] },
+ statusDiagnostics?: ReturnType<typeof createResponsesStatusDiagnostics>,
+ origin = model ? replayOrigin(model) : undefined,
): RuntimePiContext {
const piMessages: PiContext["messages"] = [];
const hostMessageIndexes: number[] = [];
let userMessageIndex = 0;
const toolNameByCallId = new Map<string, string>();
+ const foreignResponsesCalls: boolean[] = [];
+ // pi-ai 0.87.1 models deferred tools as transcript system additions. Keep
+ // these definitions out of the initial tool set so the SDK can insert them
+ // at the original tool result during replay.
+ const lateToolNames = new Set(messages.flatMap((message) => message.content.flatMap((part) =>
+ part.type === "tool_result" ? part.addedToolNames ?? [] : [])));
+ const piTools: PiTool[] | undefined = tools?.map((t) => ({
+ name: t.name,
+ description: t.description,
+ // Preserve the full JSON Schema while adding pi-ai's TypeBox marker.
+ parameters: Type.Unsafe(t.inputSchema),
+ // Only explicitly capable Responses routes receive native grammar input.
+ ...((model?.api === "openai-responses" || model?.api === "openai-codex-responses")
+ && model.compat && "supportsOpenAIGrammarTools" in model.compat
+ && model.compat.supportsOpenAIGrammarTools === true && t.constrainedSampling
+ ? { constrainedSampling: t.constrainedSampling } : {}),
+ }));
+ const toolsByName = new Map(piTools?.map((tool) => [tool.name, tool]));
+ const initialTools = piTools?.filter((tool) => !lateToolNames.has(tool.name));
+ const declaredToolNames = new Set(initialTools?.map((tool) => tool.name));
for (const msg of messages) {
if (msg.role === "system") continue;
@@ -297,6 +303,15 @@ function buildPiContext(
isError: tr.isError ?? false,
timestamp: Date.now(),
});
+ const additions = (tr.addedToolNames ?? []).flatMap((name) => {
+ const tool = toolsByName.get(name);
+ if (!tool || declaredToolNames.has(name)) return [];
+ declaredToolNames.add(name);
+ return [tool];
+ });
+ if (additions.length > 0) {
+ piMessages.push({ role: "system", content: "", toolsAdded: additions, timestamp: Date.now() });
+ }
}
// Emit user text/image content
@@ -324,7 +339,13 @@ function buildPiContext(
}
} else if (msg.role === "assistant") {
const piContent: PiAssistantMessage["content"] = [];
- for (const c of msg.content) {
+ const replaySource = model && origin ? replayMessageSource(msg.content, model, origin) : undefined;
+ for (const source of msg.content) {
+ if (statusDiagnostics && source.type === "thinking" && source.thinkingSignature) {
+ try { statusDiagnostics?.history(JSON.parse(source.thinkingSignature)); } catch { /* Legacy field names are not JSON. */ }
+ }
+ const c = model && origin ? projectReplay(source, model, origin, replaySource?.projectBlocks) : source;
+ if (!c) continue;
if (c.type === "text") {
piContent.push({
type: "text",
@@ -338,44 +359,20 @@ function buildPiContext(
continue;
}
toolNameByCallId.set(toolCallId, toolName);
+ foreignResponsesCalls.push(!!origin && !compatibleReplay(source, origin));
piContent.push({
type: "toolCall",
id: toolCallId,
name: toolName,
- arguments: c.input,
+ arguments: c.input as JsonObject,
...(c.thoughtSignature ? { thoughtSignature: c.thoughtSignature } : {}),
...(c.namespace !== undefined ? { namespace: c.namespace } : {}),
});
} else if (c.type === "thinking") {
- // Re-inject reasoning into outgoing context — required by DeepSeek
- // reasoner / Anthropic encrypted-thinking / llama.cpp gpt-oss; see
- // mapContent() for the inbound side.
- //
- // pi-ai stores `thinkingSignature` in two incompatible formats
- // depending on which provider produced the block:
- // - openai-completions adapter writes the literal field name
- // ("reasoning_content" / "reasoning" / "reasoning_text") so
- // the next-turn payload can echo `assistantMsg[signature]`
- // back as the same key.
- // - openai-responses-shared expects a JSON-encoded reasoning
- // item and does `JSON.parse(thinkingSignature)` unconditionally.
- // A cross-provider conversation (e.g. DeepSeek then gpt-5) will
- // crash the second turn with `Unexpected token 'r', "reasoning_content"
- // is not valid JSON`. Drop the signature when it would crash the
- // target adapter; losing the signature only weakens DeepSeek-style
- // "echo back" guarantees, which is acceptable cross-provider.
- const targetIsResponsesApi = model?.api === "openai-responses"
- || model?.api === "azure-openai-responses"
- || model?.api === "openai-codex-responses";
- let safeSignature = c.thinkingSignature;
- if (safeSignature && targetIsResponsesApi) {
- try { JSON.parse(safeSignature); }
- catch { safeSignature = undefined; }
- }
piContent.push({
type: "thinking",
thinking: c.thinking,
- ...(safeSignature ? { thinkingSignature: safeSignature } : {}),
+ ...(c.thinkingSignature ? { thinkingSignature: c.thinkingSignature } : {}),
...(c.redacted ? { redacted: c.redacted } : {}),
});
}
@@ -383,20 +380,17 @@ function buildPiContext(
if (piContent.length === 0) {
continue;
}
- const replay = msg.content.find(c => c.googleNativeReplay)?.googleNativeReplay;
+ const replay = msg.content.find(c => c.googleNativeReplay && (!origin || compatibleReplay(c, origin)))?.googleNativeReplay;
piMessages.push({
role: "assistant",
content: piContent,
...(replay && replay.api === model?.api && replay.provider === model.provider && replay.model === model.id
? { googleNativeReplay: replay } : {}),
- // Stamp with the current model so pi-ai's `transformMessages` sees
- // `isSameModel === true` and keeps thinking blocks (with their
- // signature) verbatim — see the param comment on `buildPiContext`.
- // Falls back to harmless placeholders only when no model is supplied
- // (utility paths like validateAuth that don't replay history).
- api: (model?.api ?? "anthropic-messages") as PiAssistantMessage["api"],
- provider: model?.provider ?? "anthropic",
- model: model?.id ?? "",
+ // Preserve the original model so pi-ai owns generic signature and
+ // tool/result conversion. The helper isolates transport/legacy cases.
+ api: (replaySource?.source.api ?? model?.api ?? "anthropic-messages") as PiAssistantMessage["api"],
+ provider: replaySource?.source.provider ?? model?.provider ?? "anthropic",
+ model: replaySource?.source.model ?? model?.id ?? "",
usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } },
stopReason: "stop",
timestamp: Date.now(),
@@ -404,30 +398,12 @@ function buildPiContext(
}
}
- // Convert tool definitions to pi-ai Tool format
- const piTools: PiTool[] | undefined = tools?.map((t) => ({
- name: t.name,
- description: t.description,
- // ToolDefinition already carries provider-ready JSON Schema. Wrapping the
- // schema keeps nested objects, array items, enums, unions, and required
- // fields intact while adding the TypeBox marker pi-ai expects. Rebuilding
- // only the top-level properties would misdeclare object inputs as strings
- // and array items as Any, teaching the model to emit invalid tool calls.
- parameters: Type.Unsafe(t.inputSchema),
- // Only explicitly capable Responses routes receive native grammar input.
- // The SDK owns declaration, streaming decode, deferred loading and replay;
- // executors and persisted messages retain their ordinary JSON arguments.
- ...((model?.api === "openai-responses" || model?.api === "openai-codex-responses")
- && model.compat && "supportsOpenAIGrammarTools" in model.compat
- && model.compat.supportsOpenAIGrammarTools === true && t.constrainedSampling
- ? { constrainedSampling: t.constrainedSampling } : {}),
- }));
-
return {
systemPrompt,
messages: piMessages,
- tools: piTools,
+ tools: initialTools,
hostMessageIndexes,
+ foreignResponsesCalls,
};
}
@@ -435,7 +411,7 @@ export function buildPiContextForTest(
messages: Message[],
systemPrompt?: string,
tools?: ToolDefinition[],
- model?: { api: string; provider: string; id: string; compat?: Model<Api>["compat"] },
+ model?: { api: string; provider: string; id: string; baseUrl?: string; compat?: Model<Api>["compat"] },
): RuntimePiContext {
return buildPiContext(messages, systemPrompt, tools, model);
}
@@ -466,10 +442,12 @@ function mapStopReason(reason: PiAssistantMessage["stopReason"]): StopReason {
* pi-ai's successful `done` envelope as proof that an empty result is safe to
* retry or switch across models.
*/
-function providerMessageError(message: PiAssistantMessage, provider: string, statusCode?: number): ProviderError {
+function providerMessageError(message: PiAssistantMessage, provider: string, statusCode?: number, original?: Error): ProviderError {
const cause = providerTerminationCategory(message.rawStopReason, message.stopReason) === 'safety'
- ? Object.assign(new Error('Provider refused generation'), { code: 'PROVIDER_EMPTY_SAFETY' })
- : undefined;
+ ? Object.assign(new Error('Provider refused generation'), { code: 'PROVIDER_EMPTY_SAFETY', cause: original })
+ : message.stopReason === 'aborted'
+ ? Object.assign(new Error('Provider request aborted'), { code: 'ABORT_ERR', cause: original })
+ : original;
return new ProviderError(message.errorMessage ?? 'Unknown provider error', provider, statusCode, cause);
}
@@ -740,10 +718,14 @@ function mapProviderContent(
content: PiAssistantMessage["content"],
normalizeLiteralLeadingThinkText = false,
replay?: GoogleNativeReplay,
+ origin?: MessageContent["replayOrigin"],
): MessageContent[] {
const mapped = mapContent(content, { stripLeadingThinkText: normalizeLiteralLeadingThinkText });
if (replay && mapped.length) mapped[0] = { ...mapped[0], googleNativeReplay: replay };
- return mapped;
+ return origin ? mapped.map(block => (block.type === 'thinking'
+ || block.type === 'text' && block.textSignature
+ || block.type === 'tool_use'
+ || block.googleNativeReplay) ? { ...block, replayOrigin: origin } : block) : mapped;
}
export const mapProviderContentForTest = mapProviderContent;
@@ -1004,11 +986,11 @@ export function createPiProvider(config: {
};
};
- const useGoogleNativeTransport = (model: Model<Api>, params: CompletionParams): boolean => {
+ const useGoogleNativeTransport = (model: Model<Api>, params: CompletionParams, origin: NonNullable<MessageContent["replayOrigin"]>): boolean => {
if (model.api !== "google-generative-ai") return false;
return config.googleNativeSearch?.(model, params.tools ?? []) === true
|| params.messages.some(message => message.role === "assistant" && message.content.some(c => {
- const replay = c.googleNativeReplay;
+ const replay = compatibleReplay(c, origin) ? c.googleNativeReplay : undefined;
return replay?.api === model.api && replay.provider === model.provider && replay.model === model.id;
}));
};
@@ -1019,20 +1001,24 @@ export function createPiProvider(config: {
async complete(params: CompletionParams): Promise<CompletionResult> {
const model = resolveModel(providerId, params.model, resolvedModel, config.baseUrl);
- const context = buildPiContext(params.messages, params.systemPrompt, params.tools, model);
+ const requestDiagnostics = createRequestDiagnostics(params.signal, params.onRequestFailure, undefined, params.requestMetadata?.contextBudgetDiagnostics);
+ const statusDiagnostics = createResponsesStatusDiagnostics(params.onRequestFailure, model,
+ requestDiagnostics.sequence, undefined);
+ const suppliedHeaders = requestHeaders(params);
+ const apiKey = config.apiKey ?? getEnvApiKey(model.provider);
+ const origin = replayOrigin(model, apiKey, suppliedHeaders);
+ const context = buildPiContext(params.messages, params.systemPrompt, params.tools, model, statusDiagnostics, origin);
const reasoning = effectiveReasoning(params.reasoning);
const sessionId = cacheSafeSessionId(params.sessionId);
const useOfficialReasoningDefaults = model.reasoning === true
&& params.reasoning === undefined
&& config.defaultReasoning === undefined;
const useProviderOutputDefault = params.requestMetadata?.outputLimitSource === "provider_default";
- const suppliedHeaders = requestHeaders(params);
const turnRouting = codexTurnRouting(model, params, config.apiKey, suppliedHeaders);
const headers = turnRouting?.headers ?? suppliedHeaders;
- const requestDiagnostics = createRequestDiagnostics(params.signal, params.onRequestFailure, undefined, params.requestMetadata?.contextBudgetDiagnostics);
- const onPayload = (useOfficialReasoningDefaults || useProviderOutputDefault || config.onPayload || context.hostMessageIndexes.length)
+ const onPayload = (statusDiagnostics || useOfficialReasoningDefaults || useProviderOutputDefault || needsDeepSeekToolReasoning(model) || config.onPayload || context.hostMessageIndexes.length || context.foreignResponsesCalls.some(Boolean))
? ((payload: unknown, hookModel: Model<Api>) => requestDiagnostics.observePayload(() => {
- payload = restoreHostMessageRoles(payload, context, hookModel);
+ payload = restoreHostMessageRoles(projectResponsesItemIds(payload, context.foreignResponsesCalls), context, hookModel);
const reasoningNormalized = useOfficialReasoningDefaults
? restoreOfficialReasoningDefaults(payload, hookModel)
: payload;
@@ -1047,38 +1033,47 @@ export function createPiProvider(config: {
// pi-ai interprets `undefined` as "keep the pre-hook payload".
// Preserve Host normalization when an observer-only hook returns
// nothing instead of accidentally restoring the generated cap.
- return transformed === undefined ? normalized : transformed;
- }))
+ const observe = (result: unknown) => {
+ const value = projectDeepSeekToolReasoning(result === undefined ? normalized : result, hookModel);
+ requestDiagnostics.observeBudget(value, hookModel.contextWindow);
+ statusDiagnostics?.payload(value);
+ return value;
+ };
+ return transformed instanceof Promise ? transformed.then(observe) : observe(transformed);
+ }).catch(errorCapture.rethrow))
: undefined;
log.debug(`complete ${providerId}/${model.id}`);
// pi-ai can flatten HTTP failures into message-only error results.
// Keep the response status local to this request for host retry policy.
+ const errorCapture = createProviderErrorCapture(
+ model.api === 'openai-responses' ? 'openai-responses'
+ : model.api === 'openai-completions' ? 'openai-completions' : undefined);
let responseErrorStatus: number | undefined;
const onResponse = (response: ProviderHttpResponse) => {
turnRouting?.observe(response);
responseErrorStatus = response.status >= 400 ? response.status : undefined;
requestDiagnostics.onResponse(response);
};
- const transportFetch = config.wrapFetch?.(requestDiagnostics.requestFetch) ?? requestDiagnostics.requestFetch;
+ const transportFetch = errorCapture.wrapFetch(config.wrapFetch?.(requestDiagnostics.requestFetch) ?? requestDiagnostics.requestFetch);
const requestFetch: typeof globalThis.fetch = async (input, init) => {
const response = await transportFetch(input, init);
onResponse(response);
return response;
};
const reportFailure = (error: unknown, aborted = false, boundary: ProviderFailureSource = 'exception') => {
- const failure = requestDiagnostics.report(error, aborted, boundary);
+ const failure = requestDiagnostics.report(error, aborted, boundary, aborted || params.signal?.aborted ? undefined : statusDiagnostics?.failure(errorCapture.rejectedInputIndex));
try { if (failure && !requestDiagnostics.observed) log.warn("provider complete failed", { ...failure }); } catch { /* Best-effort diagnostics. */ }
};
try {
let result: PiAssistantMessage;
- if (useGoogleNativeTransport(model, params)) {
+ if (useGoogleNativeTransport(model, params, origin)) {
const { streamGoogleNativeSearch } = await import('./google-native-search.js');
let completed: PiAssistantMessage | undefined;
for await (const event of streamGoogleNativeSearch(model, context, {
- apiKey: config.apiKey, headers, signal: params.signal, maxTokens: params.maxTokens,
+ apiKey, headers, signal: params.signal, maxTokens: params.maxTokens,
temperature: params.temperature, reasoning,
onPayload: onPayload ?? ((payload) => payload),
})) {
@@ -1089,7 +1084,7 @@ export function createPiProvider(config: {
result = completed;
} else if (reasoning) {
result = await piCompleteSimple(model, context, {
- apiKey: config.apiKey,
+ apiKey,
headers,
transport: CORE_AGENT_TRANSPORT,
maxRetries: 0,
@@ -1100,13 +1095,13 @@ export function createPiProvider(config: {
cacheRetention: params.cacheRetention,
sessionId,
onResponse,
- ...(model.api === 'openai-completions' || model.api === 'openai-responses' || model.api === 'openai-codex-responses'
+ ...(model.api === 'openai-completions' || model.api === 'openai-responses' || model.api === 'openai-codex-responses' || model.api === 'anthropic-messages'
? { fetch: requestFetch } : {}),
...(onPayload ? { onPayload: onPayload as any } : {}),
});
} else {
result = await piComplete(model, context, {
- apiKey: config.apiKey,
+ apiKey,
headers,
transport: CORE_AGENT_TRANSPORT,
maxRetries: 0,
@@ -1116,23 +1111,25 @@ export function createPiProvider(config: {
cacheRetention: params.cacheRetention,
sessionId,
onResponse,
- ...(model.api === 'openai-completions' || model.api === 'openai-responses' || model.api === 'openai-codex-responses'
+ ...(model.api === 'openai-completions' || model.api === 'openai-responses' || model.api === 'openai-codex-responses' || model.api === 'anthropic-messages'
? { fetch: requestFetch } : {}),
...(onPayload ? { onPayload: onPayload as any } : {}),
});
}
- if (result.stopReason === "aborted") reportFailure(result, true, "sdk_error");
- if (result.stopReason === "error") {
- reportFailure(result, false, "sdk_error");
- throw providerMessageError(result, providerId, responseErrorStatus);
+ if (result.stopReason === "error" || result.stopReason === "aborted") {
+ const error = providerMessageError(result, providerId, responseErrorStatus, errorCapture.cause(result.errorMessage));
+ reportFailure(error, result.stopReason === "aborted", "sdk_error");
+ throw error;
}
+ statusDiagnostics?.output(result.content, result.rawStopReason);
return {
content: mapProviderContent(
result.content,
config.normalizeLiteralLeadingThinkText === true,
(result as PiAssistantMessage & { googleNativeReplay?: GoogleNativeReplay }).googleNativeReplay,
+ origin,
),
stopReason: mapStopReason(result.stopReason),
usage: mapUsage(result.usage),
@@ -1146,35 +1143,42 @@ export function createPiProvider(config: {
async *stream(params: CompletionParams): AsyncIterable<StreamEvent> {
const model = resolveModel(providerId, params.model, resolvedModel, config.baseUrl);
- const context = buildPiContext(params.messages, params.systemPrompt, params.tools, model);
+ const requestDiagnostics = createRequestDiagnostics(params.signal, params.onRequestFailure, undefined, params.requestMetadata?.contextBudgetDiagnostics);
+ const statusDiagnostics = createResponsesStatusDiagnostics(params.onRequestFailure, model,
+ requestDiagnostics.sequence, undefined);
+ const suppliedHeaders = requestHeaders(params);
+ const apiKey = config.apiKey ?? getEnvApiKey(model.provider);
+ const origin = replayOrigin(model, apiKey, suppliedHeaders);
+ const context = buildPiContext(params.messages, params.systemPrompt, params.tools, model, statusDiagnostics, origin);
const reasoning = effectiveReasoning(params.reasoning);
const sessionId = cacheSafeSessionId(params.sessionId);
const useOfficialReasoningDefaults = model.reasoning === true
&& params.reasoning === undefined
&& config.defaultReasoning === undefined;
- const suppliedHeaders = requestHeaders(params);
const turnRouting = codexTurnRouting(model, params, config.apiKey, suppliedHeaders);
const headers = turnRouting?.headers ?? suppliedHeaders;
+ const errorCapture = createProviderErrorCapture(
+ model.api === 'openai-responses' ? 'openai-responses'
+ : model.api === 'openai-completions' ? 'openai-completions' : undefined);
let responseErrorStatus: number | undefined;
- const requestDiagnostics = createRequestDiagnostics(params.signal, params.onRequestFailure, undefined, params.requestMetadata?.contextBudgetDiagnostics);
const onResponse = (response: ProviderHttpResponse) => {
turnRouting?.observe(response);
responseErrorStatus = response.status >= 400 ? response.status : undefined;
requestDiagnostics.onResponse(response);
};
- const transportFetch = config.wrapFetch?.(requestDiagnostics.requestFetch) ?? requestDiagnostics.requestFetch;
+ const transportFetch = errorCapture.wrapFetch(config.wrapFetch?.(requestDiagnostics.requestFetch) ?? requestDiagnostics.requestFetch);
const requestFetch: typeof globalThis.fetch = async (input, init) => {
const response = await transportFetch(input, init);
onResponse(response);
return response;
};
const reportFailure = (error: unknown, aborted = false, boundary: ProviderFailureSource = 'exception') => {
- const failure = requestDiagnostics.report(error, aborted, boundary);
+ const failure = requestDiagnostics.report(error, aborted, boundary, aborted || params.signal?.aborted ? undefined : statusDiagnostics?.failure(errorCapture.rejectedInputIndex));
try { if (failure && !requestDiagnostics.observed) log.warn("provider stream failed", { ...failure }); } catch { /* Best-effort diagnostics. */ }
};
let effectiveMaxTokens: number | undefined;
const onPayload = (payload: unknown, hookModel: Model<Api>): Promise<unknown> => requestDiagnostics.observePayload(async () => {
- payload = restoreHostMessageRoles(payload, context, hookModel);
+ payload = restoreHostMessageRoles(projectResponsesItemIds(payload, context.foreignResponsesCalls), context, hookModel);
const reasoningNormalized = useOfficialReasoningDefaults
? restoreOfficialReasoningDefaults(payload, hookModel)
: payload;
@@ -1188,12 +1192,14 @@ export function createPiProvider(config: {
: normalized;
// pi-ai treats an undefined hook result as "keep the pre-hook
// payload". Observer-only hooks must not undo Host normalization.
- const finalPayload = transformed === undefined ? normalized : transformed;
+ const finalPayload = projectDeepSeekToolReasoning(transformed === undefined ? normalized : transformed, hookModel);
// Observe that exact final shape so this is an on-wire value, not a
// model-catalog guess made before context and adapter adjustments.
effectiveMaxTokens = effectiveMaxTokensFromPayload(finalPayload);
+ requestDiagnostics.observeBudget(finalPayload, hookModel.contextWindow);
+ statusDiagnostics?.payload(finalPayload);
return finalPayload;
- });
+ }).catch(errorCapture.rethrow);
log.debug(`stream ${providerId}/${model.id}`);
@@ -1213,14 +1219,14 @@ export function createPiProvider(config: {
}
if (activity.ended) yield { type: "thinking_end" };
};
- const eventStream = useGoogleNativeTransport(model, params)
+ const eventStream = useGoogleNativeTransport(model, params, origin)
? (await import('./google-native-search.js')).streamGoogleNativeSearch(model, context, {
- apiKey: config.apiKey, headers, signal: params.signal, maxTokens: params.maxTokens,
+ apiKey, headers, signal: params.signal, maxTokens: params.maxTokens,
temperature: params.temperature, reasoning, onPayload,
})
: reasoning
? piStreamSimple(model, context, {
- apiKey: config.apiKey,
+ apiKey,
headers,
transport: CORE_AGENT_TRANSPORT,
maxRetries: 0,
@@ -1231,12 +1237,12 @@ export function createPiProvider(config: {
cacheRetention: params.cacheRetention,
sessionId,
onResponse,
- ...(model.api === 'openai-completions' || model.api === 'openai-responses' || model.api === 'openai-codex-responses'
+ ...(model.api === 'openai-completions' || model.api === 'openai-responses' || model.api === 'openai-codex-responses' || model.api === 'anthropic-messages'
? { fetch: requestFetch } : {}),
onPayload: onPayload as any,
})
: piStream(model, context, {
- apiKey: config.apiKey,
+ apiKey,
headers,
transport: CORE_AGENT_TRANSPORT,
maxRetries: 0,
@@ -1246,7 +1252,7 @@ export function createPiProvider(config: {
cacheRetention: params.cacheRetention,
sessionId,
onResponse,
- ...(model.api === 'openai-completions' || model.api === 'openai-responses' || model.api === 'openai-codex-responses'
+ ...(model.api === 'openai-completions' || model.api === 'openai-responses' || model.api === 'openai-codex-responses' || model.api === 'anthropic-messages'
? { fetch: requestFetch } : {}),
onPayload: onPayload as any,
});
@@ -1313,6 +1319,7 @@ export function createPiProvider(config: {
yield { type: "tool_use_end", id: event.toolCall.id };
break;
case "done":
+ statusDiagnostics?.output(event.message.content, event.message.rawStopReason);
{
const text = leadingThinkFilter?.finish() || "";
yield* takeLeadingThinkEvents();
@@ -1327,6 +1334,7 @@ export function createPiProvider(config: {
event.message.content,
config.normalizeLiteralLeadingThinkText === true,
(event.message as PiAssistantMessage & { googleNativeReplay?: GoogleNativeReplay }).googleNativeReplay,
+ origin,
),
model: resolvedResponseModel(event.message, model.id),
reasoningBoundary: {
@@ -1351,10 +1359,11 @@ export function createPiProvider(config: {
}
const errorServerFallbackReason = serverFallbackReasonFromResponseId(event.error.responseId);
const responseModel = resolvedResponseModel(event.error, model.id);
- reportFailure(event.error, event.error.stopReason === "aborted", "sdk_error");
+ const error = providerMessageError(event.error, providerId, responseErrorStatus, errorCapture.cause(event.error.errorMessage));
+ reportFailure(error, event.error.stopReason === "aborted", "sdk_error");
yield {
type: "error",
- error: wrapError(providerMessageError(event.error, providerId, responseErrorStatus), providerId),
+ error: wrapError(error, providerId),
...(responseModel ? { model: responseModel } : {}),
...(errorServerFallbackReason ? { serverFallbackReason: errorServerFallbackReason } : {}),
};
@@ -1503,25 +1512,6 @@ function retryAfterMsFrom(err: unknown): number | undefined {
return undefined;
}
-/** Decode the machine error code retained in pi-ai's serialized API error.
- * Accept a complete JSON error body, optionally prefixed by the SDK's HTTP
- * 400 status. This never inspects assistant text or guesses from prose. */
-function hasSerializedContextOverflowCode(message: string): boolean {
- let body = message.trim();
- if (body.startsWith("400:")) body = body.slice(4).trim();
- else if (body.startsWith("400 ")) body = body.slice(4).trim();
- if (!body.startsWith("{")) return false;
- try {
- const parsed = JSON.parse(body) as Record<string, unknown>;
- const detail = parsed.error && typeof parsed.error === "object" && !Array.isArray(parsed.error)
- ? parsed.error as Record<string, unknown>
- : parsed;
- return detail.code === "context_length_exceeded";
- } catch {
- return false;
- }
-}
-
/** Wrap pi-ai errors into our error hierarchy.
*
* Always preserves the original error as `.cause` so downstream consumers
@@ -1534,9 +1524,10 @@ function hasSerializedContextOverflowCode(message: string): boolean {
function wrapError(err: unknown, providerId: string): Error {
if (err instanceof StorageFullError) return err;
- const original = err instanceof Error ? err : undefined;
+ const original = err instanceof Error ? err : err && typeof err === 'object'
+ ? Object.assign(new Error('Provider error'), { cause: err }) : undefined;
const msg = err instanceof Error ? err.message : String(err);
- if (isStorageFullError(err)) {
+ if (isStorageFullError(err, false)) {
return new StorageFullError(msg, original);
}
@@ -1544,27 +1535,19 @@ function wrapError(err: unknown, providerId: string): Error {
return err;
}
- if (err instanceof ProviderError) {
- if (hasSerializedContextOverflowCode(msg)) {
- return new ContextOverflowError(`${providerId} context overflow: ${msg}`, original);
- }
- return err;
+ const facts = providerErrorFacts(err, false);
+ if (facts.codes.some(code => code === 'context_length_exceeded' || code === 'CONTEXT_OVERFLOW')) {
+ return new ContextOverflowError(`${providerId} context overflow: ${msg}`, original);
}
+ if (err instanceof ProviderError) return err;
- const credentialKind = providerCredentialFailure(err);
+ const credentialKind = providerCredentialFailure(err, false);
if (credentialKind === 'auth') return new AuthError(msg, original);
if (credentialKind === 'rate_limit') return new RateLimitError(msg, retryAfterMsFrom(err), original);
- const msgLower = msg.toLowerCase();
- if (msgLower.includes("context") && (msgLower.includes("overflow") || msgLower.includes("too long") || msgLower.includes("maximum"))) {
- return new ContextOverflowError(`${providerId} context overflow: ${msg}`, original);
- }
-
// Generic ProviderError — try to forward `status` from the underlying
// SDK error (Anthropic / OpenAI both expose `.status` on APIError).
- const status = original && typeof (original as any).status === 'number'
- ? (original as any).status as number
- : undefined;
+ const status = facts.status;
return new ProviderError(msg, providerId, status, original);
}
diff --git a/src/core-agent/src/providers/replay-compatibility.ts b/src/core-agent/src/providers/replay-compatibility.ts
new file mode 100644
index 00000000..3e5f84b6
--- /dev/null
+++ b/src/core-agent/src/providers/replay-compatibility.ts
@@ -0,0 +1,130 @@
+import { createHash } from 'node:crypto';
+import type { MessageContent } from '../shared/types.js';
+
+type Origin = NonNullable<MessageContent['replayOrigin']>;
+type Target = { api: string; provider: string; id: string; baseUrl?: string; headers?: Record<string, string>; compat?: unknown };
+
+/** The configured DeepSeek adapter uses Chat Completions. Do not infer this
+ * requirement from model aliases or thinkingFormat (also used by Moonshot). */
+export function needsDeepSeekToolReasoning(model: Target & { reasoning?: boolean }): boolean {
+ if (model.api !== 'openai-completions' || model.reasoning !== true) return false;
+ if (model.provider === 'deepseek') return true;
+ try { return new URL(model.baseUrl ?? '').hostname === 'api.deepseek.com'; }
+ catch { return false; }
+}
+
+/** pi-ai supplies an empty Chat reasoning_content after foreign private state
+ * is omitted. Use the accepted nonempty placeholder only on tool-call messages;
+ * preserve real reasoning, explicit off, and the immutable session history.
+ * This restores wire compatibility, not the missing private reasoning. */
+export function projectDeepSeekToolReasoning(payload: unknown, model: Target & { reasoning?: boolean }): unknown {
+ if (!needsDeepSeekToolReasoning(model) || !payload || typeof payload !== 'object' || Array.isArray(payload)) return payload;
+ const body = payload as { thinking?: { type?: string }; reasoning_effort?: string; messages?: unknown };
+ if (body.thinking?.type === 'disabled' || body.reasoning_effort === 'none' || body.reasoning_effort === 'off'
+ || !Array.isArray(body.messages)) return payload;
+ let changed = false;
+ const messages = body.messages.map(message => {
+ if (!message || message.role !== 'assistant' || !Array.isArray(message.tool_calls) || !message.tool_calls.length
+ || typeof message.reasoning_content === 'string' && message.reasoning_content.length > 0) return message;
+ changed = true;
+ // pi-ai may replay portable plaintext under the source Chat field name.
+ const portable = [message.reasoning, message.reasoning_text]
+ .find(value => typeof value === 'string' && value.length > 0);
+ return { ...message, reasoning_content: portable ?? '.' };
+ });
+ return changed ? { ...body, messages } : payload;
+}
+
+/** Fingerprint routing/credentials without persisting their values. This is
+ * compatibility metadata, not a signature, cryptographic key or permission. */
+export function replayOrigin(model: Target, apiKey?: string, headers?: Record<string, string>): Origin {
+ return { version: 1, source: { api: model.api, provider: model.provider, model: model.id }, scope: createHash('sha256').update(JSON.stringify([
+ model.api, model.provider, model.id, model.baseUrl ?? '', apiKey ?? '', model.compat ?? null,
+ Object.entries({ ...model.headers, ...headers }).map(([k, v]) => [k.toLowerCase(), v])
+ .filter(([name]) => name !== 'x-request-id').sort(),
+ ])).digest('hex') };
+}
+
+export function compatibleReplay(content: MessageContent, target: Origin): boolean {
+ return content.replayOrigin?.version === 1 && content.replayOrigin.scope === target.scope;
+}
+
+function portableChatThinking(content: MessageContent, model: Target): boolean {
+ return content.type === 'thinking' && model.api === 'openai-completions' && !content.redacted
+ && !!content.thinking && ['reasoning_content', 'reasoning', 'reasoning_text'].includes(content.thinkingSignature ?? '');
+}
+
+/** pi-ai owns ordinary cross-model conversion. Only merged source blocks and
+ * the legacy plaintext Chat contract need per-block projection: pi-ai's source
+ * identity is message-wide and would otherwise discard valid sibling state. */
+export function replayMessageSource(content: MessageContent[], model: Target, target: Origin) {
+ const scoped = content.filter(c => c.replayOrigin || c.type === 'thinking' || c.type === 'tool_use'
+ || c.type === 'text' && c.textSignature || c.googleNativeReplay);
+ const first = scoped[0]?.replayOrigin;
+ const projectBlocks = scoped.some(c => c.replayOrigin?.scope !== first?.scope)
+ || scoped.some(c => !compatibleReplay(c, target) && portableChatThinking(c, model));
+ const current = { api: model.api, provider: model.provider, model: model.id };
+ if (projectBlocks) return { source: current, projectBlocks };
+ const same = first?.version === 1 && first.scope === target.scope;
+ const persisted = first?.version === 1 ? first.source : undefined;
+ const known = persisted && [persisted.api, persisted.provider, persisted.model]
+ .every(value => typeof value === 'string' && value.length > 0);
+ const source = known ? persisted : (same ? current : { ...current, provider: 'orkas-replay-unknown', model: '' });
+ // pi-ai cannot distinguish endpoints/accounts with identical model names.
+ // Mark only that transport mismatch foreign; preserve known model identities.
+ return { source: !same && source.api === model.api && source.provider === model.provider && source.model === model.id
+ ? { ...source, provider: 'orkas-replay-incompatible' } : source, projectBlocks };
+}
+
+/** Project only private protocol state; canonical history stays untouched.
+ * Legacy plaintext Chat reasoning fields are portable, unlike opaque blobs. */
+export function projectReplay(content: MessageContent, model: Target, target: Origin, projectBlocks = false): MessageContent | undefined {
+ const same = compatibleReplay(content, target);
+ if (content.type === 'thinking') {
+ if (!same) {
+ if (portableChatThinking(content, model)) {
+ return { type: 'thinking', thinking: content.thinking, thinkingSignature: content.thinkingSignature };
+ }
+ return undefined;
+ }
+ if (['openai-responses', 'openai-codex-responses', 'azure-openai-responses'].includes(model.api)) {
+ try {
+ const item = JSON.parse(content.thinkingSignature ?? '');
+ if (!item || typeof item !== 'object' || Array.isArray(item) || item.type !== 'reasoning') return undefined;
+ // Direct Responses endpoints reject private relay metadata.
+ const { status: _status, ...input } = item;
+ delete input._orkas_replay;
+ return { ...content, thinkingSignature: JSON.stringify(input) };
+ } catch { return undefined; }
+ }
+ return content;
+ }
+ // For ordinary single-source messages pi-ai removes foreign text/tool
+ // signatures. Do not maintain a second generic conversion implementation.
+ if (same || !projectBlocks) return content;
+ if (content.type === 'text') {
+ const { textSignature: _signature, googleNativeReplay: _replay, ...rest } = content;
+ return rest;
+ }
+ if (content.type === 'tool_use') {
+ const { thoughtSignature: _signature, googleNativeReplay: _replay, ...rest } = content;
+ return rest;
+ }
+ return content;
+}
+
+/** pi-ai 0.87.1 normalizes call/result ids, but may synthesize fc_* item ids
+ * for foreign custom calls. Remove only provider-owned item identity after its
+ * converter has paired receipts; never rewrite call_id or canonical history. */
+export function projectResponsesItemIds(payload: unknown, foreignCalls: boolean[]): unknown {
+ if (!foreignCalls.some(Boolean) || !payload || typeof payload !== 'object') return payload;
+ const body = payload as { input?: unknown };
+ if (!Array.isArray(body.input)) return payload;
+ let callIndex = 0;
+ return { ...body, input: body.input.map(item => {
+ if (!item || (item.type !== 'function_call' && item.type !== 'custom_tool_call')) return item;
+ if (!foreignCalls[callIndex++]) return item;
+ const { id: _id, namespace: _namespace, ...portable } = item;
+ return portable;
+ }) };
+}
diff --git a/src/core-agent/test/providers.test.ts b/src/core-agent/test/providers.test.ts
index 3fcb9fa4..85e64b13 100644
--- a/src/core-agent/test/providers.test.ts
+++ b/src/core-agent/test/providers.test.ts
@@ -1,16 +1,305 @@
-import { Session } from "../src/agent/session.js";
-import type { CompletionParams } from "../src/providers/base.js";
-import * as fs from "node:fs";
-import { MIRRORED_PI_AI_SERIALIZER_VERSION, restoreHostMessageRoles, assistantTextPhaseFromSignatureForTest } from "../src/providers/pi-provider.js";
-import type { StreamEvent } from "../src/shared/types.js";
+import { replayOrigin } from "../src/providers/replay-compatibility.js";
import { describe, it, expect, vi } from "vitest";
import { ProviderRegistry } from "../src/providers/registry.js";
-import { buildPiContextForTest, createAnthropicProvider, createLeadingThinkTextFilterForTest, createOpenAIProvider, createPiProvider, effectiveMaxTokensFromPayloadForTest, listPiProviders, listPiModels, mapContentForTest, mapProviderContentForTest, normalizeReasoningForProvider, providerTerminationCategoryForTest, resolvedResponseModelForTest, restoreOfficialReasoningDefaultsForTest, serverFallbackReasonFromResponseIdForTest, stripLeadingThinkTextForTest } from "../src/providers/pi-provider.js";
+import { assistantTextPhaseFromSignatureForTest, buildPiContextForTest, createAnthropicProvider, createLeadingThinkTextFilterForTest, createOpenAIProvider, createPiProvider, effectiveMaxTokensFromPayloadForTest, listPiProviders, listPiModels, mapContentForTest, mapProviderContentForTest, normalizeReasoningForProvider, providerTerminationCategoryForTest, resolvedResponseModelForTest, restoreOfficialReasoningDefaultsForTest, retryAfterMsFromForTest, serverFallbackReasonFromResponseIdForTest, stripLeadingThinkTextForTest, useProviderDefaultOutputLimitForTest, wrapErrorForTest } from "../src/providers/pi-provider.js";
+import { AuthError, ContextOverflowError, ProviderError, RateLimitError, classifyRetryableError } from "../src/shared/errors.js";
import { createConfig } from "../src/config/loader.js";
-import type { Message, MessageContent } from "../src/shared/types.js";
+import type { CompletionParams } from "../src/providers/base.js";
+import type { Message, MessageContent, StreamEvent } from "../src/shared/types.js";
import type { Model } from "@earendil-works/pi-ai";
+import { Session } from "../src/agent/session.js";
+import { MIRRORED_PI_AI_SERIALIZER_VERSION, restoreHostMessageRoles } from "../src/providers/pi-provider.js";
+import * as fs from "node:fs";
describe("Providers (pi-ai backed)", () => {
+ it.each([
+ ['complete', 'openai-completions'], ['stream', 'openai-completions'],
+ ['complete', 'openai-responses'], ['stream', 'openai-responses'],
+ ] as const)('retains stream rejection codes in diagnostics without changing failure delivery: %s / %s', async (method, api) => {
+ const provider = createPiProvider({ provider: 'custom', apiKey: 'fixture', customModel: {
+ id: 'fixture', name: 'fixture', provider: 'custom', api,
+ baseUrl: 'https://fixture.invalid/v1', reasoning: false, input: ['text'],
+ contextWindow: 128000, maxTokens: 4096,
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
+ } });
+ const failures: any[] = [];
+ try {
+ for (const code of ['invalid_request_error', 'PRIVATE_CODE']) {
+ const detail = { code, message: 'PRIVATE: context_length_exceeded' };
+ const envelope = api === 'openai-responses' ? { type: 'error', ...detail } : { error: detail };
+ const fetchStub = vi.fn(async () => new Response('data: ' + JSON.stringify(envelope) + '\n\n', {
+ status: 200, headers: { 'content-type': 'text/event-stream' },
+ }));
+ vi.stubGlobal('fetch', fetchStub);
+ const params: CompletionParams = { messages: [{ role: 'user', content: [{ type: 'text', text: 'probe' }] }],
+ onRequestFailure: failure => failures.push(failure) };
+ let delivered: unknown;
+ if (method === 'complete') {
+ try { await provider.complete(params); } catch (error) { delivered = error; }
+ } else {
+ const events: StreamEvent[] = [];
+ for await (const event of provider.stream(params)) events.push(event);
+ expect(events.filter(event => event.type === 'error')).toHaveLength(1);
+ expect(events.some(event => event.type === 'message_end')).toBe(false);
+ delivered = events.find(event => event.type === 'error')?.error;
+ }
+ expect(delivered).toBeInstanceOf(ProviderError);
+ expect((delivered as Error).message).toContain(detail.message);
+ expect(fetchStub).toHaveBeenCalledTimes(1);
+ if (code === 'invalid_request_error') expect(classifyRetryableError(delivered)).toBeNull();
+ expect(failures.at(-1)).toMatchObject({ phase: 'after_response', httpStatus: 200,
+ source: 'sdk_error', code: code === 'PRIVATE_CODE' ? 'unknown' : code });
+ }
+ expect(failures).toHaveLength(2);
+ expect(JSON.stringify(failures)).not.toContain('PRIVATE');
+ } finally { vi.unstubAllGlobals(); }
+ });
+
+ it('isolates concurrent request failures and cannot lose the original error to a broken observer', async () => {
+ const warning = vi.spyOn(console, 'warn').mockImplementation(() => { throw new Error('broken logger'); });
+ const token = Buffer.from(JSON.stringify({ 'https://api.openai.com/auth': { chatgpt_account_id: 'fixture' } })).toString('base64url');
+ const provider = createPiProvider({ provider: 'openai-codex', model: 'gpt-5.5', apiKey: `fixture.${token}.fixture` });
+ let release!: () => void;
+ let entered!: () => void;
+ const started = new Promise<void>(resolve => { entered = resolve; });
+ const gate = new Promise<void>(resolve => { release = resolve; });
+ let calls = 0;
+ vi.stubGlobal('fetch', vi.fn(async () => {
+ if (++calls === 1) {
+ entered(); await gate;
+ throw new TypeError('fetch failed', { cause: Object.assign(new Error('private'), { code: 'ECONNRESET' }) });
+ }
+ return new Response('private', { status: 503 });
+ }));
+ const first: any[] = [], second: any[] = [];
+ const params: CompletionParams = { model: 'gpt-5.5', messages: [{ role: 'user', content: [{ type: 'text', text: 'probe' }] }] };
+ try {
+ const firstCall = provider.complete({ ...params, requestMetadata: { orkasRequestId: 'a'.repeat(32) }, onRequestFailure: failure => {
+ first.push(failure); throw new Error('broken observer');
+ } }).catch(error => error);
+ await started;
+ const secondError = await provider.complete({ ...params, requestMetadata: { orkasRequestId: 'b'.repeat(32) }, onRequestFailure: failure => second.push(failure) }).catch(error => error);
+ release();
+ const firstError = await firstCall;
+ expect(firstError.message).toBe('fetch failed');
+ expect(secondError.statusCode).toBe(503);
+ expect(first).toMatchObject([{ code: 'ECONNRESET', phase: 'before_response', elapsedMs: expect.any(Number), aborted: false }]);
+ expect(second).toMatchObject([{ code: 'unknown', phase: 'after_response', httpStatus: 503, elapsedMs: expect.any(Number), aborted: false }]);
+ expect(first[0].requestRef).toBeUndefined();
+ expect(second[0].requestRef).toBeUndefined();
+ expect(calls).toBe(2);
+ } finally { release?.(); vi.unstubAllGlobals(); warning.mockRestore(); }
+ });
+
+ it.each(['aborted', 'body_failure'] as const)('records %s without guessing a flattened cause or retrying', async mode => {
+ const warning = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const token = Buffer.from(JSON.stringify({ 'https://api.openai.com/auth': { chatgpt_account_id: 'fixture' } })).toString('base64url');
+ const provider = createPiProvider({ provider: 'openai-codex', model: 'gpt-5.5', apiKey: `fixture.${token}.fixture` });
+ const controller = new AbortController();
+ const fetchStub = vi.fn(async () => {
+ if (mode === 'aborted') {
+ controller.abort(); throw new DOMException('private-canary', 'AbortError');
+ }
+ return new Response(new ReadableStream({ start(stream) {
+ stream.error(new TypeError('private-canary', { cause: { code: 'ECONNRESET' } }));
+ } }), { status: 200, headers: { 'content-type': 'text/event-stream' } });
+ });
+ vi.stubGlobal('fetch', fetchStub);
+ const failures: any[] = [];
+ try {
+ const events: StreamEvent[] = [];
+ for await (const event of provider.stream({ model: 'gpt-5.5', messages: [{ role: 'user', content: [{ type: 'text', text: 'probe' }] }],
+ signal: controller.signal, onRequestFailure: failure => failures.push(failure) })) events.push(event);
+ expect(events.filter(event => event.type === 'error')).toHaveLength(1);
+ if (mode === 'aborted') {
+ const error = events.find(event => event.type === 'error');
+ expect(classifyRetryableError(error?.type === 'error' ? error.error : undefined)).toBeNull();
+ }
+ expect(events.filter(event => event.type === 'message_end')).toHaveLength(0);
+ expect(failures).toMatchObject([{ phase: mode === 'aborted' ? 'before_response' : 'after_response',
+ code: 'unknown', aborted: mode === 'aborted', elapsedMs: expect.any(Number),
+ ...(mode === 'body_failure' ? { httpStatus: 200 } : {}),
+ }]);
+ expect(fetchStub).toHaveBeenCalledTimes(1);
+ expect(JSON.stringify(warning.mock.calls)).not.toContain('private-canary');
+ } finally { vi.unstubAllGlobals(); warning.mockRestore(); }
+ });
+
+ it('rejects complete() when the SDK stops with aborted instead of returning partial content', async () => {
+ const warning = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const token = Buffer.from(JSON.stringify({ 'https://api.openai.com/auth': { chatgpt_account_id: 'fixture' } })).toString('base64url');
+ const provider = createPiProvider({ provider: 'openai-codex', model: 'gpt-5.5', apiKey: `fixture.${token}.fixture` });
+ const controller = new AbortController();
+ vi.stubGlobal('fetch', vi.fn(async () => { controller.abort(); throw new DOMException('private-canary', 'AbortError'); }));
+ const failures: any[] = [];
+ try {
+ const error = await provider.complete({
+ model: 'gpt-5.5', messages: [{ role: 'user', content: [{ type: 'text', text: 'probe' }] }],
+ signal: controller.signal, onRequestFailure: failure => failures.push(failure),
+ }).then(() => null, err => err);
+ expect(error).toBeInstanceOf(Error);
+ expect(classifyRetryableError(error)).toBeNull();
+ expect(failures).toMatchObject([{ phase: 'before_response', code: 'unknown', aborted: true, elapsedMs: expect.any(Number) }]);
+ expect(JSON.stringify(warning.mock.calls)).not.toContain('private-canary');
+ } finally { vi.unstubAllGlobals(); warning.mockRestore(); }
+ });
+
+ it.each(['complete', 'stream'] as const)('keeps distinct pre-response causes through the real SDK in %s diagnostics', async (method) => {
+ const warning = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const token = Buffer.from(JSON.stringify({ 'https://api.openai.com/auth': { chatgpt_account_id: 'fixture' } })).toString('base64url');
+ const provider = createPiProvider({ provider: 'openai-codex', model: 'gpt-5.5', apiKey: `fixture.${token}.fixture` });
+ const failures: any[] = [];
+ try {
+ for (const code of ['ECONNRESET', 'ENOTFOUND', 'CERT_HAS_EXPIRED', 'private-canary']) {
+ const cause = Object.assign(new Error('private-canary'), { code });
+ const fetchStub = vi.fn(async () => { throw new TypeError('fetch failed', { cause }); });
+ vi.stubGlobal('fetch', fetchStub);
+ const params = { model: 'gpt-5.5', messages: [{ role: 'user', content: [{ type: 'text', text: 'probe' }] }],
+ onRequestFailure: (failure: any) => { failures.push(failure); } } as CompletionParams;
+ let error: unknown;
+ if (method === 'complete') {
+ try { await provider.complete(params); } catch (err) { error = err; }
+ } else {
+ for await (const event of provider.stream(params)) if (event.type === 'error') error = event.error;
+ }
+ expect(fetchStub).toHaveBeenCalledTimes(1);
+ expect(classifyRetryableError(error)).toBe(code === 'ECONNRESET' ? 'connection_dropped' : 'network');
+ expect(failures.at(-1)).toMatchObject({ phase: 'before_response', code: code === 'private-canary' ? 'unknown' : code, aborted: false });
+ expect(failures.at(-1).elapsedMs).toBeGreaterThanOrEqual(0);
+ }
+ expect(failures).toHaveLength(4);
+ expect(JSON.stringify(failures)).not.toContain('private-canary');
+ expect(JSON.stringify(warning.mock.calls)).not.toContain('private-canary');
+ expect(failures.map(failure => failure.code)).toContain('ECONNRESET');
+ } finally { vi.unstubAllGlobals(); warning.mockRestore(); }
+ });
+
+ it.each([
+ ['complete', undefined, 'openai-completions'], ['complete', 'low', 'openai-completions'],
+ ['stream', undefined, 'openai-completions'], ['stream', 'low', 'openai-completions'],
+ ['complete', undefined, 'google-generative-ai'], ['complete', 'low', 'google-generative-ai'],
+ ['stream', undefined, 'google-generative-ai'], ['stream', 'low', 'google-generative-ai'],
+ ] as const)('makes one SDK request on HTTP 429 for %s / reasoning=%s / %s', async (method, reasoning, api) => {
+ const fetchStub = vi.fn(async () => new Response(JSON.stringify({ error: { message: 'opaque fixture error',
+ ...(api === 'google-generative-ai' ? { code: 429, status: 'RESOURCE_EXHAUSTED' } : {}),
+ } }), {
+ status: 429, headers: { 'content-type': 'application/json', 'retry-after': '60' },
+ }));
+ vi.stubGlobal('fetch', fetchStub);
+ try {
+ const provider = createPiProvider({ provider: 'custom', apiKey: 'fixture-key', customModel: {
+ id: 'fixture-model', name: 'fixture', provider: 'custom', api,
+ baseUrl: 'https://example.invalid/v1', reasoning: true, input: ['text', 'image'],
+ contextWindow: 128000, maxTokens: 4096,
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
+ } });
+ const params: CompletionParams = { messages: [{ role: 'user', content: [{ type: 'text', text: 'hello' }] }], reasoning };
+ let error: unknown;
+ if (method === 'complete') {
+ try { await provider.complete(params); } catch (failure) { error = failure; }
+ } else {
+ for await (const event of provider.stream(params)) if (event.type === 'error') error = event.error;
+ }
+ expect(fetchStub).toHaveBeenCalledTimes(1);
+ if (api === 'openai-completions') expect(error).toMatchObject({ statusCode: 429 });
+ else expect((error as Error).message).toContain('429');
+ expect(classifyRetryableError(error)).toBeNull();
+ } finally { vi.unstubAllGlobals(); }
+ });
+
+ it.each([
+ ['complete', 'openai-completions'], ['stream', 'openai-completions'],
+ ['complete', 'anthropic-messages'], ['stream', 'anthropic-messages'],
+ ] as const)('preserves structured error types despite misleading messages in %s / %s', async (method, api) => {
+ const warning = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const provider = createPiProvider({ provider: 'custom', apiKey: 'fixture', customModel: {
+ id: 'fixture', name: 'fixture', provider: 'custom', api,
+ baseUrl: 'https://fixture.invalid/v1', reasoning: false, input: ['text'],
+ contextWindow: 128000, maxTokens: 4096,
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
+ } });
+ try {
+ for (const [type, expected] of [['upstream_error', 'service_unavailable'], ['invalid_request_error', null]] as const) {
+ const fetchStub = vi.fn(async () => new Response(JSON.stringify({ error: { type, message: 'forbidden' } }), {
+ status: 502, headers: { 'content-type': 'application/json' },
+ }));
+ vi.stubGlobal('fetch', fetchStub);
+ const params: CompletionParams = { messages: [{ role: 'user', content: [{ type: 'text', text: 'probe' }] }] };
+ let failure: unknown;
+ if (method === 'complete') {
+ try { await provider.complete(params); } catch (error) { failure = error; }
+ } else {
+ for await (const event of provider.stream(params)) if (event.type === 'error') failure = event.error;
+ }
+ expect(fetchStub).toHaveBeenCalledTimes(1);
+ expect(classifyRetryableError(failure)).toBe(expected);
+ }
+ expect(warning.mock.calls).toHaveLength(2);
+ expect(warning.mock.calls.map(call => call[2]?.code)).toEqual(['upstream_error', 'invalid_request_error']);
+ expect(JSON.stringify(warning.mock.calls)).not.toContain('forbidden');
+ } finally { vi.unstubAllGlobals(); warning.mockRestore(); }
+ });
+
+ it.each([
+ { method: "complete", reasoning: undefined },
+ { method: "complete", reasoning: "low" as const },
+ { method: "stream", reasoning: undefined },
+ { method: "stream", reasoning: "low" as const },
+ ])("preserves Codex HTTP failures for host retry policy across $method / $reasoning calls", async ({ method, reasoning }) => {
+ const originalFetch = globalThis.fetch;
+ const warning = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const tokenPayload = Buffer.from(JSON.stringify({
+ "https://api.openai.com/auth": { chatgpt_account_id: "fixture-account" },
+ })).toString("base64");
+ const provider = createPiProvider({
+ provider: "openai-codex", model: "gpt-5.5", apiKey: `fixture.${tokenPayload}.fixture`,
+ });
+ const privateBody = "request-body-private-canary";
+ try {
+ // Identical text with distinct HTTP statuses proves classification does
+ // not infer status from words. A later transport failure must not inherit
+ // an earlier permanent status from this same provider instance.
+ const failures: any[] = [];
+ for (const [status, retryKind] of [[400, null], [403, null], [429, null], [503, "service_unavailable"], [undefined, "network"]] as const) {
+ const fetchStub = vi.fn(async () => {
+ if (status === undefined) throw new Error(privateBody);
+ return new Response(status === 400
+ ? JSON.stringify({ error: { message: privateBody, type: "invalid_request_error", param: "tools", code: null } })
+ : privateBody, { status });
+ });
+ globalThis.fetch = fetchStub as typeof fetch;
+ const params: CompletionParams = {
+ messages: [{ role: "user", content: [{ type: "text", text: "check" }] }], reasoning,
+ onRequestFailure: failure => { failures.push(failure); },
+ };
+ let failure: unknown;
+ if (method === "complete") {
+ try { await provider.complete(params); } catch (error) { failure = error; }
+ } else {
+ const events: StreamEvent[] = [];
+ for await (const event of provider.stream(params)) events.push(event);
+ const errors = events.filter(event => event.type === "error");
+ expect(errors).toHaveLength(1);
+ expect(events.some(event => event.type === "message_end")).toBe(false);
+ failure = errors[0].error;
+ }
+ expect(fetchStub).toHaveBeenCalledTimes(1);
+ expect(failure).toBeInstanceOf(ProviderError);
+ expect((failure as ProviderError).statusCode).toBe(status);
+ expect(classifyRetryableError(failure)).toBe(retryKind);
+ expect(failures.at(-1)).toMatchObject({ code: "unknown", aborted: false,
+ phase: status === undefined ? "before_response" : "after_response" });
+ expect(failures.at(-1).httpStatus).toBe(status);
+ }
+ expect(failures).toHaveLength(5);
+ expect(JSON.stringify(failures)).not.toContain(privateBody);
+ expect(JSON.stringify(warning.mock.calls)).not.toContain(privateBody);
+ } finally {
+ globalThis.fetch = originalFetch;
+ warning.mockRestore();
+ }
+ });
+
it("preserves stream errors without logging their private message", async () => {
const privateMessage = "provider-private-body-canary customer draft";
const warning = vi.spyOn(console, "warn").mockImplementation(() => {});
@@ -54,7 +343,7 @@ describe("Providers (pi-ai backed)", () => {
expect(captured.messages[4].content).toEqual([{ type: "text", text: "Continue" }]);
});
-it("keeps portable roles on native serializer drift instead of failing or guessing", () => {
+ it("keeps portable roles on native serializer drift instead of failing or guessing", () => {
const context = buildPiContextForTest([
{ role: "user", content: [{ type: "text", text: "real user" }] },
{ role: "developer", content: [{ type: "text", text: "host control" }] },
@@ -78,7 +367,7 @@ it("keeps portable roles on native serializer drift instead of failing or guessi
}
});
-it("promotes Chat Completions host rows only when developer support is declared", () => {
+ it("promotes Chat Completions host rows only when developer support is declared", () => {
const context = buildPiContextForTest([
{ role: "user", content: [{ type: "text", text: "real user" }] },
{ role: "developer", content: [{ type: "text", text: "host control" }] },
@@ -91,7 +380,7 @@ it("promotes Chat Completions host rows only when developer support is declared"
expect(roles(restoreHostMessageRoles(payload(), context, chat(undefined)))).toEqual(["user", "user"]);
});
-it("pins the mirrored serializer rules to the installed pi-ai release", () => {
+ it("pins the mirrored serializer rules to the installed pi-ai release", () => {
const installed = JSON.parse(fs.readFileSync(
new URL("../../../node_modules/@earendil-works/pi-ai/package.json", import.meta.url), "utf8",
)) as { version: string };
@@ -100,7 +389,7 @@ it("pins the mirrored serializer rules to the installed pi-ai release", () => {
expect(installed.version).toBe(MIRRORED_PI_AI_SERIALIZER_VERSION);
});
-it("preserves Responses reasoning and phase across host controls and native tool images", async () => {
+ it("preserves Responses reasoning and phase across host controls and native tool images", async () => {
const payloads: any[] = [];
const provider = createPiProvider({
provider: "openai", apiKey: "test",
@@ -113,8 +402,8 @@ it("preserves Responses reasoning and phase across host controls and native tool
const messages: Message[] = [
{ role: "user", content: [{ type: "text", text: "[Internal execution control] quoted by a real user" }] },
{ role: "assistant", content: [
- { type: "thinking", thinking: "", thinkingSignature: JSON.stringify(reasoning) },
- { type: "text", text: "Checking", textSignature: JSON.stringify({ v: 1, id: "msg_original", phase: "commentary" }) },
+ { type: "thinking", thinking: "", thinkingSignature: JSON.stringify(reasoning), replayOrigin: replayOrigin({ api: "openai-responses", provider: "openai", id: "gpt-5.5", baseUrl: "https://example.test/v1" }, "test") },
+ { type: "text", text: "Checking", textSignature: JSON.stringify({ v: 1, id: "msg_original", phase: "commentary" }), replayOrigin: replayOrigin({ api: "openai-responses", provider: "openai", id: "gpt-5.5", baseUrl: "https://example.test/v1" }, "test") },
{ type: "tool_use", id: "call_image", name: "read_files", input: {} },
] },
{ role: "user", content: [{ type: "tool_result", toolUseId: "call_image", content: "image loaded",
@@ -146,7 +435,7 @@ it("preserves Responses reasoning and phase across host controls and native tool
expect(messages[0].role).toBe("user");
});
-it("reads Responses text phase only from structured signature metadata", () => {
+ it("reads Responses text phase only from structured signature metadata", () => {
expect(assistantTextPhaseFromSignatureForTest(
JSON.stringify({ v: 1, id: "msg_1", phase: "commentary" }),
)).toBe("commentary");
@@ -159,6 +448,7 @@ it("reads Responses text phase only from structured signature metadata", () => {
JSON.stringify({ v: 1, id: "msg_3", phase: "unsupported" }),
)).toBeUndefined();
});
+
describe("createAnthropicProvider", () => {
it("creates a provider with correct id and name", () => {
const provider = createAnthropicProvider({ apiKey: "test" });
@@ -209,6 +499,79 @@ it("reads Responses text phase only from structured signature metadata", () => {
expect(normalizeReasoningForProvider("high", ["low", "medium", "high"])).toBe("high");
});
+ it("keeps local model limits for planning while omitting OpenAI-compatible auxiliary wire caps", () => {
+ const model = {
+ id: "qwen3.8-max",
+ name: "Qwen 3.8 Max",
+ api: "openai-completions" as const,
+ provider: "qwen" as any,
+ baseUrl: "https://example.test/v1",
+ reasoning: true,
+ input: ["text" as const],
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
+ contextWindow: 1_000_000,
+ maxTokens: 32_000,
+ };
+ expect(useProviderDefaultOutputLimitForTest(
+ { max_completion_tokens: 32_000, messages: [] },
+ model,
+ "provider_default",
+ )).toEqual({ messages: [] });
+ expect(useProviderDefaultOutputLimitForTest(
+ { max_completion_tokens: 1_200, messages: [] },
+ model,
+ undefined,
+ )).toMatchObject({ max_completion_tokens: 1_200 });
+ });
+
+ it("sends Qwen's thinking-off parameter without an auxiliary cap for complete and stream", async () => {
+ const capturedPayloads: Record<string, unknown>[] = [];
+ const model: Model<"openai-completions"> = {
+ id: "qwen3.8-max",
+ name: "Qwen 3.8 Max",
+ api: "openai-completions",
+ provider: "qwen" as any,
+ baseUrl: "https://example.test/v1",
+ reasoning: true,
+ input: ["text"],
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
+ contextWindow: 1_000_000,
+ maxTokens: 32_000,
+ compat: { thinkingFormat: "qwen" },
+ };
+ const provider = createPiProvider({
+ provider: "qwen",
+ apiKey: "test",
+ customModel: model,
+ onPayload: (payload) => {
+ capturedPayloads.push(payload as Record<string, unknown>);
+ throw new Error("payload captured before network");
+ },
+ });
+
+ const params: CompletionParams = {
+ model: model.id,
+ messages: [{ role: "user", content: [{ type: "text", text: "summarize" }] }],
+ reasoning: "off" as const,
+ requestMetadata: { outputLimitSource: "provider_default" },
+ };
+ await expect(provider.complete(params)).rejects.toThrow(/payload captured before network/);
+ const streamEvents: StreamEvent[] = [];
+ for await (const event of provider.stream(params)) streamEvents.push(event);
+ // pi-ai represents a streaming setup failure as an error event rather
+ // than rejecting the iterator; the payload was still captured first.
+ expect(streamEvents.some((event) => event.type === "error")).toBe(true);
+
+ expect(capturedPayloads).toHaveLength(2);
+ for (const capturedPayload of capturedPayloads) {
+ expect(capturedPayload).toMatchObject({ enable_thinking: false });
+ expect(capturedPayload).not.toHaveProperty("max_tokens");
+ expect(capturedPayload).not.toHaveProperty("max_completion_tokens");
+ expect(capturedPayload).not.toHaveProperty("max_output_tokens");
+ expect(capturedPayload).not.toHaveProperty("reasoning_effort");
+ }
+ });
+
it("creates a provider for any pi-ai supported provider", () => {
const provider = createPiProvider({ provider: "anthropic", model: "claude-opus-4-8" });
expect(provider.id).toBe("anthropic");
@@ -219,6 +582,65 @@ it("reads Responses text phase only from structured signature metadata", () => {
expect(provider.id).toBe("google");
});
+ it("merges per-call transport headers without adding metadata to the payload", async () => {
+ const originalFetch = globalThis.fetch;
+ const observed: Array<{ headers: Headers; body: Record<string, unknown> }> = [];
+ globalThis.fetch = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
+ const headers = input instanceof Request
+ ? new Headers(input.headers)
+ : new Headers(init?.headers);
+ const rawBody = input instanceof Request ? await input.clone().text() : String(init?.body || "{}");
+ observed.push({ headers, body: JSON.parse(rawBody) });
+ return new Response(JSON.stringify({
+ error: { message: "intentional test response", type: "invalid_request_error" },
+ }), {
+ status: 400,
+ headers: { "content-type": "application/json" },
+ });
+ }) as typeof fetch;
+
+ try {
+ const model: Model<"openai-completions"> = {
+ id: "request-header-test",
+ name: "Request Header Test",
+ api: "openai-completions",
+ provider: "custom" as any,
+ baseUrl: "https://example.test/v1",
+ reasoning: false,
+ input: ["text"],
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
+ contextWindow: 8_192,
+ maxTokens: 1_024,
+ };
+ const provider = createPiProvider({
+ provider: "custom",
+ apiKey: "test",
+ customModel: model,
+ headers: { "x-static-test": "static" },
+ requestHeaders: (metadata) => ({
+ "x-request-id": String(metadata?.orkasRequestId || ""),
+ }),
+ });
+ const events: StreamEvent[] = [];
+ for await (const event of provider.stream({
+ model: model.id,
+ messages: [{ role: "user", content: [{ type: "text", text: "ping" }] }],
+ requestMetadata: { orkasRequestId: "0123456789abcdef0123456789abcdef" },
+ })) {
+ events.push(event);
+ }
+
+ expect(events.some((event) => event.type === "error")).toBe(true);
+ expect(observed).toHaveLength(1);
+ expect(observed[0].headers.get("x-static-test")).toBe("static");
+ expect(observed[0].headers.get("x-request-id"))
+ .toBe("0123456789abcdef0123456789abcdef");
+ expect(observed[0].body).not.toHaveProperty("orkasRequestId");
+ } finally {
+ globalThis.fetch = originalFetch;
+ }
+ });
+
it("leaves DeepSeek thinking and effort at their official defaults", async () => {
let capturedPayload: Record<string, unknown> | undefined;
const model: Model<"openai-completions"> = {
@@ -429,7 +851,8 @@ it("reads Responses text phase only from structured signature metadata", () => {
const provider = createPiProvider({
provider: "openai",
model: "gpt-4o",
- apiKey: "test",
+ // Keep this on the API-key path; non-sk credentials select ChatGPT OAuth.
+ apiKey: "sk-test-fixture",
onPayload: (payload) => {
capturedPayload = payload as Record<string, unknown>;
throw new Error("payload captured before network");
@@ -448,6 +871,110 @@ it("reads Responses text phase only from structured signature metadata", () => {
expect(capturedPayload).not.toHaveProperty("reasoning_effort");
});
+ it("uses GPT-6 Responses tools, vision, explicit cache TTL, and supported reasoning levels", async () => {
+ const payloads: Record<string, any>[] = [];
+ const provider = createPiProvider({
+ provider: "openai",
+ model: "gpt-6-astra",
+ // Keep this on the API-key path; non-sk credentials select ChatGPT OAuth.
+ apiKey: "sk-test-fixture",
+ onPayload: (payload) => {
+ payloads.push(payload as Record<string, any>);
+ throw new Error("payload captured before network");
+ },
+ });
+ const base = {
+ model: "gpt-6-astra",
+ messages: [{
+ role: "user" as const,
+ content: [
+ { type: "text" as const, text: "Read the diagram." },
+ { type: "image" as const, data: "AQID", mimeType: "image/png" },
+ ],
+ }],
+ tools: [{
+ name: "read_file",
+ description: "Read a file",
+ inputSchema: {
+ type: "object",
+ properties: { path: { type: "string" } },
+ required: ["path"],
+ },
+ }],
+ sessionId: "gpt6-payload-contract",
+ };
+
+ await expect(provider.complete({
+ ...base,
+ reasoning: "low",
+ cacheRetention: "long",
+ })).rejects.toThrow(/payload captured before network/);
+ await expect(provider.complete({
+ ...base,
+ reasoning: "off",
+ cacheRetention: "none",
+ })).rejects.toThrow(/payload captured before network/);
+
+ expect(payloads).toHaveLength(2);
+ expect(payloads[0]).toMatchObject({
+ model: "gpt-6-astra",
+ stream: true,
+ prompt_cache_key: "gpt6-payload-contract",
+ prompt_cache_options: { ttl: "30m" },
+ reasoning: { effort: "low", summary: "auto" },
+ tools: [{ type: "function", name: "read_file" }],
+ });
+ expect(payloads[0].prompt_cache_retention).toBeUndefined();
+ expect(JSON.stringify(payloads[0].input)).toContain("input_image");
+
+ expect(payloads[1]).toMatchObject({
+ model: "gpt-6-astra",
+ stream: true,
+ prompt_cache_options: { mode: "explicit" },
+ });
+ expect(payloads[1].prompt_cache_key).toBeUndefined();
+ expect(payloads[1].prompt_cache_retention).toBeUndefined();
+ expect(payloads[1]).not.toHaveProperty("reasoning");
+ expect(payloads[1]).not.toHaveProperty("include");
+ });
+
+ it.each([
+ ["openai", "gpt-6.1-sol"],
+ ["openai", "gpt-6-sol"],
+ ["openai", "gpt-6-luna"],
+ ["openai-codex", "gpt-6.1-sol"],
+ ["openai-codex", "gpt-6-sol"],
+ ["openai-codex", "gpt-6-luna"],
+ ])("sends %s %s through its native Responses adapter with image and tools", async (providerId, modelId) => {
+ let capturedPayload: Record<string, any> | undefined;
+ const codexPayload = Buffer.from(JSON.stringify({
+ "https://api.openai.com/auth": { chatgpt_account_id: "fixture-account" },
+ })).toString("base64");
+ const provider = createPiProvider({
+ provider: providerId, model: modelId,
+ apiKey: providerId === "openai-codex" ? `fixture.${codexPayload}.fixture` : "test",
+ onPayload: (payload) => {
+ capturedPayload = payload as Record<string, any>;
+ throw new Error("payload captured before network");
+ },
+ });
+ await expect(provider.complete({
+ model: modelId,
+ messages: [{ role: "user", content: [
+ { type: "text", text: "Read this" },
+ { type: "image", data: "AQID", mimeType: "image/png" },
+ ] }],
+ tools: [{ name: "read_file", description: "Read a file", inputSchema: { type: "object" } }],
+ reasoning: "low",
+ })).rejects.toThrow(/payload captured before network/);
+ expect(capturedPayload).toMatchObject({
+ model: modelId,
+ reasoning: { effort: "low" },
+ tools: [expect.objectContaining({ type: "function", name: "read_file" })],
+ });
+ expect(JSON.stringify(capturedPayload?.input)).toContain("input_image");
+ });
+
it("preserves official default toggles for built-in reasoning providers", async () => {
async function capture(providerId: string, modelId: string): Promise<Record<string, any>> {
let payload: Record<string, any> | undefined;
@@ -472,7 +999,7 @@ it("reads Responses text phase only from structured signature metadata", () => {
const google = await capture("google", "gemini-2.5-flash");
const openrouter = await capture("openrouter", "aion-labs/aion-2.0");
const zai = await capture("zai", "glm-4.7");
- const qwen = await capture("qwen-token-plan", "deepseek-v4-flash");
+ const qwen = await capture("qwen-token-plan", "qwen3.8-max");
const together = await capture("together", "MiniMaxAI/MiniMax-M3");
expect(openai).not.toHaveProperty("reasoning");
@@ -484,70 +1011,274 @@ it("reads Responses text phase only from structured signature metadata", () => {
expect(together).not.toHaveProperty("reasoning");
});
- it("prefers the actual upstream response model over the logical request model", () => {
- expect(resolvedResponseModelForTest(
- { model: "custom-model-alias", responseModel: "deepseek-v4-pro" },
- "custom-model-alias",
- )).toBe("deepseek-v4-pro");
- expect(resolvedResponseModelForTest(
- { model: "custom-model-alias" },
- "fallback",
- )).toBe("custom-model-alias");
- });
-
- it("decodes only bounded Orkas Server fallback response markers", () => {
- const cases = {
- pro_rate_limited: "rate_limited",
- pro_transport_error: "transport_error",
- pro_configuration_error: "configuration_error",
- pro_not_configured: "not_configured",
- pro_upstream_error: "upstream_error",
- pro_empty_response: "empty_response",
- pro_unavailable: "unavailable",
- } as const;
- for (const [marker, expected] of Object.entries(cases)) {
- expect(serverFallbackReasonFromResponseIdForTest(`orkas-fallback:${marker}`))
- .toBe(expected);
- }
- expect(serverFallbackReasonFromResponseIdForTest("orkas-fallback:future_reason"))
- .toBe("unknown");
- expect(serverFallbackReasonFromResponseIdForTest("chatcmpl-normal-id"))
- .toBeUndefined();
- });
-
- it("classifies native provider termination markers without leaking raw values", () => {
- expect(providerTerminationCategoryForTest("STOP", "stop")).toBe("normal");
- expect(providerTerminationCategoryForTest("completed", "stop")).toBe("normal");
- expect(providerTerminationCategoryForTest("MAX_TOKENS", "length")).toBe("length");
- expect(providerTerminationCategoryForTest("content_filter", "stop")).toBe("safety");
- expect(providerTerminationCategoryForTest("SAFETY", "stop")).toBe("safety");
- expect(providerTerminationCategoryForTest("sensitive", "stop")).toBe("safety");
- expect(providerTerminationCategoryForTest("future_provider_reason", "stop")).toBe("unknown");
- expect(providerTerminationCategoryForTest(undefined, "stop")).toBe("normal");
- expect(providerTerminationCategoryForTest(undefined, "length")).toBe("length");
- });
-
- it("does not silently fall back when an explicit model id is unknown", async () => {
- const provider = createPiProvider({ provider: "kimi-coding", apiKey: "test" });
- await expect(async () => {
- for await (const _ of provider.stream({
- model: "not-in-pi-ai-catalog",
- messages: [],
- })) {
- // resolveModel fails before any provider request is made.
- }
- }).rejects.toThrow(/No model found for provider: kimi-coding, model: not-in-pi-ai-catalog/);
- });
-
- it("replays tool results with the original tool name for Gemini function responses", () => {
- const messages: Message[] = [
- { role: "user", content: [{ type: "text", text: "list files" }] },
- {
- role: "assistant",
- content: [{ type: "tool_use", id: "call_1", name: "list_files", input: { path: "." } }],
- },
- {
- role: "user",
+ it.each([
+ ["anthropic", "claude-fable-5-1", "anthropic"],
+ ["anthropic", "claude-opus-5-5", "anthropic"],
+ ["anthropic", "claude-sonnet-5-5", "anthropic"],
+ ["openrouter", "anthropic/claude-fable-5.1", "anthropic"],
+ ["openrouter", "anthropic/claude-opus-5.5", "anthropic"],
+ ["openrouter", "anthropic/claude-sonnet-5.5", "anthropic"],
+ ["openrouter", "openai/gpt-6.1-sol", "openai"],
+ ["openrouter", "anthropic/claude-opus-5", "anthropic"],
+ ["google", "gemini-3.8-flash", "google"],
+ ["openrouter", "google/gemini-3.8-flash", "openai"],
+ ])("round-trips %s %s through a fragmented tool stream and its follow-up result", async (providerId, modelId, protocol) => {
+ const originalFetch = globalThis.fetch;
+ const requests: Array<{ url: string; body: any }> = [];
+ globalThis.fetch = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = input instanceof Request ? input.url : String(input);
+ const raw = input instanceof Request ? await input.clone().text() : String(init?.body);
+ requests.push({ url, body: JSON.parse(raw) });
+ const toolReply = requests.length === 1;
+ let data: unknown[];
+ if (protocol === "anthropic") {
+ data = [
+ { type: "message_start", message: { id: "msg-compat", type: "message", role: "assistant", model: modelId, content: [], usage: { input_tokens: 12, output_tokens: 0 } } },
+ { type: "content_block_start", index: 0, content_block: toolReply ? { type: "tool_use", id: "call_next", name: "lookup", input: {} } : { type: "text", text: "" } },
+ ...(toolReply ? [
+ { type: "content_block_delta", index: 0, delta: { type: "input_json_delta", partial_json: '{"item":' } },
+ { type: "content_block_delta", index: 0, delta: { type: "input_json_delta", partial_json: '"follow-up"}' } },
+ ] : [{ type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "verified" } }]),
+ { type: "content_block_stop", index: 0 },
+ { type: "message_delta", delta: { stop_reason: toolReply ? "tool_use" : "end_turn" }, usage: { output_tokens: 2 } },
+ { type: "message_stop" },
+ ];
+ } else if (protocol === "google") {
+ const parts = toolReply ? [{ functionCall: { id: "call_next", name: "lookup", args: { item: "follow-up" } } }] : [{ text: "verified" }];
+ data = [{ candidates: [{ index: 0, content: { role: "model", parts }, finishReason: "STOP" }], modelVersion: modelId, usageMetadata: { promptTokenCount: 12, candidatesTokenCount: 2, totalTokenCount: 14 } }];
+ } else {
+ data = toolReply ? [
+ { id: "chatcmpl-compat", model: modelId, choices: [{ index: 0, delta: { role: "assistant", tool_calls: [{ index: 0, id: "call_next", type: "function", function: { name: "lookup", arguments: '{"item":' } }] }, finish_reason: null }] },
+ { id: "chatcmpl-compat", model: modelId, choices: [{ index: 0, delta: { tool_calls: [{ index: 0, function: { arguments: '"follow-up"}' } }] }, finish_reason: "tool_calls" }], usage: { prompt_tokens: 12, completion_tokens: 2, total_tokens: 14 } },
+ ] : [{ id: "chatcmpl-compat", model: modelId, choices: [{ index: 0, delta: { role: "assistant", content: "verified" }, finish_reason: "stop" }], usage: { prompt_tokens: 12, completion_tokens: 2, total_tokens: 14 } }];
+ }
+ const sse = data.map((event: any) => `${protocol === "anthropic" ? `event: ${event.type}\n` : ""}data: ${JSON.stringify(event)}\n\n`).join("");
+ const bytes = new TextEncoder().encode(sse + (protocol === "openai" ? "data: [DONE]\n\n" : ""));
+ // Split inside SSE fields and JSON tokens, independently of event boundaries.
+ const body = new ReadableStream<Uint8Array>({
+ start(controller) {
+ for (let offset = 0; offset < bytes.length; offset += 11) controller.enqueue(bytes.slice(offset, offset + 11));
+ controller.close();
+ },
+ });
+ return new Response(body, {
+ headers: { "content-type": "text/event-stream" },
+ });
+ }) as typeof fetch;
+ try {
+ const provider = createPiProvider({ provider: providerId, model: modelId, apiKey: "test" });
+ const params: CompletionParams = {
+ model: modelId,
+ reasoning: "low",
+ tools: [{ name: "lookup", description: "Look up an item", inputSchema: { type: "object", properties: { item: { type: "string" } }, required: ["item"] } }],
+ messages: [
+ { role: "user", content: [{ type: "text", text: "Check this image" }, { type: "image", data: "aGVsbG8=", mediaType: "image/png" }] },
+ { role: "assistant", content: [{ type: "tool_use", id: "call_lookup", name: "lookup", input: { item: "sample" } }] },
+ { role: "user", content: [{ type: "tool_result", toolUseId: "call_lookup", content: "item found" }] },
+ ],
+ };
+ const events: StreamEvent[] = [];
+ for await (const event of provider.stream(params)) events.push(event);
+ expect(events.filter((event) => event.type === "error")).toEqual([]);
+ expect(events.filter((event) => event.type === "message_start")).toHaveLength(1);
+ const terminals = events.filter((event) => event.type === "message_end");
+ expect(terminals).toHaveLength(1);
+ const terminal = terminals[0];
+ expect(terminal).toMatchObject({ model: modelId, stopReason: "tool_use", usage: { inputTokens: 12, outputTokens: 2 } });
+ expect(terminal.content).toEqual([expect.objectContaining({ type: "tool_use", name: "lookup", input: { item: "follow-up" } })]);
+ const tool = terminal.content![0];
+ if (tool.type !== "tool_use") throw new Error("Expected a replayable tool call");
+ expect(tool.id).toBeTruthy();
+ expect(events.filter((event) => event.type === "tool_use_start")).toEqual([{ type: "tool_use_start", id: tool.id, name: "lookup" }]);
+ expect(events.filter((event) => event.type === "tool_use_end")).toEqual([{ type: "tool_use_end", id: tool.id }]);
+ const streamedArguments = events.filter((event) => event.type === "tool_use_delta").map((event) => event.input).join("");
+ expect(JSON.parse(streamedArguments)).toEqual({ item: "follow-up" });
+ const result = await provider.complete({
+ ...params,
+ messages: [
+ ...params.messages,
+ { role: "assistant", content: terminal.content! },
+ { role: "user", content: [{ type: "tool_result", toolUseId: tool.id, content: "follow-up found" }] },
+ ],
+ });
+ expect(result).toMatchObject({ model: modelId, stopReason: "end_turn", content: [{ type: "text", text: "verified" }], usage: { inputTokens: 12, outputTokens: 2 } });
+ expect(requests).toHaveLength(2);
+ const { url, body } = requests[0];
+ if (protocol === "anthropic") {
+ expect(url).toBe(providerId === "anthropic" ? "https://api.anthropic.com/v1/messages?beta=true" : "https://openrouter.ai/api/v1/messages?beta=true");
+ expect(body).toMatchObject({ model: modelId, thinking: { type: "adaptive" } });
+ expect(body.tools).toContainEqual(expect.objectContaining({ name: "lookup" }));
+ if (providerId === "anthropic") {
+ expect(body.tools).toContainEqual(expect.objectContaining({ name: "__pi_deferred_placeholder__", defer_loading: true }));
+ }
+ const expectedMessages = [
+ expect.objectContaining({ role: "user", content: expect.arrayContaining([{ type: "image", source: { type: "base64", media_type: "image/png", data: "aGVsbG8=" } }]) }),
+ expect.objectContaining({ role: "assistant", content: expect.arrayContaining([expect.objectContaining({ type: "tool_use", id: "call_lookup", name: "lookup", input: { item: "sample" } })]) }),
+ expect.objectContaining({ role: "user", content: expect.arrayContaining([expect.objectContaining({ type: "tool_result", tool_use_id: "call_lookup" })]) }),
+ ];
+ if (providerId === "anthropic") expectedMessages.push({ role: "system", content: [], output_config: { effort: "low" } });
+ expect(body.messages).toEqual(expect.arrayContaining(expectedMessages));
+ const replayed = requests[1].body.messages.filter((message: any) => message.role === "user").at(-1).content
+ .find((block: any) => block.type === "tool_result");
+ expect(replayed).toMatchObject({ tool_use_id: tool.id });
+ // Anthropic accepts tool-result text as either a string or text blocks.
+ expect(typeof replayed.content === "string" ? replayed.content : replayed.content.map((block: any) => block.text).join(""))
+ .toBe("follow-up found");
+ } else if (protocol === "google") {
+ expect(url).toContain(`/models/${modelId}:streamGenerateContent`);
+ expect(body.generationConfig.thinkingConfig.thinkingLevel).toBe("LOW");
+ expect(body.contents[0].parts).toContainEqual({ inlineData: { mimeType: "image/png", data: "aGVsbG8=" } });
+ expect(body.contents[1].parts).toEqual(expect.arrayContaining([expect.objectContaining({ functionCall: expect.objectContaining({ name: "lookup", args: { item: "sample" } }) })]));
+ expect(body.contents[2].parts).toEqual(expect.arrayContaining([expect.objectContaining({ functionResponse: expect.objectContaining({ name: "lookup" }) })]));
+ expect(body.tools[0].functionDeclarations[0]).toMatchObject({ name: "lookup" });
+ expect(requests[1].body.contents.at(-1).parts).toEqual(expect.arrayContaining([
+ expect.objectContaining({ functionResponse: expect.objectContaining({ name: "lookup", response: { output: "follow-up found" } }) }),
+ ]));
+ } else {
+ expect(url).toBe("https://openrouter.ai/api/v1/chat/completions");
+ expect(body).toMatchObject({ model: modelId, reasoning: { effort: "low" } });
+ expect(body.messages[0].content).toContainEqual({ type: "image_url", image_url: { url: "data:image/png;base64,aGVsbG8=" } });
+ expect(body.messages[1].tool_calls[0]).toMatchObject({ id: "call_lookup", function: { name: "lookup", arguments: '{"item":"sample"}' } });
+ expect(body.messages[2]).toMatchObject({ role: "tool", tool_call_id: "call_lookup", content: "item found" });
+ expect(body.tools[0]).toMatchObject({ type: "function", function: { name: "lookup" } });
+ expect(requests[1].body.messages.at(-1)).toMatchObject({ role: "tool", tool_call_id: tool.id, content: "follow-up found" });
+ }
+ } finally {
+ globalThis.fetch = originalFetch;
+ }
+ });
+
+ it.each(["truncated", "aborted"] as const)("does not complete a %s OpenRouter Claude stream and accepts a fresh retry", async (failure) => {
+ const originalFetch = globalThis.fetch;
+ const warning = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const abort = new AbortController();
+ const modelId = "anthropic/claude-fable-5.1";
+ let requestCount = 0;
+ globalThis.fetch = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
+ requestCount += 1;
+ const recovered = requestCount === 2;
+ const signal = input instanceof Request ? input.signal : init?.signal;
+ const events = [
+ { type: "message_start", message: { id: "msg-interrupted", type: "message", role: "assistant", model: modelId, content: [], usage: { input_tokens: 12, output_tokens: 0 } } },
+ { type: "content_block_start", index: 0, content_block: { type: "text", text: "" } },
+ { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: recovered ? "verified" : "partial" } },
+ ...(recovered ? [
+ { type: "content_block_stop", index: 0 },
+ { type: "message_delta", delta: { stop_reason: "end_turn" }, usage: { output_tokens: 2 } },
+ { type: "message_stop" },
+ ] : []),
+ ];
+ const bytes = new TextEncoder().encode(events.map((event) => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`).join(""));
+ return new Response(new ReadableStream<Uint8Array>({
+ start(controller) {
+ controller.enqueue(bytes);
+ if (recovered || failure === "truncated") controller.close();
+ else signal?.addEventListener("abort", () => controller.error(new DOMException("Request aborted", "AbortError")), { once: true });
+ },
+ }), { headers: { "content-type": "text/event-stream" } });
+ }) as typeof fetch;
+ try {
+ const provider = createPiProvider({ provider: "openrouter", model: modelId, apiKey: "test" });
+ const params: CompletionParams = { model: modelId, messages: [{ role: "user", content: [{ type: "text", text: "answer" }] }] };
+ const events: StreamEvent[] = [];
+ for await (const event of provider.stream({ ...params, signal: abort.signal })) {
+ events.push(event);
+ if (failure === "aborted" && event.type === "text_delta") abort.abort();
+ }
+ expect(events.filter((event) => event.type === "text_delta")).toEqual([{ type: "text_delta", text: "partial" }]);
+ expect(events.filter((event) => event.type === "message_end")).toEqual([]);
+ expect(events.filter((event) => event.type === "tool_use_start")).toEqual([]);
+ const errors = events.filter((event) => event.type === "error");
+ expect(errors).toHaveLength(1);
+ const errorPattern = failure === "aborted" ? /abort/i : /stream ended/i;
+ expect(errors[0].error.message).toMatch(errorPattern);
+ expect(requestCount).toBe(1);
+ expect(warning.mock.calls).toEqual([["[pi-provider]", "provider stream failed", {
+ budgetObserved: true, contextWindow: 1000000, outputLimit: 128000,
+ phase: "after_response", code: "unknown", httpStatus: 200,
+ source: "sdk_error", lastEvent: "text_delta",
+ aborted: failure === "aborted", elapsedMs: expect.any(Number),
+ }]]);
+
+ warning.mockClear();
+ const retryEvents: StreamEvent[] = [];
+ for await (const event of provider.stream(params)) retryEvents.push(event);
+ expect(retryEvents.filter((event) => event.type === "error")).toEqual([]);
+ expect(retryEvents.filter((event) => event.type === "message_end")).toEqual([
+ expect.objectContaining({ stopReason: "end_turn", content: [{ type: "text", text: "verified" }], model: modelId }),
+ ]);
+ expect(requestCount).toBe(2);
+ expect(warning).not.toHaveBeenCalled();
+ } finally {
+ globalThis.fetch = originalFetch;
+ warning.mockRestore();
+ }
+ });
+
+ it("prefers the actual upstream response model over the logical request model", () => {
+ expect(resolvedResponseModelForTest(
+ { model: "custom-model-alias", responseModel: "deepseek-v4-pro" },
+ "custom-model-alias",
+ )).toBe("deepseek-v4-pro");
+ expect(resolvedResponseModelForTest(
+ { model: "custom-model-alias" },
+ "fallback",
+ )).toBe("custom-model-alias");
+ });
+
+ it("decodes only bounded Orkas Server fallback response markers", () => {
+ const cases = {
+ pro_rate_limited: "rate_limited",
+ pro_transport_error: "transport_error",
+ pro_configuration_error: "configuration_error",
+ pro_not_configured: "not_configured",
+ pro_upstream_error: "upstream_error",
+ pro_empty_response: "empty_response",
+ pro_unavailable: "unavailable",
+ } as const;
+ for (const [marker, expected] of Object.entries(cases)) {
+ expect(serverFallbackReasonFromResponseIdForTest(`orkas-fallback:${marker}`))
+ .toBe(expected);
+ }
+ expect(serverFallbackReasonFromResponseIdForTest("orkas-fallback:future_reason"))
+ .toBe("unknown");
+ expect(serverFallbackReasonFromResponseIdForTest("chatcmpl-normal-id"))
+ .toBeUndefined();
+ });
+
+ it("classifies native provider termination markers without leaking raw values", () => {
+ expect(providerTerminationCategoryForTest("STOP", "stop")).toBe("normal");
+ expect(providerTerminationCategoryForTest("completed", "stop")).toBe("normal");
+ expect(providerTerminationCategoryForTest("MAX_TOKENS", "length")).toBe("length");
+ expect(providerTerminationCategoryForTest("content_filter", "stop")).toBe("safety");
+ expect(providerTerminationCategoryForTest("SAFETY", "stop")).toBe("safety");
+ expect(providerTerminationCategoryForTest("sensitive", "stop")).toBe("safety");
+ expect(providerTerminationCategoryForTest("future_provider_reason", "stop")).toBe("unknown");
+ expect(providerTerminationCategoryForTest(undefined, "stop")).toBe("normal");
+ expect(providerTerminationCategoryForTest(undefined, "length")).toBe("length");
+ });
+
+ it("does not silently fall back when an explicit model id is unknown", async () => {
+ const provider = createPiProvider({ provider: "kimi-coding", apiKey: "test" });
+ await expect(async () => {
+ for await (const _ of provider.stream({
+ model: "not-in-pi-ai-catalog",
+ messages: [],
+ })) {
+ // resolveModel fails before any provider request is made.
+ }
+ }).rejects.toThrow(/No model found for provider: kimi-coding, model: not-in-pi-ai-catalog/);
+ });
+
+ it("replays tool results with the original tool name for Gemini function responses", () => {
+ const messages: Message[] = [
+ { role: "user", content: [{ type: "text", text: "list files" }] },
+ {
+ role: "assistant",
+ content: [{ type: "tool_use", id: "call_1", name: "list_files", input: { path: "." } }],
+ },
+ {
+ role: "user",
content: [{ type: "tool_result", toolUseId: "call_1", content: "E_LIST_FAILED", isError: true }],
},
];
@@ -605,7 +1336,7 @@ it("reads Responses text phase only from structured signature metadata", () => {
provider: "openai" as any,
baseUrl: "https://api.openai.com/v1",
reasoning: true,
- compat: { supportsToolSearch: true, supportsAdditionalTools },
+ compat: { supportsToolSearch: true, supportsAdditionalTools, supportsMidConvoSystemMessages: true },
input: ["text"],
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
contextWindow: 1_000_000,
@@ -647,10 +1378,10 @@ it("reads Responses text phase only from structured signature metadata", () => {
expect(await capture(loadedMessages)).toEqual(loaded);
const steadyMessages: Message[] = [
...loadedMessages,
- { role: "assistant", content: mapContentForTest([{
+ { role: "assistant", content: mapProviderContentForTest([{
type: "toolCall", id: "search-1", name: "web_search",
namespace: "web_search", arguments: {},
- }]) },
+ }], false, undefined, replayOrigin(model, "test")) },
{ role: "user", content: [{ type: "tool_result", toolUseId: "search-1", content: "release notes" }] },
{ role: "assistant", content: [{ type: "tool_use", id: "load-2", name: "tool_load", input: { groups: ["web"] } }] },
{ role: "user", content: [{ type: "tool_result", toolUseId: "load-2", content: "already loaded" }] },
@@ -774,6 +1505,7 @@ it("reads Responses text phase only from structured signature metadata", () => {
name: "list_files",
input: { path: "." },
thoughtSignature: "QUJDRA==",
+ replayOrigin: replayOrigin({ api: "google-generative-ai", provider: "google", id: "gemini-3.5-flash" }),
},
],
},
@@ -816,11 +1548,19 @@ it("reads Responses text phase only from structured signature metadata", () => {
it("removes a complete leading think block only for opted-in provider routes", () => {
const providerText = "<think>private chain of thought</think>\n\nUser-facing result";
- const rawContent = [{ type: "text" as const, text: providerText }];
+ const rawContent = [{
+ type: "text" as const,
+ text: providerText,
+ }];
const content = mapProviderContentForTest(rawContent, true);
expect(content).toEqual([{ type: "text", text: "User-facing result" }]);
- expect(mapProviderContentForTest(rawContent)).toEqual(rawContent);
+ expect(mapProviderContentForTest(rawContent)).toEqual([
+ {
+ type: "text" as const,
+ text: providerText,
+ },
+ ]);
// Replay and conversion callers remain pass-through unless the owning
// provider route explicitly enables the wire-compatibility repair.
expect(mapContentForTest([{ type: "text", text: providerText }]))
@@ -832,10 +1572,31 @@ it("reads Responses text phase only from structured signature metadata", () => {
.toBe("");
});
- it("suppresses a leading think block split across streaming deltas", () => {
- const filter = createLeadingThinkTextFilterForTest();
-
- expect(filter.push("\n<th")).toBe("");
+ it("preserves official structured reasoning while normalizing opted-in text", () => {
+ expect(mapProviderContentForTest([
+ {
+ type: "thinking",
+ thinking: "structured private reasoning",
+ thinkingSignature: "reasoning_content",
+ },
+ {
+ type: "text",
+ text: "Visible result",
+ },
+ ], true)).toEqual([
+ {
+ type: "thinking",
+ thinking: "structured private reasoning",
+ thinkingSignature: "reasoning_content",
+ },
+ { type: "text", text: "Visible result" },
+ ]);
+ });
+
+ it("suppresses a leading think block split across streaming deltas", () => {
+ const filter = createLeadingThinkTextFilterForTest();
+
+ expect(filter.push("\n<th")).toBe("");
expect(filter.push("ink>private reasoning")).toBe("");
expect(filter.takeThinkingActivity()).toEqual({
started: true,
@@ -939,7 +1700,7 @@ it("reads Responses text phase only from structured signature metadata", () => {
}
});
- it("drops a non-JSON reasoning signature when history moves to an OpenAI Responses model", () => {
+ it("omits legacy foreign reasoning when history moves to an OpenAI Responses model", () => {
const messages: Message[] = [{
role: "assistant",
content: [{
@@ -959,11 +1720,8 @@ it("reads Responses text phase only from structured signature metadata", () => {
| { role: "assistant"; content: Array<{ type: string; thinking?: string; thinkingSignature?: string }> }
| undefined;
- expect(assistant?.content[0]).toMatchObject({
- type: "thinking",
- thinking: "private prior-model reasoning",
- });
- expect(assistant?.content[0]).not.toHaveProperty("thinkingSignature");
+ expect(assistant).toBeUndefined();
+ expect(messages[0].content[0]).toMatchObject({ thinkingSignature: "reasoning_content" });
});
it("preserves a Responses-compatible reasoning signature on the next model turn", () => {
@@ -974,6 +1732,7 @@ it("reads Responses text phase only from structured signature metadata", () => {
type: "thinking",
thinking: "compatible reasoning",
thinkingSignature: signature,
+ replayOrigin: replayOrigin({ api: "openai-responses", provider: "openai", id: "gpt-5.5" }),
}],
}];
@@ -1166,266 +1925,213 @@ it("reads Responses text phase only from structured signature metadata", () => {
});
});
-it("uses GPT-6 Responses tools, vision, explicit cache TTL, and supported reasoning levels", async () => {
- const payloads: Record<string, any>[] = [];
+describe("pi-provider wrapError", () => {
+ it.each(['complete', 'stream'] as const)('retains host budget errors before SDK flattening in %s', async method => {
+ const warning = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const fetchStub = vi.fn(async () => { throw new Error('must not access network'); });
+ vi.stubGlobal('fetch', fetchStub);
+ const original = Object.assign(new Error('opaque diagnostic'), { code: 'TASK_TOKEN_LIMIT_REACHED' });
+ const provider = createPiProvider({ provider: 'openai', model: 'gpt-5.5', apiKey: 'fixture',
+ onPayload() { throw original; } });
+ try {
+ const params: CompletionParams = { messages: [{ role: 'user', content: [{ type: 'text', text: 'probe' }] }] };
+ let failure: unknown;
+ if (method === 'complete') {
+ try { await provider.complete(params); } catch (error) { failure = error; }
+ } else {
+ for await (const event of provider.stream(params)) if (event.type === 'error') failure = event.error;
+ }
+ expect((failure as Error).cause).toBe(original);
+ expect(classifyRetryableError(failure)).toBeNull();
+ expect(fetchStub).not.toHaveBeenCalled();
+ expect(warning.mock.calls).toHaveLength(1);
+ expect(JSON.stringify(warning.mock.calls)).not.toContain('opaque diagnostic');
+ } finally { vi.unstubAllGlobals(); warning.mockRestore(); }
+ });
+
+ it.each(["stream", "complete"] as const)("preserves structured context overflow on the %s adapter path", async (mode) => {
+ const diagnostic = '400: {"message":"Request rejected","type":"invalid_request_error","code":"context_length_exceeded"}';
+ const warning = vi.spyOn(console, "warn").mockImplementation(() => {});
+ let intercepted = 0;
+ try {
const provider = createPiProvider({
- provider: "openai",
- model: "gpt-6-astra",
- apiKey: "test",
- onPayload: (payload) => {
- payloads.push(payload as Record<string, any>);
- throw new Error("payload captured before network");
- },
+ provider: "openai", model: "gpt-5.5", apiKey: "test",
+ onPayload() { intercepted++; throw Object.assign(new Error(diagnostic), { code: "context_length_exceeded" }); },
});
- const base = {
- model: "gpt-6-astra",
- messages: [{
- role: "user" as const,
- content: [
- { type: "text" as const, text: "Read the diagram." },
- { type: "image" as const, data: "AQID", mimeType: "image/png" },
- ],
- }],
- tools: [{
- name: "read_file",
- description: "Read a file",
- inputSchema: {
- type: "object",
- properties: { path: { type: "string" } },
- required: ["path"],
- },
- }],
- sessionId: "gpt6-payload-contract",
- };
+ const params = { model: "gpt-5.5", messages: [
+ { role: "user" as const, content: [{ type: "text" as const, text: "probe" }] },
+ ] };
+ if (mode === "complete") {
+ await expect(provider.complete(params)).rejects.toBeInstanceOf(ContextOverflowError);
+ } else {
+ const events: StreamEvent[] = [];
+ for await (const event of provider.stream(params)) events.push(event);
+ const errors = events.filter((event) => event.type === "error");
+ expect(errors).toHaveLength(1);
+ expect(errors[0].error).toBeInstanceOf(ContextOverflowError);
+ expect(events.some((event) => event.type === "tool_use_start" || event.type === "message_end")).toBe(false);
+ }
+ expect(intercepted).toBe(1); // Every request stops before network access.
+ expect(JSON.stringify(warning.mock.calls)).not.toContain(diagnostic);
+ } finally {
+ warning.mockRestore();
+ }
+ });
- await expect(provider.complete({
- ...base,
- reasoning: "low",
- cacheRetention: "long",
- })).rejects.toThrow(/payload captured before network/);
- await expect(provider.complete({
- ...base,
- reasoning: "off",
- cacheRetention: "none",
- })).rejects.toThrow(/payload captured before network/);
+ it.each([
+ '{"code":"context_length_exceeded"}',
+ '400 {"error":{"code":"context_length_exceeded"}}',
+ ])("decodes a structured overflow code without depending on message wording: %s", (diagnostic) => {
+ const original = new ProviderError(diagnostic, "openai", 400,
+ Object.assign(new Error('opaque'), { code: 'context_length_exceeded' }));
+ const wrapped = wrapErrorForTest(original, "openai");
+ expect(wrapped).toBeInstanceOf(ContextOverflowError);
+ expect(wrapped.cause).toBe(original);
+ });
- expect(payloads).toHaveLength(2);
- expect(payloads[0]).toMatchObject({
- model: "gpt-6-astra",
- stream: true,
- prompt_cache_key: "gpt6-payload-contract",
- prompt_cache_options: { ttl: "30m" },
- reasoning: { effort: "low", summary: "auto" },
- tools: [{ type: "function", name: "read_file" }],
- });
- expect(payloads[0].prompt_cache_retention).toBeUndefined();
- expect(JSON.stringify(payloads[0].input)).toContain("input_image");
+ it.each([
+ '400: {"code":"invalid_request_error","message":"context_length_exceeded"}',
+ '400: {"message":"The request context is too long"}',
+ '400: {"code":"context_length_exceeded"',
+ 'Diagnostic example: {"code":"context_length_exceeded"}',
+ '[{"code":"context_length_exceeded"}]',
+ ])("preserves generic errors with missing, malformed, or quoted codes: %s", (diagnostic) => {
+ const original = new ProviderError(diagnostic, "openai");
+ expect(wrapErrorForTest(original, "openai")).toBe(original);
+ });
- expect(payloads[1]).toMatchObject({
- model: "gpt-6-astra",
- stream: true,
- prompt_cache_options: { mode: "explicit" },
- });
- expect(payloads[1].prompt_cache_key).toBeUndefined();
- expect(payloads[1].prompt_cache_retention).toBeUndefined();
- expect(payloads[1]).not.toHaveProperty("reasoning");
- expect(payloads[1]).not.toHaveProperty("include");
+ it("preserves a statusless authentication diagnostic without inventing its type", () => {
+ const streamError = new ProviderError("The authentication token is expired", "openai-codex");
+ const wrapped = wrapErrorForTest(streamError, "openai-codex");
+ expect(wrapped).toBe(streamError);
+ });
+
+ it("preserves unrelated ProviderErrors for downstream policy classification", () => {
+ const permissionError = new ProviderError("Forbidden", "openai-codex", 403);
+ expect(wrapErrorForTest(permissionError, "openai-codex")).toBe(permissionError);
+ });
+
+ it.each([
+ 'Authentication is not the cause of this failure',
+ 'There is no rate limit on this request',
+ 'The record number is 429 and operation failed',
+ ])('does not manufacture credential types from prose: %s', (message) => {
+ const wrapped = wrapErrorForTest(new Error(message), 'custom');
+ expect(wrapped).toBeInstanceOf(ProviderError);
+ expect(wrapped.message).toBe(message);
+ });
+
+ it("parses delta-seconds retry-after from SDK error headers into retryAfterMs", () => {
+ const sdkErr = Object.assign(new Error("429 Too Many Requests"), {
+ status: 429,
+ headers: { "Retry-After": "7" },
});
+ const wrapped = wrapErrorForTest(sdkErr, "openai");
+ expect(wrapped).toBeInstanceOf(RateLimitError);
+ expect((wrapped as InstanceType<typeof RateLimitError>).retryAfterMs).toBe(7000);
+ });
-it.each([
- ["anthropic", "claude-fable-5-1", "anthropic"],
- ["openrouter", "anthropic/claude-fable-5.1", "anthropic"],
- ["openrouter", "anthropic/claude-opus-5", "anthropic"],
- ["google", "gemini-3.8-flash", "google"],
- ["openrouter", "google/gemini-3.8-flash", "openai"],
- ])("round-trips %s %s through a fragmented tool stream and its follow-up result", async (providerId, modelId, protocol) => {
- const originalFetch = globalThis.fetch;
- const requests: Array<{ url: string; body: any }> = [];
- globalThis.fetch = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
- const url = input instanceof Request ? input.url : String(input);
- const raw = input instanceof Request ? await input.clone().text() : String(init?.body);
- requests.push({ url, body: JSON.parse(raw) });
- const toolReply = requests.length === 1;
- let data: unknown[];
- if (protocol === "anthropic") {
- data = [
- { type: "message_start", message: { id: "msg-compat", type: "message", role: "assistant", model: modelId, content: [], usage: { input_tokens: 12, output_tokens: 0 } } },
- { type: "content_block_start", index: 0, content_block: toolReply ? { type: "tool_use", id: "call_next", name: "lookup", input: {} } : { type: "text", text: "" } },
- ...(toolReply ? [
- { type: "content_block_delta", index: 0, delta: { type: "input_json_delta", partial_json: '{"item":' } },
- { type: "content_block_delta", index: 0, delta: { type: "input_json_delta", partial_json: '"follow-up"}' } },
- ] : [{ type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "verified" } }]),
- { type: "content_block_stop", index: 0 },
- { type: "message_delta", delta: { stop_reason: toolReply ? "tool_use" : "end_turn" }, usage: { output_tokens: 2 } },
- { type: "message_stop" },
- ];
- } else if (protocol === "google") {
- const parts = toolReply ? [{ functionCall: { id: "call_next", name: "lookup", args: { item: "follow-up" } } }] : [{ text: "verified" }];
- data = [{ candidates: [{ index: 0, content: { role: "model", parts }, finishReason: "STOP" }], modelVersion: modelId, usageMetadata: { promptTokenCount: 12, candidatesTokenCount: 2, totalTokenCount: 14 } }];
- } else {
- data = toolReply ? [
- { id: "chatcmpl-compat", model: modelId, choices: [{ index: 0, delta: { role: "assistant", tool_calls: [{ index: 0, id: "call_next", type: "function", function: { name: "lookup", arguments: '{"item":' } }] }, finish_reason: null }] },
- { id: "chatcmpl-compat", model: modelId, choices: [{ index: 0, delta: { tool_calls: [{ index: 0, function: { arguments: '"follow-up"}' } }] }, finish_reason: "tool_calls" }], usage: { prompt_tokens: 12, completion_tokens: 2, total_tokens: 14 } },
- ] : [{ id: "chatcmpl-compat", model: modelId, choices: [{ index: 0, delta: { role: "assistant", content: "verified" }, finish_reason: "stop" }], usage: { prompt_tokens: 12, completion_tokens: 2, total_tokens: 14 } }];
- }
- const sse = data.map((event: any) => `${protocol === "anthropic" ? `event: ${event.type}\n` : ""}data: ${JSON.stringify(event)}\n\n`).join("");
- const bytes = new TextEncoder().encode(sse + (protocol === "openai" ? "data: [DONE]\n\n" : ""));
- // Split inside SSE fields and JSON tokens, independently of event boundaries.
- const body = new ReadableStream<Uint8Array>({
- start(controller) {
- for (let offset = 0; offset < bytes.length; offset += 11) controller.enqueue(bytes.slice(offset, offset + 11));
- controller.close();
- },
- });
- return new Response(body, {
- headers: { "content-type": "text/event-stream" },
- });
- }) as typeof fetch;
- try {
- const provider = createPiProvider({ provider: providerId, model: modelId, apiKey: "test" });
- const params: CompletionParams = {
- model: modelId,
- reasoning: "low",
- tools: [{ name: "lookup", description: "Look up an item", inputSchema: { type: "object", properties: { item: { type: "string" } }, required: ["item"] } }],
- messages: [
- { role: "user", content: [{ type: "text", text: "Check this image" }, { type: "image", data: "aGVsbG8=", mediaType: "image/png" }] },
- { role: "assistant", content: [{ type: "tool_use", id: "call_lookup", name: "lookup", input: { item: "sample" } }] },
- { role: "user", content: [{ type: "tool_result", toolUseId: "call_lookup", content: "item found" }] },
- ],
- };
- const events: StreamEvent[] = [];
- for await (const event of provider.stream(params)) events.push(event);
- expect(events.filter((event) => event.type === "error")).toEqual([]);
- expect(events.filter((event) => event.type === "message_start")).toHaveLength(1);
- const terminals = events.filter((event) => event.type === "message_end");
- expect(terminals).toHaveLength(1);
- const terminal = terminals[0];
- expect(terminal).toMatchObject({ model: modelId, stopReason: "tool_use", usage: { inputTokens: 12, outputTokens: 2 } });
- expect(terminal.content).toEqual([expect.objectContaining({ type: "tool_use", name: "lookup", input: { item: "follow-up" } })]);
- const tool = terminal.content![0];
- if (tool.type !== "tool_use") throw new Error("Expected a replayable tool call");
- expect(tool.id).toBeTruthy();
- expect(events.filter((event) => event.type === "tool_use_start")).toEqual([{ type: "tool_use_start", id: tool.id, name: "lookup" }]);
- expect(events.filter((event) => event.type === "tool_use_end")).toEqual([{ type: "tool_use_end", id: tool.id }]);
- const streamedArguments = events.filter((event) => event.type === "tool_use_delta").map((event) => event.input).join("");
- expect(JSON.parse(streamedArguments)).toEqual({ item: "follow-up" });
- const result = await provider.complete({
- ...params,
- messages: [
- ...params.messages,
- { role: "assistant", content: terminal.content! },
- { role: "user", content: [{ type: "tool_result", toolUseId: tool.id, content: "follow-up found" }] },
- ],
- });
- expect(result).toMatchObject({ model: modelId, stopReason: "end_turn", content: [{ type: "text", text: "verified" }], usage: { inputTokens: 12, outputTokens: 2 } });
- expect(requests).toHaveLength(2);
- const { url, body } = requests[0];
- if (protocol === "anthropic") {
- expect(url).toBe(providerId === "anthropic" ? "https://api.anthropic.com/v1/messages?beta=true" : "https://openrouter.ai/api/v1/messages?beta=true");
- expect(body).toMatchObject({ model: modelId, thinking: { type: "adaptive" }, tools: [expect.objectContaining({ name: "lookup" })] });
- expect(body.messages).toEqual(expect.arrayContaining([
- expect.objectContaining({ role: "user", content: expect.arrayContaining([{ type: "image", source: { type: "base64", media_type: "image/png", data: "aGVsbG8=" } }]) }),
- expect.objectContaining({ role: "assistant", content: expect.arrayContaining([expect.objectContaining({ type: "tool_use", id: "call_lookup", name: "lookup", input: { item: "sample" } })]) }),
- expect.objectContaining({ role: "user", content: expect.arrayContaining([expect.objectContaining({ type: "tool_result", tool_use_id: "call_lookup" })]) }),
- { role: "system", content: [], output_config: { effort: "low" } },
- ]));
- const replayed = requests[1].body.messages.filter((message: any) => message.role === "user").at(-1).content
- .find((block: any) => block.type === "tool_result");
- expect(replayed).toMatchObject({ tool_use_id: tool.id });
- // Anthropic accepts tool-result text as either a string or text blocks.
- expect(typeof replayed.content === "string" ? replayed.content : replayed.content.map((block: any) => block.text).join(""))
- .toBe("follow-up found");
- } else if (protocol === "google") {
- expect(url).toContain(`/models/${modelId}:streamGenerateContent`);
- expect(body.generationConfig.thinkingConfig.thinkingLevel).toBe("LOW");
- expect(body.contents[0].parts).toContainEqual({ inlineData: { mimeType: "image/png", data: "aGVsbG8=" } });
- expect(body.contents[1].parts).toEqual(expect.arrayContaining([expect.objectContaining({ functionCall: expect.objectContaining({ name: "lookup", args: { item: "sample" } }) })]));
- expect(body.contents[2].parts).toEqual(expect.arrayContaining([expect.objectContaining({ functionResponse: expect.objectContaining({ name: "lookup" }) })]));
- expect(body.tools[0].functionDeclarations[0]).toMatchObject({ name: "lookup" });
- expect(requests[1].body.contents.at(-1).parts).toEqual(expect.arrayContaining([
- expect.objectContaining({ functionResponse: expect.objectContaining({ name: "lookup", response: { output: "follow-up found" } }) }),
- ]));
- } else {
- expect(url).toBe("https://openrouter.ai/api/v1/chat/completions");
- expect(body).toMatchObject({ model: modelId, reasoning: { effort: "low" } });
- expect(body.messages[0].content).toContainEqual({ type: "image_url", image_url: { url: "data:image/png;base64,aGVsbG8=" } });
- expect(body.messages[1].tool_calls[0]).toMatchObject({ id: "call_lookup", function: { name: "lookup", arguments: '{"item":"sample"}' } });
- expect(body.messages[2]).toMatchObject({ role: "tool", tool_call_id: "call_lookup", content: "item found" });
- expect(body.tools[0]).toMatchObject({ type: "function", function: { name: "lookup" } });
- expect(requests[1].body.messages.at(-1)).toMatchObject({ role: "tool", tool_call_id: tool.id, content: "follow-up found" });
- }
- } finally {
- globalThis.fetch = originalFetch;
- }
+ it("absent header → retryAfterMs stays undefined (runner keeps default backoff)", () => {
+ const wrapped = wrapErrorForTest(Object.assign(new Error("429 Too Many Requests"), { status: 429 }), "openai");
+ expect(wrapped).toBeInstanceOf(RateLimitError);
+ expect((wrapped as InstanceType<typeof RateLimitError>).retryAfterMs).toBeUndefined();
+ });
+
+ it("parses the HTTP-date retry-after form relative to now", () => {
+ const target = new Date(Date.now() + 30_000).toUTCString();
+ const sdkErr = Object.assign(new Error("rate limit exceeded"), {
+ status: 429,
+ headers: { "retry-after": target },
});
+ const wrapped = wrapErrorForTest(sdkErr, "anthropic");
+ expect(wrapped).toBeInstanceOf(RateLimitError);
+ const ms = (wrapped as InstanceType<typeof RateLimitError>).retryAfterMs;
+ // toUTCString truncates milliseconds, so allow up to ~1s of slack below.
+ expect(ms).toBeGreaterThanOrEqual(25_000);
+ expect(ms).toBeLessThanOrEqual(30_000);
+ });
-it.each(["truncated", "aborted"] as const)("does not complete a %s OpenRouter Claude stream and accepts a fresh retry", async (failure) => {
- const originalFetch = globalThis.fetch;
- const warning = vi.spyOn(console, "warn").mockImplementation(() => {});
- const abort = new AbortController();
- const modelId = "anthropic/claude-fable-5.1";
- let requestCount = 0;
- globalThis.fetch = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
- requestCount += 1;
- const recovered = requestCount === 2;
- const signal = input instanceof Request ? input.signal : init?.signal;
- const events = [
- { type: "message_start", message: { id: "msg-interrupted", type: "message", role: "assistant", model: modelId, content: [], usage: { input_tokens: 12, output_tokens: 0 } } },
- { type: "content_block_start", index: 0, content_block: { type: "text", text: "" } },
- { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: recovered ? "verified" : "partial" } },
- ...(recovered ? [
- { type: "content_block_stop", index: 0 },
- { type: "message_delta", delta: { stop_reason: "end_turn" }, usage: { output_tokens: 2 } },
- { type: "message_stop" },
- ] : []),
- ];
- const bytes = new TextEncoder().encode(events.map((event) => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`).join(""));
- return new Response(new ReadableStream<Uint8Array>({
- start(controller) {
- controller.enqueue(bytes);
- if (recovered || failure === "truncated") controller.close();
- else signal?.addEventListener("abort", () => controller.error(new DOMException("Request aborted", "AbortError")), { once: true });
- },
- }), { headers: { "content-type": "text/event-stream" } });
- }) as typeof fetch;
- try {
- const provider = createPiProvider({ provider: "openrouter", model: modelId, apiKey: "test" });
- const params: CompletionParams = { model: modelId, messages: [{ role: "user", content: [{ type: "text", text: "answer" }] }] };
- const events: StreamEvent[] = [];
- for await (const event of provider.stream({ ...params, signal: abort.signal })) {
- events.push(event);
- if (failure === "aborted" && event.type === "text_delta") abort.abort();
- }
- expect(events.filter((event) => event.type === "text_delta")).toEqual([{ type: "text_delta", text: "partial" }]);
- expect(events.filter((event) => event.type === "message_end")).toEqual([]);
- expect(events.filter((event) => event.type === "tool_use_start")).toEqual([]);
- const errors = events.filter((event) => event.type === "error");
- expect(errors).toHaveLength(1);
- const errorPattern = failure === "aborted" ? /abort/i : /stream ended/i;
- expect(errors[0].error.message).toMatch(errorPattern);
- expect(requestCount).toBe(1);
- expect(warning.mock.calls).toEqual([["[pi-provider]", "provider stream failed", expect.objectContaining({
- aborted: failure === "aborted",
- code: "unknown",
- elapsedMs: expect.any(Number),
- httpStatus: 200,
- lastEvent: "text_delta",
- phase: "after_response",
- source: "sdk_error",
- })]]);
- expect(JSON.stringify(warning.mock.calls)).not.toContain(errors[0].error.message);
+ it("prefers retry-after-ms and supports WHATWG Headers instances", () => {
+ const headers = new Headers({ "retry-after-ms": "2500", "retry-after": "9" });
+ expect(retryAfterMsFromForTest(Object.assign(new Error("429"), { headers }))).toBe(2500);
+ });
- warning.mockClear();
- const retryEvents: StreamEvent[] = [];
- for await (const event of provider.stream(params)) retryEvents.push(event);
- expect(retryEvents.filter((event) => event.type === "error")).toEqual([]);
- expect(retryEvents.filter((event) => event.type === "message_end")).toEqual([
- expect.objectContaining({ stopReason: "end_turn", content: [{ type: "text", text: "verified" }], model: modelId }),
- ]);
- expect(requestCount).toBe(2);
- expect(warning).not.toHaveBeenCalled();
- } finally {
- globalThis.fetch = originalFetch;
- warning.mockRestore();
- }
+ it("walks the cause chain to the failing response's headers", () => {
+ const inner = Object.assign(new Error("upstream 429"), {
+ status: 429,
+ response: { headers: { "retry-after": "3" } },
});
+ const outer = Object.assign(new Error("too many requests"), { cause: inner });
+ const wrapped = wrapErrorForTest(outer, "openai");
+ expect(wrapped).toBeInstanceOf(RateLimitError);
+ expect((wrapped as InstanceType<typeof RateLimitError>).retryAfterMs).toBe(3000);
+ });
+
+ it("ignores unparsable retry-after values", () => {
+ expect(retryAfterMsFromForTest(Object.assign(new Error("429"), {
+ headers: { "retry-after": "soon-ish" },
+ }))).toBeUndefined();
+ expect(retryAfterMsFromForTest(Object.assign(new Error("429"), {
+ headers: { "retry-after": "-5" },
+ }))).toBeUndefined();
+ });
+});
+
+describe("pi-provider buildPiContext › tool schema fidelity (CA-1)", () => {
+ const richTool = {
+ name: "todo_tasks",
+ description: "manage the project task backlog",
+ inputSchema: {
+ type: "object",
+ properties: {
+ action: {
+ type: "string",
+ enum: ["list", "create", "update", "complete"],
+ description: "The action to perform.",
+ },
+ filter: {
+ type: "object",
+ properties: { status: { type: "string", enum: ["open", "done"] } },
+ required: ["status"],
+ },
+ tags: { type: "array", items: { type: "string" } },
+ count: { type: "number" },
+ },
+ required: ["action"],
+ },
+ };
+
+ function paramsOf() {
+ const messages: Message[] = [{ role: "user", content: [{ type: "text", text: "hi" }] }];
+ const context = buildPiContextForTest(messages, undefined, [richTool]);
+ // The provider layer reads `parameters` as a plain JSON Schema; serialize
+ // it the same way to assert what actually reaches the model.
+ return JSON.parse(JSON.stringify(context.tools![0].parameters));
+ }
+
+ it("preserves enums instead of collapsing them to a bare string", () => {
+ const p = paramsOf();
+ expect(p.properties.action.type).toBe("string");
+ expect(p.properties.action.enum).toEqual(["list", "create", "update", "complete"]);
+ expect(p.properties.filter.properties.status.enum).toEqual(["open", "done"]);
+ });
+
+ it("preserves nested object shape and its inner required", () => {
+ const p = paramsOf();
+ expect(p.properties.filter.type).toBe("object");
+ expect(p.properties.filter.properties.status.type).toBe("string");
+ expect(p.properties.filter.required).toEqual(["status"]);
+ });
+
+ it("preserves array item schemas instead of Array(Any)", () => {
+ const p = paramsOf();
+ expect(p.properties.tags.type).toBe("array");
+ expect(p.properties.tags.items).toEqual({ type: "string" });
+ });
+
+ it("keeps top-level required and scalar param types", () => {
+ const p = paramsOf();
+ expect(p.required).toEqual(["action"]);
+ expect(p.properties.count.type).toBe("number");
+ });
+});
diff --git a/src/core-agent/test/replay-compatibility.test.ts b/src/core-agent/test/replay-compatibility.test.ts
new file mode 100644
index 00000000..f73e974b
--- /dev/null
+++ b/src/core-agent/test/replay-compatibility.test.ts
@@ -0,0 +1,377 @@
+import { afterEach, expect, it, vi } from 'vitest';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { createPiProvider, buildPiContextForTest, mapProviderContentForTest } from '../src/providers/pi-provider.js';
+import { replayOrigin, projectDeepSeekToolReasoning } from '../src/providers/replay-compatibility.js';
+import { PersistentSession } from '../src/agent/persistent-session.js';
+import type { CompletionParams, LLMProvider } from '../src/providers/base.js';
+import type { MessageContent } from '../src/shared/types.js';
+import { transformMessages } from '@earendil-works/pi-ai/api/transform-messages';
+
+const model = { api: 'openai-responses' as const, provider: 'openai', id: 'fixture', name: 'fixture',
+ baseUrl: 'https://example.invalid/v1', reasoning: true, input: ['text' as const], contextWindow: 10000,
+ maxTokens: 100, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 } };
+const reasoning = { type: 'reasoning', id: 'rs_fixture', status: 'completed', summary: [], encrypted_content: 'PRIVATE_CIPHER' };
+const call = { type: 'function_call', id: 'fc_fixture', call_id: 'call_fixture', name: 'inspect', arguments: '{}' };
+const answer = { type: 'message', id: 'msg_fixture', role: 'assistant', status: 'completed',
+ content: [{ type: 'output_text', text: 'Count: 7', annotations: [] }] };
+function response(items: any[]) {
+ const events: any[] = items.flatMap((item, output_index) => [
+ { type: 'response.output_item.added', output_index, item },
+ { type: 'response.output_item.done', output_index, item },
+ ]);
+ events.push({ type: 'response.completed', response: { id: 'resp_fixture', status: 'completed', output: items,
+ usage: { input_tokens: 10, output_tokens: 3, total_tokens: 13 } } });
+ return new Response(events.map(e => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(''),
+ { headers: { 'content-type': 'text/event-stream' } });
+}
+async function invoke(provider: LLMProvider, method: 'complete' | 'stream', params: CompletionParams) {
+ if (method === 'complete') return (await provider.complete(params)).content;
+ let content: MessageContent[] | undefined;
+ for await (const event of provider.stream(params)) {
+ if (event.type === 'error') throw event.error;
+ if (event.type === 'message_end') content = event.content;
+ }
+ expect(content).toBeDefined();
+ return content!;
+}
+afterEach(() => { vi.unstubAllGlobals(); vi.restoreAllMocks(); });
+
+it.each(['complete', 'stream'] as const)('keeps managed replay provenance off direct %s requests', async method => {
+ const marked = { ...reasoning, _orkas_replay: 'v1:synthetic-managed-source' };
+ const messages: CompletionParams['messages'] = [
+ { role: 'assistant', content: [{ type: 'thinking', thinking: '',
+ thinkingSignature: JSON.stringify(marked), replayOrigin: replayOrigin(model, 'fixture') }] },
+ { role: 'user', content: [{ type: 'text', text: 'Continue' }] },
+ ];
+ const original = JSON.stringify(messages);
+ let sent: any;
+ vi.stubGlobal('fetch', vi.fn(async (_url: unknown, init: any) => {
+ sent = JSON.parse(init.body);
+ return response([answer]);
+ }));
+ await invoke(createPiProvider({ provider: 'openai', apiKey: 'fixture', customModel: model }), method, { messages });
+ expect(sent.input.find((item: any) => item.type === 'reasoning')).toEqual({
+ type: 'reasoning', id: 'rs_fixture', summary: [], encrypted_content: 'PRIVATE_CIPHER',
+ });
+ expect(JSON.stringify(messages)).toBe(original);
+
+
+});
+
+// The switch journey uses the real SDK and disk reload; the synthetic transport
+// proves projection and tool/receipt continuity, not live DeepSeek acceptance.
+it.each([
+ ['complete', undefined, 'deepseek'], ['stream', 'high', 'deepseek'],
+ ['complete', 'high', 'custom'], ['stream', undefined, 'custom'],
+] as const)('keeps reasoning and receipts after repeated switches: %s / %s / %s', async (method, effort, providerId) => {
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-deepseek-switch-'));
+ const file = path.join(directory, 'session.jsonl');
+ const bodies: any[] = [];
+ const chatModel = { ...model, api: 'openai-completions' as const, provider: providerId,
+ baseUrl: 'https://api.deepseek.com/v1', id: 'deepseek-flash' };
+ vi.stubGlobal('fetch', vi.fn(async (_url: unknown, init: any) => {
+ const body = JSON.parse(init.body); bodies.push(body);
+ if (!body.messages) return response([
+ { ...reasoning, id: `rs_${bodies.length}` },
+ { ...call, id: `fc_${bodies.length}`, call_id: `call_${bodies.length}` },
+ ]);
+ const delta = bodies.length === 2
+ ? { reasoning_content: 'Native DeepSeek thought', tool_calls: [{ index: 0, id: 'call_2',
+ type: 'function', function: { name: 'inspect', arguments: '{}' } }] }
+ : { content: 'Count: 7' };
+ return new Response(`data: ${JSON.stringify({ choices: [{ index: 0, delta: { role: 'assistant', ...delta },
+ finish_reason: bodies.length === 2 ? 'tool_calls' : 'stop' }] })}\n\ndata: [DONE]\n\n`,
+ { headers: { 'content-type': 'text/event-stream' } });
+ }));
+ try {
+ let session = new PersistentSession({ sessionFile: file });
+ session.beginUserTurn([{ type: 'text', text: 'Inspect the count' }]);
+ for (const [index, target] of [model, chatModel, model, chatModel].entries()) {
+ session = new PersistentSession({ sessionFile: file });
+ const messages = session.getMessagesForModel();
+ const before = JSON.stringify(messages);
+ const provider = createPiProvider({ provider: target.provider, apiKey: 'fixture', customModel: target,
+ // Async observer must retain all outbound normalization.
+ ...(providerId === 'custom' ? { onPayload: async () => undefined } : {}) });
+ const output = await invoke(provider, method, { messages, reasoning: effort });
+ expect(JSON.stringify(messages)).toBe(before);
+ if (index % 2 === 1) {
+ const sent = bodies.at(-1);
+ const assistants = sent.messages.filter((m: any) => m.tool_calls?.length);
+ expect(assistants.map((m: any) => m.reasoning_content)).toEqual(index === 1
+ ? ['.'] : ['.', 'Native DeepSeek thought', '.']);
+ for (const assistant of assistants) {
+ expect(assistant.tool_calls).toHaveLength(1);
+ const tool = assistant.tool_calls[0];
+ expect(tool.function).toEqual({ name: 'inspect', arguments: '{}' });
+ expect(sent.messages.find((m: any) => m.tool_call_id === tool.id)).toMatchObject({ role: 'tool', content: '{"count":7}' });
+ }
+ if (effort) expect(sent).toMatchObject({ thinking: { type: 'enabled' }, reasoning_effort: effort });
+ else { expect(sent).not.toHaveProperty('thinking'); expect(sent).not.toHaveProperty('reasoning_effort'); }
+ expect(JSON.stringify(sent)).not.toContain('PRIVATE_CIPHER');
+ } else if (index === 2) {
+ expect(bodies.at(-1).input.filter((i: any) => i.type === 'reasoning')).toEqual([
+ { type: 'reasoning', id: 'rs_1', summary: [], encrypted_content: 'PRIVATE_CIPHER' },
+ ]);
+ expect(JSON.stringify(bodies.at(-1))).not.toContain('Native DeepSeek thought');
+ }
+ session.addAssistantMessage(output);
+ if (index < 3) {
+ const tool = output.find(i => i.type === 'tool_use');
+ expect(tool?.type).toBe('tool_use');
+ session.addToolResult(tool!.type === 'tool_use' ? tool!.id : '', '{"count":7}');
+ } else expect(output).toContainEqual(expect.objectContaining({ type: 'text', text: 'Count: 7' }));
+ }
+ expect(bodies).toHaveLength(4);
+ const saved = new PersistentSession({ sessionFile: file }).getMessagesForModel();
+ expect(saved.flatMap(m => m.content).filter(c => c.type === 'thinking')
+ .some(c => c.type === 'thinking' && c.thinking === '.')).toBe(false);
+ } finally { fs.rmSync(directory, { recursive: true, force: true }); }
+});
+
+it('fills only missing DeepSeek tool reasoning without changing real thoughts, images, ids or public text', () => {
+ const target = { ...model, api: 'openai-completions', provider: 'deepseek' };
+ const tool = { id: 'c1', type: 'function', function: { name: 'inspect', arguments: '{}' } };
+ const payload = { reasoning_effort: 'high', thinking: { type: 'enabled' }, messages: [
+ { role: 'assistant', content: 'plain answer' },
+ { role: 'assistant', content: 'Checking', tool_calls: [tool, { ...tool, id: 'c2' }], reasoning_content: '' },
+ { role: 'tool', tool_call_id: 'c1', content: [{ type: 'image_url', image_url: { url: 'data:image/png;base64,AA==' } }] },
+ { role: 'assistant', tool_calls: [tool], reasoning_content: 'Real thought' },
+ { role: 'assistant', tool_calls: [tool] },
+ ] };
+ const original = JSON.stringify(payload);
+ const projected = projectDeepSeekToolReasoning(payload, target) as typeof payload;
+ expect(projected.messages).toEqual(payload.messages.map((m, i) => i === 1 || i === 4 ? { ...m, reasoning_content: '.' } : m));
+ expect(projected.reasoning_effort).toBe('high');
+ expect(projected.thinking).toEqual({ type: 'enabled' });
+ expect(projectDeepSeekToolReasoning(projected, target)).toBe(projected);
+ expect(JSON.stringify(payload)).toBe(original);
+ for (const field of ['reasoning', 'reasoning_text']) {
+ const portable = { messages: [{ role: 'assistant', tool_calls: [tool], reasoning_content: '', [field]: 'Portable thought' }] };
+ expect(projectDeepSeekToolReasoning(portable, target)).toEqual({ messages: [
+ { ...portable.messages[0], reasoning_content: 'Portable thought' },
+ ] });
+ }
+ for (const controls of [{ thinking: { type: 'disabled' } }, { reasoning_effort: 'none' }, { reasoning_effort: 'off' }]) {
+ const disabled = { ...payload, ...controls };
+ expect(projectDeepSeekToolReasoning(disabled, target)).toBe(disabled);
+ }
+ for (const patch of [
+ { reasoning: false }, { api: 'openai-responses' },
+ { provider: 'moonshot', compat: { thinkingFormat: 'deepseek', requiresReasoningContentOnAssistantMessages: true } },
+ { provider: 'custom', id: 'deepseek-flash' },
+ { provider: 'custom', baseUrl: 'https://api.deepseek.com.evil.invalid/v1' },
+ { provider: 'custom', baseUrl: 'https://other.invalid/api.deepseek.com' },
+ ]) expect(projectDeepSeekToolReasoning(payload, { ...target, ...patch })).toBe(payload);
+});
+
+it.each(['complete', 'stream'] as const)('resumes stored tool receipts through same and foreign %s providers without replaying private state', async method => {
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-replay-'));
+ const file = path.join(directory, 'session.jsonl');
+ const payloads: any[] = [];
+ vi.stubGlobal('fetch', vi.fn(async (_url: unknown, init: any) => {
+ payloads.push(JSON.parse(init.body));
+ return response(payloads.length === 1 ? [reasoning, call] : [answer]);
+ }));
+ const make = (patch = {}, apiKey = 'fixture-key', headers?: Record<string, string>) => createPiProvider({ provider: 'openai', apiKey, headers,
+ requestHeaders: () => ({ 'x-request-id': String(payloads.length) }), customModel: { ...model, ...patch } });
+ try {
+ const session = new PersistentSession({ sessionFile: file });
+ session.beginUserTurn([{ type: 'text', text: 'Inspect the count' }]);
+ const output = await invoke(make(), method, { messages: session.getMessagesForModel() });
+ session.addAssistantMessage(output);
+ const tool = output.find(i => i.type === 'tool_use');
+ expect(tool?.type).toBe('tool_use');
+ session.addToolResult(tool!.type === 'tool_use' ? tool!.id : '', '{"count":7}');
+ const stored = fs.readFileSync(file, 'utf8');
+ const messages = new PersistentSession({ sessionFile: file }).getMessagesForModel();
+ const original = JSON.stringify(messages);
+ for (const [provider, compatible] of [[make(), true], [make({ id: 'other' }), false],
+ [make({ baseUrl: 'https://other.invalid/v1' }), false], [make({}, 'other-key'), false],
+ [make({}, 'fixture-key', { Authorization: 'Bearer another-owner' }), false]] as const) {
+ const result = await invoke(provider, method, { messages });
+ const wire = payloads.at(-1).input;
+ expect(wire.filter((i: any) => i.type === 'reasoning')).toEqual(compatible
+ ? [{ type: 'reasoning', id: 'rs_fixture', summary: [], encrypted_content: 'PRIVATE_CIPHER' }] : []);
+ const sentCall = wire.find((i: any) => i.type === 'function_call');
+ const receipt = wire.find((i: any) => i.type === 'function_call_output');
+ expect(sentCall).toMatchObject({ name: 'inspect', arguments: '{}' });
+ expect(receipt).toMatchObject({ call_id: sentCall.call_id, output: '{"count":7}' });
+ expect(result.some(i => i.type === 'text' && i.text === 'Count: 7')).toBe(true);
+ expect(JSON.stringify(wire)).not.toContain('replayOrigin');
+ }
+ expect(payloads).toHaveLength(6);
+ expect(stored).not.toContain('fixture-key');
+ expect(stored).not.toContain('example.invalid');
+ expect(JSON.stringify(messages)).toBe(original);
+ expect(fs.readFileSync(file, 'utf8')).toBe(stored);
+ } finally { fs.rmSync(directory, { recursive: true, force: true }); }
+});
+
+it('keeps legacy public content and tool receipts but excludes unknown and malformed opaque state', async () => {
+ const { buildPiContextForTest } = await import('../src/providers/pi-provider.js');
+ const { replayOrigin } = await import('../src/providers/replay-compatibility.js');
+ const content: MessageContent[] = [
+ { type: 'thinking', thinking: '', thinkingSignature: JSON.stringify(reasoning) },
+ { type: 'text', text: 'Checking', textSignature: 'foreign-message-state' },
+ { type: 'tool_use', id: 'call_fixture', name: 'inspect', input: {}, thoughtSignature: 'foreign-tool-state' },
+ ];
+ const source = JSON.stringify(content);
+ const messages = [{ role: 'assistant' as const, content },
+ { role: 'user' as const, content: [{ type: 'tool_result' as const, toolUseId: 'call_fixture', content: '{"count":7}' }] }];
+ const projected = buildPiContextForTest(messages, undefined, undefined, model);
+ expect(JSON.stringify(projected)).not.toContain('PRIVATE_CIPHER');
+ // The SDK, rather than our history mapper, owns generic signature removal.
+ expect(JSON.stringify(transformMessages(projected.messages, model))).not.toContain('foreign-');
+ expect(projected.messages).toMatchObject([
+ { role: 'assistant', content: [{ type: 'text', text: 'Checking' }, { type: 'toolCall', id: 'call_fixture' }] },
+ { role: 'toolResult', toolCallId: 'call_fixture', content: [{ text: '{"count":7}' }] },
+ ]);
+ for (const signature of ['null', '[]', '"text"', '{"type":"message"}', 'not-json']) {
+ const invalid = [{ role: 'assistant' as const, content: [{ type: 'thinking' as const,
+ thinking: 'private', thinkingSignature: signature, replayOrigin: replayOrigin(model) }] }];
+ expect(buildPiContextForTest(invalid, undefined, undefined, model).messages).toEqual([]);
+ }
+ expect(JSON.stringify(content)).toBe(source);
+});
+
+it.each(['chat-to-responses', 'responses-to-chat', 'chat-to-chat', 'legacy-chat-to-chat'] as const)(
+ 'preserves tool receipt linkage and target-compatible reasoning across %s', async direction => {
+ const chatModel = { ...model, api: 'openai-completions' as const, provider: 'deepseek', id: 'deepseek-flash',
+ baseUrl: 'https://deepseek.invalid/v1' };
+ const make = (chat: boolean) => createPiProvider({ provider: chat ? 'deepseek' : 'openai', apiKey: 'fixture',
+ customModel: chat ? chatModel : model });
+ const chatResponse = (first: boolean) => {
+ const chunks = first ? [
+ { choices: [{ index: 0, delta: { role: 'assistant', reasoning_content: 'Private plaintext thought',
+ tool_calls: [{ index: 0, id: 'call_fixture', type: 'function', function: { name: 'inspect', arguments: '{}' } }] }, finish_reason: null }] },
+ { choices: [{ index: 0, delta: {}, finish_reason: 'tool_calls' }] },
+ ] : [{ choices: [{ index: 0, delta: { role: 'assistant', content: 'Count: 7' }, finish_reason: null }] },
+ { choices: [{ index: 0, delta: {}, finish_reason: 'stop' }] }];
+ return new Response(chunks.map(c => `data: ${JSON.stringify(c)}\n\n`).join('') + 'data: [DONE]\n\n',
+ { headers: { 'content-type': 'text/event-stream' } });
+ };
+ const bodies: any[] = [];
+ const sourceChat = direction !== 'responses-to-chat';
+ const targetChat = direction !== 'chat-to-responses';
+ vi.stubGlobal('fetch', vi.fn(async (_url: unknown, init: any) => {
+ const body = JSON.parse(init.body); bodies.push(body);
+ return body.messages ? chatResponse(bodies.length === 1) : response(bodies.length === 1 ? [reasoning, call] : [answer]);
+ }));
+ const messages: CompletionParams['messages'] = [{ role: 'user', content: [{ type: 'text', text: 'Inspect the count' }] }];
+ const output = JSON.parse(JSON.stringify(await invoke(make(sourceChat), 'complete', { messages }))) as MessageContent[];
+ if (direction === 'legacy-chat-to-chat') for (const block of output) delete block.replayOrigin;
+ const tool = output.find(c => c.type === 'tool_use');
+ expect(tool?.type).toBe('tool_use');
+ messages.push({ role: 'assistant', content: output }, { role: 'user', content: [{ type: 'tool_result',
+ toolUseId: tool!.type === 'tool_use' ? tool!.id : '', content: '{"count":7}' }] });
+ const original = JSON.stringify(messages);
+ await invoke(make(targetChat), 'complete', { messages });
+ expect(bodies).toHaveLength(2);
+ const sent = bodies[1];
+ expect(JSON.stringify(sent)).not.toContain('PRIVATE_CIPHER');
+ if (sourceChat && targetChat) {
+ expect(sent.messages.find((i: any) => i.tool_calls)).toMatchObject({ reasoning_content: 'Private plaintext thought' });
+ } else expect(JSON.stringify(sent)).not.toContain('Private plaintext thought');
+ if (!targetChat) {
+ const sentCall = sent.input.find((i: any) => i.type === 'function_call');
+ expect(sent.input.find((i: any) => i.type === 'function_call_output')).toMatchObject({ call_id: sentCall.call_id, output: '{"count":7}' });
+ } else {
+ const sentCall = sent.messages.find((i: any) => i.tool_calls).tool_calls[0];
+ expect(sentCall.id).not.toContain('|');
+ expect(sent.messages.find((i: any) => i.role === 'tool')).toMatchObject({ tool_call_id: sentCall.id, content: '{"count":7}' });
+ }
+ expect(JSON.stringify(messages)).toBe(original);
+});
+
+it.each([
+ { api: 'google-generative-ai' as const, provider: 'google', id: 'gemini-fixture' },
+ { api: 'anthropic-messages' as const, provider: 'anthropic', id: 'claude-fixture' },
+])('passes $provider source identity to pi so its converter removes foreign signatures', identity => {
+ const source = { ...model, ...identity };
+ const content = mapProviderContentForTest([
+ { type: 'thinking', thinking: 'PRIVATE_THOUGHT', thinkingSignature: 'PRIVATE_SIGNATURE', redacted: true },
+ { type: 'text', text: 'Checking', textSignature: 'GOOGLE_TEXT_SIGNATURE' },
+ { type: 'toolCall', id: 'call_fixture', name: 'inspect', arguments: {}, thoughtSignature: 'GOOGLE_TOOL_SIGNATURE' },
+ ], false, undefined, replayOrigin(source));
+ const messages: CompletionParams['messages'] = [{ role: 'assistant', content },
+ { role: 'user', content: [{ type: 'tool_result', toolUseId: 'call_fixture', content: '7' }] }];
+ const original = JSON.stringify(messages);
+ const context = buildPiContextForTest(messages, undefined, undefined, model);
+ expect(context.messages[0]).toMatchObject({ api: source.api, provider: source.provider, model: source.id });
+ // A deliberate boundary assertion: these reach pi, rather than being stripped
+ // by a duplicate Orkas generic converter. The outbound SDK result is the oracle.
+ expect(JSON.stringify(context.messages)).toContain('GOOGLE_TOOL_SIGNATURE');
+ const converted = transformMessages(context.messages, model);
+ expect(JSON.stringify(converted)).not.toContain('GOOGLE_');
+ expect(JSON.stringify(converted)).not.toContain('PRIVATE_');
+ expect(converted).toMatchObject([{ role: 'assistant', content: [
+ { type: 'text', text: 'Checking' }, { type: 'toolCall', id: 'call_fixture', name: 'inspect' },
+ ] }, { role: 'toolResult', toolCallId: 'call_fixture', content: [{ text: '7' }] }]);
+ expect(JSON.stringify(messages)).toBe(original);
+});
+
+it('does not treat malformed saved source identity as the target model', () => {
+ const origin = { ...replayOrigin(model), scope: 'foreign', source: {} } as unknown as NonNullable<MessageContent['replayOrigin']>;
+ const context = buildPiContextForTest([{ role: 'assistant', content: [
+ { type: 'text', text: 'Public', textSignature: 'FOREIGN_SIGNATURE', replayOrigin: origin },
+ ] }], undefined, undefined, model);
+ expect(JSON.stringify(transformMessages(context.messages, model))).not.toContain('FOREIGN_SIGNATURE');
+});
+
+it('retains compatible private state beside foreign blocks without leaking their signatures or item ids', async () => {
+ const same = replayOrigin(model, 'fixture');
+ const foreign = replayOrigin({ ...model, id: 'other' }, 'fixture');
+ const content: MessageContent[] = [
+ { type: 'thinking', thinking: '', thinkingSignature: JSON.stringify(reasoning), replayOrigin: same },
+ { type: 'text', text: 'Checking', textSignature: 'FOREIGN_TEXT_SIGNATURE', replayOrigin: foreign },
+ { type: 'tool_use', id: 'call_foreign|fc_foreign', name: 'inspect', input: {},
+ thoughtSignature: 'FOREIGN_TOOL_SIGNATURE', namespace: 'foreign_namespace', replayOrigin: foreign },
+ { type: 'tool_use', id: 'call_same|fc_same', name: 'inspect', input: {}, replayOrigin: same },
+ ];
+ let sent: any;
+ vi.stubGlobal('fetch', vi.fn(async (_url: unknown, init: any) => { sent = JSON.parse(init.body); return response([answer]); }));
+ const messages: CompletionParams['messages'] = [{ role: 'assistant', content },
+ { role: 'user', content: [
+ { type: 'tool_result', toolUseId: 'call_foreign|fc_foreign', content: '7' },
+ { type: 'tool_result', toolUseId: 'call_same|fc_same', content: '9' },
+ ] }];
+ const original = JSON.stringify(messages);
+ await invoke(createPiProvider({ provider: 'openai', apiKey: 'fixture', customModel: model }), 'complete', { messages });
+ const calls = sent.input.filter((i: any) => i.type === 'function_call');
+ expect(calls).toHaveLength(2);
+ expect(calls[0]).not.toHaveProperty('id');
+ expect(calls[0]).not.toHaveProperty('namespace');
+ expect(calls[1]).toMatchObject({ id: 'fc_same', call_id: 'call_same' });
+ expect(sent.input.filter((i: any) => i.type === 'function_call_output')).toMatchObject([
+ { call_id: calls[0].call_id, output: '7' }, { call_id: calls[1].call_id, output: '9' },
+ ]);
+ expect(JSON.stringify(sent)).toContain('PRIVATE_CIPHER');
+ expect(JSON.stringify(sent)).not.toContain('FOREIGN_');
+ expect(JSON.stringify(messages)).toBe(original);
+});
+
+it('uses pi to keep distinct parallel receipts when Responses call ids share a prefix on a Chat handoff', async () => {
+ const source = replayOrigin(model);
+ const chat = { ...model, api: 'openai-completions' as const, provider: 'deepseek', id: 'deepseek-flash' };
+ const content: MessageContent[] = ['one', 'two'].map(suffix => ({ type: 'tool_use',
+ id: `call_shared|fc_${suffix}`, name: 'inspect', input: { key: suffix }, replayOrigin: source }));
+ const messages: CompletionParams['messages'] = [{ role: 'assistant', content }, { role: 'user',
+ content: ['one', 'two'].map(suffix => ({ type: 'tool_result', toolUseId: `call_shared|fc_${suffix}`, content: suffix })) }];
+ let sent: any;
+ vi.stubGlobal('fetch', vi.fn(async (_url: unknown, init: any) => {
+ sent = JSON.parse(init.body);
+ return new Response('data: {"choices":[{"index":0,"delta":{"content":"Both checked"},"finish_reason":"stop"}]}\n\ndata: [DONE]\n\n',
+ { headers: { 'content-type': 'text/event-stream' } });
+ }));
+ await invoke(createPiProvider({ provider: 'deepseek', apiKey: 'fixture', customModel: chat }), 'complete', { messages });
+ const calls = sent.messages.find((i: any) => i.tool_calls).tool_calls;
+ const receipts = sent.messages.filter((i: any) => i.role === 'tool');
+ expect(calls).toHaveLength(2);
+ expect(new Set(calls.map((c: any) => c.id)).size).toBe(2);
+ expect(receipts).toMatchObject([
+ { tool_call_id: calls[0].id, content: 'one' }, { tool_call_id: calls[1].id, content: 'two' },
+ ]);
+});
diff --git a/src/main/features/connectors/account-choice.ts b/src/main/features/connectors/account-choice.ts
new file mode 100644
index 00000000..d9160724
--- /dev/null
+++ b/src/main/features/connectors/account-choice.ts
@@ -0,0 +1,68 @@
+/** Account selection during authorization. Credentials never cross this boundary. */
+import { randomBytes } from 'node:crypto';
+import { t } from '../../i18n';
+import { getLanguageForUser } from '../config';
+import { getActiveUserId } from '../users';
+import { registerUserSwitchHook } from '../user-switch-hooks';
+
+export interface AccountChoice { id: string; label: string }
+interface Pending {
+ uid: string;
+ ids: Set<string>;
+ finish: (id: string | null) => void;
+}
+const pending = new Map<string, Pending>();
+let broadcastOverride: ((channel: string, payload: unknown) => boolean) | undefined;
+export function _setBroadcastForTest(fn?: typeof broadcastOverride): void { broadcastOverride = fn; }
+function broadcast(channel: string, payload: unknown): boolean {
+ if (broadcastOverride) return broadcastOverride(channel, payload);
+ try {
+ const ipc = require('../../ipc') as typeof import('../../ipc');
+ return ipc.broadcastToRenderer(channel, payload);
+ } catch { return false; }
+}
+const cancelled = () => Object.assign(new Error('Authorization cancelled'), { code: 'user_cancelled' });
+
+export function requestAccountChoice(uid: string, catalogId: string, choices: AccountChoice[], signal: AbortSignal): Promise<string> {
+ if (signal.aborted || uid !== getActiveUserId()) return Promise.reject(cancelled());
+ if (!choices.length || choices.length > 100 || new Set(choices.map(choice => choice.id)).size !== choices.length
+ || choices.some(choice => !/^[1-9][0-9]{0,24}$/.test(choice.id)
+ || typeof choice.label !== 'string' || !choice.label || choice.label.length > 200)) {
+ return Promise.reject(new Error('Invalid authorized account choices'));
+ }
+ const requestId = randomBytes(16).toString('hex');
+ const lang = getLanguageForUser(uid);
+ return new Promise((resolve, reject) => {
+ let timer: NodeJS.Timeout;
+ const abort = () => finish(null);
+ const finish = (id: string | null) => {
+ if (!pending.delete(requestId)) return;
+ clearTimeout(timer);
+ signal.removeEventListener('abort', abort);
+ broadcast('connectors:account-choice-cancelled', { request_id: requestId });
+ if (id === null) reject(cancelled()); else resolve(id);
+ };
+ timer = setTimeout(abort, 10 * 60 * 1000);
+ timer.unref?.();
+ pending.set(requestId, { uid, ids: new Set(choices.map(choice => choice.id)), finish });
+ signal.addEventListener('abort', abort, { once: true });
+ const shown = broadcast('connectors:account-choice', {
+ request_id: requestId, catalog_id: catalogId,
+ title: t('connectors.account_choice.title', {}, lang),
+ message: t('connectors.account_choice.message', {}, lang),
+ choices: choices.map(({ id, label }) => ({ id, label })),
+ });
+ if (!shown) finish(null);
+ });
+}
+
+export function respondAccountChoice(uid: string, requestId: string, id: string | null): boolean {
+ const request = pending.get(requestId);
+ if (!request || request.uid !== uid || uid !== getActiveUserId() || (id !== null && !request.ids.has(id))) return false;
+ request.finish(id);
+ return true;
+}
+
+registerUserSwitchHook('connector-account-choice', previousUid => {
+ for (const request of pending.values()) if (request.uid === previousUid) request.finish(null);
+});
diff --git a/src/main/features/connectors/action_confirm.ts b/src/main/features/connectors/action_confirm.ts
index db9af996..d00564ea 100644
--- a/src/main/features/connectors/action_confirm.ts
+++ b/src/main/features/connectors/action_confirm.ts
@@ -14,6 +14,7 @@ import { getActiveUserId } from '../users';
import { registerUserSwitchHook } from '../user-switch-hooks';
import { findCatalogEntry } from './catalog';
import type { ConnectorInstance } from './types';
+import { clearTaskCreatedDrafts } from './task-created-drafts';
const log = createLogger('connector-action-confirm');
const RESPONSE_TIMEOUT_MS = 10 * 60 * 1000;
@@ -268,6 +269,7 @@ export function respond(requestId: string, approved: boolean, scope: 'once' | 't
}
function cancelMatching(matches: (scope: GrantScope) => boolean, context: { cid?: string } = {}): void {
+ clearTaskCreatedDrafts(scope => matches({ ...scope, accountLabel: '' }));
for (const [key, grant] of _taskGrants) {
if (matches(grant)) _taskGrants.delete(key);
}
diff --git a/src/main/features/connectors/action_policy.ts b/src/main/features/connectors/action_policy.ts
index 72250eaa..90a3ec26 100644
--- a/src/main/features/connectors/action_policy.ts
+++ b/src/main/features/connectors/action_policy.ts
@@ -4,6 +4,7 @@
*/
import { findCatalogEntry } from './catalog';
import type { ConnectorInstance, ToolSchema } from './types';
+import { isTaskCreatedDraft, type DraftScope } from './task-created-drafts';
export interface ConnectorActionRisk {
risk: 'R' | 'W' | 'H' | 'D';
@@ -135,8 +136,12 @@ export function connectorActionRisk(
instance: Pick<ConnectorInstance, 'id' | 'origin' | 'composio_grant'>,
tool: ToolSchema,
args: Record<string, unknown> = {},
+ taskScope?: DraftScope,
): ConnectorActionRisk {
const base = baseConnectorActionRisk(instance, tool);
+ if (instance.origin !== 'custom' && !instance.composio_grant
+ && ['gmail', 'google-workspace'].includes(instance.id) && taskScope?.connectorId === instance.id
+ && tool.name === 'delete_draft' && isTaskCreatedDraft(taskScope, args.id)) return WRITE;
// Never weaken a pinned destructive/sensitive policy or custom-tool distrust.
if (base.risk === 'H' || base.risk === 'D') return base;
// Fathom's GET actions can POST private meeting content to a caller's URL.
diff --git a/src/main/features/connectors/catalog-direct-commerce.ts b/src/main/features/connectors/catalog-direct-commerce.ts
index d63619de..19f57804 100644
--- a/src/main/features/connectors/catalog-direct-commerce.ts
+++ b/src/main/features/connectors/catalog-direct-commerce.ts
@@ -535,19 +535,29 @@ help_it: "Copia Client Secret per lo stesso ambiente di produzione. Crittografat
icon_svg: WOOCOMMERCE_ICON_SVG,
icon_source_url: 'https://woocommerce.com/wp-content/uploads/2025/01/woo-logos.zip',
icon_source_sha256: 'a59ff90335d8ca3d13b53b93630445a8aba3e187869245adad80c3ac52628842',
- description_zh: '使用店主生成的 Read/Write REST API Key 管理 WooCommerce 商品、分类、库存、订单、客户、优惠券、评价、退款与报表。',
- description_en: 'Use a store-owner-generated Read/Write REST API key to manage WooCommerce products, taxonomy, inventory, orders, customers, coupons, reviews, refunds, and reports.',
- description_es: "Usa una clave de REST API con permisos de lectura y escritura generada por el propietario de la tienda para gestionar productos, taxonomía, inventario, pedidos, clientes, cupones, reseñas, reembolsos e informes de WooCommerce.",
- description_fr: "Utilisez une clé REST API Read/Write générée par le propriétaire de la boutique pour gérer les produits WooCommerce, la taxonomie, les stocks, les commandes, les clients, les coupons, les avis, les remboursements et les rapports.",
- description_ko: "스토어 소유자가 생성한 Read/Write REST API 키로 WooCommerce 상품, 분류, 재고, 주문, 고객, 쿠폰, 리뷰, 환불, 보고서를 관리합니다.",
- description_de: "Verwenden Sie einen vom Shopinhaber erstellten Read/Write-REST-API-Schlüssel, um WooCommerce-Produkte, Taxonomie, Bestände, Bestellungen, Kunden, Gutscheine, Bewertungen, Erstattungen und Berichte zu verwalten.",
- description_ru: "Используйте созданный владельцем магазина REST API-ключ с доступом Read/Write для управления товарами WooCommerce, классификацией, запасами, заказами, клиентами, купонами, отзывами, возвратами денег и отчётами.",
- description_it: "Usa una chiave REST API Read/Write generata dal proprietario del negozio per gestire prodotti, tassonomia, scorte, ordini, clienti, coupon, recensioni, rimborsi e report di WooCommerce.",
- description_ja: "店舗所有者が発行した Read/Write REST API キーで WooCommerce の商品、分類、在庫、注文、顧客、クーポン、レビュー、返金、レポートを管理します。",
- description_pt: "Use uma chave REST API Read/Write gerada pelo proprietário para gerenciar produtos, taxonomias, estoque, pedidos, clientes, cupons, avaliações, reembolsos e relatórios WooCommerce.",
+ description_zh: "授权店铺后管理 WooCommerce 商品、库存、订单、客户、优惠券、退款与报表。",
+ description_en: "Authorize your store to manage WooCommerce products, inventory, orders, customers, coupons, refunds, and reports.",
+ description_es: "Autoriza tu tienda para gestionar productos, inventario, pedidos, clientes, cupones, reembolsos e informes de WooCommerce.",
+ description_fr: "Autorisez votre boutique pour gérer les produits, stocks, commandes, clients, coupons, remboursements et rapports WooCommerce.",
+ description_ko: "스토어를 승인하여 WooCommerce 상품, 재고, 주문, 고객, 쿠폰, 환불 및 보고서를 관리하세요.",
+ description_de: "Autorisieren Sie Ihren Shop, um WooCommerce-Produkte, Bestände, Bestellungen, Kunden, Gutscheine, Erstattungen und Berichte zu verwalten.",
+ description_ru: "Авторизуйте магазин для управления товарами, запасами, заказами, клиентами, купонами, возвратами и отчётами WooCommerce.",
+ description_it: "Autorizza il tuo negozio per gestire prodotti, scorte, ordini, clienti, coupon, rimborsi e report WooCommerce.",
+ description_ja: "ストアを認可して WooCommerce の商品、在庫、注文、顧客、クーポン、返金、レポートを管理します。",
+ description_pt: "Autorize sua loja para gerenciar produtos, estoque, pedidos, clientes, cupons, reembolsos e relatórios WooCommerce.",
auth_mode: 'local_api', local_api: { provider: 'woocommerce' },
connection_setup: {
- guide_url: 'https://woocommerce.com/document/woocommerce-rest-api/',
+ instructions_pt: "Informe a URL da loja e conecte-se; entre na loja e permita que Orkas leia e escreva. Para usar chaves existentes, preencha os dois campos opcionais.",
+ instructions_ja: "ストア URL を入力して接続し、ストアにログインして Orkas の読み書きを許可してください。既存のキーを使う場合は下の任意項目を両方入力してください。",
+ instructions_it: "Inserisci l’URL del negozio e connettiti, poi accedi e consenti a Orkas lettura e scrittura. Per usare chiavi esistenti, compila entrambi i campi facoltativi.",
+ instructions_ru: "Введите URL магазина и подключитесь, затем войдите в магазин и разрешите Orkas чтение и запись. Для существующих ключей заполните оба необязательных поля.",
+ instructions_de: "Geben Sie die Shop-URL ein und verbinden Sie sich. Melden Sie sich im Shop an und erlauben Sie Orkas Lese-/Schreibzugriff. Für vorhandene Schlüssel füllen Sie beide optionalen Felder aus.",
+ instructions_ko: "스토어 URL을 입력하고 연결한 다음 로그인하여 Orkas의 읽기/쓰기를 허용하세요. 기존 키를 사용하려면 아래 선택 항목 두 개를 모두 입력하세요.",
+ instructions_fr: "Saisissez l’URL de votre boutique et connectez-vous, puis autorisez Orkas en lecture/écriture. Pour utiliser des clés existantes, remplissez les deux champs facultatifs.",
+ instructions_es: "Introduce la URL de tu tienda y conecta; inicia sesión y permite a Orkas leer y escribir. Para usar claves existentes, completa ambos campos opcionales.",
+ instructions_en: "Enter your store URL and connect, then sign in to your store and allow Orkas read/write access. To use existing keys, fill in both optional fields below.",
+ instructions_zh: "填写店铺网址后连接,在店铺页面登录并允许 Orkas 读取和写入。若使用已有密钥,请同时填写下方两项。",
+ guide_url: 'https://developer.woocommerce.com/docs/apis/rest-api/authentication/',
guide_label_zh: '查看 WooCommerce 官方 REST API 指南',
guide_label_en: 'Open the official WooCommerce REST API guide',
guide_label_es: "Abrir la guía oficial de REST API de WooCommerce",
@@ -580,7 +590,7 @@ help_it: "Copia Client Secret per lo stesso ambiente di produzione. Crittografat
help_pt: "Informe a URL raiz HTTPS da loja. Mantenha o subdiretório se o WordPress estiver abaixo do domínio; não inclua /wp-json/wc/v3.",
},
{
- key: 'consumer_key', input: 'text', storage: 'credential', required: true,
+ key: 'consumer_key', input: 'text', storage: 'credential', required: false,
format: 'woocommerce_consumer_key', label_zh: 'Consumer Key', label_en: 'Consumer Key',
label_es: "Consumer Key",
label_fr: "Consumer Key",
@@ -588,19 +598,19 @@ help_it: "Copia Client Secret per lo stesso ambiente di produzione. Crittografat
label_de: "Consumer Key",
label_ru: "Consumer Key",
label_it: "Consumer Key", label_ja: "Consumer Key", label_pt: "Consumer Key",
- help_zh: '在 WooCommerce > 设置 > 高级 > REST API 中为有管理权限的店铺用户创建,并选择 Read/Write。仅加密保存在本机。',
- help_en: 'Create it under WooCommerce > Settings > Advanced > REST API for a store user with the required capabilities, and select Read/Write. Encrypted on this device only.',
- help_es: "Créala en WooCommerce > Settings > Advanced > REST API para un usuario de la tienda con las capacidades requeridas y selecciona Read/Write. Se cifra únicamente en este dispositivo.",
- help_fr: "Créez-la sous WooCommerce > Settings > Advanced > REST API pour un utilisateur de la boutique disposant des capacités requises, puis sélectionnez Read/Write. Chiffrée uniquement sur cet appareil.",
- help_ko: "WooCommerce > Settings > Advanced > REST API에서 필요한 권한을 가진 스토어 사용자용 키를 만들고 Read/Write를 선택하세요. 이 기기에만 암호화하여 저장합니다.",
- help_de: "Erstellen Sie ihn unter WooCommerce > Settings > Advanced > REST API für einen Shopbenutzer mit den erforderlichen Befugnissen und wählen Sie Read/Write. Nur auf diesem Gerät verschlüsselt.",
- help_ru: "Создайте его в WooCommerce > Settings > Advanced > REST API для пользователя магазина с необходимыми правами и выберите Read/Write. Хранится в зашифрованном виде только на этом устройстве.",
- help_it: "Creala in WooCommerce > Settings > Advanced > REST API per un utente del negozio con le capacità richieste e seleziona Read/Write. Crittografata solo su questo dispositivo.",
- help_ja: "WooCommerce > Settings > Advanced > REST API で必要な権限を持つ店舗ユーザー用のキーを作成し、Read/Write を選択してください。この端末にのみ暗号化して保存されます。",
- help_pt: "Crie em WooCommerce > Settings > Advanced > REST API para um usuário da loja com as capacidades necessárias e selecione Read/Write. Armazenada criptografada apenas neste dispositivo.",
+ help_zh: "可选:已有 Read/Write 密钥时填写;否则留空,通过店铺页面授权。",
+ help_en: "Optional: enter an existing Read/Write key, or leave empty to authorize in your store.",
+ help_es: "Opcional: introduce una clave Read/Write existente o deja el campo vacío para autorizar en tu tienda.",
+ help_fr: "Facultatif : saisissez une clé Read/Write existante ou laissez vide pour autoriser dans votre boutique.",
+ help_ko: "선택 사항: 기존 Read/Write 키를 입력하거나 비워 두고 스토어에서 승인하세요.",
+ help_de: "Optional: vorhandenen Read/Write-Schlüssel eingeben oder leer lassen, um im Shop zu autorisieren.",
+ help_ru: "Необязательно: введите существующий ключ Read/Write или оставьте поле пустым для авторизации в магазине.",
+ help_it: "Facoltativo: inserisci una chiave Read/Write esistente o lascia vuoto per autorizzare nel negozio.",
+ help_ja: "任意:既存の Read/Write キーを入力するか、空欄のままストアで認可してください。",
+ help_pt: "Opcional: informe uma chave Read/Write existente ou deixe vazio para autorizar na loja.",
},
{
- key: 'consumer_secret', input: 'secret', storage: 'credential', required: true,
+ key: 'consumer_secret', input: 'secret', storage: 'credential', required: false,
format: 'woocommerce_consumer_secret', label_zh: 'Consumer Secret', label_en: 'Consumer Secret',
label_es: "Consumer Secret",
label_fr: "Consumer Secret",
@@ -608,16 +618,16 @@ help_it: "Copia Client Secret per lo stesso ambiente di produzione. Crittografat
label_de: "Consumer Secret",
label_ru: "Consumer Secret",
label_it: "Consumer Secret", label_ja: "Consumer Secret", label_pt: "Consumer Secret",
- help_zh: '与 Consumer Key 同时生成;只显示一次。仅加密保存在本机。',
- help_en: 'Generated with the Consumer Key and shown only once. Encrypted on this device only.',
- help_es: "Se genera junto con Consumer Key y se muestra una sola vez. Se cifra únicamente en este dispositivo.",
- help_fr: "Généré avec la Consumer Key et affiché une seule fois. Chiffré uniquement sur cet appareil.",
- help_ko: "Consumer Key와 함께 생성되며 한 번만 표시됩니다. 이 기기에만 암호화하여 저장합니다.",
- help_de: "Wird zusammen mit dem Consumer Key erstellt und nur einmal angezeigt. Nur auf diesem Gerät verschlüsselt.",
- help_ru: "Создаётся вместе с Consumer Key и показывается только один раз. Хранится в зашифрованном виде только на этом устройстве.",
- help_it: "Generato insieme alla Consumer Key e mostrato una sola volta. Crittografato solo su questo dispositivo.",
- help_ja: "Consumer Key と一緒に発行され、一度だけ表示されます。この端末にのみ暗号化して保存されます。",
- help_pt: "Gerado com a Consumer Key e exibido apenas uma vez. Armazenado criptografado apenas neste dispositivo.",
+ help_zh: "可选:与 Consumer Key 配套填写;否则留空。密钥加密保存在本机。",
+ help_en: "Optional: enter the matching Consumer Secret, or leave empty. Keys are stored encrypted on this device.",
+ help_es: "Opcional: introduce el Consumer Secret correspondiente o deja el campo vacío. Las claves se guardan cifradas en este dispositivo.",
+ help_fr: "Facultatif : saisissez le Consumer Secret correspondant ou laissez vide. Les clés sont chiffrées sur cet appareil.",
+ help_ko: "선택 사항: 해당 Consumer Secret을 입력하거나 비워 두세요. 키는 이 기기에 암호화하여 저장됩니다.",
+ help_de: "Optional: zugehöriges Consumer Secret eingeben oder leer lassen. Schlüssel werden auf diesem Gerät verschlüsselt gespeichert.",
+ help_ru: "Необязательно: введите соответствующий Consumer Secret или оставьте поле пустым. Ключи хранятся на этом устройстве в зашифрованном виде.",
+ help_it: "Facoltativo: inserisci il Consumer Secret corrispondente o lascia vuoto. Le chiavi sono salvate crittografate su questo dispositivo.",
+ help_ja: "任意:対応する Consumer Secret を入力するか、空欄のままにしてください。キーはこの端末に暗号化して保存されます。",
+ help_pt: "Opcional: informe o Consumer Secret correspondente ou deixe vazio. As chaves são armazenadas criptografadas neste dispositivo.",
},
],
},
@@ -1549,19 +1559,19 @@ help_it: "Copialo dopo aver autorizzato autonomamente l'app privata in Solution
guide_label_ja: "Mercado Libre Global Selling 公式アプリガイドを開く",
guide_label_pt: "Abrir guia oficial de apps Mercado Libre Global Selling",
fields: [
- { key: 'user_id', input: 'text', storage: 'metadata', required: true, format: 'mercado_libre_user_id', label_zh: '卖家 User ID', label_en: 'Seller User ID',
+ { key: 'user_id', input: 'text', storage: 'metadata', required: false, format: 'mercado_libre_user_id', label_zh: '卖家 User ID', label_en: 'Seller User ID',
label_es: "ID de usuario del vendedor",
label_fr: "ID utilisateur du vendeur",
label_ko: "Seller User ID",
label_de: "Benutzer-ID des Verkäufers",
label_ru: "Seller User ID",
- label_it: "Seller User ID", label_ja: "販売者ユーザー ID", label_pt: "ID de usuário do vendedor", help_zh: '填写 Global Selling 主账号(CBT)的数字 User ID,可从该账号已有的官方授权响应 user_id 或 GET /users/me 响应 id 获取;不要填站点子账号 Seller ID,协作者/操作员不能授权。', help_en: 'Use the Global Selling owner (CBT) User ID from an existing official authorization response user_id or GET /users/me response id. Do not use a marketplace child Seller ID; operators and collaborators cannot authorize.',
-help_es: "Usa el ID de usuario del propietario de Global Selling (CBT), obtenido del campo user_id de una respuesta de autorización oficial existente o del campo id de una respuesta de GET /users/me. No uses el ID de vendedor de una cuenta secundaria de un marketplace; los operadores y colaboradores no pueden autorizar.",
-help_fr: "Utilisez le User ID du propriétaire Global Selling (CBT), issu de user_id dans une réponse d’autorisation officielle existante ou de id dans la réponse GET /users/me. N’utilisez pas le Seller ID d’un compte enfant de place de marché ; les opérateurs et les collaborateurs ne peuvent pas autoriser l’accès.",
-help_ko: "기존 공식 승인 응답의 user_id 또는 GET /users/me 응답의 id에 있는 Global Selling 소유자(CBT) User ID를 사용하세요. 마켓플레이스 하위 Seller ID는 사용하지 마세요. 운영자나 협업자는 승인할 수 없습니다.",
-help_de: "Verwenden Sie die User ID des Global Selling-Inhabers (CBT) aus user_id einer vorhandenen offiziellen Autorisierungsantwort oder id einer Antwort auf GET /users/me. Verwenden Sie keine untergeordnete Seller ID eines Marktplatzes; Betreiber und Mitarbeiter können die Autorisierung nicht vornehmen.",
-help_ru: "Используйте User ID владельца Global Selling (CBT) из поля user_id существующего официального ответа авторизации или поля id ответа GET /users/me. Не используйте дочерний Seller ID маркетплейса; операторы и сотрудники не могут пройти авторизацию.",
-help_it: "Usa lo User ID del proprietario Global Selling (CBT) ricavato da user_id in una risposta di autorizzazione ufficiale esistente o da id nella risposta di GET /users/me. Non usare il Seller ID di un account secondario del marketplace; operatori e collaboratori non possono autorizzare.", help_ja: "公式認証応答の user_id または GET /users/me の id にある Global Selling 所有者(CBT)の User ID を使用してください。市場ごとの子 Seller ID は使用できません。オペレーターや協力者は認証できません。", help_pt: "Use o User ID do proprietário Global Selling (CBT), obtido em user_id de uma autorização oficial existente ou em id de GET /users/me. Não use o Seller ID filho de um marketplace; operadores e colaboradores não podem autorizar." },
+ label_it: "Seller User ID", label_ja: "販売者ユーザー ID", label_pt: "ID de usuário do vendedor", help_zh: "留空即可在登录授权后确认 Global Selling 主账号。仅在需要限定账号时填写已知的主账号 User ID;不要填站点子账号 Seller ID。", help_en: "Leave blank to confirm the authorized Global Selling owner after login. Enter a known owner User ID only to restrict the connection; do not use a marketplace child Seller ID.",
+help_es: "Déjalo vacío para confirmar al propietario de Global Selling después de iniciar sesión. Introduce un User ID conocido solo para limitar la conexión; no uses el Seller ID de una cuenta secundaria.",
+help_fr: "Laissez vide pour confirmer le propriétaire Global Selling après la connexion. Saisissez un User ID connu uniquement pour limiter la connexion ; ne saisissez pas le Seller ID d’un compte enfant.",
+help_ko: "비워 두면 로그인 후 승인된 Global Selling 소유자 계정을 확인합니다. 계정을 제한할 때만 소유자의 User ID를 입력하세요. 마켓플레이스 하위 Seller ID는 사용할 수 없습니다.",
+help_de: "Leer lassen, um den autorisierten Global Selling-Inhaber nach der Anmeldung zu bestätigen. Nur zum Einschränken der Verbindung eine bekannte User ID eingeben; keine untergeordnete Seller ID verwenden.",
+help_ru: "Оставьте пустым, чтобы после входа подтвердить владельца Global Selling. Укажите известный User ID только для ограничения подключения; не используйте Seller ID дочернего аккаунта.",
+help_it: "Lascia vuoto per confermare il proprietario Global Selling dopo l’accesso. Inserisci uno User ID noto solo per limitare la connessione; non usare il Seller ID di un account secondario.", help_ja: "空欄のままログインし、認証された Global Selling 所有者を確認します。接続先を指定する場合のみ所有者の User ID を入力してください。市場の子 Seller ID は使用できません。", help_pt: "Deixe em branco para confirmar o proprietário Global Selling após entrar. Informe um User ID conhecido apenas para restringir a conexão; não use o Seller ID de uma conta filha." },
{ key: 'client_id', input: 'text', storage: 'credential', required: true, format: 'client_id', label_zh: 'App ID (Client ID)', label_en: 'App ID (Client ID)',
label_es: "App ID (Client ID)",
label_fr: "App ID (Client ID)",
diff --git a/src/main/features/connectors/catalog-seller-marketplaces.ts b/src/main/features/connectors/catalog-seller-marketplaces.ts
index 06723685..22920569 100644
--- a/src/main/features/connectors/catalog-seller-marketplaces.ts
+++ b/src/main/features/connectors/catalog-seller-marketplaces.ts
@@ -207,20 +207,20 @@ label_ko: "미국",
label_de: "Vereinigte Staaten",
label_ru: "США",
label_it: "Stati Uniti", label_ja: "米国", label_pt: "Estados Unidos" }] },
- { key: 'shop_id', input: 'text', storage: 'metadata', required: true, format: 'tiktok_shop_code', label_zh: '店铺代码 / Shop ID', label_en: 'Shop code / Shop ID',
+ { key: 'shop_id', input: 'text', storage: 'metadata', required: false, format: 'tiktok_shop_code', label_zh: '店铺代码 / Shop ID', label_en: 'Shop code / Shop ID',
label_es: "Código de tienda / Shop ID",
label_fr: "Code de boutique / ID de boutique",
label_ko: "상점 코드 / Shop ID",
label_de: "Shopcode / Shop-ID",
label_ru: "Код магазина / Shop ID",
label_it: "Shop code / Shop ID", label_ja: "ショップコード / ショップ ID", label_pt: "Código da loja / Shop ID",
- help_zh: '从 Seller Center 的店铺资料复制店铺代码,或填写已知的 API Shop ID。授权后会精确匹配该店铺;无需填写 shop_cipher。', help_en: 'Copy the shop code from your Seller Center shop profile, or enter a known API Shop ID. Orkas matches it after authorization; you do not need shop_cipher.',
- help_es: "Copia el código de tienda del perfil de tu tienda en Seller Center o introduce un Shop ID de la API que conozcas. Orkas lo identifica tras la autorización; no necesitas shop_cipher.",
- help_fr: "Copiez le code de boutique depuis votre profil de boutique dans Seller Center, ou saisissez un Shop ID API connu. Orkas l’associe après l’autorisation ; vous n’avez pas besoin de shop_cipher.",
- help_ko: "Seller Center의 상점 프로필에서 상점 코드를 복사하거나 알고 있는 API Shop ID를 입력하세요. Orkas가 승인 후 일치 여부를 확인하므로 shop_cipher는 필요하지 않습니다.",
- help_de: "Kopieren Sie den Shopcode aus Ihrem Shopprofil im Seller Center oder geben Sie eine bekannte API-Shop ID ein. Orkas ordnet ihn nach der Autorisierung zu; Sie benötigen keinen shop_cipher.",
- help_ru: "Скопируйте код магазина из профиля магазина в Seller Center или введите известный API Shop ID. Orkas сопоставит его после авторизации; shop_cipher не нужен.",
- help_it: "Copia il codice del negozio dal profilo del negozio in Seller Center oppure inserisci uno Shop ID API noto. Orkas lo associa dopo l'autorizzazione; non serve shop_cipher.", help_ja: "Seller Center の店舗プロフィールからショップコードをコピーするか、既知の API Shop ID を入力してください。認証後に Orkas が照合します。shop_cipher は不要です。", help_pt: "Copie o código da loja no perfil do Seller Center ou informe um Shop ID conhecido da API. Orkas faz a correspondência após a autorização; não é necessário shop_cipher." },
+ help_zh: "留空即可在登录授权后选择店铺。仅在需要限定店铺时填写已知的店铺代码或 API Shop ID。", help_en: "Leave blank to choose an authorized shop after login. Enter a known shop code or API Shop ID only to restrict the connection.",
+ help_es: "Déjalo vacío para elegir una tienda autorizada después de iniciar sesión. Introduce un código de tienda o API Shop ID conocido solo para limitar la conexión.",
+ help_fr: "Laissez vide pour choisir une boutique autorisée après la connexion. Saisissez un code de boutique ou un API Shop ID connu uniquement pour limiter la connexion.",
+ help_ko: "비워 두면 로그인 후 승인된 상점을 선택합니다. 상점을 제한할 때만 상점 코드나 API Shop ID를 입력하세요.",
+ help_de: "Leer lassen, um nach der Anmeldung einen autorisierten Shop auszuwählen. Nur zum Einschränken der Verbindung einen bekannten Shopcode oder eine API Shop ID eingeben.",
+ help_ru: "Оставьте пустым, чтобы после входа выбрать авторизованный магазин. Укажите известный код магазина или API Shop ID только для ограничения подключения.",
+ help_it: "Lascia vuoto per scegliere un negozio autorizzato dopo l’accesso. Inserisci un codice negozio o API Shop ID noto solo per limitare la connessione.", help_ja: "空欄のままログインし、認証された店舗を選択します。接続先を指定する場合のみ店舗コードまたは API Shop ID を入力してください。", help_pt: "Deixe em branco para escolher uma loja autorizada após entrar. Informe um código de loja ou API Shop ID conhecido apenas para restringir a conexão." },
{ key: 'service_id', input: 'text', storage: 'credential', required: true, format: 'tiktok_service_id', label_zh: 'Service ID', label_en: 'Service ID',
label_es: "Service ID",
label_fr: "ID du service",
diff --git a/src/main/features/connectors/catalog.ts b/src/main/features/connectors/catalog.ts
index 1174d0dd..3c74ba55 100644
--- a/src/main/features/connectors/catalog.ts
+++ b/src/main/features/connectors/catalog.ts
@@ -62,6 +62,10 @@ export const CONNECTOR_CATALOG: CatalogEntry[] = [
composioCatalogEntry({
id: 'outlook',
display_name: 'Outlook',
+ // Names the scope: this toolkit cannot read mail (Microsoft 365 Mail can), and
+ // a bare "Outlook" card was staged and described as mail access.
+ display_name_zh: 'Outlook 联系人与任务',
+ display_name_en: 'Outlook Contacts & Tasks',
icon_svg: MICROSOFT_ICON_SVG,
category: 'communication',
description_zh: '读取 Outlook 个人资料、联系人、邮箱设置和任务。',
@@ -78,6 +82,8 @@ export const CONNECTOR_CATALOG: CatalogEntry[] = [
composioCatalogEntry({
id: 'm365-mail',
display_name: 'Microsoft 365 Mail',
+ // The general `outlook` entry cannot read mail; mail-capable Outlook access is this toolkit.
+ search_aliases: ['Outlook', 'Outlook 邮箱'],
icon_svg: MICROSOFT_ICON_SVG,
category: 'communication',
description_zh: '搜索、读取、撰写和发送 Microsoft 365 邮件。',
@@ -435,6 +441,7 @@ export const CONNECTOR_CATALOG: CatalogEntry[] = [
},
{
id: 'gmail',
+ search_aliases: ['谷歌邮箱'],
display_name: 'Gmail',
icon_svg: '<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path fill="#4285f4" d="M24 5.457v13.909c0 .904-.732 1.636-1.636 1.636h-3.819V11.73L12 16.64l-6.545-4.91v9.273H1.636A1.636 1.636 0 0 1 0 19.366V5.457c0-2.023 2.309-3.178 3.927-1.964L5.455 4.64 12 9.548l6.545-4.91 1.528-1.145C21.69 2.28 24 3.434 24 5.457z"/><path fill="#34a853" d="M5.455 21.003V11.73l-3.819-2.864v10.5c0 .904.732 1.637 1.636 1.637z"/><path fill="#ea4335" d="M18.545 21.003V11.73l3.819-2.864v10.5a1.636 1.636 0 0 1-1.636 1.637z"/><path fill="#fbbc04" d="M5.455 11.73 12 16.64l6.545-4.91V4.64L12 9.548 5.455 4.64z"/><path fill="#c5221f" d="M0 5.457v3.41l5.455 4.092V4.64L3.927 3.494C2.309 2.28 0 3.434 0 5.457z"/></svg>',
category: 'communication',
diff --git a/src/main/features/connectors/custom-transport.ts b/src/main/features/connectors/custom-transport.ts
index 4934b165..e18e82b2 100644
--- a/src/main/features/connectors/custom-transport.ts
+++ b/src/main/features/connectors/custom-transport.ts
@@ -24,6 +24,8 @@ const ENV_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
export interface CustomConnectorInput {
display_name: string;
+ /** Explicit browser OAuth opt-in for a remote MCP server. */
+ auth_mode?: 'none' | 'oauth';
transport: {
kind: 'stdio' | 'streamable-http';
/** stdio */
@@ -37,6 +39,17 @@ export interface CustomConnectorInput {
};
}
+export function validateCustomAuthMode(raw: unknown, transport: Transport): 'none' | 'oauth' {
+ if (raw === undefined || raw === 'none') return 'none';
+ if (raw !== 'oauth' || transport.kind !== 'streamable-http') {
+ throw new CustomTransportError('E_AUTH_MODE', 'OAuth is available only for remote HTTP MCP servers');
+ }
+ if (Object.keys(transport.headers || {}).some((name) => name.toLowerCase() === 'authorization')) {
+ throw new CustomTransportError('E_AUTH_MODE', 'OAuth cannot be combined with an Authorization header');
+ }
+ return 'oauth';
+}
+
export class CustomTransportError extends Error {
/** Stable machine code for the renderer to i18n. */
code: string;
diff --git a/src/main/features/connectors/index.ts b/src/main/features/connectors/index.ts
index f69a6710..d84940fd 100644
--- a/src/main/features/connectors/index.ts
+++ b/src/main/features/connectors/index.ts
@@ -5,6 +5,8 @@ export {
beginOAuthConnect,
connectViaOAuth,
addCustomInstance,
+ authorizeCustomInstance,
+ beginCustomOAuthConnect,
removeInstance,
removeApiKeyConnectors,
refreshTools,
diff --git a/src/main/features/connectors/local-api.ts b/src/main/features/connectors/local-api.ts
index af1d1e4c..13d784f9 100644
--- a/src/main/features/connectors/local-api.ts
+++ b/src/main/features/connectors/local-api.ts
@@ -12,14 +12,20 @@ import { resolveBackgroundNodeRuntime, withBackgroundNodeEnv } from '../../util/
import { buildChildProxyEnvironment } from '../../util/proxy-dispatcher';
import { getLanguageForUser } from '../config';
import { t } from '../../i18n';
+import { createLogger } from '../../logger';
+import { logErrorSummary } from '../../util/log-redact';
+import { authorizeWooCommerce } from './woocommerce-auth';
import { startLocalApiBrowserOAuth, startLocalApiCredentialAuthorization } from './oauth-dcr';
import { LOCAL_API_REDIRECT_URI } from './oauth-redirect';
+import { requestAccountChoice, type AccountChoice } from './account-choice';
import {
startInteractiveCliSession,
waitInteractiveCliSession,
} from '../../model/core-agent/interactive-cli-sessions';
import type { CatalogConnectionField, CatalogEntry, LocalApiConfig, Transport } from './types';
+const log = createLogger('connectors:local-api');
+
const CREDENTIAL_KEY_NAMESPACE = 'connectors.local-api-key';
const PAYLOAD_PREFIX = 'ORKAPI1:';
// Only new installations use this default; persisted runtime bindings stay authoritative.
@@ -286,6 +292,10 @@ export function normalizeLocalApiConnectionInput(entry: CatalogEntry, raw: unkno
const value = normalizeField(field, raw[field.key]);
(field.storage === 'credential' ? credentials : metadata)[field.key] = value;
}
+ if (entry.local_api?.provider === 'woocommerce'
+ && Boolean(credentials.consumer_key) !== Boolean(credentials.consumer_secret)) {
+ throw new Error(t('connectors.woocommerce.credentials_incomplete'));
+ }
if (PRODUCTION_ONLY_LOCAL_API_PROVIDERS.has(entry.local_api!.provider)) metadata.environment = 'live';
if (entry.local_api?.provider === 'ebay') {
require(path.join(pcDirForChild(), 'bin/ebay-signature.cjs')).signingKey(credentials);
@@ -446,10 +456,16 @@ export async function authorizeLocalApi(
uid: string,
entry: CatalogEntry,
raw: unknown,
- opts: { attemptId?: string } = {},
+ opts: { attemptId?: string; existingBinding?: Record<string, string> } = {},
): Promise<Record<string, string>> {
const config = requireLocalApi(entry);
const normalized = normalizeLocalApiConnectionInput(entry, raw);
+ // A reconnect without a typed ID keeps the previously selected account/store.
+ const bindingKey = config.provider === 'mercado_libre' ? 'user_id' : config.provider === 'tiktok_shop' ? 'shop_id' : null;
+ if (bindingKey && !normalized.metadata[bindingKey] && opts.existingBinding?.[bindingKey]) {
+ const field = entry.connection_setup!.fields.find(candidate => candidate.key === bindingKey)!;
+ normalized.metadata[bindingKey] = normalizeField(field, opts.existingBinding[bindingKey]);
+ }
const userAppAuth = require(path.join(pcDirForChild(), 'bin/local-api-auth.cjs'));
if (userAppAuth.BROWSER_OAUTH_PROVIDERS.has(config.provider) || userAppAuth.SELF_AUTH_PROVIDERS.has(config.provider)) {
try {
@@ -460,7 +476,18 @@ export async function authorizeLocalApi(
credentials = await startLocalApiBrowserOAuth(entry.id, (state, redirectUri) => {
flow = userAppAuth.createBrowserAuthorization(env, state, redirectUri);
return flow.url;
- }, (code) => flow.complete(code), opts);
+ }, async (code, signal) => {
+ const authorized = await flow.complete(code);
+ if (config.provider === 'mercado_libre' && !normalized.metadata.user_id) {
+ const identity = authorized.identity as { user_id: string; nickname?: string };
+ const id = await requestAccountChoice(uid, entry.id, [{
+ id: identity.user_id,
+ label: `${String(identity.nickname || entry.display_name).slice(0, 120)} (${identity.user_id})`,
+ }], signal);
+ normalized.metadata.user_id = id;
+ }
+ return authorized;
+ }, opts);
} else {
credentials = await startLocalApiCredentialAuthorization(entry.id, () => userAppAuth.authorizeConfigured(env), opts);
}
@@ -469,6 +496,7 @@ export async function authorizeLocalApi(
} catch (error) {
const code = (error as { code?: string })?.code;
if (code === 'user_cancelled') throw error;
+ log.warn('local API authorization failed', { id: entry.id, provider: config.provider, ...logErrorSummary(error) });
if (code?.startsWith('storefront_')) {
const key = code === 'storefront_permission_denied' ? 'permission_denied'
: code === 'storefront_binding_mismatch' ? 'binding_mismatch' : 'request_failed';
@@ -485,12 +513,17 @@ export async function authorizeLocalApi(
try {
const credentials = await startLocalApiBrowserOAuth(entry.id, (state, redirectUri) => sellerApi.authorizeUrl(
config.provider, normalized.metadata, normalized.credentials, state, redirectUri,
- ), (code) => sellerApi.authorize(config.provider, normalized.metadata, normalized.credentials, code), opts);
+ ), (code, signal) => sellerApi.authorize(config.provider, normalized.metadata, normalized.credentials, code, undefined,
+ (choices: AccountChoice[]) => requestAccountChoice(uid, entry.id, choices, signal)), opts);
+ if (config.provider === 'tiktok_shop' && !normalized.metadata.shop_id) {
+ normalized.metadata.shop_id = (credentials.identity as { binding_shop_id: string }).binding_shop_id;
+ }
saveCredentials(uid, entry, credentials);
return normalized.metadata;
} catch (error) {
const code = (error as { code?: string })?.code;
if (code === 'user_cancelled') throw error;
+ log.warn('local API authorization failed', { id: entry.id, provider: config.provider, ...logErrorSummary(error) });
const key = code === 'seller_shop_mismatch' ? 'shop_mismatch'
: code === 'seller_request_failed' ? 'request_failed' : 'authorization_failed';
throw Object.assign(new Error(t(`connectors.seller.${key}`, {}, getLanguageForUser(uid))), {
@@ -498,6 +531,19 @@ export async function authorizeLocalApi(
});
}
}
+ if (config.provider === 'woocommerce' && !normalized.credentials.consumer_key) {
+ try {
+ const credentials = await authorizeWooCommerce(entry.id, normalized.metadata.store_url, opts);
+ saveCredentials(uid, entry, credentials);
+ return normalized.metadata;
+ } catch (error) {
+ if ((error as { code?: string })?.code === 'user_cancelled') throw error;
+ log.warn('local API authorization failed', { id: entry.id, provider: config.provider, ...logErrorSummary(error) });
+ throw Object.assign(new Error(t('connectors.woocommerce.authorization_failed', {}, getLanguageForUser(uid))), {
+ code: 'local_api_authorization_failed',
+ });
+ }
+ }
if (config.provider !== 'constant_contact') {
saveCredentials(uid, entry, normalized.credentials);
return normalized.metadata;
diff --git a/src/main/features/connectors/manager.ts b/src/main/features/connectors/manager.ts
index 7e0debe4..4191cafd 100644
--- a/src/main/features/connectors/manager.ts
+++ b/src/main/features/connectors/manager.ts
@@ -24,7 +24,7 @@ import { applyTemplate } from './apply-template';
import { resolveCatalogConnection } from './connection-parameters';
import { assertConnectorRuntimeEnabled, isConnectorRuntimeEnabled } from './availability';
import { startComposioConnect, startOAuth, refreshIfStale, startGoogleSheetsPicker } from './oauth';
-import { startMcpDcrOAuth, refreshDcrIfStale } from './oauth-dcr';
+import { startMcpDcrOAuth, startCustomMcpOAuth, refreshDcrIfStale } from './oauth-dcr';
import { createLogger } from '../../logger';
import { isConnectorActionBlocked } from './action_policy';
import { logErrorSummary } from '../../util/log-redact';
@@ -37,7 +37,7 @@ import { preflightConnectorCredits } from './usage-metering';
import { registerUserSwitchHook } from '../user-switch-hooks';
import { broadcastOAuthConnectOutcome, broadcastOAuthConnectProgress, type OAuthConnectOutcome } from './oauth-events';
import { sanitizeAuthorizationDetail } from './local-cli-auth-error';
-import { deriveCustomId, validateCustomTransport, validateDisplayName, type CustomConnectorInput } from './custom-transport';
+import { deriveCustomId, validateCustomAuthMode, validateCustomTransport, validateDisplayName, type CustomConnectorInput } from './custom-transport';
import {
authorizeLocalCli,
checkLocalCliPermissions,
@@ -212,7 +212,7 @@ function _transportForPersistence(
current: Transport,
resolved: Transport,
): Transport {
- return entry?.auth_mode === 'local_api' ? current : resolved;
+ return !entry || entry.auth_mode === 'local_api' ? current : resolved;
}
/** Apply the catalog's reviewed MCP action boundary before schemas reach persistence or the LLM.
@@ -813,14 +813,36 @@ async function _refreshGrantIfStale(
}
async function _resolveTransport(uid: string, inst: ConnectorInstance): Promise<{ transport: Transport; grant: OAuthGrant | null } | null> {
- // Custom instances use their stored transport verbatim — no catalog
- // template, no OAuth grant, no refresh cycle. The transport (incl. any
- // API-key headers/env) lives inside secrets_enc like every other one.
if (inst.origin === 'custom') {
if (!inst.transport) {
log.warn('custom instance has no transport', { id: inst.origin === 'custom' ? 'custom' : inst.id });
return null;
}
+ if (inst.custom_auth_mode === 'oauth') {
+ if (inst.transport.kind !== 'streamable-http' || !inst.oauth_grant || !inst.dcr_client) return null;
+ const key = _runtimeKey(uid, inst.id);
+ const existing = _refreshLocks.get(key);
+ let grant: OAuthGrant;
+ if (existing) grant = await existing.promise;
+ else {
+ const lock: RefreshLock = { promise: Promise.resolve(null as never), force: false, attemptedRemote: false };
+ const pending = (async () => {
+ try {
+ const latest = registry.load(uid).connections[inst.id];
+ if (!latest?.oauth_grant || !latest.dcr_client) throw new Error('custom OAuth grant missing; reconnect required');
+ const next = await refreshDcrIfStale(latest.dcr_client, latest.oauth_grant, { strict: true });
+ if (next !== latest.oauth_grant) {
+ await registry.update(uid, inst.id, (cur) => ({ ...cur, oauth_grant: next, updated_at: _nowIso() }));
+ }
+ return next;
+ } finally { if (_refreshLocks.get(key) === lock) _refreshLocks.delete(key); }
+ })();
+ lock.promise = pending;
+ _refreshLocks.set(key, lock);
+ grant = await pending;
+ }
+ return { transport: { ...inst.transport, headers: { ...inst.transport.headers, Authorization: `Bearer ${grant.access_token}` } }, grant };
+ }
return { transport: inst.transport, grant: null };
}
const entry = findCatalogEntry(inst.id);
@@ -1402,9 +1424,15 @@ export async function connectViaOAuth(
assertConnectorRuntimeEnabled(catalogId);
await preflightConnectorCredits(catalogEntry, 'connect');
_assertRuntimeEpoch(runtimeEpoch);
+ let authorizationCompleted = false;
+ const hasDiscoveredBinding = ['mercado_libre', 'tiktok_shop'].includes(catalogEntry.local_api!.provider);
+ const existingBinding = hasDiscoveredBinding ? registry.load(uid).connections[catalogId]?.connection_parameters : undefined;
try {
- const metadata = await authorizeLocalApi(uid, catalogEntry, opts.connectionParameters, { attemptId: opts.attemptId });
+ const metadata = await authorizeLocalApi(uid, catalogEntry, opts.connectionParameters, {
+ attemptId: opts.attemptId, ...(existingBinding ? { existingBinding } : {}),
+ });
_assertRuntimeEpoch(runtimeEpoch);
+ authorizationCompleted = true;
const instance = await _provisionLocalApiInstance(uid, catalogEntry, metadata, runtimeEpoch);
if (instance.status.kind === 'error') {
throw new Error(instance.status.message || 'local API account verification failed');
@@ -1412,8 +1440,10 @@ export async function connectViaOAuth(
return instance;
} catch (error) {
_assertRuntimeEpoch(runtimeEpoch);
- removeLocalApiAuthorization(uid, catalogEntry);
- await registry.remove(uid, catalogEntry.id);
+ if (authorizationCompleted || (!hasDiscoveredBinding && catalogEntry.local_api!.provider !== 'woocommerce')) {
+ removeLocalApiAuthorization(uid, catalogEntry);
+ await registry.remove(uid, catalogEntry.id);
+ }
throw error;
}
}
@@ -1749,11 +1779,14 @@ async function _provisionLocalApiInstance(
* instance in `error` status (visible in the UI, fixable by remove+re-add)
* instead of silently discarding the user's input.
*/
-export async function addCustomInstance(uid: string, input: CustomConnectorInput): Promise<ConnectorInstance> {
+export async function addCustomInstance(
+ uid: string, input: CustomConnectorInput, opts: { deferOAuth?: boolean } = {},
+): Promise<ConnectorInstance> {
if (!uid) throw new Error('uid required');
const runtimeEpoch = _runtimeEpoch;
const displayName = validateDisplayName(input?.display_name);
const transport = validateCustomTransport(input?.transport);
+ const authMode = validateCustomAuthMode(input?.auth_mode, transport);
// Unique id derived from the name; suffix on collision with an existing
// row. The `custom-` prefix guarantees catalog ids can never be shadowed.
@@ -1766,6 +1799,7 @@ export async function addCustomInstance(uid: string, input: CustomConnectorInput
id,
display_name: displayName,
origin: 'custom',
+ ...(authMode === 'oauth' ? { custom_auth_mode: 'oauth' as const } : {}),
transport,
enabled_subtools: null,
tools_cache: [],
@@ -1776,9 +1810,76 @@ export async function addCustomInstance(uid: string, input: CustomConnectorInput
};
log.info('custom connector add', { id: 'custom', kind: transport.kind });
await registry.upsert(uid, draft);
+ if (authMode === 'oauth') {
+ if (opts.deferOAuth) return draft;
+ try { return await authorizeCustomInstance(uid, id); }
+ catch { return registry.load(uid).connections[id] || draft; }
+ }
return _connectAndCacheTools(uid, draft, undefined, runtimeEpoch);
}
+/** Reauthorize a custom remote MCP server after its grant expires or was revoked. */
+export async function authorizeCustomInstance(
+ uid: string, id: string, opts: { attemptId?: string } = {},
+): Promise<ConnectorInstance> {
+ if (!uid) throw new Error('uid required');
+ const runtimeEpoch = _runtimeEpoch;
+ const inst = registry.load(uid).connections[id];
+ if (!inst || inst.origin !== 'custom' || inst.custom_auth_mode !== 'oauth'
+ || inst.transport?.kind !== 'streamable-http') throw new Error('custom OAuth connector not found');
+ await _closeDiscoveredConnection(uid, id, runtimeEpoch);
+ try {
+ const { grant, client } = await startCustomMcpOAuth(id, inst.transport.url, opts);
+ _assertRuntimeEpoch(runtimeEpoch);
+ const updated = await registry.update(uid, id, (cur) => ({
+ ...cur, oauth_grant: grant, dcr_client: client,
+ status: { kind: 'connecting' }, updated_at: _nowIso(),
+ }));
+ if (!updated) throw new Error('custom connector removed during authorization');
+ return _connectAndCacheTools(uid, updated, undefined, runtimeEpoch);
+ } catch (error) {
+ _assertRuntimeEpoch(runtimeEpoch);
+ const reason = String((error as Error | null)?.message || '');
+ const safeMessage = /^(DCR registration failed: HTTP [0-9]{3}|token endpoint HTTP [0-9]{3}|provider does not support client metadata or DCR registration)$/.test(reason)
+ ? reason : 'OAuth authorization failed; reconnect to try again';
+ await registry.update(uid, id, (cur) => ({ ...cur,
+ status: { kind: 'error', message: safeMessage, at: _now() },
+ updated_at: _nowIso(),
+ }));
+ throw error;
+ }
+}
+
+/** Browser OAuth runs after IPC returns; the callback/result uses the catalog event channel. */
+export function beginCustomOAuthConnect(uid: string, id: string): OAuthConnectStart {
+ const inst = uid ? registry.load(uid).connections[id] : null;
+ if (!inst || inst.origin !== 'custom' || inst.custom_auth_mode !== 'oauth'
+ || inst.transport?.kind !== 'streamable-http') throw new Error('custom OAuth connector not found');
+ const attemptId = crypto.randomUUID();
+ const startedAt = Date.now();
+ const runtimeEpoch = _runtimeEpoch;
+ void authorizeCustomInstance(uid, id, { attemptId }).then((result) => {
+ if (runtimeEpoch !== _runtimeEpoch) return;
+ const failed = result.status.kind !== 'connected';
+ broadcastOAuthConnectOutcome({ attempt_id: attemptId, catalog_id: id,
+ result: failed ? 'failure' : 'success', duration_ms: Date.now() - startedAt,
+ ...(failed ? { code: 'mcp_connect_failed', error: result.status.kind === 'error' || result.status.kind === 'degraded'
+ ? result.status.message : 'MCP connection failed' } : {}),
+ });
+ }).catch((error) => {
+ if (runtimeEpoch !== _runtimeEpoch) return;
+ const code = _oauthConnectErrorCode(error);
+ broadcastOAuthConnectOutcome({ attempt_id: attemptId, catalog_id: id,
+ result: code === 'user_cancelled' || code === 'superseded' ? 'cancelled' : 'failure',
+ duration_ms: Date.now() - startedAt, code,
+ error: registry.load(uid).connections[id]?.status.kind === 'error'
+ ? (registry.load(uid).connections[id]?.status as { message: string }).message
+ : 'OAuth authorization failed',
+ });
+ });
+ return { attempt_id: attemptId };
+}
+
export async function removeInstance(
uid: string, id: string, options: { disconnectRemote?: boolean } = {},
): Promise<boolean> {
diff --git a/src/main/features/connectors/mcp-client.ts b/src/main/features/connectors/mcp-client.ts
index 35c2f6ae..7a3def18 100644
--- a/src/main/features/connectors/mcp-client.ts
+++ b/src/main/features/connectors/mcp-client.ts
@@ -1,10 +1,10 @@
/**
* MCP client wrapper.
*
- * Owns the underlying `@modelcontextprotocol/sdk` `Client` for one connector instance. Two
- * transports supported in Phase 0: `stdio` (local subprocess via SDK's StdioClientTransport)
- * and `streamable-http` (remote HTTP). SSE transport is intentionally not implemented — the
- * MCP spec has deprecated it in favor of streamable HTTP.
+ * Owns the underlying `@modelcontextprotocol/sdk` `Client` for one connector instance.
+ * Local stdio and remote Streamable HTTP use the official SDK transports. Custom remote
+ * servers can fall back to the SDK's legacy SSE transport when their endpoint rejects the
+ * Streamable HTTP handshake with a transport-shape 4xx response.
*
* Why this file is the sole spawn site for MCP child processes: PC/CLAUDE.md §1 calls out
* `features/local_agents/` as the only spawn entry for coding-CLI dispatches. MCP servers are
@@ -87,21 +87,24 @@ interface SdkBundle {
Client: typeof import('@modelcontextprotocol/sdk/client/index.js').Client;
StdioClientTransport: typeof import('@modelcontextprotocol/sdk/client/stdio.js').StdioClientTransport;
StreamableHTTPClientTransport: typeof import('@modelcontextprotocol/sdk/client/streamableHttp.js').StreamableHTTPClientTransport;
+ SSEClientTransport: typeof import('@modelcontextprotocol/sdk/client/sse.js').SSEClientTransport;
}
let _sdk: SdkBundle | null = null;
async function _loadSdk(): Promise<SdkBundle> {
if (_sdk) return _sdk;
- const [clientMod, stdioMod, httpMod] = await Promise.all([
+ const [clientMod, stdioMod, httpMod, sseMod] = await Promise.all([
import('@modelcontextprotocol/sdk/client/index.js'),
import('@modelcontextprotocol/sdk/client/stdio.js'),
import('@modelcontextprotocol/sdk/client/streamableHttp.js'),
+ import('@modelcontextprotocol/sdk/client/sse.js'),
]);
_sdk = {
Client: clientMod.Client,
StdioClientTransport: stdioMod.StdioClientTransport,
StreamableHTTPClientTransport: httpMod.StreamableHTTPClientTransport,
+ SSEClientTransport: sseMod.SSEClientTransport,
};
return _sdk;
}
@@ -142,6 +145,7 @@ export class McpConnection {
if (this._connected) return;
const startedAt = Date.now();
const sdk = await _loadSdk();
+ let activeTransportKind: Transport['kind'] | 'sse' = this.transport.kind;
let transport: import('@modelcontextprotocol/sdk/shared/transport.js').Transport;
if (this.transport.kind === 'stdio') {
const proxyEnv = await buildChildProxyEnvironment(this.transport.proxyTargetUrl);
@@ -177,33 +181,62 @@ export class McpConnection {
}
transport = new sdk.StreamableHTTPClientTransport(url, opts);
}
- const client = new sdk.Client(CLIENT_INFO, {});
- try {
- // Bound process/transport startup and initialization together. Pass the same budget
- // to the SDK so its default handshake timeout cannot terminate a configured wait early.
- const connectTimeoutMs = resolveMcpConnectTimeoutMs(this.transport.kind);
+ let client = new sdk.Client(CLIENT_INFO, {});
+ const connectTimeoutMs = resolveMcpConnectTimeoutMs(this.transport.kind);
+ let connectDeadline = 0;
+ const connectAttempt = async (
+ nextClient: typeof client,
+ nextTransport: typeof transport,
+ ): Promise<void> => {
+ if (!connectDeadline) connectDeadline = Date.now() + connectTimeoutMs;
+ const remaining = Math.max(1, connectDeadline - Date.now());
let to: NodeJS.Timeout | undefined;
const timeout = new Promise<never>((_resolve, reject) => {
const seconds = Math.round(connectTimeoutMs / 1000);
- to = setTimeout(() => reject(new Error(`MCP connect timed out (>${seconds}s); likely npx/network is slow or the server crashed on launch`)), connectTimeoutMs);
+ to = setTimeout(() => reject(new Error(`MCP connect timed out (>${seconds}s); likely npx/network is slow or the server crashed on launch`)), remaining);
});
try {
- await Promise.race([client.connect(transport, { timeout: connectTimeoutMs }), timeout]);
+ await Promise.race([nextClient.connect(nextTransport, { timeout: remaining }), timeout]);
} finally {
if (to) clearTimeout(to);
}
+ };
+ try {
+ try {
+ await connectAttempt(client, transport);
+ } catch (error) {
+ const status = (error as { code?: unknown } | null)?.code;
+ // A legacy SSE endpoint commonly rejects the initial JSON-RPC POST. A 401/403
+ // is authorization, and 5xx/network failures are not evidence of legacy SSE.
+ // Catalog entries declare their own protocol and must not silently change it.
+ if (this.id.startsWith('custom-') && this.transport.kind === 'streamable-http'
+ && (status === 400 || status === 404 || status === 405)) {
+ try { await transport.close?.(); } catch { /* preserve the original handshake result */ }
+ log.info('retrying custom MCP endpoint with legacy SSE', { id: 'custom' });
+ const url = new URL(this.transport.url);
+ const headers = this.transport.headers;
+ transport = new sdk.SSEClientTransport(url, {
+ ...(headers && Object.keys(headers).length ? { requestInit: { headers } } : {}),
+ });
+ activeTransportKind = 'sse';
+ client = new sdk.Client(CLIENT_INFO, {});
+ await connectAttempt(client, transport);
+ } else {
+ throw error;
+ }
+ }
this._client = client;
this._connected = true;
log.info('MCP connect ok', {
id: this.id.startsWith('custom-') ? 'custom' : this.id,
- transport: this.transport.kind,
+ transport: activeTransportKind,
duration_ms: Date.now() - startedAt,
timeout_ms: connectTimeoutMs,
});
} catch (err) {
log.warn('connect failed', {
id: this.id.startsWith('custom-') ? 'custom' : this.id,
- transport: this.transport.kind,
+ transport: activeTransportKind,
duration_ms: Date.now() - startedAt,
error: logErrorSummary(err),
});
diff --git a/src/main/features/connectors/oauth-dcr.ts b/src/main/features/connectors/oauth-dcr.ts
index cc9db9d0..a7118a47 100644
--- a/src/main/features/connectors/oauth-dcr.ts
+++ b/src/main/features/connectors/oauth-dcr.ts
@@ -1,10 +1,10 @@
/**
- * MCP-spec OAuth (Dynamic Client Registration) client.
+ * MCP-spec OAuth client (Client ID Metadata Document or Dynamic Client Registration).
*
* For providers that host their own OAuth authorization server per the MCP authorization spec
* (Notion, Atlassian, Cloudflare suite, …). Orkas has no pre-registered OAuth App at the
- * provider — PC self-registers at first connect via DCR (RFC 7591) and drives the initial
- * OAuth handshake from the PC side.
+ * provider — PC uses a public Client ID Metadata Document when available, otherwise
+ * self-registers via DCR (RFC 7591), then drives OAuth from the PC side.
*
* The Server-bridge in `oauth.ts` handles a different class of providers (GitHub Copilot MCP
* today) where Orkas registered an OAuth App and Server holds the secret. The two flows live
@@ -24,6 +24,8 @@
import * as crypto from 'node:crypto';
import { URL, URLSearchParams } from 'node:url';
import { shell } from 'electron';
+import { buildDiscoveryUrls, extractWWWAuthenticateParams } from '@modelcontextprotocol/sdk/client/auth.js';
+import { LATEST_PROTOCOL_VERSION } from '@modelcontextprotocol/sdk/types.js';
import { accountApiBase, tokenStore } from './_server_bridge';
import { withCommonHeaders } from '../api_common';
@@ -54,6 +56,9 @@ interface PendingDcrFlow {
kind: 'dcr';
callbackStarted?: boolean;
catalogId: string;
+ storeLocally?: boolean;
+ issuer?: string;
+ issuerRequired?: boolean;
attemptId?: string;
state: string; // CSRF token — match incoming deep link
codeVerifier: string; // PKCE
@@ -73,7 +78,8 @@ interface PendingLocalApiFlow {
state: string;
relayBase: string;
attemptId?: string;
- exchange: (code: string) => Promise<Record<string, unknown>>;
+ controller: AbortController;
+ exchange: (code: string, signal: AbortSignal) => Promise<Record<string, unknown>>;
resolve: (credentials: Record<string, unknown>) => void;
reject: (err: Error) => void;
timer: NodeJS.Timeout;
@@ -88,14 +94,15 @@ export function cancelDcrOAuth(): boolean {
const pending = _pending;
_pending = null;
clearTimeout(pending.timer);
+ if (pending.kind === 'local_api') pending.controller.abort();
pending.reject(Object.assign(new Error('Authorization cancelled'), { code: 'user_cancelled' }));
return true;
}
export function startLocalApiBrowserOAuth(
catalogId: string,
- buildAuthorizeUrl: (state: string, redirectUri: string) => string,
- exchange: (code: string) => Promise<Record<string, unknown>>,
+ buildAuthorizeUrl: (state: string, redirectUri: string, signal: AbortSignal) => string | Promise<string>,
+ exchange: (code: string, signal: AbortSignal) => Promise<Record<string, unknown>>,
opts: { attemptId?: string } = {},
): Promise<Record<string, unknown>> {
return _startLocalApiAuthorization(catalogId, exchange, opts, buildAuthorizeUrl);
@@ -112,16 +119,16 @@ export function startLocalApiCredentialAuthorization(
function _startLocalApiAuthorization(
catalogId: string,
- exchange: (code: string) => Promise<Record<string, unknown>>,
+ exchange: (code: string, signal: AbortSignal) => Promise<Record<string, unknown>>,
opts: { attemptId?: string },
- buildAuthorizeUrl?: (state: string, redirectUri: string) => string,
+ buildAuthorizeUrl?: (state: string, redirectUri: string, signal: AbortSignal) => string | Promise<string>,
): Promise<Record<string, unknown>> {
cancelDcrOAuth();
const state = _localizedState();
- const authorizeUrl = buildAuthorizeUrl?.(state, LOCAL_API_REDIRECT_URI);
return new Promise((resolve, reject) => {
const pending: PendingLocalApiFlow = {
kind: 'local_api', catalogId, state, relayBase: 'https://orkas.ai/api', exchange, resolve, reject,
+ controller: new AbortController(),
...(opts.attemptId ? { attemptId: opts.attemptId } : {}),
timer: setTimeout(() => {
if (_pending === pending) _cancelPending('Authorization timed out; connect again');
@@ -129,12 +136,12 @@ function _startLocalApiAuthorization(
};
pending.timer.unref?.();
_pending = pending;
- if (!authorizeUrl) {
+ if (!buildAuthorizeUrl) {
pending.callbackStarted = true;
if (opts.attemptId) broadcastOAuthConnectProgress({ attempt_id: opts.attemptId, catalog_id: catalogId });
Promise.resolve().then(() => {
if (_pending !== pending) throw new Error('Authorization cancelled');
- return exchange('');
+ return exchange('', pending.controller.signal);
}).then((credentials) => {
if (_pending !== pending) return;
_pending = null;
@@ -148,9 +155,20 @@ function _startLocalApiAuthorization(
});
return;
}
- shell.openExternal(authorizeUrl).catch(() => {
- if (_pending === pending) _cancelPending('Could not open the authorization page; connect again');
- });
+ const open = (url: string) => {
+ if (_pending !== pending) return;
+ return shell.openExternal(url);
+ };
+ const failed = (error: unknown) => {
+ if (_pending !== pending) return;
+ log.warn('authorization page could not be prepared', { catalog_id: catalogId, ...logErrorSummary(error) });
+ _cancelPending('Could not open the authorization page; connect again');
+ };
+ try {
+ const url = buildAuthorizeUrl(state, LOCAL_API_REDIRECT_URI, pending.controller.signal);
+ if (typeof url === 'string') open(url)?.catch(failed);
+ else url.then(open).catch(failed);
+ } catch (error) { failed(error); }
});
}
@@ -159,6 +177,7 @@ function _cancelPending(reason: string): void {
const p = _pending;
_pending = null;
clearTimeout(p.timer);
+ if (p.kind === 'local_api') p.controller.abort();
p.reject(new Error(reason));
}
@@ -170,6 +189,9 @@ interface ProtectedResourceMetadata {
}
interface AuthServerMetadata {
+ issuer?: string;
+ authorization_response_iss_parameter_supported?: boolean;
+ client_id_metadata_document_supported?: boolean;
authorization_endpoint: string;
token_endpoint: string;
registration_endpoint?: string;
@@ -204,7 +226,7 @@ function _fetchDcr(label: string, url: string, init: RequestInit = {}): Promise<
/** Fetch `<base>/.well-known/<name>`, falling back to root-level discovery if path-suffixed
* fails (per MCP authorization spec — providers can serve discovery at either location). */
-async function _fetchWellKnown<T>(mcpUrl: string, wellKnownName: string): Promise<T> {
+async function _fetchWellKnown<T>(mcpUrl: string, wellKnownName: string, strict = false): Promise<T> {
const url = new URL(mcpUrl);
// Path-suffixed first (e.g. https://mcp.notion.com/mcp/.well-known/oauth-protected-resource),
// then root well-known with the MCP path appended (e.g. Atlassian's
@@ -217,7 +239,7 @@ async function _fetchWellKnown<T>(mcpUrl: string, wellKnownName: string): Promis
let lastErr: Error | null = null;
for (const cand of Array.from(new Set(candidates))) {
try {
- const r = await _fetchDcr(`DCR ${wellKnownName}`, cand);
+ const r = await _fetchDcr(`DCR ${wellKnownName}`, cand, strict ? { redirect: 'error' } : {});
if (r.ok) return await r.json() as T;
lastErr = new Error(`DCR ${wellKnownName} metadata HTTP ${r.status}`);
} catch (err) {
@@ -227,11 +249,14 @@ async function _fetchWellKnown<T>(mcpUrl: string, wellKnownName: string): Promis
throw lastErr || new Error(`failed to fetch ${wellKnownName}`);
}
-async function _fetchAuthServerMetadata(authServer: string, mcpUrl: string): Promise<AuthServerMetadata> {
+async function _fetchAuthServerMetadata(authServer: string, mcpUrl: string, strict = false): Promise<AuthServerMetadata> {
const url = new URL(authServer);
const trimmed = url.pathname.replace(/\/+$/, '');
const mcp = new URL(mcpUrl);
const candidates = Array.from(new Set([
+ // For custom issuers, prefer the SDK's issuer-specific RFC 8414 and OIDC
+ // locations before a generic root document that may belong to another tenant.
+ ...(strict ? buildDiscoveryUrls(url).map(candidate => candidate.url.toString()) : []),
...(trimmed ? [`${url.origin}${trimmed}/.well-known/oauth-authorization-server`] : []),
`${url.origin}/.well-known/oauth-authorization-server`,
`${mcp.origin}/.well-known/oauth-authorization-server`,
@@ -240,7 +265,7 @@ async function _fetchAuthServerMetadata(authServer: string, mcpUrl: string): Pro
for (const cand of candidates) {
let r: Response;
try {
- r = await _fetchDcr('DCR auth server metadata', cand);
+ r = await _fetchDcr('DCR auth server metadata', cand, strict ? { redirect: 'error' } : {});
} catch (err) {
lastErr = _fmtFetchErr('DCR auth server metadata fetch failed', err);
continue;
@@ -251,20 +276,81 @@ async function _fetchAuthServerMetadata(authServer: string, mcpUrl: string): Pro
throw lastErr || new Error('failed to fetch auth server metadata');
}
-async function _discoverAuthServer(mcpUrl: string): Promise<{ meta: AuthServerMetadata; resource: string }> {
- const prm = await _fetchWellKnown<ProtectedResourceMetadata>(mcpUrl, 'oauth-protected-resource');
+/** Some MCP resources advertise a non-default PRM location only in the 401
+ * challenge. Probe with a standard initialize request without credentials;
+ * never follow redirects or treat an unprotected response as authorization. */
+async function _fetchChallengedResourceMetadata(mcpUrl: string): Promise<ProtectedResourceMetadata> {
+ const response = await _fetchDcr('MCP authorization challenge', mcpUrl, {
+ method: 'POST',
+ redirect: 'error',
+ headers: { 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream' },
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'initialize', params: {
+ protocolVersion: LATEST_PROTOCOL_VERSION, capabilities: {}, clientInfo: { name: 'orkas-pc', version: '0.1.0' },
+ } }),
+ });
+ try {
+ if (response.status !== 401) throw new Error('MCP server did not advertise OAuth resource metadata');
+ const resourceMetadataUrl = extractWWWAuthenticateParams(response).resourceMetadataUrl;
+ if (!resourceMetadataUrl) throw new Error('MCP authorization challenge lacks resource_metadata');
+ _validateCustomOAuthUrl(mcpUrl, resourceMetadataUrl.toString());
+ const metadataResponse = await _fetchDcr('MCP challenged resource metadata', resourceMetadataUrl.toString(), {
+ redirect: 'error',
+ });
+ if (!metadataResponse.ok) throw new Error(`MCP resource metadata HTTP ${metadataResponse.status}`);
+ return await metadataResponse.json() as ProtectedResourceMetadata;
+ } finally { await response.body?.cancel().catch(() => {}); }
+}
+
+async function _discoverAuthServer(mcpUrl: string, custom = false): Promise<{ meta: AuthServerMetadata; resource: string }> {
+ let prm: ProtectedResourceMetadata;
+ try {
+ prm = await _fetchWellKnown<ProtectedResourceMetadata>(mcpUrl, 'oauth-protected-resource', custom);
+ } catch (error) {
+ if (!custom) throw error;
+ prm = await _fetchChallengedResourceMetadata(mcpUrl);
+ }
const authServer = prm.authorization_servers?.[0];
if (!authServer) throw new Error('protected resource metadata missing authorization_servers');
+ if (custom) _validateCustomOAuthUrl(mcpUrl, authServer);
// RFC 8707 resource indicator — the canonical resource URI from PRM. Required by the MCP
// authorization spec on every authorize / token / refresh request, otherwise the issued
// access_token isn't audience-bound to this MCP server and the server rejects it with
// `invalid_token` at the first protected request. PRM is authoritative; fall back to
// mcpUrl origin only when PRM omits the field (shouldn't happen per spec).
const resource = Array.isArray(prm.resource) ? prm.resource[0] : prm.resource;
- const meta = await _fetchAuthServerMetadata(authServer, mcpUrl);
+ const meta = await _fetchAuthServerMetadata(authServer, mcpUrl, custom);
+ if (custom && meta.issuer !== authServer) {
+ throw new Error('OAuth authorization server issuer mismatch');
+ }
return { meta, resource: resource || new URL(mcpUrl).origin };
}
+function _validateCustomOAuthUrl(mcpUrl: string, value: string): URL {
+ let url: URL;
+ try { url = new URL(value); } catch { throw new Error('OAuth metadata contains invalid endpoint'); }
+ const host = new URL(mcpUrl).hostname;
+ const isLocal = (name: string) => ['localhost', '127.0.0.1', '[::1]'].includes(name)
+ || name.endsWith('.localhost');
+ if (url.username || url.password || url.hash || (url.protocol !== 'https:'
+ && !(url.protocol === 'http:' && isLocal(host) && isLocal(url.hostname)))) {
+ throw new Error('OAuth metadata contains insecure endpoint');
+ }
+ return url;
+}
+
+/** Custom-server metadata is untrusted, including every advertised OAuth endpoint. */
+function _validateCustomOAuthEndpoints(mcpUrl: string, meta: AuthServerMetadata, resource: string): void {
+ for (const value of [meta.authorization_endpoint, meta.token_endpoint, resource,
+ ...(meta.registration_endpoint ? [meta.registration_endpoint] : []),
+ ...(meta.issuer ? [meta.issuer] : [])]) {
+ if (typeof value !== 'string' || !value) throw new Error('OAuth metadata missing endpoint');
+ _validateCustomOAuthUrl(mcpUrl, value);
+ }
+ if (new URL(resource).origin !== new URL(mcpUrl).origin) {
+ throw new Error('OAuth resource does not match MCP server origin');
+ }
+}
+
type DcrTokenAuthMethod = NonNullable<DcrClientCredentials['token_endpoint_auth_method']>;
function _chooseTokenAuthMethod(meta: AuthServerMetadata): DcrTokenAuthMethod {
@@ -311,17 +397,20 @@ async function _registerClient(
registrationEndpoint: string,
redirectUri: string,
tokenEndpointAuthMethod: DcrTokenAuthMethod,
+ strict = false,
): Promise<{ client_id: string; client_secret?: string; token_endpoint_auth_method?: string }> {
let r: Response;
try {
r = await _fetchDcr('DCR client registration', registrationEndpoint, {
method: 'POST',
+ ...(strict ? { redirect: 'error' as const } : {}),
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
body: JSON.stringify({
client_name: CLIENT_NAME,
redirect_uris: [redirectUri],
grant_types: ['authorization_code', 'refresh_token'],
response_types: ['code'],
+ application_type: 'web',
token_endpoint_auth_method: tokenEndpointAuthMethod,
}),
});
@@ -358,31 +447,54 @@ export async function startMcpDcrOAuth(
if (!entry.transport_template || entry.transport_template.kind !== 'streamable-http') {
throw new Error('DCR flow only supports streamable-http transports');
}
+ return _startDcrOAuth(entry.id, entry.transport_template.url, entry.required_oauth_scopes || [], opts);
+}
+
+export async function startCustomMcpOAuth(
+ id: string,
+ mcpUrl: string,
+ opts: { attemptId?: string } = {},
+): Promise<{ grant: OAuthGrant; client: DcrClientCredentials }> {
+ return _startDcrOAuth(id, mcpUrl, [], opts, true);
+}
+
+async function _startDcrOAuth(
+ id: string,
+ mcpUrl: string,
+ scopes: string[],
+ opts: { attemptId?: string },
+ storeLocally = false,
+): Promise<{ grant: OAuthGrant; client: DcrClientCredentials }> {
_cancelPending('superseded by a new DCR start');
const generation = ++_startGeneration;
-
- const mcpUrl = entry.transport_template.url;
- log.info('DCR flow starting', { catalog_id: entry.id });
+ log.info('DCR flow starting', { catalog_id: storeLocally ? 'custom' : id });
// Discover endpoints.
- const { meta, resource } = await _discoverAuthServer(mcpUrl);
- if (!meta.registration_endpoint) {
- throw new Error(`provider ${entry.id} does not advertise registration_endpoint — DCR unsupported`);
+ const { meta, resource } = await _discoverAuthServer(mcpUrl, storeLocally);
+ if (storeLocally) _validateCustomOAuthEndpoints(mcpUrl, meta, resource);
+ if (storeLocally && meta.authorization_response_iss_parameter_supported && !meta.issuer) {
+ throw new Error('OAuth metadata missing issuer');
}
- const tokenEndpointAuthMethod = _chooseTokenAuthMethod(meta);
+ const redirectUri = `${accountApiBase().replace(/\/+$/, '')}/connectors/oauth/dcr-callback`;
+ const metadataUrl = `${accountApiBase().replace(/\/+$/, '')}/connectors/oauth/client-metadata`;
+ const useMetadata = storeLocally && meta.client_id_metadata_document_supported === true
+ && metadataUrl.startsWith('https://');
+ if (!useMetadata && !meta.registration_endpoint) throw new Error('provider does not support client metadata or DCR registration');
+ const tokenEndpointAuthMethod = useMetadata ? 'none' : _chooseTokenAuthMethod(meta);
log.info('DCR endpoints discovered', {
- catalog_id: entry.id,
- has_registration_endpoint: true,
+ catalog_id: storeLocally ? 'custom' : id,
+ has_registration_endpoint: !!meta.registration_endpoint,
+ client_metadata: useMetadata,
has_resource: !!resource,
token_auth: tokenEndpointAuthMethod,
});
- // Register with the same Server environment that will exchange the callback.
- // Source and packaged builds both use the production bridge.
- const redirectUri = `${accountApiBase().replace(/\/+$/, '')}/connectors/oauth/dcr-callback`;
- const registered = await _registerClient(meta.registration_endpoint, redirectUri, tokenEndpointAuthMethod);
+ // Source and packaged builds both use the production HTTPS callback bridge.
+ const registered = useMetadata
+ ? { client_id: metadataUrl, token_endpoint_auth_method: 'none' as const }
+ : await _registerClient(meta.registration_endpoint!, redirectUri, tokenEndpointAuthMethod, storeLocally);
if (generation !== _startGeneration) throw Object.assign(new Error('Authorization superseded'), { code: 'user_cancelled' });
- log.info('DCR registration done', { catalog_id: entry.id });
+ log.info('DCR registration done', { catalog_id: storeLocally ? 'custom' : id });
const registeredTokenAuthMethod = registered.token_endpoint_auth_method === 'client_secret_basic'
|| registered.token_endpoint_auth_method === 'client_secret_post'
@@ -395,7 +507,7 @@ export async function startMcpDcrOAuth(
token_endpoint_auth_method: registeredTokenAuthMethod,
authorization_endpoint: meta.authorization_endpoint,
token_endpoint: meta.token_endpoint,
- registration_endpoint: meta.registration_endpoint,
+ ...(meta.registration_endpoint ? { registration_endpoint: meta.registration_endpoint } : {}),
resource,
};
@@ -410,10 +522,10 @@ export async function startMcpDcrOAuth(
authUrl.searchParams.set('code_challenge', pkce.challenge);
authUrl.searchParams.set('code_challenge_method', 'S256');
authUrl.searchParams.set('resource', resource);
- const requiredScopes = [...new Set(entry.required_oauth_scopes || [])];
+ const requiredScopes = [...new Set(scopes)];
if (requiredScopes.length) authUrl.searchParams.set('scope', requiredScopes.join(' '));
- log.info('opening DCR authorize URL', { catalog_id: entry.id });
+ log.info('opening DCR authorize URL', { catalog_id: storeLocally ? 'custom' : id });
return new Promise<{ grant: OAuthGrant; client: DcrClientCredentials }>((resolve, reject) => {
const timer = setTimeout(() => {
@@ -422,7 +534,10 @@ export async function startMcpDcrOAuth(
timer.unref?.();
const pending: PendingDcrFlow = {
kind: 'dcr',
- catalogId: entry.id,
+ catalogId: id,
+ storeLocally,
+ ...(meta.issuer ? { issuer: meta.issuer } : {}),
+ issuerRequired: meta.authorization_response_iss_parameter_supported === true,
...(opts.attemptId ? { attemptId: opts.attemptId } : {}),
state,
codeVerifier: pkce.verifier,
@@ -435,8 +550,8 @@ export async function startMcpDcrOAuth(
timer,
};
_pending = pending;
- shell.openExternal(authUrl.toString()).catch((err) => {
- if (_pending === pending) _cancelPending(`failed to open browser: ${(err as Error).message}`);
+ shell.openExternal(authUrl.toString()).catch(() => {
+ if (_pending === pending) _cancelPending('failed to open authorization browser');
});
});
}
@@ -472,7 +587,7 @@ export async function handleDcrCallbackUrl(rawUrl: string): Promise<void> {
// Pull {oauth_code, oauth_state} from Server. Server uses the namespaced keys (not bare
// `code`/`state`) because `json_response` spreads data flat — a bare `code` key would
// collide with the response status `code` field. See Server `api/connectors.py` comment.
- let payload: { code: string; state: string };
+ let payload: { code: string; state: string; issuer?: string };
try {
const relayBase = pending.kind === 'local_api' ? pending.relayBase : accountApiBase();
const res = await _fetchDcr('DCR exchange', `${relayBase}/connectors/oauth/dcr-exchange`, {
@@ -489,11 +604,13 @@ export async function handleDcrCallbackUrl(rawUrl: string): Promise<void> {
msg?: string;
oauth_code?: string;
oauth_state?: string;
+ oauth_issuer?: string;
};
if (body.code !== 0 || !body.oauth_code || !body.oauth_state) {
throw new Error(body.msg || 'dcr exchange response invalid');
}
- payload = { code: body.oauth_code, state: body.oauth_state };
+ payload = { code: body.oauth_code, state: body.oauth_state,
+ ...(body.oauth_issuer ? { issuer: body.oauth_issuer } : {}) };
} catch (err) {
if (_pending === pending) _cancelPending(`dcr exchange failed: ${_fmtFetchErr('', err).message}`);
return;
@@ -506,10 +623,15 @@ export async function handleDcrCallbackUrl(rawUrl: string): Promise<void> {
_cancelPending('state mismatch (CSRF guard)');
return;
}
+ if (pending.kind === 'dcr' && ((payload.issuer && payload.issuer !== pending.issuer)
+ || (pending.issuerRequired && !payload.issuer))) {
+ _cancelPending('authorization issuer mismatch');
+ return;
+ }
if (pending.kind === 'local_api') {
try {
- const credentials = await pending.exchange(payload.code);
+ const credentials = await pending.exchange(payload.code, pending.controller.signal);
if (_pending !== pending) return;
_pending = null;
clearTimeout(pending.timer);
@@ -534,6 +656,7 @@ export async function handleDcrCallbackUrl(rawUrl: string): Promise<void> {
});
const res = await _fetchDcr('DCR token exchange', pending.client.token_endpoint, {
method: 'POST',
+ ...(pending.storeLocally ? { redirect: 'error' as const } : {}),
headers: tokenReq.headers,
body: tokenReq.body.toString(),
});
@@ -569,7 +692,7 @@ export async function handleDcrCallbackUrl(rawUrl: string): Promise<void> {
_pending = null;
clearTimeout(pending.timer);
log.info('DCR grant resolved', {
- catalog_id: pending.catalogId,
+ catalog_id: pending.storeLocally ? 'custom' : pending.catalogId,
has_refresh: !!localGrant.refresh_token,
expires_in: tokens.expires_in ?? null,
});
@@ -584,7 +707,7 @@ export async function handleDcrCallbackUrl(rawUrl: string): Promise<void> {
export async function refreshDcrIfStale(
client: DcrClientCredentials,
grant: OAuthGrant,
- opts: { force?: boolean } = {},
+ opts: { force?: boolean; strict?: boolean } = {},
): Promise<OAuthGrant> {
if (!opts.force && !grant.expires_at) return grant;
if (!opts.force && grant.expires_at - Date.now() > REFRESH_BUFFER_MS) return grant;
@@ -601,6 +724,7 @@ export async function refreshDcrIfStale(
try {
res = await _fetchDcr('DCR token refresh', client.token_endpoint, {
method: 'POST',
+ ...(opts.strict ? { redirect: 'error' as const } : {}),
headers: tokenReq.headers,
body: tokenReq.body.toString(),
});
diff --git a/src/main/features/connectors/protocol.ts b/src/main/features/connectors/protocol.ts
index 8c852098..dd2fda77 100644
--- a/src/main/features/connectors/protocol.ts
+++ b/src/main/features/connectors/protocol.ts
@@ -43,7 +43,9 @@ function _extractConnectorCallback(argv: readonly string[] | undefined): string
function _focusMainWindow(): void {
const win = BrowserWindow.getAllWindows().find((candidate) => !candidate.isDestroyed());
- if (!win) return;
+ // Background windows deliberately opt out of desktop activation. Keep
+ // callback delivery independent from showing that window.
+ if (!win || !win.isFocusable()) return;
if (win.isMinimized()) win.restore();
win.show();
win.focus();
diff --git a/src/main/features/connectors/task-created-drafts.ts b/src/main/features/connectors/task-created-drafts.ts
new file mode 100644
index 00000000..9cfd34a9
--- /dev/null
+++ b/src/main/features/connectors/task-created-drafts.ts
@@ -0,0 +1,34 @@
+/** Ephemeral Host evidence for cleanup of a draft created by this task. Provider
+ * names, argument hints and draft ids supplied by a model are not ownership. */
+export interface DraftScope {
+ uid: string;
+ cid: string;
+ connectorId: string;
+ accountKey: string;
+}
+const drafts = new Map<string, DraftScope>();
+function key(scope: DraftScope, id: string): string {
+ return JSON.stringify([scope.uid, scope.cid, scope.connectorId, scope.accountKey, id]);
+}
+export function clearTaskCreatedDrafts(matches: (scope: DraftScope) => boolean): void {
+ for (const [id, scope] of drafts) if (matches(scope)) drafts.delete(id);
+}
+export function isTaskCreatedDraft(scope: DraftScope | undefined, id: unknown): boolean {
+ return !!scope?.uid && !!scope.cid && typeof id === 'string' && drafts.has(key(scope, id));
+}
+export function observeTaskDraftResult(scope: DraftScope | undefined, action: string, args: Record<string, unknown>, raw: unknown): void {
+ if (!scope?.uid || !scope.cid || !['gmail', 'google-workspace'].includes(scope.connectorId)) return;
+ if (!raw || typeof raw !== 'object' || (raw as { isError?: unknown }).isError === true) return;
+ const content = (raw as { content?: unknown }).content;
+ if (!Array.isArray(content) || content.length !== 1 || content[0]?.type !== 'text'
+ || typeof content[0].text !== 'string' || content[0].text.length > 4_096) return;
+ try {
+ const value = JSON.parse(content[0].text);
+ if (action === 'delete_draft' && value?.ok === true && typeof args.id === 'string') drafts.delete(key(scope, args.id));
+ if (action !== 'create_draft' || typeof value?.id !== 'string' || !value.id || value.id.length > 256
+ || typeof value.messageId !== 'string' || !value.messageId) return;
+ // Bounded per-host memory; eviction only restores confirmation.
+ if (drafts.size >= 256) drafts.delete(drafts.keys().next().value!);
+ drafts.set(key(scope, value.id), scope);
+ } catch { /* Unknown response shapes provide no evidence. */ }
+}
diff --git a/src/main/features/connectors/types.ts b/src/main/features/connectors/types.ts
index cc5dca09..c26e59cc 100644
--- a/src/main/features/connectors/types.ts
+++ b/src/main/features/connectors/types.ts
@@ -124,10 +124,11 @@ export interface ConnectorInstance {
display_name: string;
/** Where the instance came from. Missing/undefined = 'catalog' (pre-existing rows).
* 'custom' = user-supplied MCP server (id always carries the `custom-` prefix so it can
- * never collide with a catalog entry id); its transport is used verbatim — no catalog
- * template, no OAuth grant, no server-side refresh. See `CLAUDE.md` under
+ * never collide with a catalog entry id); its transport is user-supplied. See `CLAUDE.md` under
* "Connectors And Knowledge Base". */
origin?: 'catalog' | 'custom';
+ /** Optional MCP OAuth for a user-supplied streamable HTTP server. */
+ custom_auth_mode?: 'oauth';
transport: Transport;
/** Tool subset to expose. `null` = all reported tools; `string[]` = whitelist of tool names. */
enabled_subtools: string[] | null;
@@ -144,6 +145,8 @@ export interface ConnectorInstance {
* The manager rewrites the transport env at spawn time using `oauth_grant.access_token`;
* refresh logic in `oauth.ts::refreshIfStale` runs before connect / after a 401. */
oauth_grant?: OAuthGrant;
+ /** Legacy incoming-webhook targets retained for decrypting existing connections. */
+ discord_webhook_targets?: DiscordWebhookTarget[];
/** DCR-issued client identity for MCP-spec auth (`auth_mode === 'mcp_dcr'`). The public build
* stores this with the grant inside the encrypted local registry and never uploads it to the
* Orkas account service. */
@@ -333,9 +336,9 @@ export interface OAuthConfig {
provider_id: string;
}
-/** Dynamic Client Registration result (RFC 7591) for MCP-spec OAuth providers. Stored locally
- * with the connector's encrypted secrets. All endpoints are captured at first connect —
- * re-discovery on every refresh would add latency and assumes stable provider endpoints. */
+/** MCP OAuth client identity from DCR (RFC 7591) or a Client ID Metadata Document.
+ * Stored with the grant in the encrypted local registry. Discovery endpoints are retained
+ * for refresh without repeating discovery. */
export interface DcrClientCredentials {
client_id: string;
/** Most providers issue one; some omit (public clients). */
@@ -485,6 +488,10 @@ export interface CatalogEntry extends LocalizedCatalogCopy<'description'> {
* uses `display_name_en`. `display_name` remains the stable persisted/default fallback. */
display_name_zh?: string;
display_name_en?: string;
+ /** Other product names people use for this exact service (for example "Outlook" for the
+ * Microsoft 365 mail toolkit). Commander's connector search matches them like display names;
+ * they are never displayed. List only names of this service, not category words. */
+ search_aliases?: string[];
/** Inline SVG markup for the brand logo. Required on every shipped catalog entry — the
* renderer draws this on a white rounded square. Keep the inner SVG `width` / `height`
* either absent or `100%` so CSS-set 40×40 card box governs the rendered size.
@@ -558,3 +565,17 @@ export interface CatalogEntry extends LocalizedCatalogCopy<'description'> {
* `manager.ts::connectViaOAuth`. */
bundle_member_ids?: string[];
}
+
+export interface DiscordWebhookTarget {
+ id: string;
+ webhook_id: string;
+ webhook_token?: string;
+ webhook_url: string;
+ guild_id?: string;
+ guild_name?: string;
+ channel_id?: string;
+ channel_name?: string;
+ name?: string;
+ created_at: string;
+ updated_at: string;
+}
diff --git a/src/main/features/connectors/woocommerce-auth.ts b/src/main/features/connectors/woocommerce-auth.ts
new file mode 100644
index 00000000..630648f7
--- /dev/null
+++ b/src/main/features/connectors/woocommerce-auth.ts
@@ -0,0 +1,81 @@
+/** WooCommerce application-auth endpoint; the desktop alone can decrypt relay keys. */
+import { generateKeyPair, privateDecrypt, type KeyObject } from 'node:crypto';
+import { fetchAndReadWithTimeout, throwIfAborted } from '../../util/abort';
+import { withCommonHeaders } from '../api_common';
+import { startLocalApiBrowserOAuth } from './oauth-dcr';
+import { LOCAL_API_REDIRECT_URI } from './oauth-redirect';
+
+const RELAY_BASE = new URL('../woocommerce/auth/', LOCAL_API_REDIRECT_URI).href;
+
+async function readJson(url: string, init: RequestInit, signal: AbortSignal): Promise<Record<string, unknown>> {
+ const { body } = await fetchAndReadWithTimeout(url, { ...init, redirect: 'error' }, 60_000, signal,
+ 'Authorization request timed out; connect again', async response => {
+ if (!response.ok) throw new Error('Could not verify the store connection');
+ // Keep both the timeout and body bound active while reading a shop response.
+ const reader = response.body?.getReader();
+ if (!reader) throw new Error('Could not verify the store connection');
+ const chunks: Uint8Array[] = [];
+ let size = 0;
+ try {
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ size += value.length;
+ if (size > 1024 * 1024) throw new Error('Could not verify the store connection');
+ chunks.push(value);
+ }
+ } finally { await reader.cancel(); }
+ const value = JSON.parse(Buffer.concat(chunks).toString('utf8'));
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('Could not verify the store connection');
+ return value;
+ });
+ throwIfAborted(signal);
+ return body;
+}
+
+export function authorizeWooCommerce(
+ catalogId: string, storeUrl: string, opts: { attemptId?: string },
+): Promise<Record<string, unknown>> {
+ let privateKey: KeyObject;
+ let expectedState: string;
+ return startLocalApiBrowserOAuth(catalogId, async (state, _redirect, signal) => {
+ expectedState = state;
+ const pair = await new Promise<{ publicKey: KeyObject; privateKey: KeyObject }>((resolve, reject) => {
+ generateKeyPair('rsa', { modulusLength: 2048 }, (error, publicKey, key) => {
+ if (error) reject(error); else resolve({ publicKey, privateKey: key });
+ });
+ });
+ throwIfAborted(signal);
+ privateKey = pair.privateKey;
+ const result = await readJson(`${RELAY_BASE}start`, {
+ method: 'POST', headers: withCommonHeaders({ 'content-type': 'application/json' }),
+ body: JSON.stringify({ state, public_key: pair.publicKey.export({ type: 'spki', format: 'pem' }) }),
+ }, signal);
+ if (result.code !== 0 || typeof result.ticket !== 'string' || !/^[A-Za-z0-9_-]{43}$/.test(result.ticket)) {
+ throw new Error('Could not start store authorization; connect again');
+ }
+ const url = new URL(`${storeUrl}/wc-auth/v1/authorize`);
+ url.search = new URLSearchParams({
+ app_name: 'Orkas', scope: 'read_write', user_id: result.ticket,
+ callback_url: `${RELAY_BASE}callback`, return_url: `${RELAY_BASE}return?lang=${encodeURIComponent(state.split('_')[1])}`,
+ }).toString();
+ return url.href;
+ }, async (encrypted, signal) => {
+ throwIfAborted(signal);
+ if (!privateKey || !/^[A-Za-z0-9+/]{342}==$/.test(encrypted)) throw new Error('Invalid store authorization');
+ const credentials = JSON.parse(privateDecrypt({
+ key: privateKey, oaepHash: 'sha256', oaepLabel: Buffer.from(expectedState),
+ }, Buffer.from(encrypted, 'base64')).toString('utf8'));
+ if (!/^ck_[a-fA-F0-9]{40}$/.test(credentials?.consumer_key || '')
+ || !/^cs_[a-fA-F0-9]{40}$/.test(credentials?.consumer_secret || '')) throw new Error('Invalid store authorization');
+ const { consumer_key, consumer_secret } = credentials;
+ const status = await readJson(`${storeUrl}/wp-json/wc/v3/system_status`, {
+ headers: { accept: 'application/json', authorization: `Basic ${Buffer.from(`${consumer_key}:${consumer_secret}`).toString('base64')}` },
+ }, signal);
+ const environment = status.environment as Record<string, unknown> | undefined;
+ if (typeof environment?.site_url !== 'string' || typeof environment?.version !== 'string') {
+ throw new Error('Could not verify the store connection');
+ }
+ return { consumer_key, consumer_secret };
+ }, opts);
+}
diff --git a/src/main/features/group_chat/connector_setup_tool.ts b/src/main/features/group_chat/connector_setup_tool.ts
index 349ad819..75192cf1 100644
--- a/src/main/features/group_chat/connector_setup_tool.ts
+++ b/src/main/features/group_chat/connector_setup_tool.ts
@@ -222,18 +222,68 @@ function searchText(entry: CatalogEntry, catalog: readonly CatalogEntry[]): stri
variant.description_it,
);
}
- return normalizeSearch([...parts, ...additionalLocalizedParts].filter(Boolean).join(' '));
+ // Aliases go last for the same offset-stability reason; name ranking covers exact alias hits.
+ return normalizeSearch([...parts, ...additionalLocalizedParts, ...(entry.search_aliases || [])]
+ .filter(Boolean).join(' '));
}
-function searchRank(entry: CatalogEntry, query: string, catalog: readonly CatalogEntry[]): number {
+/** 0 = exact id, 1 = exact name or alias, 2 = id/name/alias prefix, null = text match only. */
+function nameRank(entry: CatalogEntry, query: string): number | null {
const normalizedId = normalizeSearch(entry.id);
- const names = [entry.display_name, entry.display_name_zh, entry.display_name_en]
+ const names = [entry.display_name, entry.display_name_zh, entry.display_name_en, ...(entry.search_aliases || [])]
.map(normalizeSearch)
.filter(Boolean);
if (normalizedId === query) return 0;
if (names.includes(query)) return 1;
if (normalizedId.startsWith(query) || names.some((name) => name.startsWith(query))) return 2;
- return 3 + Math.max(0, searchText(entry, catalog).indexOf(query));
+ return null;
+}
+
+function searchRank(entry: CatalogEntry, query: string, catalog: readonly CatalogEntry[]): number {
+ return nameRank(entry, query) ?? 3 + Math.max(0, searchText(entry, catalog).indexOf(query));
+}
+
+interface SearchMatch {
+ entry: CatalogEntry;
+ /** Present only for any-term fallback results. */
+ matchedTerms?: string[];
+}
+
+/**
+ * Every term must match one entry. When no entry contains all terms (a service name mixed with
+ * descriptive words, or several services in one query), fall back to entries matching any term:
+ * exact id/name/alias hits first, then more matched terms, then the best single-term rank.
+ */
+function matchConnectorSetups(query: string, catalog: readonly CatalogEntry[]): SearchMatch[] {
+ const normalizedQuery = normalizeSearch(query).trim();
+ const terms = [...new Set(normalizedQuery.split(/\s+/).filter(Boolean))];
+ const candidates = catalog
+ .filter((entry) => !entry.catalog_parent_id)
+ .map((entry) => ({ entry, haystack: searchText(entry, catalog) }));
+ const complete = candidates
+ .filter(({ haystack }) => terms.every((term) => haystack.includes(term)))
+ .map(({ entry }) => entry)
+ .sort((a, b) => (
+ searchRank(a, normalizedQuery, catalog) - searchRank(b, normalizedQuery, catalog)
+ || a.id.localeCompare(b.id)
+ ));
+ if (complete.length || terms.length < 2) return complete.map((entry) => ({ entry }));
+ return candidates
+ .map(({ entry, haystack }) => {
+ const matchedTerms = terms.filter((term) => haystack.includes(term));
+ const bestRank = Math.min(...matchedTerms.map((term) => (
+ nameRank(entry, term) ?? 3 + Math.max(0, haystack.indexOf(term))
+ )));
+ return { entry, matchedTerms, bestRank };
+ })
+ .filter(({ matchedTerms }) => matchedTerms.length > 0)
+ .sort((a, b) => (
+ Number(b.bestRank <= 1) - Number(a.bestRank <= 1)
+ || b.matchedTerms.length - a.matchedTerms.length
+ || a.bestRank - b.bestRank
+ || a.entry.id.localeCompare(b.entry.id)
+ ))
+ .map(({ entry, matchedTerms }) => ({ entry, matchedTerms }));
}
export function searchConnectorSetups(
@@ -243,20 +293,9 @@ export function searchConnectorSetups(
instances: readonly ConnectorInstance[],
enabledSnapshot: Pick<ComponentEnabledFile, 'connectors'>,
): Array<Record<string, unknown>> {
- const normalizedQuery = normalizeSearch(query).trim();
- const terms = normalizedQuery.split(/\s+/).filter(Boolean);
- return catalog
- .filter((entry) => !entry.catalog_parent_id)
- .filter((entry) => {
- const haystack = searchText(entry, catalog);
- return terms.every((term) => haystack.includes(term));
- })
- .sort((a, b) => (
- searchRank(a, normalizedQuery, catalog) - searchRank(b, normalizedQuery, catalog)
- || a.id.localeCompare(b.id)
- ))
+ return matchConnectorSetups(query, catalog)
.slice(0, SEARCH_RESULT_CAP)
- .map((entry) => ({
+ .map(({ entry, matchedTerms }) => ({
connector_id: entry.id,
name: localized(entry as unknown as Record<string, unknown>, 'display_name', language),
category: entry.category,
@@ -264,6 +303,7 @@ export function searchConnectorSetups(
requires_extra_configuration: connectorSetupKind(entry) !== 'one_click_oauth',
can_start: entry.availability !== 'visible_disabled' && !entry.unavailable_reason,
...publicStatus(entry, catalog, instances, enabledSnapshot),
+ ...(matchedTerms ? { matched_terms: matchedTerms } : {}),
}));
}
diff --git a/src/main/ipc/connectors.ts b/src/main/ipc/connectors.ts
index dd10c981..79d7009e 100644
--- a/src/main/ipc/connectors.ts
+++ b/src/main/ipc/connectors.ts
@@ -5,7 +5,8 @@
* connectors.catalog → { catalog }
* connectors.list → { instances }
* connectors.start_oauth → { started, attempt_id } (returns after accepting the browser flow)
- * connectors.add_custom → { instance } (user-supplied MCP server; validated form input)
+ * connectors.add_custom → { instance, started?, attempt_id? } (custom MCP; OAuth detaches)
+ * connectors.authorize_custom → { started, attempt_id } (reconnect custom OAuth)
* connectors.remove → { removed }
* connectors.refresh → { tools, instance }
* connectors.set_subtools → { instance }
@@ -40,6 +41,7 @@ interface ClientConnectorInstance {
id: string;
display_name: string;
origin?: 'catalog' | 'custom';
+ custom_auth_mode?: 'oauth';
connection_environment?: 'sandbox' | 'live';
transport?:
| { kind: 'stdio'; summary: string; command?: string; argument_count?: number }
@@ -85,6 +87,7 @@ function toClientInstance(inst: ConnectorInstance, enabled?: boolean, uid?: stri
id: inst.id,
display_name: inst.display_name,
...(inst.origin ? { origin: inst.origin } : {}),
+ ...(inst.custom_auth_mode ? { custom_auth_mode: inst.custom_auth_mode } : {}),
...(transport ? { transport } : {}),
enabled_subtools: inst.enabled_subtools,
tools_cache: inst.tools_cache,
@@ -227,6 +230,13 @@ export const invokeHandlers = {
return { handled: installConfirm.respond(payload.request_id, payload.approved) };
},
+ 'connectors.account_choice_response': async (payload: { request_id?: unknown; choice_id?: unknown }, ctx: { userId: string }) => {
+ if (typeof payload?.request_id !== 'string' || !/^[a-f0-9]{32}$/.test(payload.request_id)) throw new Error('invalid request_id');
+ if (payload.choice_id !== null && (typeof payload.choice_id !== 'string' || !/^[1-9][0-9]{0,24}$/.test(payload.choice_id))) throw new Error('invalid choice_id');
+ const { respondAccountChoice } = await import('../features/connectors/account-choice');
+ return { handled: respondAccountChoice(ctx.userId, payload.request_id, payload.choice_id as string | null) };
+ },
+
/** Renderer answer to a per-action sensitive connector confirmation. */
'connectors.action_confirm_response': async (payload: { request_id?: unknown; approved?: unknown; scope?: unknown }, ctx: { sender: { id: number } }) => {
if (typeof payload?.request_id !== 'string' || !payload.request_id) throw new Error('invalid request_id');
@@ -238,7 +248,7 @@ export const invokeHandlers = {
},
'connectors.add_custom': async (
- payload: { display_name?: unknown; transport?: unknown },
+ payload: { display_name?: unknown; transport?: unknown; auth_mode?: unknown },
ctx: { userId: string },
) => {
// Validation (shape, HTTPS/explicit-loopback rule, header/env hygiene) lives in
@@ -246,8 +256,18 @@ export const invokeHandlers = {
const instance = await connectors.addCustomInstance(ctx.userId, {
display_name: payload?.display_name as string,
transport: payload?.transport as never,
- });
- return { instance: toClientInstance(instance, isConnectorEnabled(ctx.userId, instance.id), ctx.userId) };
+ auth_mode: payload?.auth_mode as 'none' | 'oauth',
+ }, { deferOAuth: payload?.auth_mode === 'oauth' });
+ const started = instance.custom_auth_mode === 'oauth'
+ ? connectors.beginCustomOAuthConnect(ctx.userId, instance.id) : null;
+ return { instance: toClientInstance(instance, isConnectorEnabled(ctx.userId, instance.id), ctx.userId),
+ ...(started ? { started: true, attempt_id: started.attempt_id } : {}) };
+ },
+
+ 'connectors.authorize_custom': async (payload: { id?: unknown }, ctx: { userId: string }) => {
+ if (typeof payload?.id !== 'string' || !connectors.isValidInstanceId(payload.id)) throw new Error('invalid id');
+ const started = connectors.beginCustomOAuthConnect(ctx.userId, payload.id);
+ return { started: true, attempt_id: started.attempt_id };
},
'connectors.remove': async (payload: { id?: unknown }, ctx: { userId: string }) => {
diff --git a/src/main/model/core-agent/auth-error.ts b/src/main/model/core-agent/auth-error.ts
index 8f8b88f8..4e66a843 100644
--- a/src/main/model/core-agent/auth-error.ts
+++ b/src/main/model/core-agent/auth-error.ts
@@ -1,57 +1,7 @@
-/**
- * Key-failure classification for the auto-rotation path.
- *
- * "Key failure" = a response the server rejected **because of this
- * specific credential**. Rotating to another key in the same
- * `(provider, model)` group has a chance of succeeding.
- *
- * Five kinds we recognize:
- * - `auth` → HTTP 401 / `authentication_error` / `invalid_api_key`
- * - `permission` → HTTP 403 / `permission_error` / `plan_required` /
- * `subscription_expired` (key revoked, missing tier)
- * - `rate_limit` → HTTP 429 / `rate_limit_error` / `too_many_requests`
- * / `quota_exceeded` (this key is rate-limited right now)
- * - `balance` → HTTP 402 / `insufficient_balance` / `insufficient_quota`
- * / `payment_required` (this account is out of money)
- * - `network` → ECONNRESET / ETIMEDOUT / ENOTFOUND / "fetch failed" /
- * "Client network socket disconnected before secure TLS"
- * (TCP/TLS reset. Rotating to a different provider can
- * help inside the current request, but we do NOT cooldown
- * network failures; the next user request starts from the
- * configured entries list again).
- *
- * **Not** key failures (return null — error propagates, no rotation):
- * - 400 malformed request / invalid model param (config issue, same on any key)
- * - content-policy / safety / content_filter (model will refuse again)
- * - 5xx server_error (server issue, not key's fault)
- *
- * Signal flow:
- * 1. pi-ai SDK throws a raw `Error` with `status`/`message` (Anthropic /
- * OpenAI SDK shapes).
- * 2. `pi-provider.ts::wrapError` maps some of these into core-agent's
- * typed errors (`AuthError` / `RateLimitError` / `ContextOverflowError`
- * / generic `ProviderError`). Status code is **not** always carried
- * through — `wrapError` pattern-matches on message only for non-
- * instanceof cases.
- * 3. `classifyKeyFailure` below checks both the typed instance AND a
- * message-pattern fallback so we catch cases pi-ai dropped on the
- * floor (notably 402 balance errors which pi-ai has no typed class
- * for).
- *
- * The cause chain is walked up to depth 5 so we don't miss a wrapped
- * error whose outer message is generic.
- */
-
-/**
- * Note on instanceof checks
- * ─────────────────────────
- * We deliberately **do not** use `err instanceof AuthError` etc here. pi-ai
- * is loaded through the ESM branch (dynamic `import('#core-agent')`) while
- * Orkas main is CJS — which causes `core-agent/src/shared/errors.js` to be
- * loaded **twice**, once per module system. Two class identities, so
- * `instanceof` silently returns false across the boundary. Every signal we
- * need lives in `err.status` / `err.message` / `err.cause.*` anyway, so we
- * rely on those exclusively.
+/** Credential/account failures use structured status/code evidence only.
+ * Transport failures retain their existing recovery policy. The shared facts
+ * reader follows SDK cause chains and machine error envelopes;
+ * incidental prose must never cool down a credential or assert an account cause.
*/
import { isProviderSafetyError } from '../../../core-agent/src/shared/errors';
@@ -59,32 +9,6 @@ import { providerCredentialFailure, providerErrorFacts } from '../../../core-age
export type KeyFailureKind = 'auth' | 'permission' | 'rate_limit' | 'balance' | 'network';
-// ─── Message patterns ────────────────────────────────────────────────────
-
-const AUTH_RE =
- /invalid[_\s-]?api[_\s-]?key|incorrect[_\s-]?api[_\s-]?key|authentication[_\s-]?error|\bunauthorized\b|api[_\s-]?key[_\s-]?(invalid|incorrect|expired|missing|not[_\s-]?found|appears)|\bauth[_\s-]?failed\b|invalidated[_\s-]+oauth[_\s-]+token|oauth[_\s-]+token.{0,80}\b(invalid|invalidated|expired|revoked)\b|appears to be invalid|\bno[_\s-]?such[_\s-]?api[_\s-]?key\b|\bsk-[a-z0-9\-_]{4,}\b.*?(invalid|incorrect|expired)/i;
-
-// Provider error codes are a stronger signal than prose. Keep this exact-ish
-// so generic words such as "invalid" do not turn request/config failures into
-// credential failures.
-const AUTH_CODE_RE =
- /^(token_invalidated|invalid_token|invalid_api_key|authentication_error|unauthorized|oauth_token_(invalid|invalidated|expired|revoked))$/i;
-
-const PERM_RE =
- /permission[_\s-]?error|\bforbidden\b|plan[_\s-]?required|subscription[_\s-]?(expired|required|invalid|canceled)|access[_\s-]?denied/i;
-
-const RATE_RE =
- /rate[_\s-]?limit|too[_\s-]?many[_\s-]?requests|quota[_\s-]?exceeded|usage[_\s-]?limit|requests[_\s-]?per[_\s-]?minute|throttled/i;
-
-const BALANCE_RE =
- /insufficient[_\s-]?(balance|quota|credits|funds)|payment[_\s-]?required|balance[_\s-]?not[_\s-]?enough|余额不足|账户余额|积分不足|out of credits|credit[_\s-]?exhausted|requires?\s+more\s+credits?|can\s+only\s+afford/i;
-
-// Explicit non-key failures — patterns that MUST NOT be classified as key
-// failure even if they overlap the above (e.g. "invalid request" contains
-// "invalid" which auth regex also picks up). Checked first.
-const NON_KEY_RE =
- /content[_\s-]?policy|content[_\s-]?filter|safety[_\s-]?violation|content_filter|invalid[_\s-]?request[_\s-]?error|bad[_\s-]?request|model[_\s-]?not[_\s-]?found|context[_\s-]?(length|overflow|too[_\s-]?long)/i;
-
// Network-layer failures: TCP reset / TLS handshake aborted / DNS failure /
// generic fetch failure. These propagate up as `TypeError("fetch failed")`
// from undici with the real cause buried in `err.cause.code` (Node's net
@@ -95,14 +19,10 @@ const NETWORK_CODE_SET: ReadonlySet<string> = new Set([
'EHOSTUNREACH', 'UND_ERR_SOCKET', 'UND_ERR_CONNECT_TIMEOUT',
]);
-const NETWORK_RE =
- /\bECONNRESET\b|\bETIMEDOUT\b|\bENOTFOUND\b|\bECONNREFUSED\b|\bENETUNREACH\b|\bEAI_AGAIN\b|\bEPIPE\b|\bEHOSTUNREACH\b|socket\s*hang\s*up|socket[_\s-]?disconnected|network[_\s-]?socket[_\s-]?disconnected|Client\s+network\s+socket\s+disconnected\s+before\s+secure\s+TLS|fetch[_\s-]?failed|network[_\s-]?error|request[_\s-]?timed[_\s-]?out|connection[_\s-]?reset|getaddrinfo\s+(EAI_AGAIN|ENOTFOUND)|connect\s+ETIMEDOUT/i;
-
// ─── Helpers ─────────────────────────────────────────────────────────────
/**
- * Aggregate error messages along the cause chain so we match against the
- * whole story, not just the outermost Error's `.message`. Depth-limited
+ * Aggregate display diagnostics along the cause chain, never for classification. Depth-limited
* to avoid runaway loops from circular causes.
*/
function collectMessages(err: unknown, maxDepth = 5): string {
@@ -129,41 +49,6 @@ function collectMessages(err: unknown, maxDepth = 5): string {
return parts.join(' │ ');
}
-/**
- * Read a `status` / `statusCode` / `http_status` number from anywhere in
- * the cause chain. Returns undefined if none found.
- */
-function collectStatus(err: unknown, maxDepth = 5): number | undefined {
- let cur: unknown = err;
- let depth = 0;
- while (cur && depth < maxDepth) {
- const s = (cur as { status?: unknown; statusCode?: unknown }) || {};
- if (typeof s.status === 'number') return s.status;
- if (typeof s.statusCode === 'number') return s.statusCode;
- if (cur instanceof Error) cur = (cur as { cause?: unknown }).cause;
- else break;
- depth++;
- }
- return undefined;
-}
-
-/** Walk the cause chain collecting any string `code` properties (Node's
- * ECONNRESET / ETIMEDOUT etc. typically live on `err.cause.code` rather
- * than the outer message). */
-function collectCodes(err: unknown, maxDepth = 5): string[] {
- const codes: string[] = [];
- let cur: unknown = err;
- let depth = 0;
- while (cur && depth < maxDepth) {
- const c = (cur as { code?: unknown })?.code;
- if (typeof c === 'string') codes.push(c);
- if (cur instanceof Error) cur = (cur as { cause?: unknown }).cause;
- else break;
- depth++;
- }
- return codes;
-}
-
// ─── Classification ──────────────────────────────────────────────────────
/**
@@ -178,18 +63,15 @@ export function classifyKeyFailure(err: unknown): KeyFailureKind | null {
// so rotation cannot bypass a structured safety code.
if (isProviderSafetyError(err)) return null;
- const credentialKind = providerCredentialFailure(err);
+ const credentialKind = providerCredentialFailure(err, false);
if (credentialKind) return credentialKind;
- const { status, codes } = providerErrorFacts(err);
+ const { status, codes } = providerErrorFacts(err, false);
if (status !== undefined) return null;
- const msg = collectMessages(err);
// Network-layer last — checked after auth-style classifications so a
// "fetch failed" wrapping a 401 (rare but possible) still ends up as auth.
- // Two-pass: cause-chain `code` first (Node's reliable signal), then a
- // message regex for cases where the code didn't propagate.
+ // Only cause-chain machine codes establish a network failure.
if (codes.some((c) => NETWORK_CODE_SET.has(c))) return 'network';
- if (NETWORK_RE.test(msg)) return 'network';
return null;
}
diff --git a/src/main/model/core-agent/connector-meta-tools.ts b/src/main/model/core-agent/connector-meta-tools.ts
index 312688ca..462e76b3 100644
--- a/src/main/model/core-agent/connector-meta-tools.ts
+++ b/src/main/model/core-agent/connector-meta-tools.ts
@@ -38,6 +38,7 @@ import { validateCustomTransport, validateDisplayName, CustomTransportError } fr
import { requestInstallConfirm } from '../../features/connectors/install_confirm';
import { requestActionConfirm, connectorAccountKey, type AppUsageScope } from '../../features/connectors/action_confirm';
import { connectorActionRisk, isConnectorActionBlocked } from '../../features/connectors/action_policy';
+import { observeTaskDraftResult } from '../../features/connectors/task-created-drafts';
import { findCatalogEntry } from '../../features/connectors/catalog';
import { resolveLanguageForUser } from '../../features/config';
import { descriptionLang } from '../../i18n';
@@ -436,7 +437,9 @@ function createCallConnectorToolTool(opts: ConnectorMetaToolsOpts): AgentTool {
`This connector action accepts at most ${policy.max_batch_size} items in any array argument. Split the request into smaller batches.`,
);
}
- const actionRisk = connectorActionRisk(match.instance, toolMatch, normalizedArgs);
+ const draftScope = !opts.appUsage && !match.instance.composio_grant && opts.cid
+ ? { uid: opts.userId, cid: opts.cid, connectorId: cid, accountKey: connectorAccountKey(match.instance) } : undefined;
+ const actionRisk = connectorActionRisk(match.instance, toolMatch, normalizedArgs, draftScope);
if (actionRisk.risk === 'H' || actionRisk.risk === 'D') {
const approved = await requestActionConfirm({
userId: opts.userId,
@@ -466,6 +469,7 @@ function createCallConnectorToolTool(opts: ConnectorMetaToolsOpts): AgentTool {
}
}
const raw = await manager.callTool(opts.userId, cid, toolName, normalizedArgs, { signal: ctx.signal });
+ if (!ctx.signal?.aborted) observeTaskDraftResult(draftScope, toolName, normalizedArgs, raw);
const content = stringifyMcpResult(raw);
const protocolError = !!raw && typeof raw === 'object' && (raw as { isError?: unknown }).isError === true;
return protocolError ? { content, isError: true } : { content };
diff --git a/src/main/model/core-agent/external-providers.ts b/src/main/model/core-agent/external-providers.ts
index 1b52b924..21db4626 100644
--- a/src/main/model/core-agent/external-providers.ts
+++ b/src/main/model/core-agent/external-providers.ts
@@ -103,35 +103,15 @@ function configuredModelVisionDeclaration(model: {
return undefined;
}
-function alignDeepSeekReasoningPayload(params: unknown): unknown {
- try {
- const p = params as { reasoning_effort?: string; messages?: Array<{ role?: string; reasoning_content?: unknown; reasoning?: unknown }> };
- const priorAssistants = (p.messages || []).filter((m) => m && m.role === 'assistant');
- if (priorAssistants.length === 0) {
- // No prior turns — nothing to be inconsistent with. Preserve an
- // explicitly requested reasoning_effort; an omitted control remains
- // omitted so DeepSeek applies the selected model's official defaults.
- return params;
- }
- const allHaveReasoning = priorAssistants.every(
- (m) => (typeof m.reasoning_content === 'string' && m.reasoning_content.length > 0)
- || (typeof m.reasoning === 'string' && (m.reasoning as string).length > 0),
- );
- if (!allHaveReasoning && p.reasoning_effort !== undefined) {
- delete p.reasoning_effort;
- }
- } catch { /* never let onPayload throw — pi-ai treats throw as fatal */ }
- return params;
+export function repairOpenAICompatiblePayload(params: unknown): unknown {
+ return repairOpenAIToolMessageOrder(params);
}
export function repairDeepSeekPayload(params: unknown): unknown {
- return repairOpenAIToolMessageOrder(alignDeepSeekReasoningPayload(params));
-}
-
-export function repairOpenAICompatiblePayload(params: unknown): unknown {
return repairOpenAIToolMessageOrder(params);
}
+
/** Remove an output limit the host added from its own model-default
* reservation so selected providers can apply their native output default. */
function omitReservedOutputLimit(
@@ -282,7 +262,8 @@ const MOONSHOT_K3_PROTOCOL_FALLBACK: Pick<
supportsStrictMode: false,
thinkingFormat: 'deepseek',
requiresReasoningContentOnAssistantMessages: true,
- deferredToolsMode: 'kimi',
+ supportsMidConvoSystemMessages: true,
+ supportsMidConvoToolAdditions: true,
},
};
@@ -421,9 +402,9 @@ export function buildDeepSeekModel(modelId: string): Model<'openai-completions'>
api: 'openai-completions',
provider: 'deepseek' as any,
baseUrl: DEEPSEEK_BASE_URL,
- // Keep V4 models and the V4.1 Flash alias reasoning-capable. This
- // advertises support; it does not choose an effort level for the caller.
- // createDeepSeekProvider preserves explicit choices through its payload hook.
+ // Keep the known Flash/V4 families reasoning-capable. The core adapter
+ // retains explicit choices and removes SDK-synthesized off controls only
+ // when the caller left thinking at the provider default.
reasoning: modelId === 'deepseek-flash' || /^deepseek-v4-/.test(modelId),
// Official Pro/Flash aliases remain text-only. Flash Vision and remotely
// configured models can declare supportsVision explicitly; an omitted
@@ -438,6 +419,7 @@ export function buildDeepSeekModel(modelId: string): Model<'openai-completions'>
maxTokens: Object.prototype.hasOwnProperty.call(DEEPSEEK_MAX_OUTPUT_TOKENS, modelId)
? deepseekMaxOutputTokens(modelId)
: configuredPositiveInteger(curated?.maxTokens, deepseekMaxOutputTokens(modelId)),
+ compat: { supportsLongCacheRetention: false },
};
}
@@ -455,29 +437,7 @@ export async function createDeepSeekProvider(config: CreateDeepSeekProviderConfi
provider: 'deepseek',
apiKey: config.apiKey,
customModel: model,
- // DeepSeek V4 server-side validation has two symmetric failure modes
- // with the same misleading error message ("reasoning_content in the
- // thinking mode must be passed back to the API"):
- // A. `reasoning_effort` missing + history has
- // assistant.reasoning_content → 400
- // B. `reasoning_effort` present + history has an assistant message
- // missing reasoning_content → 400
- // The actual rule is: the presence of `reasoning_effort` must match
- // the presence of reasoning_content across all history (all-or-none);
- // a "half-open" mix is rejected.
- //
- // Observed scenario B: rotating-provider falls over from primary
- // candidate openai-codex to deepseek; pi-ai/transform-messages.js
- // downgrades codex's `thinking` blocks to plain text on a
- // cross-provider hop (losing thinkingSignature), so the history's
- // assistant message has no reasoning_content. Adding reasoning_effort
- // then triggers B.
- //
- // Fix: `onPayload` decides reasoning_effort dynamically — inspect
- // every prior assistant turn for reasoning_content
- // ("reasoning consistent"):
- // - all have → keep an explicitly requested reasoning_effort
- // - not all → drop only that explicit effort
+ // Replay compatibility is projected by the core adapter.
onPayload: repairDeepSeekPayload,
});
}
diff --git a/src/main/model/public_model_catalog.ts b/src/main/model/public_model_catalog.ts
index c51e6716..256f0106 100644
--- a/src/main/model/public_model_catalog.ts
+++ b/src/main/model/public_model_catalog.ts
@@ -42,9 +42,11 @@ export interface ProviderModelEntry {
export const PUBLIC_PROVIDER_MODELS: Readonly<Record<string, readonly ProviderModelEntry[]>> = {
anthropic: [
+ { id: 'claude-opus-5-5', name: 'Claude Opus 5.5', maxInputImages: 20 },
{ id: 'claude-opus-5', name: 'Claude Opus 5', maxInputImages: 20 },
{ id: 'claude-fable-5-1', name: 'Claude Fable 5.1', maxInputImages: 20 },
{ id: 'claude-fable-5', name: 'Claude Fable 5', maxInputImages: 20 },
+ { id: 'claude-sonnet-5-5', name: 'Claude Sonnet 5.5', maxInputImages: 20 },
{ id: 'claude-sonnet-5', name: 'Claude Sonnet 5', maxInputImages: 20 },
],
'openai-codex': [
@@ -52,6 +54,9 @@ export const PUBLIC_PROVIDER_MODELS: Readonly<Record<string, readonly ProviderMo
// of the vendor ceiling; main turns send no output limit
// (see omitReservedOutputLimitForProvider).
{ id: 'gpt-6-astra', name: 'GPT-6 Astra', maxTokens: 128_000, maxInputImages: 20 },
+ { id: 'gpt-6.1-sol', name: 'GPT-6.1 Sol', maxTokens: 64_000, maxInputImages: 20 },
+ { id: 'gpt-6-sol', name: 'GPT-6 Sol', maxTokens: 64_000, maxInputImages: 20 },
+ { id: 'gpt-6-luna', name: 'GPT-6 Luna', maxTokens: 64_000, maxInputImages: 20 },
{ id: 'gpt-5.6-sol', name: 'GPT-5.6 Sol', template: 'gpt-5.5', maxTokens: 64000, maxInputImages: 20 },
{ id: 'gpt-5.6-terra', name: 'GPT-5.6 Terra', template: 'gpt-5.5', maxTokens: 64000, maxInputImages: 20 },
{ id: 'gpt-5.6-luna', name: 'GPT-5.6 Luna', template: 'gpt-5.5', maxTokens: 64000, maxInputImages: 20 },
@@ -61,6 +66,9 @@ export const PUBLIC_PROVIDER_MODELS: Readonly<Record<string, readonly ProviderMo
// of the vendor ceiling; main turns send no output limit
// (see omitReservedOutputLimitForProvider).
{ id: 'gpt-6-astra', name: 'GPT-6 Astra', maxTokens: 128_000, maxInputImages: 20 },
+ { id: 'gpt-6.1-sol', name: 'GPT-6.1 Sol', maxTokens: 64_000, maxInputImages: 20 },
+ { id: 'gpt-6-sol', name: 'GPT-6 Sol', maxTokens: 64_000, maxInputImages: 20 },
+ { id: 'gpt-6-luna', name: 'GPT-6 Luna', maxTokens: 64_000, maxInputImages: 20 },
{ id: 'gpt-5.6-sol', name: 'GPT-5.6 Sol', template: 'gpt-5.5', maxTokens: 64000, maxInputImages: 20 },
{ id: 'gpt-5.6-terra', name: 'GPT-5.6 Terra', template: 'gpt-5.5', maxTokens: 64000, maxInputImages: 20 },
{ id: 'gpt-5.6-luna', name: 'GPT-5.6 Luna', template: 'gpt-5.5', maxTokens: 64000, maxInputImages: 20 },
@@ -114,11 +122,16 @@ export const PUBLIC_PROVIDER_MODELS: Readonly<Record<string, readonly ProviderMo
// OpenRouter exposes hundreds of models. Prefer recent generations but
// retain capability-driven exceptions such as Gemini 3.1 Pro. Settings
// also accepts a user-entered model id.
+ { id: 'anthropic/claude-opus-5.5', name: 'Claude Opus 5.5', maxInputImages: 20 },
{ id: 'anthropic/claude-opus-5', name: 'Claude Opus 5', maxInputImages: 20 },
{ id: 'anthropic/claude-fable-5.1', name: 'Claude Fable 5.1', maxInputImages: 20 },
{ id: 'anthropic/claude-fable-5', name: 'Claude Fable 5', maxInputImages: 20 },
+ { id: 'anthropic/claude-sonnet-5.5', name: 'Claude Sonnet 5.5', maxInputImages: 20 },
{ id: 'anthropic/claude-sonnet-5', name: 'Claude Sonnet 5', maxInputImages: 20 },
{ id: 'openai/gpt-6-astra', name: 'GPT-6 Astra', maxTokens: 128_000, maxInputImages: 20 },
+ { id: 'openai/gpt-6.1-sol', name: 'GPT-6.1 Sol', maxInputImages: 20 },
+ { id: 'openai/gpt-6-sol', name: 'GPT-6 Sol', maxInputImages: 20 },
+ { id: 'openai/gpt-6-luna', name: 'GPT-6 Luna', maxInputImages: 20 },
{ id: 'openai/gpt-5.6-sol', name: 'GPT-5.6 Sol', template: 'openai/gpt-5.5', maxInputImages: 20 },
{ id: 'openai/gpt-5.6-terra', name: 'GPT-5.6 Terra', template: 'openai/gpt-5.5', maxInputImages: 20 },
{ id: 'openai/gpt-5.6-luna', name: 'GPT-5.6 Luna', template: 'openai/gpt-5.5', maxInputImages: 20 },
diff --git a/src/renderer/modules/connector-account-dialog.js b/src/renderer/modules/connector-account-dialog.js
new file mode 100644
index 00000000..7534a645
--- /dev/null
+++ b/src/renderer/modules/connector-account-dialog.js
@@ -0,0 +1,34 @@
+// Host-owned authorization choices contain names and IDs only, never credentials.
+(function () {
+ const active = new Map();
+ const log = createLogger('connector-account-dialog');
+ window.addEventListener('DOMContentLoaded', () => {
+ if (!window.orkas || !window.orkas.onPushEvent) return;
+ window.orkas.onPushEvent('connectors:account-choice-cancelled', (info) => {
+ const controller = active.get(info && info.request_id);
+ if (controller) controller.abort();
+ });
+ window.orkas.onPushEvent('connectors:account-choice', async (info) => {
+ if (!info || typeof info.request_id !== 'string' || active.has(info.request_id)) return;
+ const controller = new AbortController();
+ active.set(info.request_id, controller);
+ let choice = null;
+ try {
+ choice = await uiChoice({ title: info.title, message: info.message,
+ choices: info.choices, choiceLayout: 'group', signal: controller.signal });
+ } catch {
+ log.warn('Account selection dialog failed');
+ } finally {
+ active.delete(info.request_id);
+ }
+ if (controller.signal.aborted) return;
+ try {
+ await window.orkas.invoke('connectors.account_choice_response', {
+ request_id: info.request_id, choice_id: choice,
+ });
+ } catch {
+ log.warn('Account selection response failed');
+ }
+ });
+ });
+})();
diff --git a/src/renderer/modules/connector-action-dialog.js b/src/renderer/modules/connector-action-dialog.js
index 711860c6..0ddc190b 100644
--- a/src/renderer/modules/connector-action-dialog.js
+++ b/src/renderer/modules/connector-action-dialog.js
@@ -4,6 +4,7 @@ function _connectorActionMessage(info) {
const displayName = catalogEntry ? _connectorDisplayName(catalogEntry) : (info.display_name || info.connector_id);
return [
`${t('connectors.action_confirm.connector')}: ${displayName}`,
+ ...(info.account_label ? [`${t('connectors.action_confirm.account')}: ${info.account_label}`] : []),
`${t('connectors.action_confirm.action')}: ${info.action_name || info.tool_name}`,
].join('\n');
}
diff --git a/src/renderer/modules/connectors.js b/src/renderer/modules/connectors.js
index 728f9ef8..c6b691e0 100644
--- a/src/renderer/modules/connectors.js
+++ b/src/renderer/modules/connectors.js
@@ -110,11 +110,11 @@ async function _assistConnectorSetup(entry, button, onReady) {
if (!started) {
if (cid && currentCid === cid) {
const input = document.getElementById('chat-input');
- if (input && !input.value) {
- input.value = t('connectors.setup.assist_request', {
+ if (input && !composerText(input)) {
+ composerSetText(input, t('connectors.setup.assist_request', {
name: _connectorDisplayName(entry) || entry.id, id: entry.id,
- });
- input.dispatchEvent(new Event('input', { bubbles: true }));
+ }));
+ composerNotify(input);
}
}
await uiAlert(t('connectors.setup.assist_failed'));
@@ -175,6 +175,8 @@ let _connectorsState = {
};
let _connectorsSearchQuery = '';
let _connectorsActiveCategory = '';
+let _connectorsHighlightedId = '';
+let _connectorsHighlightTimer = null;
// Reuse the Agent category vocabulary with a connector-specific browse order. Classify the
// exposed capability: General holds cross-domain services, Office holds work/organization flows,
@@ -364,25 +366,31 @@ function _sanitizeConnectorArray(value, options = {}) {
return arr.filter((item) => !(item.status && item.status.kind === 'error'));
}
-function _hydrateConnectorsRenderCache() {
- if (_connectorsState.catalog.length || _connectorsState.instances.length) return false;
+function _readConnectorsRenderCache() {
try {
const raw = localStorage.getItem(_connectorsRenderCacheKey());
- if (!raw) return false;
+ if (!raw) return null;
const parsed = JSON.parse(raw);
- if (!parsed || parsed.version !== _CONNECTORS_RENDER_CACHE_VERSION) return false;
- if (Date.now() - Number(parsed.updated_at || 0) > _CONNECTORS_RENDER_CACHE_TTL_MS) return false;
+ if (!parsed || parsed.version !== _CONNECTORS_RENDER_CACHE_VERSION) return null;
+ if (Date.now() - Number(parsed.updated_at || 0) > _CONNECTORS_RENDER_CACHE_TTL_MS) return null;
const catalog = _sanitizeConnectorArray(parsed.catalog);
const instances = _sanitizeConnectorArray(parsed.instances, { dropErrored: true });
- if (!catalog.length && !instances.length) return false;
- _connectorsState.catalog = catalog;
- _connectorsState.instances = instances;
- return true;
+ if (!catalog.length && !instances.length) return null;
+ return { catalog, instances };
} catch (_) {
- return false;
+ return null;
}
}
+function _hydrateConnectorsRenderCache() {
+ if (_connectorsState.catalog.length || _connectorsState.instances.length) return false;
+ const cached = _readConnectorsRenderCache();
+ if (!cached) return false;
+ _connectorsState.catalog = cached.catalog;
+ _connectorsState.instances = cached.instances;
+ return true;
+}
+
function _persistConnectorsRenderCache() {
if (!_connectorsState.catalog.length && !_connectorsState.instances.length) return;
try {
@@ -470,10 +478,68 @@ function _connectorDisplayName(entry) {
: (entry.display_name_en || entry.display_name || entry.id || '');
}
+// Chat configure cards name the connector they open. They read the page catalog when it is
+// loaded, else the page's render cache, else one catalog fetch per session; none of these
+// changes Connectors page state. A compatibility child is labeled as the card it opens.
+let _connectorNavCatalog = null;
+let _connectorNavCatalogLoad = null;
+
+function _connectorNavTargetIn(catalog, id) {
+ const find = (key) => catalog.find((entry) => entry && entry.id === key) || null;
+ let entry = find(id);
+ if (entry && entry.catalog_parent_id) entry = find(entry.catalog_parent_id) || entry;
+ const name = _connectorDisplayName(entry);
+ if (!name) return null;
+ const iconSvg = typeof sanitizeSvgIconHtml === 'function' ? sanitizeSvgIconHtml(entry.icon_svg) : '';
+ return { name, iconSvg };
+}
+
+window.connectorNavTarget = function connectorNavTarget(id) {
+ const targetId = String(id || '').trim();
+ if (!targetId) return null;
+ if (_connectorsState.catalog.length) return _connectorNavTargetIn(_connectorsState.catalog, targetId);
+ if (!_connectorNavCatalog) {
+ const cached = _readConnectorsRenderCache();
+ if (cached && cached.catalog.length) _connectorNavCatalog = cached.catalog;
+ }
+ return _connectorNavCatalog ? _connectorNavTargetIn(_connectorNavCatalog, targetId) : null;
+};
+
+window.loadConnectorNavTarget = async function loadConnectorNavTarget(id) {
+ const now = window.connectorNavTarget(id);
+ if (now) return now;
+ if (!_connectorNavCatalogLoad) {
+ _connectorNavCatalogLoad = Promise.resolve()
+ .then(() => window.orkas.invoke('connectors.catalog', {}))
+ .then((res) => (res && res.ok && Array.isArray(res.catalog) ? _sanitizeConnectorArray(res.catalog) : null))
+ .catch(() => null)
+ .then((catalog) => {
+ // A failed fetch may be retried by a later card; a completed one is reused.
+ if (catalog) _connectorNavCatalog = catalog;
+ else _connectorNavCatalogLoad = null;
+ return catalog;
+ });
+ }
+ await _connectorNavCatalogLoad;
+ return window.connectorNavTarget(id);
+};
+
// Connector catalog copy supports all UI locales; agent/skill description fallback is separate.
function _connectorCopy(item, field, lang) {
if (!item) return '';
- const locale = String(lang || ((typeof getLang === 'function') ? getLang() : 'en')).toLowerCase().split(/[-_]/)[0];
+ const currentLanguage = (typeof getLang === 'function') ? getLang() : 'en';
+ const normalizeCopyLocale = value => {
+ const tag = String(value).toLowerCase().replace(/_/g, '-');
+ return ['zh-tw', 'pt-pt', 'es-419'].includes(tag) ? tag : tag.split('-')[0];
+ };
+ const locale = normalizeCopyLocale(lang || currentLanguage);
+ // Renderer-only copy leaves shared catalog setup guidance and model tool output intact.
+ if (field === 'description' && item.id && !item._custom && typeof t === 'function'
+ && locale === normalizeCopyLocale(currentLanguage)) {
+ const key = `connectors.catalog.${item.id}.description`;
+ const translated = t(key);
+ if (translated && translated !== key) return translated;
+ }
return item[`${field}_${locale}`] || item[`${field}_en`] || item[`${field}_zh`] || '';
}
@@ -494,6 +560,7 @@ function _connectorSearchText(entry) {
entry.display_name,
entry.display_name_zh,
entry.display_name_en,
+ _connectorCopy(entry, 'description'),
entry.description_zh,
entry.description_en,
entry.description_ja,
@@ -515,6 +582,7 @@ function _connectorSearchText(entry) {
concrete.display_name,
concrete.display_name_zh,
concrete.display_name_en,
+ _connectorCopy(concrete, 'description'),
concrete.description_zh,
concrete.description_en,
concrete.description_ja,
@@ -538,6 +606,7 @@ function _connectorSearchText(entry) {
concrete.display_name,
concrete.display_name_zh,
concrete.display_name_en,
+ _connectorCopy(concrete, 'description'),
concrete.description_zh,
concrete.description_en,
concrete.description_ja,
@@ -559,6 +628,7 @@ function _connectorSearchText(entry) {
member.display_name,
member.display_name_zh,
member.display_name_en,
+ _connectorCopy(member, 'description'),
member.description_zh,
member.description_en,
member.description_ja,
@@ -732,17 +802,33 @@ window.focusConnectorById = async function focusConnectorById(id) {
// nothing has been painted yet or a load is still in flight, whose final
// paint would replace the card about to be focused.
if (!_connectorsState.catalog.length || _connectorsState.loading) await loadConnectors();
+ const uiId = _catalogUiId(targetId);
+ const bundle = _connectorsState.catalog.find((entry) => Array.isArray(entry.bundle_member_ids)
+ && entry.bundle_member_ids.includes(uiId));
+ const cardId = bundle ? bundle.id : uiId;
// An explicit navigation target must not depend on previous browse filters.
+ const hadFilters = !!(_connectorsSearchQuery || _connectorsActiveCategory);
_connectorsSearchQuery = '';
_connectorsActiveCategory = '';
const search = document.getElementById('connectors-search-input');
if (search) search.value = '';
- _renderConnectorsGrid();
+ // Loading already paints the grid. Reuse its nodes unless clearing filters changes the list.
+ if (hadFilters) _renderConnectorsGrid();
const card = Array.from(document.querySelectorAll('.connector-card[data-id]'))
- .find((candidate) => candidate.dataset.id === targetId);
+ .find((candidate) => candidate.dataset.id === cardId);
if (!card) return false;
+ clearTimeout(_connectorsHighlightTimer);
+ document.querySelectorAll('.connector-card.is-highlighted').forEach((el) => el.classList.remove('is-highlighted'));
+ _connectorsHighlightedId = cardId;
+ card.classList.add('is-highlighted');
+ _connectorsHighlightTimer = setTimeout(() => {
+ _connectorsHighlightedId = '';
+ _connectorsHighlightTimer = null;
+ document.querySelectorAll('.connector-card.is-highlighted').forEach((el) => el.classList.remove('is-highlighted'));
+ }, 2500);
card.setAttribute('tabindex', '-1');
- card.scrollIntoView({ block: 'center', behavior: 'smooth' });
+ // Position synchronously: starting OAuth can repaint the grid and open the browser immediately.
+ card.scrollIntoView({ block: 'center', behavior: 'instant' });
card.focus({ preventScroll: true });
return true;
};
@@ -762,6 +848,7 @@ window.openConnectorSetupById = async function openConnectorSetupById(id) {
if (!entry || (installed && !installed.reauthorization_required && !_isReconnectableError(entry, installed))) {
return window.focusConnectorById(entry ? entry.id : targetId);
}
+ await window.focusConnectorById(entry.id);
// The protected form is owned by the catalog, not by a filtered DOM card.
// A user opening it must not reopen the guide and revoke Commander control.
_runConnect(entry, 'agent').catch(() => uiAlert(t('connectors.errors.connect_failed')));
@@ -1116,7 +1203,8 @@ function _renderCatalogCard(entry, instance) {
: true;
const card = document.createElement('div');
- card.className = `connector-card${connected && !enabledFlag ? ' is-disabled' : ''}${degraded ? ' is-unverified' : ''}`;
+ // Connection progress replaces card nodes; keep the navigation cue until its original timer ends.
+ card.className = `connector-card${connected && !enabledFlag ? ' is-disabled' : ''}${degraded ? ' is-unverified' : ''}${e.id === _connectorsHighlightedId ? ' is-highlighted' : ''}`;
card.dataset.id = e.id;
// Brand-color square per design (Surface E) — applied ONLY to the
@@ -1200,11 +1288,9 @@ function _renderCatalogCard(entry, instance) {
// pointless re-authorization for what is usually a server-side outage.
action = `<button class="btn btn-sm btn-primary" data-act="retry-degraded">${escapeHtml(t('connectors.action.retry'))}</button>`;
} else if (e._custom) {
- // Custom server, not connected: retry probes the stored transport
- // (`connectors.refresh`), never OAuth. Disconnect stays available so a
- // dead entry can be removed.
+ // OAuth servers need a new browser authorization when their grant is rejected.
action = `
- <button class="btn btn-sm btn-primary" data-act="retry-custom">${escapeHtml(t('connectors.action.retry'))}</button>
+ <button class="btn btn-sm btn-primary" data-act="${instance?.custom_auth_mode === 'oauth' ? 'authorize-custom' : 'retry-custom'}">${escapeHtml(t(instance?.custom_auth_mode === 'oauth' ? 'connectors.custom.reauthorize' : 'connectors.action.retry'))}</button>
<button class="btn btn-sm btn-danger" data-act="disconnect">${escapeHtml(t('connectors.action.disconnect'))}</button>`;
} else if (_isReconnectableError(e, instance)) {
action = `<button class="btn btn-sm btn-primary" data-act="connect">${escapeHtml(t('connectors.action.connect'))}</button>`;
@@ -1298,6 +1384,7 @@ function _renderCatalogCard(entry, instance) {
else if (act === 'menu') _openCardMenu(btn, e, instance);
else if (act === 'use-connector' && enabledFlag) _useConnector(e, instance);
else if (act === 'retry-custom') _retryConnect(e, 'connector_custom_retry', instance);
+ else if (act === 'authorize-custom') _authorizeCustom(e, instance);
else if (act === 'retry-degraded') _retryConnect(e, 'connector_degraded_retry', instance);
});
});
@@ -1714,6 +1801,7 @@ function _handleOAuthConnectResult(info) {
}
if (busyChanged) _renderConnectorsGrid();
if (pending) _pendingConnectAttempts.delete(info.attempt_id);
+ _connectorsState.connecting.delete(uiCatalogId);
const entry = _connectorsState.catalog.find((item) => item && item.id === info.catalog_id) || { id: info.catalog_id };
if (info.result !== 'success') {
const errLike = {
@@ -1803,7 +1891,8 @@ function _parseEnvLines(text) {
// Add-custom-MCP-server dialog. The form IS the consent surface (plan §C3):
// for stdio the user types the exact command that will run on their machine,
// and the warning line states that plainly. Submission funnels into the
-// single validated IPC route `connectors.add_custom`.
+// single validated IPC route `connectors.add_custom`. Remote OAuth starts
+// asynchronously and finishes through the shared connector OAuth result event.
function _customConnectorMarkup() {
return `
<div class="modal modal-standard ui-dialog connector-custom-dialog" role="dialog" aria-modal="true" aria-labelledby="connector-custom-title">
@@ -1825,6 +1914,13 @@ function _customConnectorMarkup() {
<label>${escapeHtml(t('connectors.custom.url_label'))}</label>
<input type="text" data-f="url" placeholder="https://example.com/mcp" />
</div>
+ <div class="form-row">
+ <label>${escapeHtml(t('connectors.custom.auth_label'))}</label>
+ <select data-f="auth_mode">
+ <option value="none">${escapeHtml(t('connectors.custom.auth_none'))}</option>
+ <option value="oauth">${escapeHtml(t('connectors.custom.auth_oauth'))}</option>
+ </select>
+ </div>
<div class="form-row">
<label>${escapeHtml(t('connectors.custom.headers_label'))}</label>
<textarea data-f="headers" rows="2" placeholder="Authorization: Bearer ..."></textarea>
@@ -1861,6 +1957,7 @@ function _openAddCustomDialog() {
document.body.appendChild(overlay);
const f = (name) => overlay.querySelector(`[data-f="${name}"]`);
+ let oauthInFlight = false;
const secHttp = overlay.querySelector('[data-sec="http"]');
const secStdio = overlay.querySelector('[data-sec="stdio"]');
f('kind').addEventListener('change', () => {
@@ -1876,6 +1973,7 @@ function _openAddCustomDialog() {
};
window.addEventListener('i18n-change', onLanguageChanged);
const close = () => {
+ if (oauthInFlight) void window.orkas.invoke('connectors.cancel_oauth', {});
document.removeEventListener('keydown', onKey, true);
window.removeEventListener('i18n-change', onLanguageChanged);
overlay.remove();
@@ -1913,14 +2011,20 @@ function _openAddCustomDialog() {
}
okBtn.disabled = true;
okBtn.textContent = t('connectors.action.connecting');
+ oauthInFlight = kind === 'streamable-http' && f('auth_mode').value === 'oauth';
let added = false;
try {
const res = await window.orkas.invoke('connectors.add_custom', {
display_name: f('name').value.trim(),
transport,
+ auth_mode: kind === 'streamable-http' ? f('auth_mode').value : 'none',
});
if (res && res.ok && res.instance) {
+ if (res.started && typeof res.attempt_id === 'string') {
+ _pendingConnectAttempts.set(res.attempt_id, { uiCatalogId: res.instance.id });
+ }
added = true;
+ oauthInFlight = false;
close();
const st = res.instance.status || {};
if (st.kind === 'connected') {
@@ -1940,6 +2044,7 @@ function _openAddCustomDialog() {
_connectorsLog.warn('custom connector add failed', _connectorFailureDetail(err, 'custom_add_exception'));
uiAlert(_formatConnectError(err));
} finally {
+ oauthInFlight = false;
okBtn.disabled = false;
okBtn.textContent = t('connectors.custom.submit');
}
@@ -1948,6 +2053,24 @@ function _openAddCustomDialog() {
setTimeout(() => f('name').focus(), 0);
}
+async function _authorizeCustom(entry, instance) {
+ _connectorsState.connecting.add(entry.id);
+ _renderConnectorsGrid();
+ try {
+ const res = await window.orkas.invoke('connectors.authorize_custom', { id: instance.id });
+ if (res && res.ok && res.started && typeof res.attempt_id === 'string') {
+ _pendingConnectAttempts.set(res.attempt_id, { uiCatalogId: instance.id });
+ } else {
+ uiAlert(_formatConnectError(res));
+ _connectorsState.connecting.delete(entry.id);
+ }
+ } catch (err) {
+ uiAlert(_formatConnectError(err));
+ _connectorsState.connecting.delete(entry.id);
+ }
+ await loadConnectors();
+}
+
function _connectorStructuredErrorCode(errLike) {
if (!errLike || typeof errLike !== 'object') return '';
const nested = errLike.error && typeof errLike.error === 'object' ? errLike.error : null;
@@ -1976,7 +2099,7 @@ function _formatConnectError(errLike, fallbackKey = 'connectors.errors.connect_f
if (/HTTP 5\d{2}|exchange_http_5xx/i.test(marker)) return _connectorErrorFallback('network');
if (/fetch failed|network|timeout|timed out|econnreset|econnrefused|eai_again|enotfound|socket|connection (closed|reset|dropped)|terminated|refresh_failed|刷新授权失败|failed to refresh authorization|認証の更新に失敗|Falha ao atualizar a autorização/i.test(marker)) return _connectorErrorFallback('network');
if (/composio_not_configured|discord_client_invalid|unsupported_provider|invalid_catalog_id/i.test(marker)) return t('connectors.errors.service_configuration');
- if (/does not advertise registration_endpoint|DCR unsupported|protected resource metadata missing|compatible token_endpoint_auth_method/i.test(marker)) return t('connectors.errors.service_configuration');
+ if (/does not advertise registration_endpoint|does not support client metadata or DCR registration|DCR unsupported|protected resource metadata missing|compatible token_endpoint_auth_method/i.test(marker)) return t('connectors.errors.service_configuration');
if (/DCR registration failed|token endpoint HTTP 4\d{2}|HTTP 40[13]/i.test(marker)) return t('connectors.errors.authorization_failed');
if (/state_expired|invalid_state|bad_state|oauth_code_invalid|exchange_http_4xx|missing_exchange_code/i.test(marker)) return t('connectors.errors.authorization_expired');
if (/local_api_authorization_failed|seller_authorization_failed/i.test(marker)) return t('connectors.seller.authorization_failed');
@@ -2060,6 +2183,7 @@ async function _drainConnectorInstallQueue() {
if (controller) _connectorInstallControllers.set(requestId, controller);
try {
ok = await uiConfirm({
+ context: info,
message: `${t('connectors.install_confirm.message', { name: info.display_name })}\n\n${typeof info.target === 'string' ? t(info.kind === 'stdio' ? 'connectors.install_confirm.stdio_summary' : 'connectors.install_confirm.http_summary', { target: info.target }) : info.summary}${warn}`,
okLabel: t('connectors.install_confirm.approve'),
cancelLabel: t('connectors.install_confirm.decline'),
diff --git a/test/e2e/connector-account_e2e_selection.spec.ts b/test/e2e/connector-account_e2e_selection.spec.ts
new file mode 100644
index 00000000..86f04ee5
--- /dev/null
+++ b/test/e2e/connector-account_e2e_selection.spec.ts
@@ -0,0 +1,36 @@
+import * as path from 'node:path';
+import { expect, test } from './fixtures/orkas';
+
+
+test('authorization account selection binds an explicit choice and dismisses cancellation', async ({ orkas }) => {
+ const page = orkas.page!;
+ const electron = orkas.electronApp!;
+ const root = path.resolve(__dirname, '../..');
+ for (const mode of ['select', 'cancel', 'host-cancel']) {
+ await electron.evaluate((_electron, { root }) => {
+ const host = process as any;
+ const load = host.mainModule.require.bind(host.mainModule);
+ const gate = load(`${root}/src/main/features/connectors/account-choice.ts`);
+ const users = load(`${root}/src/main/features/users.ts`);
+ host.__accountChoiceController = new AbortController();
+ host.__accountChoiceOutcome = null;
+ void gate.requestAccountChoice(users.getActiveUserId(), 'tiktok-shop', [
+ { id: '123', label: '<img src=x onerror=alert(1)> Shop A' },
+ { id: '456', label: 'Shop B (456)' },
+ ], host.__accountChoiceController.signal).then(
+ (id: string) => { host.__accountChoiceOutcome = { id }; },
+ (error: { code: string }) => { host.__accountChoiceOutcome = { code: error.code }; },
+ );
+ }, { root });
+ const dialog = page.getByRole('dialog', { name: 'Choose the account to connect' });
+ await expect(dialog).toBeVisible();
+ await expect(dialog.locator('img')).toHaveCount(0);
+ await expect(dialog.getByRole('button', { name: '<img src=x onerror=alert(1)> Shop A', exact: true })).toBeVisible();
+ if (mode === 'select') await dialog.getByRole('button', { name: 'Shop B (456)', exact: true }).click();
+ else if (mode === 'cancel') await dialog.getByRole('button', { name: 'Cancel', exact: true }).click();
+ else await electron.evaluate(() => (process as any).__accountChoiceController.abort());
+ await expect(dialog).toHaveCount(0);
+ await expect.poll(() => electron.evaluate(() => (process as any).__accountChoiceOutcome))
+ .toEqual(mode === 'select' ? { id: '456' } : { code: 'user_cancelled' });
+ }
+});
diff --git a/test/e2e/connectors_e2e_validation.spec.ts b/test/e2e/connectors_e2e_validation.spec.ts
index 6e012c23..5045c8ef 100644
--- a/test/e2e/connectors_e2e_validation.spec.ts
+++ b/test/e2e/connectors_e2e_validation.spec.ts
@@ -1,3 +1,4 @@
+import { expectComposerText } from './fixtures/composer';
import { readFileSync, writeFileSync } from 'node:fs';
import { expect, test, type OrkasTestApp } from './fixtures/orkas';
@@ -91,7 +92,7 @@ rl.on('line', (line) => {
);
await expect(connectorOption).toContainText('E2E Local MCP');
await connectorOption.click();
- await expect(page.locator('#new-chat-input')).toHaveValue(/Connector: E2E Local MCP/);
+ await expectComposerText(page.locator('#new-chat-input'), /Connector: E2E Local MCP/);
};
return { page, instance, card, callStatePath, startConnectorChat };
}
diff --git a/test/e2e/woocommerce_e2e_setup.spec.ts b/test/e2e/woocommerce_e2e_setup.spec.ts
new file mode 100644
index 00000000..777a4f22
--- /dev/null
+++ b/test/e2e/woocommerce_e2e_setup.spec.ts
@@ -0,0 +1,27 @@
+import { expect, test } from './fixtures/orkas';
+
+
+test('WooCommerce setup accepts a store URL without keys and retains manual fields across locales', async ({ orkas }) => {
+ const page = orkas.page!;
+ await page.locator('#connectors-btn').click();
+ await page.locator('#connectors-search-input').fill('woocommerce');
+ await page.locator('.connector-card[data-id="woocommerce"] [data-act="connect"]').click();
+ const dialog = page.locator('#connectors-connect-modal');
+ await expect(dialog).toBeVisible();
+ await expect(dialog.locator('[data-connector-field][required]')).toHaveCount(1);
+ await dialog.locator('#connector-setup-field-0').fill('https://shop.example.com/wordpress');
+ expect(await dialog.locator('form').evaluate(form => (form as HTMLFormElement).checkValidity())).toBe(true);
+ await expect(dialog.locator('#connector-setup-field-1')).toHaveValue('');
+ await expect(dialog.locator('#connector-setup-field-2')).toHaveValue('');
+ for (const lang of ['en', 'zh', 'ja', 'pt', 'es', 'fr', 'ko', 'de', 'ru', 'it']) {
+ await page.evaluate(async locale => { await (window as any).setLang(locale); }, lang);
+ await expect(dialog.locator('.connectors-setup-instructions')).not.toBeEmpty();
+ await expect(dialog).not.toContainText('connectors.setup.');
+ await expect(dialog.locator('#connector-setup-field-0')).toHaveValue('https://shop.example.com/wordpress');
+ await expect(dialog.locator('#connector-setup-field-2')).toHaveAttribute('type', 'password');
+ }
+ await dialog.locator('[data-act="cancel"]').click();
+ await expect(dialog).toHaveCount(0);
+ const state = await orkas.invoke<{ instances: Array<{ id: string }> }>('connectors.list');
+ expect(state.instances.some(instance => instance.id === 'woocommerce')).toBe(false);
+});
diff --git a/test/main/features/auth.test.ts b/test/main/features/auth.test.ts
index db2986f7..58460220 100644
--- a/test/main/features/auth.test.ts
+++ b/test/main/features/auth.test.ts
@@ -400,18 +400,14 @@ describe('auth › listProviders grouping', () => {
expect(anth.supportsOAuth).toBe(true);
expect(anth.oauthProvider).toBe('anthropic');
- // openai — API-key only. OAuth lives on the separate `openai-codex`
- // entry since the Codex endpoint is a different API surface.
+ // pi-ai 0.99.1 exposes native OpenAI OAuth alongside the Codex endpoint.
const openai = providers.find((p) => p.id === 'openai')!;
expect(openai.supportsApiKey).toBe(true);
- expect(openai.supportsOAuth).toBe(false);
-
- // openai-codex — surfaced as its own provider, OAuth only.
- const codex = providers.find((p) => p.id === 'openai-codex');
- expect(codex).toBeTruthy();
- expect(codex!.supportsApiKey).toBe(false);
- expect(codex!.supportsOAuth).toBe(true);
- expect(codex!.oauthProvider).toBe('openai-codex');
+ expect(openai.supportsOAuth).toBe(true);
+ expect(openai.oauthProvider).toBe('openai');
+ expect(providers.find((p) => p.id === 'openai-codex')).toMatchObject({
+ supportsApiKey: false, supportsOAuth: true, oauthProvider: 'openai-codex',
+ });
});
});
@@ -1042,6 +1038,9 @@ describe('auth › listModels', () => {
const a = await import('../../../src/main/features/auth');
expect((await a.listModels('openai-codex')).models.map((model) => model.id)).toEqual([
'gpt-6-astra',
+ 'gpt-6.1-sol',
+ 'gpt-6-sol',
+ 'gpt-6-luna',
'gpt-5.6-sol',
'gpt-5.6-terra',
'gpt-5.6-luna',
diff --git a/test/main/features/client_config.test.ts b/test/main/features/client_config.test.ts
index 22fe5042..e4890d67 100644
--- a/test/main/features/client_config.test.ts
+++ b/test/main/features/client_config.test.ts
@@ -85,6 +85,9 @@ describe('client_config', () => {
it('ships the synchronized public model catalog with compatibility metadata', () => {
expect(DEFAULT_PROVIDER_MODELS['openai-codex']).toEqual([
{ id: 'gpt-6-astra', name: 'GPT-6 Astra', maxTokens: 128000, maxInputImages: 20 },
+ { id: 'gpt-6.1-sol', name: 'GPT-6.1 Sol', maxTokens: 64000, maxInputImages: 20 },
+ { id: 'gpt-6-sol', name: 'GPT-6 Sol', maxTokens: 64000, maxInputImages: 20 },
+ { id: 'gpt-6-luna', name: 'GPT-6 Luna', maxTokens: 64000, maxInputImages: 20 },
{ id: 'gpt-5.6-sol', name: 'GPT-5.6 Sol', template: 'gpt-5.5', maxTokens: 64000, maxInputImages: 20 },
{ id: 'gpt-5.6-terra', name: 'GPT-5.6 Terra', template: 'gpt-5.5', maxTokens: 64000, maxInputImages: 20 },
{ id: 'gpt-5.6-luna', name: 'GPT-5.6 Luna', template: 'gpt-5.5', maxTokens: 64000, maxInputImages: 20 },
diff --git a/test/main/features/connectors/account-choice.test.ts b/test/main/features/connectors/account-choice.test.ts
new file mode 100644
index 00000000..055ce889
--- /dev/null
+++ b/test/main/features/connectors/account-choice.test.ts
@@ -0,0 +1,67 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const user = vi.hoisted(() => ({ id: 'account-choice-user' }));
+vi.mock('../../../../src/main/features/users', () => ({ getActiveUserId: () => user.id }));
+vi.mock('../../../../src/main/features/config', () => ({ getLanguageForUser: () => 'en' }));
+import { _setBroadcastForTest, requestAccountChoice, respondAccountChoice } from '../../../../src/main/features/connectors/account-choice';
+import { notifyUserSwitch } from '../../../../src/main/features/user-switch-hooks';
+
+let events: Array<{ channel: string; payload: any }>;
+let controller: AbortController;
+const uid = 'account-choice-user';
+const choices = [{ id: '123', label: 'Shop A' }, { id: '456', label: 'Shop B' }];
+beforeEach(() => {
+ user.id = uid;
+ events = [];
+ controller = new AbortController();
+ _setBroadcastForTest((channel, payload) => { events.push({ channel, payload }); return true; });
+});
+afterEach(() => { controller.abort(); _setBroadcastForTest(); vi.useRealTimers(); });
+
+describe('authorization account choice', () => {
+ it('accepts one offered account from its owner and rejects forged, foreign or replayed answers', async () => {
+ const flow = requestAccountChoice(uid, 'tiktok-shop', choices, controller.signal);
+ const info = events[0].payload;
+ expect(info).toMatchObject({ choices, title: 'Choose the account to connect' });
+ expect(respondAccountChoice('other-user', info.request_id, '123')).toBe(false);
+ expect(respondAccountChoice(uid, info.request_id, '789')).toBe(false);
+ expect(respondAccountChoice(uid, info.request_id, '456')).toBe(true);
+ await expect(flow).resolves.toBe('456');
+ expect(respondAccountChoice(uid, info.request_id, '123')).toBe(false);
+ expect(events.at(-1)?.channel).toBe('connectors:account-choice-cancelled');
+ });
+
+ it.each(['decline', 'abort', 'timeout', 'switch'] as const)('dismisses %s and makes any later answer ineffective', async mode => {
+ vi.useFakeTimers();
+ const flow = requestAccountChoice(uid, 'tiktok-shop', choices, controller.signal);
+ const rejected = expect(flow).rejects.toMatchObject({ code: 'user_cancelled' });
+ const id = events[0].payload.request_id;
+ if (mode === 'decline') respondAccountChoice(uid, id, null);
+ if (mode === 'abort') controller.abort();
+ if (mode === 'timeout') await vi.advanceTimersByTimeAsync(600_000);
+ if (mode === 'switch') { notifyUserSwitch(uid, 'other-user'); user.id = 'other-user'; }
+ await rejected;
+ expect(events.at(-1)).toEqual({ channel: 'connectors:account-choice-cancelled', payload: { request_id: id } });
+ expect(respondAccountChoice(uid, id, '123')).toBe(false);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('fails closed without a renderer or active owner and never forwards extra provider properties', async () => {
+ _setBroadcastForTest(() => false);
+ await expect(requestAccountChoice(uid, 'tiktok-shop', choices, controller.signal)).rejects.toMatchObject({ code: 'user_cancelled' });
+ await expect(requestAccountChoice('other-user', 'tiktok-shop', choices, controller.signal)).rejects.toMatchObject({ code: 'user_cancelled' });
+ _setBroadcastForTest((channel, payload) => { events.push({ channel, payload }); return true; });
+ const flow = requestAccountChoice(uid, 'tiktok-shop', [{ ...choices[0], access_token: 'private' } as any], controller.signal);
+ expect(JSON.stringify(events)).not.toContain('private');
+ respondAccountChoice(uid, events[0].payload.request_id, '123');
+ await expect(flow).resolves.toBe('123');
+ });
+
+ it('rejects missing, ambiguous, unbounded or malformed account choices before presenting a dialog', async () => {
+ for (const invalid of [[], [choices[0], choices[0]], [{ id: '../123', label: 'Shop' }],
+ [{ id: '123', label: 'x'.repeat(201) }], Array.from({ length: 101 }, (_, i) => ({ id: String(i + 1), label: 'Shop' }))]) {
+ await expect(requestAccountChoice(uid, 'tiktok-shop', invalid, controller.signal)).rejects.toThrow('Invalid authorized');
+ }
+ expect(events).toEqual([]);
+ });
+});
diff --git a/test/main/features/connectors/catalog.test.ts b/test/main/features/connectors/catalog.test.ts
index 574fc1e2..6f2f2bf8 100644
--- a/test/main/features/connectors/catalog.test.ts
+++ b/test/main/features/connectors/catalog.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest';
import { createRequire } from 'node:module';
import { createHash } from 'node:crypto';
import sharp from 'sharp';
+import { readFileSync } from 'node:fs';
const require = createRequire(import.meta.url);
@@ -32,6 +33,20 @@ describe('connector catalog', () => {
expect(missingCopy(broken)).toEqual(['canary.connection_setup.fields.0.label_ja']);
});
+ it('provides renderer-only catalog descriptions for every supported UI locale', async () => {
+ const { CONNECTOR_CATALOG } = await import('../../../../src/main/features/connectors/catalog');
+ const { SUPPORTED_LANGS } = await import('../../../../src/main/i18n');
+ for (const language of SUPPORTED_LANGS) {
+ const table = JSON.parse(readFileSync(new URL(`../../../../src/renderer/locales/${language}.json`, import.meta.url), 'utf8'));
+ for (const entry of CONNECTOR_CATALOG) {
+ const key = `connectors.catalog.${entry.id}.description`;
+ expect(typeof table[key], `${language}/${key}`).toBe('string');
+ expect(table[key].trim(), `${language}/${key}`).not.toBe('');
+ if (language === 'en') expect(table[key], key).toBe(entry.description_en);
+ }
+ }
+ });
+
it('provides a localized HTTPS guide for every built-in connector that requires setup fields', async () => {
const { CONNECTOR_CATALOG } = await import('../../../../src/main/features/connectors/catalog');
const setupEntries = CONNECTOR_CATALOG.filter((entry) => entry.connection_setup?.fields?.length);
@@ -426,11 +441,11 @@ describe('connector catalog', () => {
]) },
});
expect(catalog.findCatalogEntry('woocommerce')).toMatchObject({
- description_en: expect.stringContaining('Read/Write REST API key'),
+ auth_mode: 'local_api',
connection_setup: { fields: expect.arrayContaining([
expect.objectContaining({ key: 'store_url', storage: 'metadata', format: 'woocommerce_store_url' }),
- expect.objectContaining({ key: 'consumer_key', storage: 'credential', format: 'woocommerce_consumer_key' }),
- expect.objectContaining({ key: 'consumer_secret', input: 'secret', storage: 'credential', format: 'woocommerce_consumer_secret' }),
+ expect.objectContaining({ key: 'consumer_key', storage: 'credential', format: 'woocommerce_consumer_key', required: false }),
+ expect.objectContaining({ key: 'consumer_secret', input: 'secret', storage: 'credential', format: 'woocommerce_consumer_secret', required: false }),
]) },
});
expect(catalog.findCatalogEntry('walmart-marketplace')).toMatchObject({
diff --git a/test/main/features/connectors/custom-instance.test.ts b/test/main/features/connectors/custom-instance.test.ts
index a3ae0bd6..8db09b76 100644
--- a/test/main/features/connectors/custom-instance.test.ts
+++ b/test/main/features/connectors/custom-instance.test.ts
@@ -12,9 +12,10 @@ const TEST_UID = 'u-connectors-custom';
let tmpDir: string;
let prevWs: string | undefined;
-function mockMcpClient(behavior: { failConnect?: boolean } = {}) {
+function mockMcpClient(behavior: { failConnect?: boolean; onTransport?: (transport: unknown) => void } = {}) {
vi.doMock('../../../../src/main/features/connectors/mcp-client', () => ({
- McpConnection: vi.fn().mockImplementation(function MockMcpConnection() {
+ McpConnection: vi.fn().mockImplementation(function MockMcpConnection(_id: string, transport: unknown) {
+ behavior.onTransport?.(transport);
return {
connect: vi.fn(async () => {
if (behavior.failConnect) throw new Error('boom: connection refused by test');
@@ -39,6 +40,8 @@ beforeEach(async () => {
afterEach(() => {
vi.doUnmock('../../../../src/main/features/connectors/mcp-client');
+ vi.doUnmock('../../../../src/main/features/connectors/oauth-dcr');
+ vi.doUnmock('../../../../src/main/features/connectors/oauth-events');
process.env.ORKAS_WORKSPACE_ROOT = prevWs;
fs.rmSync(tmpDir, { recursive: true, force: true });
});
@@ -112,4 +115,106 @@ describe('connectors/manager › addCustomInstance', () => {
const result = await manager.callTool(TEST_UID, inst.id, 'noop', {});
expect(result).toEqual({ content: [{ type: 'text', text: 'ok' }] });
});
+
+ it('rejects OAuth on stdio and conflicting Authorization headers', async () => {
+ mockMcpClient();
+ const manager = await import('../../../../src/main/features/connectors/manager');
+ await expect(manager.addCustomInstance(TEST_UID, {
+ display_name: 'Bad stdio OAuth', auth_mode: 'oauth',
+ transport: { kind: 'stdio', command: 'mcp-server' },
+ })).rejects.toMatchObject({ code: 'E_AUTH_MODE' });
+ await expect(manager.addCustomInstance(TEST_UID, {
+ display_name: 'Bad header OAuth', auth_mode: 'oauth',
+ transport: { kind: 'streamable-http', url: 'https://mcp.example/mcp', headers: { authorization: 'Bearer old' } },
+ })).rejects.toMatchObject({ code: 'E_AUTH_MODE' });
+ });
+
+ it('authorizes custom HTTP MCP, refreshes a rotating grant, and never persists a bearer header', async () => {
+ const transports: Array<{ headers?: Record<string, string> }> = [];
+ mockMcpClient({ onTransport: (transport) => transports.push(transport as { headers?: Record<string, string> }) });
+ const refresh = vi.fn(async (_client, grant) => grant.expires_at > Date.now()
+ ? grant
+ : { ...grant, access_token: 'new-access-secret', refresh_token: 'new-refresh-secret',
+ expires_at: Date.now() + 3600_000 });
+ vi.doMock('../../../../src/main/features/connectors/oauth-dcr', async (importOriginal) => ({
+ ...await importOriginal<typeof import('../../../../src/main/features/connectors/oauth-dcr')>(),
+ startCustomMcpOAuth: vi.fn(async () => ({
+ grant: { access_token: 'old-access-secret', refresh_token: 'old-refresh-secret',
+ expires_at: Date.now() + 3600_000, scopes: [], token_type: 'Bearer' },
+ client: { client_id: 'custom-client', token_endpoint: 'https://auth.example/token',
+ authorization_endpoint: 'https://auth.example/authorize', resource: 'https://mcp.example/mcp' },
+ })),
+ refreshDcrIfStale: refresh,
+ }));
+ const manager = await import('../../../../src/main/features/connectors/manager');
+ const instance = await manager.addCustomInstance(TEST_UID, {
+ display_name: 'OAuth MCP', auth_mode: 'oauth',
+ transport: { kind: 'streamable-http', url: 'https://mcp.example/mcp', headers: { 'X-Custom': 'ok' } },
+ });
+ expect(instance.status.kind).toBe('connected');
+ expect(instance.custom_auth_mode).toBe('oauth');
+ expect(transports[0]?.headers).toMatchObject({ Authorization: 'Bearer old-access-secret', 'X-Custom': 'ok' });
+ const registry = await import('../../../../src/main/features/connectors/registry');
+ const stored = registry.load(TEST_UID).connections[instance.id]!;
+ expect(stored.transport).toEqual(instance.transport);
+ expect((stored.transport as { headers?: Record<string, string> }).headers?.Authorization).toBeUndefined();
+ await registry.update(TEST_UID, instance.id, (current) => ({ ...current,
+ oauth_grant: { ...current.oauth_grant!, expires_at: Date.now() - 1 },
+ }));
+ await manager.refreshTools(TEST_UID, instance.id);
+ expect(transports.at(-1)?.headers?.Authorization).toBe('Bearer new-access-secret');
+ expect(registry.load(TEST_UID).connections[instance.id]?.oauth_grant?.refresh_token).toBe('new-refresh-secret');
+ const paths = await import('../../../../src/main/paths');
+ const rawDisk = fs.readFileSync(paths.userConnectorsConfigFile(TEST_UID), 'utf8');
+ expect(rawDisk).not.toMatch(/old-access-secret|old-refresh-secret|new-access-secret|new-refresh-secret/);
+ });
+
+ it('retains a failed OAuth registration as a reconnectable custom instance', async () => {
+ mockMcpClient();
+ vi.doMock('../../../../src/main/features/connectors/oauth-dcr', async (importOriginal) => ({
+ ...await importOriginal<typeof import('../../../../src/main/features/connectors/oauth-dcr')>(),
+ startCustomMcpOAuth: vi.fn(async () => { throw new Error('DCR registration failed: HTTP 403'); }),
+ }));
+ const manager = await import('../../../../src/main/features/connectors/manager');
+ const instance = await manager.addCustomInstance(TEST_UID, {
+ display_name: 'Restricted MCP', auth_mode: 'oauth',
+ transport: { kind: 'streamable-http', url: 'https://mcp.example/mcp' },
+ });
+ expect(instance).toMatchObject({ origin: 'custom', custom_auth_mode: 'oauth',
+ status: { kind: 'error', message: 'DCR registration failed: HTTP 403' } });
+ const registry = await import('../../../../src/main/features/connectors/registry');
+ expect(registry.load(TEST_UID).connections[instance.id]?.custom_auth_mode).toBe('oauth');
+ await expect(manager.authorizeCustomInstance(TEST_UID, instance.id)).rejects.toThrow('HTTP 403');
+ });
+
+ it('starts browser authorization after the add request returns and reports completion', async () => {
+ mockMcpClient();
+ let finish!: (result: unknown) => void;
+ const pending = new Promise((resolve) => { finish = resolve; });
+ const outcome = vi.fn();
+ vi.doMock('../../../../src/main/features/connectors/oauth-events', () => ({
+ broadcastOAuthConnectOutcome: outcome, broadcastOAuthConnectProgress: vi.fn(),
+ }));
+ vi.doMock('../../../../src/main/features/connectors/oauth-dcr', async (importOriginal) => ({
+ ...await importOriginal<typeof import('../../../../src/main/features/connectors/oauth-dcr')>(),
+ startCustomMcpOAuth: vi.fn(() => pending),
+ }));
+ const manager = await import('../../../../src/main/features/connectors/manager');
+ const draft = await manager.addCustomInstance(TEST_UID, {
+ display_name: 'Async OAuth MCP', auth_mode: 'oauth',
+ transport: { kind: 'streamable-http', url: 'https://mcp.example/mcp' },
+ }, { deferOAuth: true });
+ expect(draft.status.kind).toBe('connecting');
+ const started = manager.beginCustomOAuthConnect(TEST_UID, draft.id);
+ expect(started.attempt_id).toBeTruthy();
+ expect(outcome).not.toHaveBeenCalled();
+ finish({ grant: { access_token: 'access-secret', refresh_token: null, expires_at: null,
+ scopes: [], token_type: 'Bearer' }, client: { client_id: 'client', token_endpoint: 'https://login.example/token',
+ authorization_endpoint: 'https://login.example/authorize' } });
+ await vi.waitFor(() => expect(outcome).toHaveBeenCalledWith(expect.objectContaining({
+ attempt_id: started.attempt_id, catalog_id: draft.id, result: 'success',
+ })));
+ const registry = await import('../../../../src/main/features/connectors/registry');
+ expect(registry.load(TEST_UID).connections[draft.id]?.status.kind).toBe('connected');
+ });
});
diff --git a/test/main/features/connectors/device-local.test.ts b/test/main/features/connectors/device-local.test.ts
index a643a5fb..93617448 100644
--- a/test/main/features/connectors/device-local.test.ts
+++ b/test/main/features/connectors/device-local.test.ts
@@ -41,7 +41,7 @@ afterEach(() => {
vi.restoreAllMocks();
if (previousRoot === undefined) delete process.env.ORKAS_WORKSPACE_ROOT;
else process.env.ORKAS_WORKSPACE_ROOT = previousRoot;
- fs.rmSync(root, { recursive: true, force: true });
+ fs.rmSync(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 });
});
describe('device-local CLI connector lifecycle', () => {
diff --git a/test/main/features/connectors/local-api.test.ts b/test/main/features/connectors/local-api.test.ts
index bbae274b..564459a1 100644
--- a/test/main/features/connectors/local-api.test.ts
+++ b/test/main/features/connectors/local-api.test.ts
@@ -406,6 +406,17 @@ describe('device-local commerce API credentials', () => {
})).toThrow('unknown connector parameter: redirect_uri');
});
+ it('allows WooCommerce owner consent without keys and rejects incomplete manual pairs', () => {
+ expect(normalizeLocalApiConnectionInput(entry('woocommerce'), {
+ store_url: 'https://shop.example.com/wordpress',
+ })).toEqual({ metadata: { store_url: 'https://shop.example.com/wordpress' }, credentials: {} });
+ for (const field of ['consumer_key', 'consumer_secret']) {
+ expect(() => normalizeLocalApiConnectionInput(entry('woocommerce'), {
+ store_url: 'https://shop.example.com', [field]: `${field === 'consumer_key' ? 'ck' : 'cs'}_${'a'.repeat(40)}`,
+ })).toThrow('Provide both WooCommerce credentials');
+ }
+ });
+
it('binds direct-commerce network targets without exposing credentials', async () => {
const commerceLayer = entry('commerce-layer');
const commerceLayerMetadata = await authorizeLocalApi(TEST_UID, commerceLayer, {
diff --git a/test/main/features/connectors/manager.test.ts b/test/main/features/connectors/manager.test.ts
index 67b34952..7ad46788 100644
--- a/test/main/features/connectors/manager.test.ts
+++ b/test/main/features/connectors/manager.test.ts
@@ -2376,6 +2376,36 @@ describe('OAuth refresh ownership', () => {
);
});
+ it.each(['mercado-libre-global-selling', 'tiktok-shop'])('retains the previous %s binding and credentials when reauthorization is cancelled', async id => {
+ const registry = await import('../../../../src/main/features/connectors/registry');
+ const manager = await import('../../../../src/main/features/connectors/manager');
+ const binding = id === 'tiktok-shop' ? { shop_id: '12345', region: 'us' } : { user_id: '12345' };
+ mocks.localApi.authorize = vi.fn(async () => binding);
+ mocks.mcp.listTools = vi.fn(async () => [{ name: 'execute_read', description: 'Read', input_schema: {} }]);
+ await manager.connectViaOAuth(TEST_UID, id, { connectionParameters: {} });
+ const previous = registry.load(TEST_UID).connections[id];
+ mocks.localApi.authorize = vi.fn(async () => { throw Object.assign(new Error('Cancelled'), { code: 'user_cancelled' }); });
+ mocks.localApi.remove.mockClear();
+ await expect(manager.connectViaOAuth(TEST_UID, id, { connectionParameters: {} })).rejects.toMatchObject({ code: 'user_cancelled' });
+ expect(mocks.localApi.authorize).toHaveBeenCalledWith(TEST_UID, expect.objectContaining({ id }), {}, expect.objectContaining({ existingBinding: binding }));
+ expect(mocks.localApi.remove).not.toHaveBeenCalled();
+ expect(registry.load(TEST_UID).connections[id]).toEqual(previous);
+ });
+
+ it('retains the installed WooCommerce store when a replacement authorization is cancelled', async () => {
+ const registry = await import('../../../../src/main/features/connectors/registry');
+ const manager = await import('../../../../src/main/features/connectors/manager');
+ mocks.localApi.authorize = vi.fn(async () => ({ store_url: 'https://shop.example.com' }));
+ mocks.mcp.listTools = vi.fn(async () => [{ name: 'execute_read', description: 'Read', input_schema: {} }]);
+ await manager.connectViaOAuth(TEST_UID, 'woocommerce', { connectionParameters: {} });
+ const previous = registry.load(TEST_UID).connections.woocommerce;
+ mocks.localApi.authorize = vi.fn(async () => { throw Object.assign(new Error('Cancelled'), { code: 'user_cancelled' }); });
+ mocks.localApi.remove.mockClear();
+ await expect(manager.connectViaOAuth(TEST_UID, 'woocommerce', { connectionParameters: {} })).rejects.toMatchObject({ code: 'user_cancelled' });
+ expect(mocks.localApi.remove).not.toHaveBeenCalled();
+ expect(registry.load(TEST_UID).connections.woocommerce).toEqual(previous);
+ });
+
it('keeps direct-commerce credentials device-local across connect, refresh, list, and removal', async () => {
const liveTransports: any[] = [];
mocks.mcp.connect = vi.fn(function (this: any) {
diff --git a/test/main/features/connectors/mcp-remote_e2e_compat.test.ts b/test/main/features/connectors/mcp-remote_e2e_compat.test.ts
new file mode 100644
index 00000000..134b68cc
--- /dev/null
+++ b/test/main/features/connectors/mcp-remote_e2e_compat.test.ts
@@ -0,0 +1,106 @@
+import { spawnSync } from 'node:child_process';
+import { createRequire } from 'node:module';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+import { describe, expect, it } from 'vitest';
+
+const require = createRequire(import.meta.url);
+
+/** A real loopback MCP peer verifies protocol fallback, credential propagation,
+ * and the absence of a second connection on auth/server failures. */
+function probe(mode: 'modern' | 'legacy' | 'unauthorized' | 'broken' | 'catalog', status = 405) {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-mcp-remote-'));
+ const probePath = path.join(root, 'probe.cjs');
+ fs.writeFileSync(probePath, [
+ `require.cache[require.resolve(${JSON.stringify(path.resolve('src/main/logger.ts'))})] = { exports: { createLogger: () => ({ info() {}, warn() {} }) } };`,
+ `const { McpConnection } = require(${JSON.stringify(path.resolve('src/main/features/connectors/mcp-client.ts'))});`,
+ `const { Server } = require(${JSON.stringify(require.resolve('@modelcontextprotocol/sdk/server/index.js'))});`,
+ `const { SSEServerTransport } = require(${JSON.stringify(require.resolve('@modelcontextprotocol/sdk/server/sse.js'))});`,
+ `const { ListToolsRequestSchema } = require(${JSON.stringify(require.resolve('@modelcontextprotocol/sdk/types.js'))});`,
+ "const http = require('node:http');",
+ `const mode = ${JSON.stringify(mode)}; const status = ${status};`,
+ 'const requests = []; let peer;',
+ "const server = http.createServer(async (req, res) => {",
+ " requests.push({ method: req.method, path: req.url, authorization: req.headers.authorization || null, accept: req.headers.accept || null });",
+ " if (mode === 'modern') {",
+ " if (req.method === 'GET') { res.writeHead(405); res.end(); return; }",
+ " const chunks = []; for await (const chunk of req) chunks.push(chunk);",
+ " const message = JSON.parse(Buffer.concat(chunks).toString('utf8'));",
+ " if (message.method === 'notifications/initialized') { res.writeHead(202); res.end(); return; }",
+ " const result = message.method === 'initialize'",
+ " ? { protocolVersion: '2025-11-25', capabilities: { tools: {} }, serverInfo: { name: 'modern-fixture', version: '1.0' } }",
+ " : message.method === 'tools/list' ? { tools: [{ name: 'read_fixture', inputSchema: { type: 'object' } }] } : null;",
+ " if (!result) { res.writeHead(404); res.end(); return; }",
+ " res.writeHead(200, { 'content-type': 'application/json' }); res.end(JSON.stringify({ jsonrpc: '2.0', id: message.id, result })); return;",
+ ' }',
+ " if (req.method === 'POST' && req.url === '/sse') { res.writeHead(mode === 'unauthorized' ? 401 : mode === 'broken' ? 500 : status); res.end(); return; }",
+ " if (req.method === 'GET' && req.url === '/sse') {",
+ " peer = new SSEServerTransport('/messages', res);",
+ " const mcp = new Server({ name: 'legacy-fixture', version: '1.0' }, { capabilities: { tools: {} } });",
+ " mcp.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: [{ name: 'read_fixture', inputSchema: { type: 'object' } }] }));",
+ ' await mcp.connect(peer); return;',
+ ' }',
+ " if (req.method === 'POST' && req.url.startsWith('/messages?sessionId=') && peer) { await peer.handlePostMessage(req, res); return; }",
+ ' res.writeHead(404); res.end();',
+ '});',
+ '(async () => {',
+ " await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));",
+ " const conn = new McpConnection(mode === 'catalog' ? 'catalog-fixture' : 'custom-fixture', { kind: 'streamable-http', url: 'http://127.0.0.1:' + server.address().port + '/sse', headers: { Authorization: 'Bearer fixture-token' } });",
+ ' let tools, error;',
+ ' try { await conn.connect(); tools = await conn.listTools();',
+ " if (mode === 'modern') await new Promise(resolve => { let waited = 0; const check = () => { if (requests.some(r => r.method === 'GET') || waited >= 500) resolve(); else { waited += 10; setTimeout(check, 10); } }; check(); });",
+ ' } catch (e) { error = { code: e.code, name: e.name, message: e.message }; }',
+ ' finally { await conn.close(); if (peer) await peer.close(); server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); }',
+ ' process.stdout.write(JSON.stringify({ tools, error, requests }));',
+ '})().catch(error => { process.stderr.write(error.stack || String(error)); process.exitCode = 1; });',
+ ].join('\n'));
+ try {
+ const result = spawnSync(process.execPath, ['-r', require.resolve('tsx/cjs'), probePath], {
+ cwd: root,
+ env: { ...process.env, ELECTRON_RUN_AS_NODE: '1', ORKAS_WORKSPACE_ROOT: root },
+ encoding: 'utf8', timeout: 12_000, maxBuffer: 1024 * 1024,
+ });
+ expect(result.status, result.stderr).toBe(0);
+ expect(result.stderr).toBe('');
+ return JSON.parse(result.stdout) as {
+ tools?: { name: string }[];
+ error?: { code?: number; name: string };
+ requests: { method: string; path: string; authorization: string | null; accept: string | null }[];
+ };
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true });
+ }
+}
+
+describe('custom MCP remote transport compatibility', () => {
+ it('sends both required Accept types and tolerates a 405 on the optional HTTP GET stream', () => {
+ const outcome = probe('modern');
+ expect(outcome.error, JSON.stringify(outcome)).toBeUndefined();
+ expect(outcome.tools?.map(tool => tool.name)).toEqual(['read_fixture']);
+ expect(outcome.requests.some(req => req.path.startsWith('/messages'))).toBe(false);
+ expect(outcome.requests.some(req => req.method === 'GET' && req.path === '/sse')).toBe(true);
+ expect(outcome.requests.filter(req => req.method === 'POST').every(req =>
+ req.accept?.includes('application/json') && req.accept.includes('text/event-stream'))).toBe(true);
+ expect(outcome.requests.every(req => req.authorization === 'Bearer fixture-token')).toBe(true);
+ });
+
+ it.each([400, 404, 405])('connects to a legacy SSE-only server after HTTP %i and lists its tools', (status) => {
+ const outcome = probe('legacy', status);
+ expect(outcome.error, JSON.stringify(outcome)).toBeUndefined();
+ expect(outcome.tools?.map(tool => tool.name)).toEqual(['read_fixture']);
+ expect(outcome.requests.slice(0, 2).map(req => `${req.method} ${req.path}`))
+ .toEqual(['POST /sse', 'GET /sse']);
+ expect(outcome.requests.slice(2).map(req => `${req.method} ${req.path.split('?')[0]}`))
+ .toEqual(['POST /messages', 'POST /messages', 'POST /messages']);
+ expect(outcome.requests.every(req => req.authorization === 'Bearer fixture-token')).toBe(true);
+ });
+
+ it.each(['unauthorized', 'broken', 'catalog'] as const)('does not misclassify %s as a legacy server', (mode) => {
+ const outcome = probe(mode);
+ expect(outcome.tools).toBeUndefined();
+ expect(outcome.error).toBeDefined();
+ expect(outcome.requests.map(req => `${req.method} ${req.path}`)).toEqual(['POST /sse']);
+ });
+});
diff --git a/test/main/features/connectors/oauth-dcr.test.ts b/test/main/features/connectors/oauth-dcr.test.ts
index 69837c9b..1dd6a535 100644
--- a/test/main/features/connectors/oauth-dcr.test.ts
+++ b/test/main/features/connectors/oauth-dcr.test.ts
@@ -128,6 +128,200 @@ afterEach(() => {
});
describe('features/connectors/oauth-dcr', () => {
+ it('authorizes a custom MCP server with PKCE and keeps its rotating grant local', async () => {
+ const fetchMock = vi.fn(async (raw: string, init?: RequestInit) => {
+ const url = new URL(raw);
+ if (url.pathname.includes('oauth-protected-resource')) return jsonResponse({
+ authorization_servers: ['https://login.example.com'], resource: 'https://mcp.example.com/mcp',
+ });
+ if (url.pathname.includes('oauth-authorization-server')) return jsonResponse({
+ issuer: 'https://login.example.com',
+ authorization_endpoint: 'https://login.example.com/authorize',
+ token_endpoint: 'https://login.example.com/token',
+ registration_endpoint: 'https://login.example.com/register',
+ });
+ if (url.pathname === '/register') return jsonResponse({ client_id: 'dynamic-client' });
+ if (url.pathname.endsWith('/dcr-exchange')) return jsonResponse({ code: 0, oauth_code: 'auth-code',
+ oauth_state: new URL(String(electronMock.openExternal.mock.calls[0][0])).searchParams.get('state') });
+ if (url.pathname === '/token') {
+ expect(String(init?.body)).toContain('code_verifier=');
+ return jsonResponse({ access_token: 'private-access', refresh_token: 'private-refresh', expires_in: 3600 });
+ }
+ throw new Error('Unexpected request');
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const oauth = await import('../../../../src/main/features/connectors/oauth-dcr');
+ const flow = oauth.startCustomMcpOAuth('custom-example', 'https://mcp.example.com/mcp');
+ await vi.waitFor(() => expect(electronMock.openExternal).toHaveBeenCalledTimes(1));
+ const opened = new URL(String(electronMock.openExternal.mock.calls[0][0]));
+ expect(opened.searchParams.get('code_challenge_method')).toBe('S256');
+ expect(opened.searchParams.get('resource')).toBe('https://mcp.example.com/mcp');
+ await oauth.handleDcrCallbackUrl('orkas://connectors/oauth/dcr-callback?exchange_code=receipt');
+ await expect(flow).resolves.toMatchObject({ grant: { access_token: 'private-access', refresh_token: 'private-refresh' },
+ client: { client_id: 'dynamic-client' } });
+ expect(fetchMock.mock.calls.some(([url]) => String(url).endsWith('/dcr-store'))).toBe(false);
+ expect(fetchMock.mock.calls.filter(([url]) => !String(url).endsWith('/dcr-exchange'))
+ .every(([, init]) => init?.redirect === 'error')).toBe(true);
+ });
+
+ it('rejects a custom OAuth authorization server that advertises an insecure URL', async () => {
+ vi.stubGlobal('fetch', vi.fn(async (raw: string) => {
+ if (String(raw).includes('oauth-protected-resource')) return jsonResponse({
+ authorization_servers: ['http://private.example'], resource: 'https://mcp.example.com/mcp',
+ });
+ throw new Error('Authorization-server discovery must not be called');
+ }));
+ const { startCustomMcpOAuth } = await import('../../../../src/main/features/connectors/oauth-dcr');
+ await expect(startCustomMcpOAuth('custom-example', 'https://mcp.example.com/mcp'))
+ .rejects.toThrow('insecure endpoint');
+ expect(electronMock.openExternal).not.toHaveBeenCalled();
+ });
+
+ it('discovers custom OAuth through a 401 resource challenge and path-based OIDC issuer', async () => {
+ const fetchMock = vi.fn(async (raw: string, init?: RequestInit) => {
+ const url = String(raw);
+ if (url.includes('oauth-protected-resource')) return jsonResponse({}, false, 404);
+ if (url === 'https://mcp.example.com/mcp') {
+ expect(init?.method).toBe('POST');
+ expect(JSON.parse(String(init?.body)).method).toBe('initialize');
+ return new Response(null, { status: 401, headers: {
+ 'WWW-Authenticate': 'Bearer resource_metadata="https://mcp.example.com/auth/resource-metadata"',
+ } });
+ }
+ if (url === 'https://mcp.example.com/auth/resource-metadata') return jsonResponse({
+ resource: 'https://mcp.example.com/mcp', authorization_servers: ['https://login.example.com/tenant'],
+ });
+ if (url === 'https://login.example.com/.well-known/oauth-authorization-server') return jsonResponse({
+ authorization_endpoint: 'https://login.example.com/wrong-tenant',
+ token_endpoint: 'https://login.example.com/wrong-token',
+ });
+ if (url.includes('oauth-authorization-server') || url === 'https://login.example.com/.well-known/openid-configuration/tenant') {
+ if (url.includes('oauth-authorization-server')) return jsonResponse({}, false, 404);
+ return jsonResponse({
+ issuer: 'https://login.example.com/tenant',
+ authorization_endpoint: 'https://login.example.com/authorize',
+ token_endpoint: 'https://login.example.com/token',
+ registration_endpoint: 'https://login.example.com/register',
+ });
+ }
+ if (url === 'https://login.example.com/register') return jsonResponse({ client_id: 'client-1' });
+ throw new Error(`unexpected request ${url}`);
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const oauth = await import('../../../../src/main/features/connectors/oauth-dcr');
+ const pending = oauth.startCustomMcpOAuth('custom-example', 'https://mcp.example.com/mcp');
+ const outcome = expect(pending).rejects.toThrow();
+ await vi.waitFor(() => expect(electronMock.openExternal).toHaveBeenCalledTimes(1));
+ expect(new URL(String(electronMock.openExternal.mock.calls[0][0])).searchParams.get('resource'))
+ .toBe('https://mcp.example.com/mcp');
+ await oauth.handleDcrCallbackUrl('orkas://connectors/oauth/dcr-callback?status=cancelled');
+ await outcome;
+ expect(fetchMock.mock.calls.some(([url]) => String(url) === 'https://login.example.com/.well-known/openid-configuration/tenant'))
+ .toBe(true);
+ expect(fetchMock.mock.calls.some(([url]) => String(url) === 'https://login.example.com/.well-known/oauth-authorization-server'))
+ .toBe(false);
+ });
+
+ it('rejects root metadata for a different tenant when custom issuer discovery falls back', async () => {
+ const fetchMock = vi.fn(async (raw: string) => {
+ const url = String(raw);
+ if (url.includes('oauth-protected-resource')) return jsonResponse({
+ authorization_servers: ['https://login.example.com/tenant'],
+ resource: 'https://mcp.example.com/mcp',
+ });
+ if (url === 'https://login.example.com/.well-known/oauth-authorization-server') return jsonResponse({
+ issuer: 'https://login.example.com',
+ authorization_endpoint: 'https://login.example.com/authorize',
+ token_endpoint: 'https://login.example.com/token',
+ registration_endpoint: 'https://login.example.com/register',
+ });
+ return jsonResponse({}, false, 404);
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const { startCustomMcpOAuth } = await import('../../../../src/main/features/connectors/oauth-dcr');
+ await expect(startCustomMcpOAuth('custom-example', 'https://mcp.example.com/mcp'))
+ .rejects.toThrow('issuer mismatch');
+ expect(electronMock.openExternal).not.toHaveBeenCalled();
+ expect(fetchMock.mock.calls.some(([url]) => String(url) === 'https://login.example.com/register'))
+ .toBe(false);
+ });
+
+ it('rejects a challenge pointing at an insecure resource-metadata URL before fetching it', async () => {
+ const fetchMock = vi.fn(async (raw: string) => {
+ if (String(raw).includes('oauth-protected-resource')) return jsonResponse({}, false, 404);
+ if (String(raw) === 'https://mcp.example.com/mcp') return new Response(null, { status: 401, headers: {
+ 'WWW-Authenticate': 'Bearer resource_metadata="http://other.example/private"',
+ } });
+ throw new Error('untrusted metadata URL must not be fetched');
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const { startCustomMcpOAuth } = await import('../../../../src/main/features/connectors/oauth-dcr');
+ await expect(startCustomMcpOAuth('custom-example', 'https://mcp.example.com/mcp'))
+ .rejects.toThrow('insecure endpoint');
+ expect(electronMock.openExternal).not.toHaveBeenCalled();
+ });
+
+ it('prefers CIMD when advertised and rejects an issuer mismatch before token exchange', async () => {
+ const fetchMock = vi.fn(async (raw: string) => {
+ const url = new URL(raw);
+ if (url.pathname.includes('oauth-protected-resource')) return jsonResponse({
+ authorization_servers: ['https://login.example.com'], resource: 'https://mcp.example.com/mcp',
+ });
+ if (url.pathname.includes('oauth-authorization-server')) return jsonResponse({
+ issuer: 'https://login.example.com', authorization_response_iss_parameter_supported: true,
+ client_id_metadata_document_supported: true,
+ authorization_endpoint: 'https://login.example.com/authorize',
+ token_endpoint: 'https://login.example.com/token',
+ });
+ if (url.pathname.endsWith('/dcr-exchange')) return jsonResponse({ code: 0, oauth_code: 'auth-code',
+ oauth_state: new URL(String(electronMock.openExternal.mock.calls[0][0])).searchParams.get('state'),
+ oauth_issuer: 'https://other.example.com' });
+ throw new Error('CIMD must not register or exchange a mismatched issuer');
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const oauth = await import('../../../../src/main/features/connectors/oauth-dcr');
+ const flow = oauth.startCustomMcpOAuth('custom-example', 'https://mcp.example.com/mcp');
+ const outcome = expect(flow).rejects.toThrow('issuer mismatch');
+ await vi.waitFor(() => expect(electronMock.openExternal).toHaveBeenCalledTimes(1));
+ const opened = new URL(String(electronMock.openExternal.mock.calls[0][0]));
+ expect(opened.searchParams.get('client_id')).toBe('https://account.example/api/connectors/oauth/client-metadata');
+ await oauth.handleDcrCallbackUrl('orkas://connectors/oauth/dcr-callback?exchange_code=receipt');
+ await outcome;
+ expect(fetchMock.mock.calls.some(([url]) => String(url).endsWith('/register'))).toBe(false);
+ });
+
+ it('completes a CIMD authorization without dynamic registration', async () => {
+ const fetchMock = vi.fn(async (raw: string, init?: RequestInit) => {
+ const url = new URL(raw);
+ if (url.pathname.includes('oauth-protected-resource')) return jsonResponse({
+ authorization_servers: ['https://login.example.com'], resource: 'https://mcp.example.com/mcp',
+ });
+ if (url.pathname.includes('oauth-authorization-server')) return jsonResponse({
+ issuer: 'https://login.example.com', authorization_response_iss_parameter_supported: true,
+ client_id_metadata_document_supported: true,
+ authorization_endpoint: 'https://login.example.com/authorize',
+ token_endpoint: 'https://login.example.com/token',
+ });
+ if (url.pathname.endsWith('/dcr-exchange')) return jsonResponse({ code: 0, oauth_code: 'auth-code',
+ oauth_state: new URL(String(electronMock.openExternal.mock.calls[0][0])).searchParams.get('state'),
+ oauth_issuer: 'https://login.example.com' });
+ if (url.pathname === '/token') {
+ expect(new URLSearchParams(String(init?.body)).get('client_id'))
+ .toBe('https://account.example/api/connectors/oauth/client-metadata');
+ return jsonResponse({ access_token: 'cimd-access', refresh_token: 'cimd-refresh', expires_in: 3600 });
+ }
+ throw new Error('CIMD must not register a dynamic client');
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const oauth = await import('../../../../src/main/features/connectors/oauth-dcr');
+ const flow = oauth.startCustomMcpOAuth('custom-example', 'https://mcp.example.com/mcp');
+ await vi.waitFor(() => expect(electronMock.openExternal).toHaveBeenCalledTimes(1));
+ await oauth.handleDcrCallbackUrl('orkas://connectors/oauth/dcr-callback?exchange_code=receipt');
+ await expect(flow).resolves.toMatchObject({ grant: { access_token: 'cimd-access', refresh_token: 'cimd-refresh' },
+ client: { client_id: 'https://account.example/api/connectors/oauth/client-metadata', token_endpoint_auth_method: 'none' } });
+ expect(fetchMock.mock.calls.some(([url]) => String(url).endsWith('/register'))).toBe(false);
+ });
+
it.each(['complete', 'omitted', 'reduced'])('Color Me Shop requests pinned scopes and handles a %s grant before storage', async mode => {
const { findCatalogEntry } = await import('../../../../src/main/features/connectors/catalog');
const entry = findCatalogEntry('colorme-shop')!;
diff --git a/test/main/features/connectors/protocol.test.ts b/test/main/features/connectors/protocol.test.ts
index a80fcfd2..de658d12 100644
--- a/test/main/features/connectors/protocol.test.ts
+++ b/test/main/features/connectors/protocol.test.ts
@@ -5,6 +5,7 @@ const electronMock = vi.hoisted(() => {
const window = {
isDestroyed: vi.fn(() => false),
isMinimized: vi.fn(() => true),
+ isFocusable: vi.fn(() => true),
restore: vi.fn(),
show: vi.fn(),
focus: vi.fn(),
@@ -39,6 +40,7 @@ describe('connector callback protocol', () => {
vi.clearAllMocks();
electronMock.listeners.clear();
electronMock.app.isReady.mockReturnValue(true);
+ electronMock.window.isFocusable.mockReturnValue(true);
});
it('accepts only connector OAuth callbacks', async () => {
@@ -69,6 +71,19 @@ describe('connector callback protocol', () => {
expect(electronMock.window.focus).toHaveBeenCalled();
});
+ it('keeps a non-focusable background window hidden while still delivering callbacks', async () => {
+ electronMock.window.isFocusable.mockReturnValue(false);
+ const protocol = await import('../../../../src/main/features/connectors/protocol');
+ protocol.registerConnectorProtocol();
+ const secondInstance = electronMock.listeners.get('second-instance')!;
+ secondInstance({}, [], '');
+ secondInstance({}, ['orkas://connectors/oauth/callback?exchange_code=background'], '');
+ await vi.waitFor(() => expect(connectorMock.handleCallbackUrl).toHaveBeenCalledOnce());
+ expect(electronMock.window.restore).not.toHaveBeenCalled();
+ expect(electronMock.window.show).not.toHaveBeenCalled();
+ expect(electronMock.window.focus).not.toHaveBeenCalled();
+ });
+
it('does not intercept stripped account-login links', async () => {
const protocol = await import('../../../../src/main/features/connectors/protocol');
protocol.registerConnectorProtocol();
diff --git a/test/main/features/connectors/seller-marketplace_e2e_authorization.test.ts b/test/main/features/connectors/seller-marketplace_e2e_authorization.test.ts
index 69bf872c..746f3775 100644
--- a/test/main/features/connectors/seller-marketplace_e2e_authorization.test.ts
+++ b/test/main/features/connectors/seller-marketplace_e2e_authorization.test.ts
@@ -6,6 +6,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
// Journey coverage: combined setup -> browser -> relay -> shop verification -> encrypted
// grant -> existing MCP actions. External boundaries are fake; no real store is contacted.
const mocks = vi.hoisted(() => ({ open: vi.fn(async (_url: string) => undefined) }));
+vi.mock('../../../../src/main/features/users', () => ({ getActiveUserId: () => 'seller-e2e-test' }));
vi.mock('electron', () => ({ app: { isPackaged: false }, shell: { openExternal: mocks.open } }));
vi.mock('../../../../src/main/features/connectors/_server_bridge', () => ({ accountApiBase: () => 'https://orkas.ai/api', tokenStore: { getDeviceId: () => 'seller-test-device', authHeaders: () => ({}) } }));
vi.mock('../../../../src/main/features/config', () => ({ getLanguage: () => 'en', getLanguageForUser: () => 'en' }));
@@ -25,6 +26,7 @@ vi.mock('../../../../src/main/model/core-agent/interactive-cli-sessions', () =>
waitInteractiveCliSession: vi.fn(),
}));
+import { _setBroadcastForTest, respondAccountChoice } from '../../../../src/main/features/connectors/account-choice';
import { findCatalogEntry } from '../../../../src/main/features/connectors/catalog';
import { authorizeLocalApi, hasLocalApiAuthorization, localApiRuntimeDir, localApiTransport,
normalizeLocalApiConnectionInput, removeLocalApiAuthorization } from '../../../../src/main/features/connectors/local-api';
@@ -77,12 +79,90 @@ const callback = () => handleDcrCallbackUrl('orkas://connectors/oauth/dcr-callba
beforeEach(() => { vi.clearAllMocks(); });
afterEach(() => {
cancelDcrOAuth();
+ _setBroadcastForTest();
for (const id of Object.keys(inputs)) removeLocalApiAuthorization(UID, findCatalogEntry(id)!);
vi.unstubAllGlobals();
vi.restoreAllMocks();
});
describe('seller-owned marketplace authorization journey', () => {
+ it('chooses an authorized shop without a manually supplied ID and binds subsequent calls to it', async () => {
+ const entry = findCatalogEntry('tiktok-shop')!;
+ let choice: any;
+ _setBroadcastForTest((channel, payload) => { if (channel === 'connectors:account-choice') choice = payload; return true; });
+ const requests = relay('tiktok_shop', url => url.pathname.endsWith('/shops') ? json({ code: 0, data: { shops: [
+ ...identity('tiktok_shop').data!.shops!,
+ { id: '7495355150342452342', name: 'Other market', cipher: 'row-private', region: 'GB' },
+ ] } }) : undefined);
+ const { shop_id: _unused, ...input } = inputs['tiktok-shop'];
+ const flow = authorizeLocalApi(UID, entry, input);
+ const completion = callback();
+ await vi.waitFor(() => expect(choice).toBeDefined());
+ expect(choice.choices.map((item: any) => item.id)).toEqual(['7495355150342452340', '7495355150342452341']);
+ expect(JSON.stringify(choice)).not.toMatch(/cipher|access-test|refresh-test|Other market/);
+ expect(hasLocalApiAuthorization(UID, entry)).toBe(false);
+ expect(respondAccountChoice(UID, choice.request_id, '7495355150342452342')).toBe(false);
+ expect(respondAccountChoice(UID, choice.request_id, '7495355150342452341')).toBe(true);
+ await completion;
+ const metadata = await flow;
+ expect(metadata).toEqual({ region: 'us', shop_id: '7495355150342452341' });
+ const transport = await localApiTransport(UID, entry, metadata);
+ if (transport.kind !== 'stdio') throw new Error('Expected stdio');
+ const config = adapter.configured(transport.env);
+ expect(config.credentials.identity).toMatchObject({ binding_shop_id: metadata.shop_id, shop_cipher: 'other-private-cipher' });
+ await adapter.callTool('execute_read', { action: 'products.list' }, transport.env);
+ expect(new URL(requests.mock.calls.at(-1)![0]).searchParams.get('shop_cipher')).toBe('other-private-cipher');
+ expect(respondAccountChoice(UID, choice.request_id, metadata.shop_id)).toBe(false);
+ });
+
+ it('cancels shop selection without saving credentials and ignores a late response', async () => {
+ const entry = findCatalogEntry('tiktok-shop')!;
+ let choice: any;
+ const events: string[] = [];
+ _setBroadcastForTest((channel, payload) => { events.push(channel); if (channel === 'connectors:account-choice') choice = payload; return true; });
+ relay('tiktok_shop');
+ const { shop_id: _unused, ...input } = inputs['tiktok-shop'];
+ const flow = authorizeLocalApi(UID, entry, input);
+ const rejected = expect(flow).rejects.toMatchObject({ code: 'user_cancelled' });
+ const completion = callback();
+ await vi.waitFor(() => expect(choice).toBeDefined());
+ expect(cancelInFlightOAuth()).toBe(true);
+ await completion;
+ await rejected;
+ expect(events).toContain('connectors:account-choice-cancelled');
+ expect(respondAccountChoice(UID, choice.request_id, '7495355150342452340')).toBe(false);
+ expect(hasLocalApiAuthorization(UID, entry)).toBe(false);
+ });
+
+ it.each(['empty', 'wrong-market', 'duplicate', 'malformed'] as const)('rejects %s shop discovery before selection or persistence', async fault => {
+ const entry = findCatalogEntry('tiktok-shop')!;
+ const first = { id: '7495355150342452340', name: 'Fixture shop', cipher: 'private-cipher', region: 'US' };
+ const shops = fault === 'empty' ? [] : fault === 'wrong-market' ? [{ ...first, region: 'GB' }]
+ : fault === 'duplicate' ? [first, first] : [{ ...first, id: 7495355150342452340 }];
+ const shown = vi.fn(() => true);
+ _setBroadcastForTest(shown);
+ relay('tiktok_shop', url => url.pathname.endsWith('/shops') ? json({ code: 0, data: { shops } }) : undefined);
+ const { shop_id: _unused, ...input } = inputs['tiktok-shop'];
+ const flow = authorizeLocalApi(UID, entry, input);
+ const rejected = expect(flow).rejects.toThrow();
+ await callback(); await rejected;
+ expect(shown).not.toHaveBeenCalled();
+ expect(hasLocalApiAuthorization(UID, entry)).toBe(false);
+ });
+
+ it('retains an existing shop binding when reconnecting with an empty optional ID', async () => {
+ const entry = findCatalogEntry('tiktok-shop')!;
+ relay('tiktok_shop');
+ const shown = vi.fn(() => true);
+ _setBroadcastForTest(shown);
+ const flow = authorizeLocalApi(UID, entry, { ...inputs['tiktok-shop'], shop_id: '' }, {
+ existingBinding: { shop_id: 'USSELLERCODE', region: 'us' },
+ });
+ await callback();
+ await expect(flow).resolves.toEqual({ region: 'us', shop_id: 'USSELLERCODE' });
+ expect(shown).not.toHaveBeenCalled();
+ });
+
it('accepts official local/global seller types and rejects creator, partner or malformed grants', async () => {
const entry = findCatalogEntry('tiktok-shop')!;
for (const userType of [0, 4, 5, 1, 2, 3, undefined]) {
diff --git a/test/main/features/connectors/task-created-drafts.test.ts b/test/main/features/connectors/task-created-drafts.test.ts
new file mode 100644
index 00000000..7fb3deec
--- /dev/null
+++ b/test/main/features/connectors/task-created-drafts.test.ts
@@ -0,0 +1,34 @@
+import { afterEach, expect, it } from 'vitest';
+import { clearTaskCreatedDrafts, isTaskCreatedDraft, observeTaskDraftResult } from '../../../../src/main/features/connectors/task-created-drafts';
+import { connectorActionRisk } from '../../../../src/main/features/connectors/action_policy';
+
+const scope = { uid: 'user', cid: 'task', connectorId: 'gmail', accountKey: 'account' };
+const result = { content: [{ type: 'text', text: '{"id":"new-draft","messageId":"message"}' }] };
+afterEach(() => clearTaskCreatedDrafts(() => true));
+
+it('requires successful native creation evidence, with no cross-task or account inheritance', () => {
+ expect(isTaskCreatedDraft(scope, 'new-draft')).toBe(false);
+ observeTaskDraftResult(scope, 'create_draft', {}, result);
+ expect(isTaskCreatedDraft(scope, 'new-draft')).toBe(true);
+ for (const variation of [{ uid: 'other' }, { cid: 'other' }, { connectorId: 'google-workspace' }, { accountKey: 'other' }]) {
+ expect(isTaskCreatedDraft({ ...scope, ...variation }, 'new-draft')).toBe(false);
+ }
+ const tool = { name: 'delete_draft', description: '', input_schema: {} };
+ expect(connectorActionRisk({ id: 'gmail', origin: 'catalog' }, tool, { id: 'new-draft' }, scope).risk).toBe('W');
+ expect(connectorActionRisk({ id: 'gmail', origin: 'custom' }, tool, { id: 'new-draft' }, scope).risk).toBe('H');
+ expect(connectorActionRisk({ id: 'google-workspace', origin: 'catalog' }, {
+ ...tool, name: 'create_event',
+ }, { attendees: [], visibility: 'private' }, scope).risk).toBe('H');
+ clearTaskCreatedDrafts(item => item.uid === 'user');
+ expect(isTaskCreatedDraft(scope, 'new-draft')).toBe(false);
+});
+
+it.each([
+ { ...result, isError: true },
+ { content: [{ type: 'text', text: '{"id":"new-draft"}' }] },
+ { content: [{ type: 'text', text: 'Created draft new-draft' }] },
+ { content: [{ type: 'text', text: '{"id":"new-draft","messageId":"message","padding":"' + 'a'.repeat(4096) + '"}' }] },
+])('does not manufacture ownership from an error or unrecognized result shape', raw => {
+ observeTaskDraftResult(scope, 'create_draft', {}, raw);
+ expect(isTaskCreatedDraft(scope, 'new-draft')).toBe(false);
+});
diff --git a/test/main/features/connectors/user-owned-app_e2e_authorization.test.ts b/test/main/features/connectors/user-owned-app_e2e_authorization.test.ts
index 354be878..8eee13f9 100644
--- a/test/main/features/connectors/user-owned-app_e2e_authorization.test.ts
+++ b/test/main/features/connectors/user-owned-app_e2e_authorization.test.ts
@@ -6,6 +6,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
// Journey coverage: combined setup -> browser -> relay -> shop verification -> encrypted
// grant -> existing MCP actions. External boundaries are fake; no real store is contacted.
const mocks = vi.hoisted(() => ({ open: vi.fn(async (_url: string) => undefined) }));
+vi.mock('../../../../src/main/features/users', () => ({ getActiveUserId: () => 'user-app-e2e-test' }));
vi.mock('electron', () => ({ app: { isPackaged: false }, shell: { openExternal: mocks.open } }));
vi.mock('../../../../src/main/features/connectors/_server_bridge', () => ({ accountApiBase: () => 'https://orkas.ai/api', tokenStore: { getDeviceId: () => 'seller-test-device', authHeaders: () => ({}) } }));
vi.mock('../../../../src/main/features/config', () => ({ getLanguage: () => 'en', getLanguageForUser: () => 'en' }));
@@ -25,6 +26,7 @@ vi.mock('../../../../src/main/model/core-agent/interactive-cli-sessions', () =>
waitInteractiveCliSession: vi.fn(),
}));
+import { _setBroadcastForTest, respondAccountChoice } from '../../../../src/main/features/connectors/account-choice';
import { findCatalogEntry } from '../../../../src/main/features/connectors/catalog';
import { authorizeLocalApi, hasLocalApiAuthorization, localApiRuntimeDir, localApiTransport,
normalizeLocalApiConnectionInput, removeLocalApiAuthorization } from '../../../../src/main/features/connectors/local-api';
@@ -92,12 +94,83 @@ const callback = () => handleDcrCallbackUrl('orkas://connectors/oauth/dcr-callba
beforeEach(() => vi.clearAllMocks());
afterEach(() => {
cancelDcrOAuth();
+ _setBroadcastForTest();
for (const row of cases) removeLocalApiAuthorization(UID, findCatalogEntry(row.id)!);
vi.unstubAllGlobals();
vi.restoreAllMocks();
});
describe('user-owned app authorization journey', () => {
+ it('discovers and confirms the Mercado Libre owner without a manually supplied ID', async () => {
+ const row = cases.find(row => row.provider === 'mercado_libre')!;
+ const requests = boundary(row);
+ let choice: any;
+ _setBroadcastForTest((channel, payload) => { if (channel === 'connectors:account-choice') choice = payload; return true; });
+ const entry = findCatalogEntry(row.id)!;
+ const flow = authorizeLocalApi(UID, entry, client);
+ const completion = callback();
+ await vi.waitFor(() => expect(choice).toBeDefined());
+ expect(choice.choices).toEqual([{ id: '12345', label: 'Fixture seller (12345)' }]);
+ expect(JSON.stringify(choice)).not.toMatch(/private|secret|token/);
+ expect(hasLocalApiAuthorization(UID, entry)).toBe(false);
+ respondAccountChoice(UID, choice.request_id, '12345');
+ await completion;
+ const metadata = await flow;
+ expect(metadata).toEqual({ user_id: '12345' });
+ expect(requests.mock.calls).toHaveLength(3);
+ const transport = await localApiTransport(UID, entry, metadata);
+ if (transport.kind !== 'stdio') throw new Error('Expected stdio');
+ expect(adapter.configured(transport.env).credentials.identity.user_id).toBe('12345');
+ });
+
+ it('does not save a newly discovered Mercado Libre grant when the user declines the account', async () => {
+ const row = cases.find(row => row.provider === 'mercado_libre')!;
+ boundary(row);
+ let choice: any;
+ _setBroadcastForTest((channel, payload) => { if (channel === 'connectors:account-choice') choice = payload; return true; });
+ const entry = findCatalogEntry(row.id)!;
+ const flow = authorizeLocalApi(UID, entry, client);
+ const rejected = expect(flow).rejects.toMatchObject({ code: 'user_cancelled' });
+ const completion = callback();
+ await vi.waitFor(() => expect(choice).toBeDefined());
+ respondAccountChoice(UID, choice.request_id, null);
+ await completion; await rejected;
+ expect(hasLocalApiAuthorization(UID, entry)).toBe(false);
+ });
+
+ it.each([undefined, 'different', 9007199254740992])('rejects invalid discovered Mercado Libre identity %s', async userId => {
+ const row = cases.find(row => row.provider === 'mercado_libre')!;
+ boundary({ ...row, replies: [{ ...grant, user_id: userId }, { id: 12345 }] });
+ const shown = vi.fn(() => true);
+ _setBroadcastForTest(shown);
+ const entry = findCatalogEntry(row.id)!;
+ const flow = authorizeLocalApi(UID, entry, client);
+ const rejected = expect(flow).rejects.toThrow('Could not authorize');
+ await callback(); await rejected;
+ expect(shown).not.toHaveBeenCalled();
+ expect(hasLocalApiAuthorization(UID, entry)).toBe(false);
+ });
+
+ it('checks the discovered owner against the account endpoint and preserves explicit or existing bindings', async () => {
+ const row = cases.find(row => row.provider === 'mercado_libre')!;
+ const entry = findCatalogEntry(row.id)!;
+ for (const [input, existingBinding, replies, accepts] of [
+ [client, undefined, [{ ...grant, user_id: 12345 }, { id: 54321 }], false],
+ [client, { user_id: '54321' }, row.replies, false],
+ [client, { user_id: '12345' }, row.replies, true],
+ [{ ...client, user_id: '54321' }, undefined, row.replies, false],
+ ] as const) {
+ boundary({ ...row, replies: [...replies] });
+ const shown = vi.fn(() => true); _setBroadcastForTest(shown);
+ const flow = authorizeLocalApi(UID, entry, input, { existingBinding });
+ const outcome = accepts ? expect(flow).resolves.toEqual({ user_id: '12345' }) : expect(flow).rejects.toThrow('Could not authorize');
+ await callback(); await outcome;
+ expect(shown).not.toHaveBeenCalled();
+ expect(hasLocalApiAuthorization(UID, entry)).toBe(accepts);
+ removeLocalApiAuthorization(UID, entry);
+ }
+ });
+
it('exposes the complete credential panel and pins callbacks only for browser providers', () => {
// Short copy is intentional; assert the platform prerequisite, not prose length.
const prerequisites: Record<string, [RegExp, RegExp]> = {
@@ -119,7 +192,7 @@ describe('user-owned app authorization journey', () => {
const setup = entry.connection_setup!;
const optionalKeys = row.id === 'ebay-seller' ? ['signing_key_jwe', 'signing_private_key'] : [];
expect(setup.fields.map((field) => field.key).sort()).toEqual([...Object.keys(row.input), ...optionalKeys].sort());
- expect(setup.fields.filter((field) => field.required).map((field) => field.key).sort()).toEqual(Object.keys(row.input).sort());
+ expect(setup.fields.filter((field) => field.required).map((field) => field.key).sort()).toEqual(Object.keys(row.input).filter(key => !(row.id === 'mercado-libre-global-selling' && key === 'user_id')).sort());
for (const key of optionalKeys) {
expect(setup.fields.find((field) => field.key === key)).toMatchObject({ required: false, input: 'secret', storage: 'credential' });
}
diff --git a/test/main/features/connectors/woocommerce-auth_e2e_flow.test.ts b/test/main/features/connectors/woocommerce-auth_e2e_flow.test.ts
new file mode 100644
index 00000000..75264f25
--- /dev/null
+++ b/test/main/features/connectors/woocommerce-auth_e2e_flow.test.ts
@@ -0,0 +1,148 @@
+import { createRequire } from 'node:module';
+import { publicEncrypt } from 'node:crypto';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const browser = vi.hoisted(() => ({ open: vi.fn(async (_url: string) => undefined) }));
+vi.mock('electron', () => ({ app: { isPackaged: false }, shell: { openExternal: browser.open } }));
+vi.mock('../../../../src/main/features/account/server', () => ({ accountApiBase: () => 'https://orkas.test/api' }));
+vi.mock('../../../../src/main/features/account/token_store', () => ({ getDeviceId: () => 'test-device' }));
+vi.mock('../../../../src/main/features/api_common', () => ({ withCommonHeaders: (h: unknown) => h }));
+vi.mock('../../../../src/main/features/config', () => ({ getLanguage: () => 'en', getLanguageForUser: () => 'en' }));
+vi.mock('../../../../src/main/util/local-secret-store', () => ({
+ encryptLocalSecret: (_ctx: unknown, value: string) => `TEST:${value}`,
+ decryptLocalSecret: (_ctx: unknown, value: string) => value.slice(5),
+}));
+vi.mock('../../../../src/main/features/connectors/oauth-events', () => ({ broadcastOAuthConnectProgress: vi.fn() }));
+
+import { findCatalogEntry } from '../../../../src/main/features/connectors/catalog';
+import { authorizeLocalApi, localApiRuntimeDir, removeLocalApiAuthorization } from '../../../../src/main/features/connectors/local-api';
+import { cancelDcrOAuth, handleDcrCallbackUrl } from '../../../../src/main/features/connectors/oauth-dcr';
+
+const require = createRequire(import.meta.url);
+const codec = require('../../../../bin/local-api-credential-codec.cjs');
+const uid = 'woo-auth-flow-tests';
+const entry = findCatalogEntry('woocommerce')!;
+const store = 'https://shop.example.com/wordpress';
+const ticket = 't'.repeat(43);
+const credentials = { consumer_key: `ck_${'a'.repeat(40)}`, consumer_secret: `cs_${'b'.repeat(40)}` };
+let registration: { state: string; public_key: string };
+let ciphertext: string;
+let fetchMock: ReturnType<typeof vi.fn>;
+
+function stored() {
+ const dir = localApiRuntimeDir(uid, entry.id);
+ const key = fs.readFileSync(path.join(dir, 'credential-key.enc'), 'utf8').trim().slice(5);
+ return codec.readCredentialFile(path.join(dir, 'credentials.enc'), key);
+}
+function ciphertextFor(state = registration.state) {
+ return publicEncrypt({ key: registration.public_key, oaepHash: 'sha256', oaepLabel: Buffer.from(state) },
+ Buffer.from(JSON.stringify(credentials))).toString('base64');
+}
+async function consent() {
+ await vi.waitFor(() => expect(browser.open).toHaveBeenCalledOnce());
+ const url = new URL(browser.open.mock.calls[0][0]);
+ expect(url.origin + url.pathname).toBe(`${store}/wc-auth/v1/authorize`);
+ expect(Object.fromEntries(url.searchParams)).toEqual({
+ app_name: 'Orkas', scope: 'read_write', user_id: ticket,
+ callback_url: 'https://orkas.ai/api/connectors/woocommerce/auth/callback',
+ return_url: 'https://orkas.ai/api/connectors/woocommerce/auth/return?lang=en',
+ });
+ expect(url.href).not.toContain(credentials.consumer_key);
+}
+async function callback() {
+ await handleDcrCallbackUrl('orkas://connectors/oauth/dcr-callback?status=success&exchange_code=one-time-code');
+}
+
+beforeEach(() => {
+ browser.open.mockClear();
+ ciphertext = '';
+ fetchMock = vi.fn(async (url: string, init: RequestInit) => {
+ if (url.endsWith('/woocommerce/auth/start')) {
+ registration = JSON.parse(String(init.body));
+ return Response.json({ code: 0, ticket });
+ }
+ if (url.endsWith('/oauth/dcr-exchange')) {
+ return Response.json({ code: 0, oauth_state: registration.state, oauth_code: ciphertext || ciphertextFor() });
+ }
+ expect(url).toBe(`${store}/wp-json/wc/v3/system_status`);
+ expect(init.redirect).toBe('error');
+ expect((init.headers as Record<string, string>).authorization).toBe(`Basic ${Buffer.from(`${credentials.consumer_key}:${credentials.consumer_secret}`).toString('base64')}`);
+ return Response.json({ environment: { site_url: store, version: '10.0.0' } });
+ });
+ vi.stubGlobal('fetch', fetchMock);
+});
+afterEach(() => {
+ cancelDcrOAuth();
+ removeLocalApiAuthorization(uid, entry);
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+});
+
+describe('WooCommerce owner authorization to encrypted local connection', () => {
+ it('accepts only a store URL, verifies returned keys at that store, and saves no plaintext', async () => {
+ const pending = authorizeLocalApi(uid, entry, { store_url: store });
+ await consent();
+ expect(fs.existsSync(path.join(localApiRuntimeDir(uid, entry.id), 'credentials.enc'))).toBe(false);
+ await callback();
+ await expect(pending).resolves.toEqual({ store_url: store });
+ expect(stored()).toEqual({ provider: 'woocommerce', ...credentials });
+ const file = fs.readFileSync(path.join(localApiRuntimeDir(uid, entry.id), 'credentials.enc'), 'utf8');
+ expect(file).not.toContain(credentials.consumer_key);
+ expect(file).not.toContain(credentials.consumer_secret);
+ const count = fetchMock.mock.calls.length;
+ await callback();
+ expect(fetchMock).toHaveBeenCalledTimes(count);
+ });
+
+ it.each(['wrong-state', 'store-denied', 'invalid-store-response'])('keeps existing credentials after %s', async failure => {
+ const old = { consumer_key: `ck_${'c'.repeat(40)}`, consumer_secret: `cs_${'d'.repeat(40)}` };
+ await authorizeLocalApi(uid, entry, { store_url: store, ...old });
+ const pending = authorizeLocalApi(uid, entry, { store_url: store });
+ const rejected = expect(pending).rejects.toMatchObject({ code: 'local_api_authorization_failed' });
+ await consent();
+ if (failure === 'wrong-state') ciphertext = ciphertextFor('other-state');
+ else {
+ const upstream = fetchMock.getMockImplementation()!;
+ fetchMock.mockImplementation(async (url, init) => url.endsWith('/system_status')
+ ? failure === 'store-denied' ? new Response('Denied', { status: 401 }) : Response.json({ ok: true })
+ : upstream(url, init));
+ }
+ await callback();
+ await rejected;
+ expect(stored()).toEqual({ provider: 'woocommerce', ...old });
+ if (failure === 'wrong-state') expect(fetchMock.mock.calls.some(([url]) => url.endsWith('/system_status'))).toBe(false);
+ });
+
+ it('cancels while preparing authorization without opening a late browser or saving keys', async () => {
+ let release!: (response: Response) => void;
+ fetchMock.mockImplementation(async () => new Promise<Response>(resolve => { release = resolve; }));
+ const pending = authorizeLocalApi(uid, entry, { store_url: store });
+ const rejected = expect(pending).rejects.toMatchObject({ code: 'user_cancelled' });
+ await vi.waitFor(() => expect(release).toBeTypeOf('function'));
+ cancelDcrOAuth();
+ release(Response.json({ code: 0, ticket }));
+ await rejected;
+ await new Promise(resolve => setImmediate(resolve));
+ expect(browser.open).not.toHaveBeenCalled();
+ expect(fs.existsSync(path.join(localApiRuntimeDir(uid, entry.id), 'credentials.enc'))).toBe(false);
+ });
+
+ it('does not save a late store response after the user cancels verification', async () => {
+ let release!: (response: Response) => void;
+ const upstream = fetchMock.getMockImplementation()!;
+ fetchMock.mockImplementation(async (url, init) => url.endsWith('/system_status')
+ ? new Promise<Response>(resolve => { release = resolve; }) : upstream(url, init));
+ const pending = authorizeLocalApi(uid, entry, { store_url: store });
+ const rejected = expect(pending).rejects.toMatchObject({ code: 'user_cancelled' });
+ await consent();
+ const returning = callback();
+ await vi.waitFor(() => expect(release).toBeTypeOf('function'));
+ cancelDcrOAuth();
+ release(Response.json({ environment: { site_url: store, version: '10.0.0' } }));
+ await returning;
+ await rejected;
+ expect(fs.existsSync(path.join(localApiRuntimeDir(uid, entry.id), 'credentials.enc'))).toBe(false);
+ });
+});
diff --git a/test/main/features/group_chat/connector-setup-tool.test.ts b/test/main/features/group_chat/connector-setup-tool.test.ts
index c9dc4c65..f206b0c4 100644
--- a/test/main/features/group_chat/connector-setup-tool.test.ts
+++ b/test/main/features/group_chat/connector-setup-tool.test.ts
@@ -146,6 +146,91 @@ describe('connector_setup', () => {
expect(stageConfigure).not.toHaveBeenCalled();
});
+ // Queries below are verbatim from a live onboarding run (2026-09-29) against the real catalog.
+ function builtInSearchTool() {
+ const stageConfigure = vi.fn(() => ({ ok: true as const }));
+ const tool = buildConnectorSetupTool({
+ uid: 'u1', language: 'zh', stageConfigure,
+ dependencies: { catalog: () => CONNECTOR_CATALOG, instances: () => [],
+ enabledSnapshot: () => ({ connectors: {} }) },
+ });
+ const search = async (query: string) => (await run(tool, { operation: 'search', query }))
+ .result.results as Array<{ connector_id: string; name: string; matched_terms?: string[] }>;
+ return { search, stageConfigure };
+ }
+
+ it('offers mail-capable Microsoft access when Outlook or a mailbox is named, without renaming the card', async () => {
+ const { search, stageConfigure } = builtInSearchTool();
+ // The general Outlook entry reads profile, contacts, settings and tasks, not mail.
+ const outlook = await search('Outlook');
+ expect(outlook.map((item) => item.connector_id)).toEqual(expect.arrayContaining(['outlook', 'm365-mail']));
+ expect(outlook.find((item) => item.connector_id === 'm365-mail')?.name).toBe('Microsoft 365 Mail');
+ expect(outlook.some((item) => item.matched_terms)).toBe(false);
+ const mailbox = (await search('邮箱')).map((item) => item.connector_id);
+ expect(mailbox).toEqual(expect.arrayContaining(['gmail', 'm365-mail']));
+ expect(stageConfigure).not.toHaveBeenCalled();
+ });
+
+ it('names the non-mail Outlook entry by its scope so it is not taken for mail access', async () => {
+ for (const [language, expected] of [['zh', 'Outlook 联系人与任务'], ['en', 'Outlook Contacts & Tasks'], ['ja', 'Outlook Contacts & Tasks']] as const) {
+ const tool = buildConnectorSetupTool({
+ uid: 'u1', language, stageConfigure: vi.fn(() => ({ ok: true as const })),
+ dependencies: { catalog: () => CONNECTOR_CATALOG, instances: () => [], enabledSnapshot: () => ({ connectors: {} }) },
+ });
+ const results = (await run(tool, { operation: 'search', query: 'Outlook' })).result.results as Array<{ connector_id: string; name: string }>;
+ expect(results.find((item) => item.connector_id === 'outlook')?.name, language).toBe(expected);
+ expect(results.find((item) => item.connector_id === 'm365-mail')?.name, language).toBe('Microsoft 365 Mail');
+ }
+ // The stable fallback name, used by installed instances and older data, is unchanged.
+ expect(CONNECTOR_CATALOG.find((entry) => entry.id === 'outlook')?.display_name).toBe('Outlook');
+ });
+
+ it.each([
+ ['email Gmail Outlook 邮箱', ['gmail', 'outlook', 'm365-mail']],
+ ['Outlook Microsoft 365 mail calendar', ['m365-mail', 'outlook']],
+ ['Feishu 文档 日历 消息 企业协作', ['feishu']],
+ ['Notion documents workspace', ['notion']],
+ ['GitHub repositories issues pull requests', ['github']],
+ ])('ranks named services first when no connector contains every word of %s', async (query, named) => {
+ const { search, stageConfigure } = builtInSearchTool();
+ const results = await search(query);
+ expect(results.slice(0, named.length).map((item) => item.connector_id).sort()).toEqual([...named].sort());
+ for (const item of results) {
+ expect(item.matched_terms?.length).toBeGreaterThan(0);
+ expect(item.matched_terms!.every((term) => query.toLocaleLowerCase().split(/\s+/).includes(term))).toBe(true);
+ }
+ expect(stageConfigure).not.toHaveBeenCalled();
+ });
+
+ it('keeps precise and empty searches unchanged when the any-term fallback does not apply', async () => {
+ const { search } = builtInSearchTool();
+ // Every word matches one connector: no fallback candidates are mixed in.
+ expect(await search('飞书 Lark')).toEqual([expect.objectContaining({ connector_id: 'feishu' })]);
+ expect((await search('飞书 Lark'))[0]).not.toHaveProperty('matched_terms');
+ // A single unknown service name is still an empty result, not a guess.
+ expect(await search('twitter')).toEqual([]);
+ // Several words that match nothing stay empty too.
+ expect(await search('qzxv wkjp')).toEqual([]);
+ });
+
+ it('keeps hidden child entries out of any-term fallback results', async () => {
+ const tool = buildConnectorSetupTool({
+ uid: 'u1', language: 'en', stageConfigure: vi.fn(() => ({ ok: true as const })),
+ dependencies: {
+ catalog: () => [
+ entry({ id: 'parent', display_name: 'Parent', description_en: 'Team chat.' }),
+ entry({ id: 'child', catalog_parent_id: 'parent', display_name: 'Child', description_en: 'Legacy edition.' }),
+ entry({ id: 'other', display_name: 'Other', description_en: 'Chat archive.' }),
+ ],
+ instances: () => [], enabledSnapshot: () => ({ connectors: {} }),
+ },
+ });
+ const output = await run(tool, { operation: 'search', query: 'child chat calendar' });
+ expect(output.result.results.map((item: { connector_id: string }) => item.connector_id))
+ .toEqual(['parent', 'other']);
+ expect(output.result.results[0].matched_terms).toEqual(['child', 'chat']);
+ });
+
it('keeps existing related-description search ordering when new translations have different lengths', async () => {
const parent = (id: string, descriptionFr: string) => entry({
id, display_name: 'Catalog', description_fr: descriptionFr,
diff --git a/test/main/ipc/connectors.test.ts b/test/main/ipc/connectors.test.ts
index 0c3ecfbd..a0145e2b 100644
--- a/test/main/ipc/connectors.test.ts
+++ b/test/main/ipc/connectors.test.ts
@@ -47,6 +47,26 @@ function baseInstance(transport: any): any {
}
describe('ipc/connectors renderer DTO', () => {
+ it('validates account-choice responses and uses the host user rather than a payload identity', async () => {
+ const gate = await import('../../../src/main/features/connectors/account-choice');
+ const users = await import('../../../src/main/features/users');
+ users.activateUser('choice-ipc');
+ const { invokeHandlers } = await import('../../../src/main/ipc/connectors');
+ let info: any;
+ gate._setBroadcastForTest((channel, payload) => { if (channel === 'connectors:account-choice') info = payload; return true; });
+ const controller = new AbortController();
+ try {
+ const flow = gate.requestAccountChoice('choice-ipc', 'tiktok-shop', [{ id: '123', label: 'Shop' }], controller.signal);
+ const answer = (payload: any, userId = 'choice-ipc') => invokeHandlers['connectors.account_choice_response'](payload, { userId });
+ await expect(answer({ request_id: info.request_id, choice_id: {} })).rejects.toThrow('invalid choice_id');
+ await expect(answer({ request_id: 'bad', choice_id: '123' })).rejects.toThrow('invalid request_id');
+ await expect(answer({ request_id: info.request_id, choice_id: '456' })).resolves.toEqual({ handled: false });
+ await expect(answer({ request_id: info.request_id, choice_id: '123', userId: 'choice-ipc' }, 'other')).resolves.toEqual({ handled: false });
+ await expect(answer({ request_id: info.request_id, choice_id: '123' })).resolves.toEqual({ handled: true });
+ await expect(flow).resolves.toBe('123');
+ } finally { controller.abort(); gate._setBroadcastForTest(); }
+ });
+
it('accepts one-time and task approval responses and rejects unknown scopes', async () => {
// IPC deliberately uses CJS for the gate; share that module instance.
const users = require('../../../src/main/features/users') as typeof import('../../../src/main/features/users');
diff --git a/test/main/ipc/model-config-auth.test.ts b/test/main/ipc/model-config-auth.test.ts
new file mode 100644
index 00000000..af142616
--- /dev/null
+++ b/test/main/ipc/model-config-auth.test.ts
@@ -0,0 +1,257 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import { trustedIpcSender } from '../../helpers/trusted-ipc-sender';
+
+type InvokeFn = (
+ event: unknown,
+ req: { channel: string; payload?: unknown },
+) => Promise<{ ok: boolean; error?: string } & Record<string, unknown>>;
+
+let invokeHandler: InvokeFn | null = null;
+
+vi.mock('electron', () => ({
+ app: {
+ isPackaged: false,
+ getVersion: vi.fn(() => '9.8.7'),
+ on: vi.fn(),
+ off: vi.fn(),
+ },
+ ipcMain: {
+ handle: (channel: string, fn: InvokeFn) => {
+ if (channel === 'orkas.invoke') invokeHandler = fn;
+ },
+ on: vi.fn(),
+ },
+ shell: { openExternal: vi.fn(async () => undefined), showItemInFolder: vi.fn() },
+ BrowserWindow: { getAllWindows: vi.fn(() => []), getFocusedWindow: vi.fn(() => null) },
+ dialog: { showOpenDialog: vi.fn(async () => ({ canceled: true, filePaths: [] })) },
+ systemPreferences: {
+ getMediaAccessStatus: vi.fn(() => 'granted'),
+ askForMediaAccess: vi.fn(async () => true),
+ },
+}));
+
+let tmpDir: string;
+let prevWs: string | undefined;
+const TEST_UID = 'u_model_config';
+
+beforeEach(async () => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-model-config-ipc-'));
+ prevWs = process.env.ORKAS_WORKSPACE_ROOT;
+ process.env.ORKAS_WORKSPACE_ROOT = tmpDir;
+ invokeHandler = null;
+ vi.resetModules();
+
+ const users = await import('../../../src/main/features/users');
+ users.activateUser(TEST_UID);
+
+ const ipc = await import('../../../src/main/ipc/index');
+ ipc.register();
+});
+
+afterEach(() => {
+ process.env.ORKAS_WORKSPACE_ROOT = prevWs;
+ fs.rmSync(tmpDir, { recursive: true, force: true });
+});
+
+function call(channel: string, payload: unknown = {}): ReturnType<InvokeFn> {
+ if (!invokeHandler) throw new Error('invoke handler not registered');
+ return invokeHandler({ sender: trustedIpcSender() }, { channel, payload });
+}
+
+function profileProviders(res: Record<string, unknown>): string[] {
+ return ((res.profiles || []) as Array<{ provider?: string }>).map((p) => String(p.provider || ''));
+}
+
+function profileIds(res: Record<string, unknown>): string[] {
+ return ((res.profiles || []) as Array<{ id?: string }>).map((p) => String(p.id || ''));
+}
+
+function profileByProvider(res: Record<string, unknown>, provider: string): Record<string, unknown> | undefined {
+ return ((res.profiles || []) as Array<Record<string, unknown>>)
+ .find((profile) => profile.provider === provider);
+}
+
+function imageProfiles(res: Record<string, unknown>): Array<{ provider?: string; model?: string }> {
+ return (res.profiles || []) as Array<{ provider?: string; model?: string }>;
+}
+
+function entryProviders(res: Record<string, unknown>): string[] {
+ return ((res.entries || []) as Array<{ provider?: string }>).map((entry) => String(entry.provider || ''));
+}
+
+
+describe('ipc › model config auth lists', () => {
+
+ it('selects a custom entry and its catalog model version through one IPC call', async () => {
+ const profile = await call('auth.addApiKey', {
+ provider: 'openai',
+ apiKey: 'sk-composer-version-ipc-test',
+ label: 'composer-version',
+ });
+ const entry = await call('auth.addEntry', {
+ provider: 'openai',
+ model: 'gpt-5.6-sol',
+ profileId: profile.profileId,
+ });
+
+ const selected = await call('auth.selectEntry', {
+ entryId: entry.entryId,
+ model: 'gpt-5.6-terra',
+ });
+ expect(selected).toMatchObject({
+ ok: true,
+ entries: [expect.objectContaining({
+ entryId: entry.entryId,
+ model: 'gpt-5.6-terra',
+ modelName: 'GPT-5.6 Terra',
+ })],
+ });
+ });
+
+ it('keeps the renderer model guard closed without replacing an unreadable credential store', async () => {
+ const paths = await import('../../../src/main/paths');
+ const storePath = paths.userAuthProfilesFile(TEST_UID);
+ const unreadable = 'credential-store-recovery-sentinel';
+ fs.mkdirSync(path.dirname(storePath), { recursive: true });
+ fs.writeFileSync(storePath, unreadable, 'utf8');
+
+ expect(await call('auth.hasConfiguredModel')).toMatchObject({
+ ok: true,
+ configured: false,
+ });
+ expect(fs.readFileSync(storePath, 'utf8')).toBe(unreadable);
+ });
+
+ it('persists a newly added user model without managed fallback entries', async () => {
+ const added = await call('auth.addApiKeyEntry', {
+ provider: 'openai',
+ model: 'gpt-5.5',
+ apiKey: 'sk-model-test-key',
+ label: 'default',
+ });
+ expect(added.ok).toBe(true);
+
+ expect(entryProviders(await call('auth.listEntries'))).toEqual(['openai']);
+ });
+
+ it('rejects an unavailable model without leaving a credential-only partial save', async () => {
+ const added = await call('auth.addApiKeyEntry', {
+ provider: 'openai',
+ apiKey: 'sk-invalid-model-test-key',
+ label: 'invalid-model',
+ model: 'gpt-not-listed',
+ });
+ expect(added).toMatchObject({ ok: false, code: 'MODEL_NOT_AVAILABLE' });
+ expect(entryProviders(await call('auth.listEntries'))).toEqual([]);
+ const providers = await call('auth.listProviders');
+ expect(profileIds(providers)).not.toContain('openai:invalid-model');
+ });
+
+ it('adds a custom OpenAI-compatible model through one atomic IPC command', async () => {
+ const added = await call('auth.addCustomModelEntry', {
+ baseUrl: 'https://gateway.example.test/v1/chat/completions',
+ model: 'acme/reasoner-v2',
+ apiKey: 'sk-custom-ipc-test-key',
+ });
+ expect(added).toMatchObject({ ok: true, profileId: 'custom:default' });
+
+ expect(await call('auth.listEntries')).toMatchObject({
+ ok: true,
+ entries: [
+ expect.objectContaining({
+ provider: 'custom',
+ model: 'acme/reasoner-v2',
+ modelName: 'acme/reasoner-v2',
+ modelEditable: false,
+ profileMasked: 'sk-c…-key',
+ }),
+ ],
+ });
+ });
+
+ it('returns a stable error for an invalid custom API key without a partial save', async () => {
+ const added = await call('auth.addCustomModelEntry', {
+ baseUrl: 'https://gateway.example.test/v1',
+ model: 'acme/reasoner-v2',
+ apiKey: 'щ-custom-key',
+ });
+ expect(added).toMatchObject({ ok: false, code: 'CUSTOM_API_KEY_INVALID' });
+ expect(entryProviders(await call('auth.listEntries'))).toEqual([]);
+ expect(profileIds(await call('auth.listProviders'))).toEqual([]);
+ });
+
+ it('returns unavailable saved models only for the Settings remediation query', async () => {
+ const apiKey = await call('auth.addApiKey', {
+ provider: 'openai',
+ apiKey: 'sk-removed-model-test-key',
+ label: 'removed-model',
+ });
+ const added = await call('auth.addEntry', {
+ provider: 'openai',
+ model: 'gpt-5.6-terra',
+ profileId: apiKey.profileId,
+ });
+ expect(added.ok).toBe(true);
+
+ const { clientConfig } = await import('../../../src/main/features/client_config');
+ clientConfig.applyServerPayload({
+ immediate: {
+ model_catalog: {
+ providers: {
+ openai: [{ id: 'gpt-5.6-sol', name: 'GPT-5.6 Sol' }],
+ },
+ },
+ },
+ restart: {},
+ config_hash: 'sha256:ipc-model-removal',
+ }, '"ipc-model-removal"');
+
+ expect(entryProviders(await call('auth.listEntries'))).toEqual([]);
+ const remediation = await call('auth.listEntries', { includeUnavailable: true });
+ expect(remediation.entries).toEqual([
+ expect.objectContaining({
+ provider: 'openai',
+ model: 'gpt-5.6-terra',
+ modelAvailable: false,
+ }),
+ ]);
+ });
+
+ it('lists and persists the selected Doubao Seedream 5.0 image model', async () => {
+ const initial = await call('imageAuth.list');
+ expect(initial.modelsByProvider).toBeUndefined();
+ expect(initial.providers).toEqual(expect.arrayContaining([
+ expect.objectContaining({
+ id: 'doubao:doubao-seedream-5-0-lite-260128',
+ provider: 'doubao',
+ model: 'doubao-seedream-5-0-lite-260128',
+ label: 'DouBao · Seedream 5.0 Lite',
+ }),
+ expect.objectContaining({
+ id: 'doubao:doubao-seedream-5-0-pro-260628',
+ provider: 'doubao',
+ model: 'doubao-seedream-5-0-pro-260628',
+ label: 'DouBao · Seedream 5.0 Pro',
+ }),
+ ]));
+
+ const added = await call('imageAuth.add', {
+ provider: 'doubao',
+ model: 'doubao-seedream-5-0-pro-260628',
+ apiKey: 'doubao-image-test-key',
+ label: 'pro',
+ });
+ expect(added.ok).toBe(true);
+
+ const profiles = imageProfiles(await call('imageAuth.list'));
+ expect(profiles[0]).toMatchObject({
+ provider: 'doubao',
+ model: 'doubao-seedream-5-0-pro-260628',
+ });
+ expect(profiles.every((profile) => profile.provider === 'doubao')).toBe(true);
+ });
+
+});
diff --git a/test/main/model/core-agent/auth-error.test.ts b/test/main/model/core-agent/auth-error.test.ts
index e2d04511..6a89f355 100644
--- a/test/main/model/core-agent/auth-error.test.ts
+++ b/test/main/model/core-agent/auth-error.test.ts
@@ -13,18 +13,40 @@ import {
} from '../../../../src/core-agent/src/shared/errors';
describe('auth-error › classifyKeyFailure › status code fast path', () => {
+ it.each([
+ 'Not authorized to operate on this resource',
+ 'Unable to generate this resource',
+ 'Quota is not the reason this operation was denied',
+ ])('keeps a 403 permission failure despite incidental wording: %s', (message) => {
+ expect(classifyKeyFailure({ status: 403, message })).toBe('permission');
+ });
+
+ it('uses an explicit rate-limit code even when its HTTP envelope is 403', () => {
+ expect(classifyKeyFailure({ status: 403, code: 'rate_limit_error', message: 'opaque' })).toBe('rate_limit');
+ });
it('401 → auth', () => {
const err = Object.assign(new Error('Unauthorized'), { status: 401 });
expect(classifyKeyFailure(err)).toBe('auth');
});
+ it('401 + invalid_request_error + token_invalidated → auth(具体凭证信号优先)', () => {
+ const err = Object.assign(new Error(JSON.stringify({
+ error: {
+ message: 'Encountered invalidated oauth token for user, failing request',
+ type: 'invalid_request_error',
+ code: 'token_invalidated',
+ },
+ })), { status: 401, code: 'token_invalidated' });
+ expect(classifyKeyFailure(err)).toBe('auth');
+ });
+
it('403 → permission(默认)', () => {
const err = Object.assign(new Error('Forbidden'), { status: 403 });
expect(classifyKeyFailure(err)).toBe('permission');
});
- it('403 带 rate/quota 字样 → 归到 rate_limit(一些云商用 403 返限速)', () => {
- // 例:Google Vertex AI 偶发 403 "Resource has been exhausted (e.g. check quota)"
+ it('keeps a 403 as permission without an explicit throttling code', () => {
+ // Prose alone cannot override the HTTP status.
const err = Object.assign(new Error('Resource has been exhausted: quota'), { status: 403 });
expect(classifyKeyFailure(err)).toBe('permission');
});
@@ -34,70 +56,65 @@ describe('auth-error › classifyKeyFailure › status code fast path', () => {
expect(classifyKeyFailure(err)).toBe('rate_limit');
});
- it('402 → balance', () => {
- const err = Object.assign(new Error('Payment Required'), { status: 402 });
+ it('429 + insufficient_quota → balance(余额不足,不是限流)', () => {
+ const err = Object.assign(new Error('429 {"error":{"message":"积分不足","type":"insufficient_quota","code":"orkas_llm_quota_exceeded"}}'), { status: 429, code: 'insufficient_quota' });
expect(classifyKeyFailure(err)).toBe('balance');
});
-});
-describe('auth-error › classifyKeyFailure › 跨模块边界 (message-only)', () => {
- // 故意不用 instanceof — pi-provider 在 ESM 加载 AuthError,我们在 CJS 加载,
- // 跨模块 instanceof 返 false。靠 err.message / err.status 分类。
- it('pi-provider 的 wrapError 产物 "auth failed" 前缀 → auth', () => {
- // pi-provider.ts::wrapError 构造的 message 格式
- const err = new Error('openai auth failed: 401 Incorrect API key provided: sk-xxx');
- expect(classifyKeyFailure(err)).toBeNull();
+ it('429 + code=insufficient_quota → balance', () => {
+ const err = Object.assign(new Error('429'), { status: 429, code: 'insufficient_quota' });
+ expect(classifyKeyFailure(err)).toBe('balance');
});
- it('"auth failed" 前缀带 permission 关键词 → permission', () => {
- const err = new Error('anthropic auth failed: forbidden: subscription expired');
- expect(classifyKeyFailure(err)).toBeNull();
+ it('does not override HTTP 429 with a message-only balance claim', () => {
+ expect(classifyKeyFailure({ status: 429, message: '429 积分不足' })).toBe('rate_limit');
});
- it('rate_limit message', () => {
- expect(classifyKeyFailure(new Error('rate limited: too many requests per minute'))).toBeNull();
+ it('402 → balance', () => {
+ const err = Object.assign(new Error('Payment Required'), { status: 402 });
+ expect(classifyKeyFailure(err)).toBe('balance');
});
- it('context_length_exceeded → null(不换 key,换了一样溢出)', () => {
- expect(classifyKeyFailure(new Error('context_length_exceeded: max 8k'))).toBeNull();
+ it('402 + generic quota_exceeded code → balance(HTTP payment status wins)', () => {
+ const err = Object.assign(new Error('quota exceeded'), {
+ status: 402,
+ code: 'orkas_llm_quota_exceeded',
+ });
+ expect(classifyKeyFailure(err)).toBe('balance');
});
- it('request timed out → "network"(同 key 重试无用,但换 endpoint 有救)', () => {
- expect(classifyKeyFailure(new Error('request timed out after 30s'))).toBe('network');
+ it('Orkas quota business code remains balance even without an HTTP status', () => {
+ const err = Object.assign(new Error('upstream rejected request'), {
+ code: 'orkas_llm_quota_exceeded',
+ });
+ expect(classifyKeyFailure(err)).toBe('balance');
});
});
-describe('auth-error › classifyKeyFailure › message fallback', () => {
- it('Kimi/Anthropic 风格的 authentication_error JSON 体', () => {
- // 这正是用户看到的 401 报文
- const body = '401 {"error":{"type":"authentication_error","message":"The API Key appears to be invalid or may have expired. Please verify your credentials and try again."},"type":"error"}';
- const err = new ProviderError(body, 'kimi-coding');
- expect(classifyKeyFailure(err)).toBe('auth');
- });
+describe('auth-error structured evidence and unclassified diagnostics', () => {
- it('中文"余额不足"', () => {
- const err = new ProviderError('账户余额不足,请充值后重试', 'moonshot');
- expect(classifyKeyFailure(err)).toBeNull();
+ it.each([
+ ['auth', { code: 'AUTH_ERROR', message: 'opaque' }],
+ ['rate_limit', { code: 'RATE_LIMIT', message: 'opaque' }],
+ ['auth', { error: { type: 'invalid_request_error', code: 'token_invalidated' } }],
+ ['auth', { error: { message: 'Missing Authentication header', code: 401 } }],
+ ['auth', new ProviderError('opaque', 'custom', 401)],
+ ['permission', { status: 403, code: 'unrecognized_gateway_code', message: 'opaque' }],
+ ] as const)('preserves %s through typed or nested protocol metadata', (kind, error) => {
+ expect(classifyKeyFailure(error)).toBe(kind);
});
- it('OpenAI "insufficient_quota"', () => {
- const err = new Error('You exceeded your current quota — insufficient_quota');
- expect(classifyKeyFailure(err)).toBeNull();
- });
+ it.each(['constructor', '__proto__', 'not_a_rate_limit_error', 'quota_exceeded'])(
+ 'does not invent an account cause for unknown code %s', (code) => {
+ expect(classifyKeyFailure({ code, message: 'opaque' })).toBeNull();
+ },
+ );
- it('permission error 不带状态码也能识别', () => {
- const err = new Error('permission_error: this API key does not have access to the requested model');
- expect(classifyKeyFailure(err)).toBeNull();
- });
-
- it('rate limit 英文报文', () => {
- const err = new Error('rate_limit_error: too many requests per minute');
- expect(classifyKeyFailure(err)).toBeNull();
- });
-
- it('balance 关键词排在 auth 前面("insufficient credits" 不应误判为 invalid)', () => {
- const err = new Error('Your request was blocked: insufficient credits');
- expect(classifyKeyFailure(err)).toBeNull();
+ it('bounds parsing and handles a cyclic plain-object cause', () => {
+ const error: { message: string; cause?: unknown } = { message: 'opaque' };
+ error.cause = error;
+ expect(classifyKeyFailure(error)).toBeNull();
+ expect(classifyKeyFailure(new Error('{"code":"rate_limit_error","message":"' + 'x'.repeat(65_536) + '"}'))).toBeNull();
});
});
@@ -117,6 +134,13 @@ describe('auth-error › classifyKeyFailure › 反例(不触发轮转)', ()
expect(classifyKeyFailure(err)).toBeNull();
});
+ it('structured safety code wins over incidental balance wording', () => {
+ const err = Object.assign(new Error('Request requires more credits to evaluate'), {
+ code: 'ResponsibleAIPolicyViolation',
+ });
+ expect(classifyKeyFailure(err)).toBeNull();
+ });
+
it('500 / 502 / 503 server error → null(默认不触发,跟 isRetryableError 区分开)', () => {
const err500 = Object.assign(new Error('Internal Server Error'), { status: 500 });
const err502 = Object.assign(new Error('Bad Gateway'), { status: 502 });
@@ -144,9 +168,9 @@ describe('auth-error › classifyKeyFailure › 反例(不触发轮转)', ()
expect(classifyKeyFailure(Object.assign(new Error('connect ECONNREFUSED'), { code: 'ECONNREFUSED' }))).toBe('network');
});
- it('"fetch failed" 仅消息无 cause code → "network"(消息正则兜底)', () => {
+ it('keeps a message-only fetch failure unclassified', () => {
const err = new TypeError('fetch failed');
- expect(classifyKeyFailure(err)).toBe('network');
+ expect(classifyKeyFailure(err)).toBeNull();
});
it('"fetch failed" 包裹 401 cause → 仍然按 auth 分类(网络判断在最后)', () => {
diff --git a/test/main/model/core-agent/connector-meta-tools.test.ts b/test/main/model/core-agent/connector-meta-tools.test.ts
index af76df95..e033e044 100644
--- a/test/main/model/core-agent/connector-meta-tools.test.ts
+++ b/test/main/model/core-agent/connector-meta-tools.test.ts
@@ -208,6 +208,31 @@ async function runTool(
return tool.execute(input, { workingDir: '.', signal } as any);
}
+it('cleans only a native draft created by this task, revoking that proof at task end', async () => {
+ const tools = ['create_draft', 'delete_draft'].map(name => ({ name, description: '', input_schema: { type: 'object', properties: { id: { type: 'string' } } } }));
+ fixtures.instances = [makeInstance({ id: 'gmail', tools })];
+ fixtures.actionApproved = false;
+ const dispatched: string[] = [];
+ fixtures.callTool = async (_uid, _id, name) => {
+ dispatched.push(name);
+ return { content: [{ type: 'text', text: JSON.stringify(name === 'create_draft'
+ ? { id: 'draft-owned', messageId: 'message-owned' } : { ok: true }) }] };
+ };
+ const { createConnectorMetaTools } = await loadModule();
+ const [, call] = await createConnectorMetaTools({ userId: UID, cid: 'draft-task' });
+ const invoke = (tool_name: string, id?: string) => runTool(call, { connector_id: 'gmail', tool_name, args: id ? { id } : {} });
+ expect((await invoke('create_draft')).isError).toBeFalsy();
+ expect((await invoke('delete_draft', 'draft-owned')).isError).toBeFalsy();
+ expect(fixtures.actionConfirmCalls).toHaveLength(0);
+ expect((await invoke('delete_draft', 'existing-user-draft')).isError).toBe(true);
+ await invoke('create_draft');
+ const confirm = await import('../../../../src/main/features/connectors/action_confirm');
+ confirm.cancelForCid('draft-task');
+ expect((await invoke('delete_draft', 'draft-owned')).isError).toBe(true);
+ expect(dispatched).toEqual(['create_draft', 'delete_draft', 'create_draft']);
+ expect(fixtures.actionConfirmCalls).toHaveLength(2);
+});
+
// ── connectorExposureFromSessionId (the runner.ts session-kind gate) ────
//
// session_id is now `<kind>-<tail>` (CLAUDE.md §5 — uid no longer in session_id, since the
diff --git a/test/main/model/core-agent/external-providers.test.ts b/test/main/model/core-agent/external-providers.test.ts
index e4e074c3..3d53611f 100644
--- a/test/main/model/core-agent/external-providers.test.ts
+++ b/test/main/model/core-agent/external-providers.test.ts
@@ -1,4 +1,4 @@
-import { describe, it, expect } from 'vitest';
+import { describe, it, expect, vi } from 'vitest';
import {
buildCustomOpenAICompatibleModel,
buildDeepSeekModel,
@@ -6,6 +6,7 @@ import {
buildMoonshotModel,
buildOrkasApiModel,
createMoonshotProvider,
+ repairDeepSeekPayload,
} from '../../../../src/main/model/core-agent/external-providers';
import { isSelectableModel, modelInputImageLimit } from '../../../../src/main/model/provider_catalog';
@@ -181,3 +182,70 @@ describe('external-providers › createMoonshotProvider', () => {
expect(typeof p.validateAuth).toBe('function');
});
});
+
+describe('external-providers › DeepSeek request compatibility', () => {
+ it.each(['complete', 'stream'] as const)('omits unsupported cache controls from DeepSeek %s requests', async mode => {
+ const { createPiProvider } = await vi.importActual<typeof import('#core-agent')>('#core-agent');
+ for (const modelId of ['deepseek-flash', 'deepseek-v4-flash']) {
+ for (const cacheRetention of ['long', 'short', 'none'] as const) {
+ let wire: Record<string, unknown> | undefined;
+ const provider = createPiProvider({
+ provider: 'deepseek', apiKey: 'test',
+ customModel: buildDeepSeekModel(modelId),
+ onPayload: (payload, model, metadata) => {
+ wire = JSON.parse(JSON.stringify(repairDeepSeekPayload(payload)));
+ throw new Error('captured before network');
+ },
+ });
+ const request = {
+ model: modelId, sessionId: 'cache-contract', cacheRetention,
+ messages: [{ role: 'user' as const, content: [{ type: 'text' as const, text: 'hello' }] }],
+ };
+ if (mode === 'complete') {
+ await expect(provider.complete(request)).rejects.toThrow('captured before network');
+ } else {
+ const events = [];
+ for await (const event of provider.stream(request)) events.push(event);
+ expect(events.some(event => event.type === 'error')).toBe(true);
+ }
+ expect(wire).toMatchObject({ model: modelId, stream: true });
+ expect(wire).not.toHaveProperty('prompt_cache_key');
+ expect(wire).not.toHaveProperty('prompt_cache_retention');
+ expect(wire).not.toHaveProperty('prompt_cache_options');
+ }
+ }
+ });
+});
+
+
+ it('preserves explicit effort across mixed history while repairing orphan receipts', () => {
+ const plainPayload = {
+ thinking: { type: 'enabled' },
+ reasoning_effort: 'low',
+ messages: [
+ { role: 'assistant', content: 'plain assistant message' },
+ { role: 'tool', tool_call_id: 'lost_call', content: 'tool output' },
+ ],
+ };
+ const mixedPayload = {
+ thinking: { type: 'enabled' },
+ reasoning_effort: 'medium',
+ messages: [
+ { role: 'assistant', content: 'reasoned answer', reasoning_content: 'reasoning' },
+ { role: 'assistant', content: 'plain fallback answer' },
+ { role: 'user', content: 'continue' },
+ ],
+ };
+
+ const repaired = repairDeepSeekPayload(plainPayload) as Record<string, unknown>;
+ const mixed = repairDeepSeekPayload(mixedPayload) as Record<string, unknown>;
+
+ expect(repaired.reasoning_effort).toBe('low');
+ expect(repaired.thinking).toEqual({ type: 'enabled' });
+ expect((repaired.messages as Array<Record<string, unknown>>)[1]).toMatchObject({
+ role: 'user',
+ content: expect.stringContaining('tool output'),
+ });
+ expect(mixed.reasoning_effort).toBe('medium');
+ expect(mixed.thinking).toEqual({ type: 'enabled' });
+ });
diff --git a/test/main/model/core-agent/official-model_e2e_compatibility.test.ts b/test/main/model/core-agent/official-model_e2e_compatibility.test.ts
new file mode 100644
index 00000000..e4394bec
--- /dev/null
+++ b/test/main/model/core-agent/official-model_e2e_compatibility.test.ts
@@ -0,0 +1,68 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { CompletionParams, LLMProvider, StreamEvent } from '#core-agent';
+import { createDeepSeekProvider, createCustomOpenAICompatibleProvider } from '../../../../src/main/model/core-agent/external-providers';
+import { _clearAll } from '../../../../src/main/model/core-agent/profile-cooldown';
+
+// Keep the SDK and public provider factories real; only HTTP is synthetic.
+const host = vi.hoisted(() => ({
+ refresh: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn(),
+}));
+vi.mock('../../../../src/main/logger', () => ({ createLogger: () => ({
+ info: host.info, warn: host.warn, error: host.error, debug: vi.fn(),
+}) }));
+
+async function invoke(provider: LLMProvider, mode: 'stream' | 'complete', params: CompletionParams) {
+ if (mode === 'complete') return provider.complete(params);
+ const events: StreamEvent[] = [];
+ for await (const event of provider.stream(params)) {
+ if (event.type === 'error') throw event.error;
+ events.push(event);
+ }
+ expect(events.filter(e => e.type === 'message_end')).toHaveLength(1);
+ return events.find(e => e.type === 'message_end');
+}
+beforeEach(() => { vi.clearAllMocks(); _clearAll(); });
+afterEach(() => {
+ try { expect(host.error).not.toHaveBeenCalled(); }
+ finally { vi.unstubAllGlobals(); vi.restoreAllMocks(); _clearAll(); }
+});
+
+it.each(['complete', 'stream'] as const)('preserves DeepSeek thinking choices through configured factories and %s SDK requests', async mode => {
+ const wire: any[] = [];
+ vi.stubGlobal('fetch', vi.fn(async (_url, init) => {
+ wire.push(JSON.parse(init.body));
+ return new Response('data: {"choices":[{"index":0,"delta":{"role":"assistant","content":"Saved record 42."},"finish_reason":"stop"}]}\n\ndata: [DONE]\n\n',
+ { headers: { 'content-type': 'text/event-stream' } });
+ }));
+ const messages: CompletionParams['messages'] = [
+ { role: 'assistant', content: [
+ { type: 'thinking', thinking: '', thinkingSignature: '{"type":"reasoning","encrypted_content":"foreign-private-state"}' },
+ { type: 'tool_use', id: 'call_save|fc_save', name: 'save_record', input: { value: 42 } },
+ ] },
+ { role: 'user', content: [{ type: 'tool_result', toolUseId: 'call_save|fc_save', content: 'saved-record-42' }] },
+ ];
+ const original = JSON.stringify(messages);
+ for (const provider of [
+ await createDeepSeekProvider({ apiKey: 'fixture', modelId: 'deepseek-flash' }),
+ await createCustomOpenAICompatibleProvider({ apiKey: 'fixture', modelId: 'deepseek-flash',
+ baseUrl: 'https://api.deepseek.com/v1', supportsReasoning: true, reasoningEffort: 'high', contextWindow: 128000, maxTokens: 4096 }),
+ ]) {
+ for (const reasoning of ['high', 'off'] as const) {
+ const result = await invoke(provider, mode, { messages, reasoning });
+ expect(result?.content).toContainEqual(expect.objectContaining({ type: 'text', text: 'Saved record 42.' }));
+ const sent = wire.at(-1);
+ const assistant = sent.messages.find((m: any) => m.tool_calls);
+ expect(assistant.reasoning_content).toBe(reasoning === 'high' ? '.' : '');
+ expect(sent.thinking).toEqual({ type: reasoning === 'high' ? 'enabled' : 'disabled' });
+ if (reasoning === 'high') expect(sent.reasoning_effort).toBe('high');
+ expect(sent.messages.find((m: any) => m.role === 'tool')).toMatchObject({
+ tool_call_id: assistant.tool_calls[0].id, content: 'saved-record-42',
+ });
+ expect(JSON.stringify(sent)).not.toContain('foreign-private-state');
+ expect(JSON.stringify(messages)).toBe(original);
+ }
+ }
+ expect(wire).toHaveLength(4);
+ expect(host.warn).not.toHaveBeenCalled();
+});
+
diff --git a/test/main/model/core-agent/rotating-provider.test.ts b/test/main/model/core-agent/rotating-provider.test.ts
index 260aaaba..afd72b69 100644
--- a/test/main/model/core-agent/rotating-provider.test.ts
+++ b/test/main/model/core-agent/rotating-provider.test.ts
@@ -1,4 +1,4 @@
-import { describe, it, expect, beforeEach } from 'vitest';
+import { describe, it, expect, beforeEach, vi } from 'vitest';
import { classifyTransientNetworkError } from '../../../../src/core-agent/src/shared/errors';
import {
@@ -10,9 +10,11 @@ import {
type RotatingCandidate,
} from '../../../../src/main/model/core-agent/rotating-provider';
import type { LLMProvider, StreamEvent, CompletionParams, CompletionResult } from '#core-agent';
-import { AgentRunner, createConfig, defineTool, ProviderError, ProviderRegistry } from '#core-agent';
+import { createPiProvider, AgentRunner, createConfig, defineTool, ProviderError, ProviderRegistry } from '#core-agent';
import { _clearAll, getCooldown } from '../../../../src/main/model/core-agent/profile-cooldown';
+import { normalizeElectronNetFetchError } from '../../../../src/main/util/proxy-dispatcher';
+
// ── Fake LLMProvider factory ────────────────────────────────────────────
interface FakeBehavior {
@@ -395,7 +397,7 @@ describe('rotating-provider › rotatable stream failures', () => {
});
it('treats a 429 insufficient-quota response as balance exhaustion without a network retry', async () => {
- const quotaErr = Object.assign(new Error('429 {"error":{"message":"insufficient quota","type":"insufficient_quota"}}'), { status: 429 });
+ const quotaErr = Object.assign(new Error('429 {"error":{"message":"insufficient quota","type":"insufficient_quota"}}'), { status: 429, code: 'insufficient_quota' });
const p = createRotatingProvider({
providerId: 'test',
networkRetryDelayMs: () => 0,
@@ -460,7 +462,7 @@ describe('rotating-provider › rotatable stream failures', () => {
});
it('retries a fetch failure three times before moving to the next candidate', async () => {
- const netErr = new TypeError('fetch failed');
+ const netErr = Object.assign(new TypeError('fetch failed'), { code: 'ECONNRESET' });
let p1Builds = 0;
let p2Builds = 0;
const p = createRotatingProvider({
@@ -537,7 +539,7 @@ describe('rotating-provider › rotatable stream failures', () => {
});
it('does not refresh the same-candidate retry budget during an AgentRunner recovery attempt', async () => {
- const netErr = new TypeError('fetch failed');
+ const netErr = Object.assign(new TypeError('fetch failed'), { code: 'ECONNRESET' });
let primaryBuilds = 0;
let fallbackBuilds = 0;
const p = createRotatingProvider({
@@ -762,7 +764,7 @@ describe('rotating-provider › non-rotatable stream failures', () => {
expect(getCooldown('p1')).toBeUndefined();
});
- it('Server retry policy can blacklist otherwise retryable pre-content errors', async () => {
+ it('legacy Server message patterns cannot suppress structured transient recovery', async () => {
const users = await import('../../../../src/main/features/users');
const paths = await import('../../../../src/main/paths');
const storage = await import('../../../../src/main/storage');
@@ -788,7 +790,7 @@ describe('rotating-provider › non-rotatable stream failures', () => {
providerId: 'test',
networkRetryDelayMs: () => 0,
candidates: [
- candidate('p1', { throwBefore: new Error('custom_non_retryable') }),
+ candidate('p1', { throwBefore: Object.assign(new Error('custom_non_retryable'), { status: 503 }) }),
{
profileId: 'p2',
providerId: 'test',
@@ -800,8 +802,10 @@ describe('rotating-provider › non-rotatable stream failures', () => {
},
],
});
- await expect(collect(p.stream(PARAMS))).rejects.toThrow(/custom_non_retryable/);
- expect(p2Called).toBe(false);
+ const events = await collect(p.stream(PARAMS));
+ expect(events.filter(event => event.type === 'retry')).toHaveLength(3);
+ expect(events.at(-1)).toMatchObject({ type: 'text_delta', text: 'ok' });
+ expect(p2Called).toBe(true);
expect(getCooldown('p1')).toBeUndefined();
} finally {
fs.rmSync(path.dirname(file), { recursive: true, force: true });
@@ -1381,7 +1385,7 @@ describe('rotating-provider › exhausted stream candidates', () => {
});
it('retries each network-failing candidate and surfaces a stable exhausted error without cooldown', async () => {
- const netErr = new TypeError('fetch failed');
+ const netErr = Object.assign(new TypeError('fetch failed'), { code: 'ECONNRESET' });
let p1Builds = 0;
let p2Builds = 0;
const p = createRotatingProvider({
@@ -1732,7 +1736,7 @@ describe('rotating-provider › complete calls and per-call stream policy', () =
});
it('complete does not refresh its retry budget during an AgentRunner recovery attempt', async () => {
- const netErr = new TypeError('fetch failed');
+ const netErr = Object.assign(new TypeError('fetch failed'), { code: 'ECONNRESET' });
let primaryBuilds = 0;
let fallbackBuilds = 0;
const p = createRotatingProvider({
@@ -1857,7 +1861,7 @@ describe('rotating-provider › complete calls and per-call stream policy', () =
completionCalls += 1;
if (completionCalls === 1) {
firstAttemptFailed.resolve();
- throw new TypeError('fetch failed');
+ throw Object.assign(new TypeError('fetch failed'), { code: 'ECONNRESET' });
}
return { content: [], stopReason: 'end_turn' } as any;
},
@@ -2013,7 +2017,7 @@ it('latches a network-exhausted candidate out of later model rounds once a fallb
// candidate-specific way (e.g. its fetch path ignores the proxy) re-pays
// the full timeout/retry ladder on every remaining round of the turn
// before reaching the fallback that actually serves the reply.
- const netErr = new TypeError('fetch failed');
+ const netErr = Object.assign(new TypeError('fetch failed'), { code: 'ECONNRESET' });
let p1Builds = 0;
let p2Builds = 0;
const p = createRotatingProvider({
@@ -2058,7 +2062,7 @@ it('does not latch anything when every candidate fails network-class, so recover
// this provider instance and swallows the exhausted error, so a transient
// machine-local outage must leave the next call free to retry every
// candidate. Only a sweep where a later candidate commits may latch.
- const netErr = new TypeError('fetch failed');
+ const netErr = Object.assign(new TypeError('fetch failed'), { code: 'ECONNRESET' });
let p1Builds = 0;
let p2Builds = 0;
let blip = true;
@@ -2173,7 +2177,7 @@ it('complete() latches a network-exhausted candidate after a fallback succeeds,
// Equivalent-path invariant with stream(): auxiliary complete() callers
// repeat within one run too, and must not re-pay a dead candidate's
// retry ladder once a fallback has proven the failure candidate-specific.
- const netErr = new TypeError('fetch failed');
+ const netErr = Object.assign(new TypeError('fetch failed'), { code: 'ECONNRESET' });
let p1Builds = 0;
let p2Builds = 0;
const okResult = { content: [{ type: 'text', text: 'ok' }], stopReason: 'end_turn', usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 }, model: 'test' };
@@ -2230,3 +2234,172 @@ it('applies image limits to native tool-result images without mutating their rec
expect(JSON.stringify(boundMessagesForImageLimit(messages, 0))).not.toContain('"data"');
expect(messages).toEqual(before);
});
+
+describe('structured HTTP retry policy through the real SDK', () => {
+ it.each(['Upstream access forbidden, please contact administrator', 'invalid_request', '服务暂时不可用', ''])
+ ('recovers a 502 with the same bounded candidate sequence regardless of message: %s', async message => {
+ _clearAll();
+ const requests: string[] = [];
+ const warning = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const fetchStub = vi.fn(async (input: string | URL | Request) => {
+ const endpoint = String(input);
+ requests.push(endpoint.includes('primary.invalid') ? 'primary' : 'fallback');
+ if (endpoint.includes('primary.invalid')) return new Response(JSON.stringify({
+ error: { type: 'upstream_error', message },
+ }), { status: 502, headers: { 'content-type': 'application/json' } });
+ return new Response('data: ' + JSON.stringify({ choices: [{ index: 0, delta: { content: 'recovered' }, finish_reason: 'stop' }] }) + '\n\ndata: [DONE]\n\n', {
+ headers: { 'content-type': 'text/event-stream' },
+ });
+ });
+ vi.stubGlobal('fetch', fetchStub);
+ try {
+ const provider = createRotatingProvider({
+ providerId: 'custom', networkRetryDelayMs: () => 0,
+ candidates: ['primary', 'fallback'].map(name => ({
+ profileId: name, providerId: 'custom', modelId: 'fixture',
+ build: async () => createPiProvider({ provider: 'custom', apiKey: 'fixture', customModel: {
+ id: 'fixture', name: 'fixture', provider: 'custom', api: 'openai-completions',
+ baseUrl: `https://${name}.invalid/v1`, reasoning: false, input: ['text'],
+ contextWindow: 128000, maxTokens: 4096,
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
+ } }),
+ })),
+ });
+ const events = await collect(provider.stream({ ...PARAMS, model: 'fixture' }));
+ expect(requests).toEqual(['primary', 'primary', 'primary', 'primary', 'fallback']);
+ expect(events.filter(event => event.type === 'retry')).toHaveLength(3);
+ expect(events.some(event => event.type === 'text_delta' && event.text === 'recovered')).toBe(true);
+ expect(events.filter(event => event.type === 'message_end')).toHaveLength(1);
+ expect(getCooldown('primary')).toBeUndefined();
+ expect(getCooldown('fallback')).toBeUndefined();
+ // Expected HTTP failures are redacted diagnostic facts, never body text.
+ expect(warning.mock.calls).toHaveLength(4);
+ expect(JSON.stringify(warning.mock.calls)).not.toContain('administrator');
+ } finally { vi.unstubAllGlobals(); warning.mockRestore(); }
+ });
+});
+
+// Real SDK flattening must not turn an explicit rejection into network retries.
+describe('structured stream rejection through the real SDK', () => {
+ it.each(['complete', 'stream'] as const)('stops rejected requests and retains transient recovery in %s', async method => {
+ const warning = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ try {
+ for (const api of ['openai-responses', 'openai-completions'] as const) {
+ for (const status of [400, 503]) {
+ _clearAll();
+ const requests: string[] = [];
+ vi.stubGlobal('fetch', vi.fn(async (_input, init) => {
+ requests.push(String(init?.body));
+ const error = { code: status === 400 ? 'invalid_request_error' : 'upstream_error', status,
+ message: 'Synthetic diagnostic including misleading 401 invalid_api_key' };
+ const body = api === 'openai-responses'
+ ? 'event: error\ndata: ' + JSON.stringify({ ...error, type: 'error' }) + '\n\n'
+ : 'data: ' + JSON.stringify({ error }) + '\n\ndata: [DONE]\n\n';
+ return new Response(body, { headers: { 'content-type': 'text/event-stream' } });
+ }));
+ const provider = createRotatingProvider({
+ providerId: 'custom', networkRetryDelayMs: () => 0,
+ candidates: [{ profileId: 'stream-rejection', providerId: 'custom', modelId: 'fixture',
+ build: async () => createPiProvider({ provider: 'custom', apiKey: 'fixture', customModel: {
+ id: 'fixture', name: 'fixture', api, provider: 'custom', baseUrl: 'https://fixture.invalid/v1',
+ reasoning: false, input: ['text'], contextWindow: 128000, maxTokens: 4096,
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
+ } }),
+ }],
+ });
+ if (method === 'complete') await expect(provider.complete({ ...PARAMS, model: 'fixture' })).rejects.toThrow();
+ else {
+ const events: any[] = [];
+ const run = async () => { for await (const event of provider.stream({ ...PARAMS, model: 'fixture' })) events.push(event); };
+ await expect(run()).rejects.toThrow();
+ expect(events.filter(event => event.type === 'message_end')).toHaveLength(0);
+ expect(events.filter(event => event.type === 'retry')).toHaveLength(status === 400 ? 0 : 3);
+ }
+ expect(requests).toHaveLength(status === 400 ? 1 : 4);
+ expect(new Set(requests).size).toBe(1);
+ expect(getCooldown('stream-rejection')).toBeUndefined();
+ }
+ }
+ expect(warning.mock.calls.length).toBeGreaterThan(0);
+ expect(JSON.stringify(warning.mock.calls)).not.toContain('misleading');
+ } finally { vi.unstubAllGlobals(); warning.mockRestore(); _clearAll(); }
+ });
+});
+
+it('continues a real SDK tool round on a configured fallback without foreign ciphertext or a duplicate write', async () => {
+ _clearAll();
+ const wire: any[] = [];
+ let writes = 0;
+ const sse = (items: any[]) => {
+ const events: any[] = items.flatMap((item, output_index) => [
+ { type: 'response.output_item.added', output_index, item },
+ { type: 'response.output_item.done', output_index, item },
+ ]);
+ events.push({ type: 'response.completed', response: { id: 'resp_fixture', status: 'completed', output: items,
+ usage: { input_tokens: 10, output_tokens: 2, total_tokens: 12 } } });
+ return new Response(events.map(event => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`).join(''),
+ { headers: { 'content-type': 'text/event-stream' } });
+ };
+ const fetch = vi.fn(async (_url: unknown, init: any) => {
+ const payload = JSON.parse(init.body);
+ wire.push(payload);
+ if (wire.length === 1) return sse([
+ { type: 'reasoning', id: 'rs_fixture', status: 'completed', summary: [], encrypted_content: 'source-private-state' },
+ { type: 'function_call', id: 'fc_fixture', call_id: 'call_fixture', name: 'write_once', arguments: '{}' },
+ ]);
+ if (wire.length === 2) return new Response('{"error":{"type":"authentication_error","code":"invalid_api_key"}}',
+ { status: 401, headers: { 'content-type': 'application/json' } });
+ expect(payload.model).toBe('model-b');
+ expect(payload.input.some((i: any) => i.type === 'reasoning')).toBe(false);
+ expect(payload.input.filter((i: any) => i.type === 'function_call_output')).toEqual([
+ { type: 'function_call_output', call_id: 'call_fixture', output: 'saved-record-42' },
+ ]);
+ return sse([{ type: 'message', id: 'msg_fixture', role: 'assistant', status: 'completed',
+ content: [{ type: 'output_text', text: 'Saved once.', annotations: [] }] }]);
+ });
+ const originalFetch = globalThis.fetch;
+ globalThis.fetch = fetch;
+ try {
+ const rotating = createRotatingProvider({ providerId: 'mock', candidates: ['a', 'b'].map(id => ({
+ profileId: `replay-${id}`, providerId: 'openai', modelId: `model-${id}`,
+ build: async () => createPiProvider({ provider: 'openai', apiKey: `key-${id}`, customModel: {
+ api: 'openai-responses', provider: 'openai', id: `model-${id}`, name: 'fixture',
+ baseUrl: `https://${id}.invalid/v1`, reasoning: true, input: ['text'],
+ contextWindow: 128000, maxTokens: 1000, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
+ } }),
+ })) });
+ const registry = new ProviderRegistry();
+ registry.registerFactory('mock', () => rotating);
+ const runner = new AgentRunner({
+ config: createConfig({ agent: { defaultProvider: 'mock', defaultModel: 'model-a' } }),
+ providers: registry, evolution: { enabled: false },
+ tools: [defineTool({ name: 'write_once', description: 'Save fixture',
+ inputSchema: { type: 'object', properties: {} },
+ async execute() { writes++; return { content: 'saved-record-42' }; },
+ })],
+ });
+ const result = await runner.run({ message: 'Save the record and report the result.' });
+ expect(result.text).toBe('Saved once.');
+ expect(writes).toBe(1);
+ expect(fetch).toHaveBeenCalledTimes(3);
+ expect(wire[1].input.find((i: any) => i.type === 'reasoning')).toEqual({
+ type: 'reasoning', id: 'rs_fixture', summary: [], encrypted_content: 'source-private-state',
+ });
+ } finally { globalThis.fetch = originalFetch; _clearAll(); }
+});
+
+ it('reports a message-only Electron proxy outage as network exhaustion', async () => {
+ const transportError = normalizeElectronNetFetchError(new Error('net::ERR_PROXY_CONNECTION_FAILED'));
+ const p = createRotatingProvider({
+ providerId: 'test',
+ networkRetryDelayMs: () => 0,
+ networkRetryAttempts: 1,
+ candidates: [candidate('p1', { throwBefore: transportError })],
+ });
+
+ await expect(collect(p.stream(PARAMS))).rejects.toMatchObject({
+ code: 'PROVIDER_NETWORK_EXHAUSTED',
+ cause: transportError,
+ });
+ expect(getCooldown('p1')).toBeUndefined();
+ });
diff --git a/test/main/model/native-search_e2e_provider.test.ts b/test/main/model/native-search_e2e_provider.test.ts
index 66f08593..647380ae 100644
--- a/test/main/model/native-search_e2e_provider.test.ts
+++ b/test/main/model/native-search_e2e_provider.test.ts
@@ -1,3 +1,4 @@
+import { replayOrigin } from "../../../src/core-agent/src/providers/replay-compatibility";
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
@@ -31,7 +32,7 @@ describe('native search through the production payload hook and real SDK', () =>
const provider = createPiProvider({ provider: providerId, apiKey: fakeToken,
customModel: { id, name: id, api, provider: providerId, baseUrl: 'https://example.invalid',
reasoning: true, input: ['text'], cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
- contextWindow: 272000, maxTokens: 128000, compat: { supportsToolSearch: true, supportsAdditionalTools } },
+ contextWindow: 272000, maxTokens: 128000, compat: { supportsToolSearch: true, supportsAdditionalTools, supportsMidConvoSystemMessages: true, supportsMidConvoToolAdditions: true } },
onPayload: (payload, model) => {
raw = structuredClone(payload);
sent = hook(payload, model);
@@ -350,6 +351,7 @@ describe('Google server tool context through the SDK and durable session', () =>
expect(JSON.stringify(body)).toContain('https://example.org/release');
for (const partsJson of ['invalid-json', 'x'.repeat(2000001)]) {
const messages: any[] = [{ role: 'assistant', content: [{ type: 'text', text: 'Previous answer',
+ replayOrigin: replayOrigin({ api: 'google-generative-ai', provider: 'google', id: 'gemini-3.8-flash', baseUrl: 'https://example.invalid/v1beta' }, 'fixture-key'),
googleNativeReplay: { api: 'google-generative-ai', provider: 'google', model: 'gemini-3.8-flash', partsJson } }] }];
await expect(provider.complete({ model: 'gemini-3.8-flash', tools: definitions, messages })).rejects.toThrow('Invalid Google tool context');
}
diff --git a/test/main/model/provider_catalog.test.ts b/test/main/model/provider_catalog.test.ts
index e05c3936..435eea36 100644
--- a/test/main/model/provider_catalog.test.ts
+++ b/test/main/model/provider_catalog.test.ts
@@ -151,19 +151,11 @@ describe('provider_catalog › CURATED_MODELS', () => {
});
it('exposes GPT-6 and the current GPT-5.6 family for OpenAI and OpenAI Codex', () => {
- const expected = ['gpt-6-astra', 'gpt-5.6-sol', 'gpt-5.6-terra', 'gpt-5.6-luna'];
+ const expected = ['gpt-6-astra', 'gpt-6.1-sol', 'gpt-6-sol', 'gpt-6-luna', 'gpt-5.6-sol', 'gpt-5.6-terra', 'gpt-5.6-luna'];
expect((CURATED_MODELS.openai || []).map((m) => m.id)).toEqual(expected);
expect((CURATED_MODELS['openai-codex'] || []).map((m) => m.id)).toEqual(expected);
});
- it('natively resolves the GPT-5.6 family and retained 5.5/5.4 generations', () => {
- const expected = ['gpt-5.6-sol', 'gpt-5.6-terra', 'gpt-5.6-luna', 'gpt-5.5', 'gpt-5.4'];
- for (const provider of ['openai', 'openai-codex'] as const) {
- for (const modelId of expected) {
- expect(getBuiltinModel(provider, modelId)).toBeDefined();
- }
- }
- });
it('openrouter catalog includes DeepSeek / Qwen / GLM / Kimi / MiniMax', () => {
const ids = (CURATED_MODELS.openrouter || []).map((m) => m.id);
@@ -181,9 +173,11 @@ describe('provider_catalog › CURATED_MODELS', () => {
.map((m) => m.id)
.filter((id) => id.includes('/claude-'));
expect(claudeIds).toEqual([
+ 'anthropic/claude-opus-5.5',
'anthropic/claude-opus-5',
'anthropic/claude-fable-5.1',
'anthropic/claude-fable-5',
+ 'anthropic/claude-sonnet-5.5',
'anthropic/claude-sonnet-5',
]);
});
@@ -194,6 +188,9 @@ describe('provider_catalog › CURATED_MODELS', () => {
.filter((id) => id.startsWith('openai/gpt-'));
expect(ids).toEqual([
'openai/gpt-6-astra',
+ 'openai/gpt-6.1-sol',
+ 'openai/gpt-6-sol',
+ 'openai/gpt-6-luna',
'openai/gpt-5.6-sol',
'openai/gpt-5.6-terra',
'openai/gpt-5.6-luna',
@@ -592,3 +589,59 @@ describe('provider_catalog › pickLatestGenerations (fallback)', () => {
expect(pickLatestGenerations(null as any, 2)).toEqual([]);
});
});
+
+ it('natively resolves GPT-6 tiers and every retained GPT-5.6 tier', () => {
+ const expected = ['gpt-6-astra', 'gpt-6.1-sol', 'gpt-6-sol', 'gpt-6-luna', 'gpt-5.6-sol', 'gpt-5.6-terra', 'gpt-5.6-luna'];
+ expect((CURATED_MODELS.openai || []).map((m) => m.id)).toEqual(expected);
+ expect((CURATED_MODELS['openai-codex'] || []).map((m) => m.id)).toEqual(expected);
+
+ for (const provider of ['openai', 'openai-codex'] as const) {
+ for (const modelId of expected) {
+ expect(getBuiltinModel(provider, modelId)).toBeDefined();
+ }
+ }
+
+ expect(getBuiltinModel('openai', 'gpt-6-astra')).toMatchObject({
+ id: 'gpt-6-astra',
+ provider: 'openai',
+ api: 'openai-responses',
+ reasoning: true,
+ input: ['text', 'image'],
+ maxTokens: 128_000,
+ thinkingLevelMap: { off: null, minimal: null, low: 'low', max: 'max' },
+ compat: { supportsExplicitPromptCacheMode: true },
+ });
+ expect(getBuiltinModel('openai-codex', 'gpt-6-astra')).toMatchObject({
+ id: 'gpt-6-astra',
+ provider: 'openai-codex',
+ api: 'openai-codex-responses',
+ reasoning: true,
+ input: ['text', 'image'],
+ maxTokens: 128_000,
+ });
+ for (const id of ['gpt-6-sol', 'gpt-6-luna']) {
+ expect(getBuiltinModel('openai', id)).toMatchObject({
+ id, api: 'openai-responses', contextWindow: 272_000, maxTokens: 128_000,
+ });
+ expect(getBuiltinModel('openai-codex', id)).toMatchObject({
+ id, api: 'openai-codex-responses', contextWindow: 272_000, maxTokens: 128_000,
+ });
+ }
+ });
+
+ it('inherits each GPT provider window from pi-ai while retaining output reservations', () => {
+ const catalog = { getPiModel: getBuiltinModel as any };
+ const ids = ['gpt-6-astra', 'gpt-6.1-sol', 'gpt-6-sol', 'gpt-6-luna', 'gpt-5.6-sol', 'gpt-5.6-terra', 'gpt-5.6-luna'];
+ for (const provider of ['openai', 'openai-codex', 'openrouter']) {
+ for (const id of ids) {
+ const modelId = provider === 'openrouter' ? `openai/${id}` : id;
+ const sdk = (getBuiltinModel as any)(provider, modelId);
+ const resolved = resolveConfiguredPiModel(catalog, provider, modelId);
+ expect(resolved?.model.contextWindow, `${provider}/${id}`).toBe(sdk.contextWindow);
+ expect(resolved?.model.maxTokens).toBe(
+ provider === 'openrouter' ? sdk.maxTokens : id === 'gpt-6-astra' ? 128_000 : 64_000,
+ );
+ expect(resolved?.needsCustomModel).toBe(true);
+ }
+ }
+ });
diff --git a/test/main/model/public_model_catalog.test.ts b/test/main/model/public_model_catalog.test.ts
index 619f1201..55e68fb7 100644
--- a/test/main/model/public_model_catalog.test.ts
+++ b/test/main/model/public_model_catalog.test.ts
@@ -25,8 +25,8 @@ describe('public model catalog', () => {
}
});
- it('keeps every variant in the curated current GPT generations', () => {
- const expected = ['gpt-6-astra', 'gpt-5.6-sol', 'gpt-5.6-terra', 'gpt-5.6-luna'];
+ it('offers GPT-6 tiers while retaining the GPT-5.6 selections', () => {
+ const expected = ['gpt-6-astra', 'gpt-6.1-sol', 'gpt-6-sol', 'gpt-6-luna', 'gpt-5.6-sol', 'gpt-5.6-terra', 'gpt-5.6-luna'];
expect(PUBLIC_PROVIDER_MODELS.openai?.map((model) => model.id)).toEqual(expected);
expect(PUBLIC_PROVIDER_MODELS['openai-codex']?.map((model) => model.id)).toEqual(expected);
expect(PUBLIC_PROVIDER_MODELS.openai?.every((model) => model.maxInputImages === 20)).toBe(true);
@@ -35,9 +35,11 @@ describe('public model catalog', () => {
it('tracks recent Anthropic models and the Gemini 3.1 Pro exception', () => {
expect(PUBLIC_PROVIDER_MODELS.anthropic?.map((model) => model.id)).toEqual([
+ 'claude-opus-5-5',
'claude-opus-5',
'claude-fable-5-1',
'claude-fable-5',
+ 'claude-sonnet-5-5',
'claude-sonnet-5',
]);
expect(PUBLIC_PROVIDER_MODELS.google?.map((model) => model.id)).toEqual([
@@ -99,11 +101,16 @@ describe('public model catalog', () => {
it('keeps the explicitly curated OpenRouter shortcut set', () => {
expect(PUBLIC_PROVIDER_MODELS.openrouter?.map((model) => model.id)).toEqual([
+ 'anthropic/claude-opus-5.5',
'anthropic/claude-opus-5',
'anthropic/claude-fable-5.1',
'anthropic/claude-fable-5',
+ 'anthropic/claude-sonnet-5.5',
'anthropic/claude-sonnet-5',
'openai/gpt-6-astra',
+ 'openai/gpt-6.1-sol',
+ 'openai/gpt-6-sol',
+ 'openai/gpt-6-luna',
'openai/gpt-5.6-sol',
'openai/gpt-5.6-terra',
'openai/gpt-5.6-luna',
@@ -140,7 +147,12 @@ describe('public model catalog', () => {
maxTokens: 128_000,
maxInputImages: 20,
});
- for (const model of PUBLIC_PROVIDER_MODELS[provider]?.slice(1, 4) || []) {
+ for (const model of PUBLIC_PROVIDER_MODELS[provider]?.filter((model) => /^gpt-6(?:\.1)?-(sol|luna)$/.test(model.id)) || []) {
+ expect(model.template).toBeUndefined();
+ expect(model.contextWindow).toBeUndefined();
+ expect(model.maxTokens).toBe(64_000);
+ }
+ for (const model of PUBLIC_PROVIDER_MODELS[provider]?.filter((model) => model.id.startsWith('gpt-5.6-')) || []) {
expect(model.template).toBe('gpt-5.5');
expect(model.contextWindow).toBeUndefined();
// 64K is the host's output reservation, not
diff --git a/test/renderer/connectors-degraded-card.test.ts b/test/renderer/connectors-degraded-card.test.ts
index ac0362a7..d1cd2b59 100644
--- a/test/renderer/connectors-degraded-card.test.ts
+++ b/test/renderer/connectors-degraded-card.test.ts
@@ -1,3 +1,4 @@
+import { composerAccessorSource } from './composer-test-source';
/**
* A connector that cannot reach its backend must never render as "已连接".
*
@@ -30,6 +31,13 @@ function makeElement(tag: string): any {
_html: '',
textContent: '',
title: '',
+ scrollIntoView: vi.fn(),
+ focus: vi.fn(),
+ classList: {
+ add: (name: string) => { el.className = [...new Set([...el.className.split(' ').filter(Boolean), name])].join(' '); },
+ remove: (name: string) => { el.className = el.className.split(' ').filter((item: string) => item !== name).join(' '); },
+ contains: (name: string) => el.className.split(' ').includes(name),
+ },
get innerHTML() { return el._html; },
set innerHTML(v: string) { el._html = v; },
appendChild: (c: any) => { el.children.push(c); return c; },
@@ -166,7 +174,7 @@ describe('connector setup assistance', () => {
expect(html.includes('connectors.action.authorize_permissions')).toBe(required);
expect(await ctx.window.openConnectorSetupById(entry.id)).toBe(true);
expect(ctx._runConnect).toHaveBeenCalledTimes(required ? 1 : 0);
- expect(ctx.window.focusConnectorById).toHaveBeenCalledTimes(required ? 0 : 1);
+ expect(ctx.window.focusConnectorById).toHaveBeenCalledExactlyOnceWith(entry.id);
});
it.each(['error', 'degraded'])('offers reauthorization from a %s CLI connection', kind => {
@@ -190,10 +198,16 @@ describe('connector setup assistance', () => {
}
for (const entry of [{ id: 'oauth', auth_mode: 'mcp_dcr' }, {
...complex, availability: 'visible_disabled',
- }, { ...complex, _custom: true }]) {
+ }]) {
expect(ctx._renderCatalogCard(entry, null).innerHTML).not.toContain('data-act="setup-assist"');
expect(ctx._connectorSetupMarkup(entry, [], 'en', 'setup')).not.toContain('data-act="setup-assist"');
}
+ // Custom cards are derived from installed instances, never catalog-only rows.
+ const custom = { ...complex, id: 'custom-fixture', _custom: true };
+ expect(ctx._renderCatalogCard(custom, {
+ id: custom.id, origin: 'custom', custom_auth_mode: 'none', status: { kind: 'disconnected' },
+ }).innerHTML).not.toContain('data-act="setup-assist"');
+ expect(ctx._connectorSetupMarkup(custom, [], 'en', 'setup')).not.toContain('data-act="setup-assist"');
expect(ctx._renderCatalogCard(complex, { status: { kind: 'connected' } }).innerHTML)
.not.toContain('data-act="setup-assist"');
expect(ctx._connectorSetupMarkup(complex, [], 'en', 'setup')).toContain('data-act="setup-assist"');
@@ -404,6 +418,7 @@ function loadConnectorsRenderer(
context.window.window = context.window;
context.window.globalThis = context.globalThis;
vm.createContext(context);
+ vm.runInContext(composerAccessorSource, context);
vm.runInContext(code, context, { filename: 'connectors.js' });
vm.runInContext(fs.readFileSync(path.join(__dirname, '../../src/renderer/modules/connector-action-dialog.js'), 'utf8'), context);
// `_connectorsState` is a top-level `let`, so it is NOT a property of the context object (only
@@ -483,6 +498,12 @@ function mountCategoryGrid(ctx: any) {
let onInput = () => {};
search.addEventListener = (_event: string, handler: () => void) => { onInput = handler; };
ctx.document.getElementById = (id: string) => elements.get(id) || null;
+ ctx.document.querySelectorAll = (selector: string) => {
+ const cards = ['connected', 'available'].flatMap(group => elements.get(`connectors-grid-${group}`).children);
+ if (selector === '.connector-card[data-id]') return cards;
+ if (selector === '.connector-card.is-highlighted') return cards.filter(card => card.classList.contains('is-highlighted'));
+ return [];
+ };
return {
elements,
categories: () => buttons.map(button => button.dataset.connectorsCat),
@@ -498,6 +519,102 @@ function mountCategoryGrid(ctx: any) {
}
describe('connector category browsing', () => {
+ it('reuses painted cards for repeated navigation in All without rebuilding the list or reloading data', async () => {
+ const invoke = vi.fn(async () => ({ ok: true }));
+ const ctx = loadConnectorsRenderer(invoke);
+ const grid = mountCategoryGrid(ctx);
+ ctx.__setCatalog([
+ { id: 'github', display_name: 'GitHub', category: 'developer' },
+ { id: 'notion', display_name: 'Notion', category: 'productivity' },
+ ]);
+ ctx._renderConnectorsGrid();
+ const cards = [...grid.elements.get('connectors-grid-available').children];
+ const createElement = vi.spyOn(ctx.document, 'createElement');
+ for (const id of ['notion', 'github', 'notion']) {
+ expect(await ctx.window.focusConnectorById(id)).toBe(true);
+ const card = cards.find(item => item.dataset.id === id);
+ expect(card.classList.contains('is-highlighted')).toBe(true);
+ expect(card.scrollIntoView).toHaveBeenCalledWith({ block: 'center', behavior: 'instant' });
+ expect(card.focus).toHaveBeenCalledWith({ preventScroll: true });
+ expect(ctx.document.querySelectorAll('.connector-card.is-highlighted')).toEqual([card]);
+ }
+ ctx.__advanceTimers(2500);
+ expect(ctx.document.querySelectorAll('.connector-card.is-highlighted')).toEqual([]);
+ expect(createElement).not.toHaveBeenCalled();
+ expect(invoke).not.toHaveBeenCalled();
+ expect(grid.elements.get('connectors-grid-available').children[0]).toBe(cards[0]);
+ });
+
+ it('reveals and highlights a filtered setup target before OAuth, including the launch repaint', async () => {
+ let ctx: any;
+ let grid: ReturnType<typeof mountCategoryGrid>;
+ let revealed: any;
+ const invoke = vi.fn(async (channel: string) => {
+ if (channel === 'connectors.start_oauth') {
+ const card = grid.elements.get('connectors-grid-available').children.find((item: any) => item.dataset.id === 'notion');
+ expect(card.classList.contains('is-highlighted')).toBe(true);
+ expect(revealed.scrollIntoView).toHaveBeenCalledWith({ block: 'center', behavior: 'instant' });
+ return { ok: true, started: true, attempt_id: 'revealed-target' };
+ }
+ return { ok: true };
+ });
+ ctx = loadConnectorsRenderer(invoke);
+ grid = mountCategoryGrid(ctx);
+ ctx.__setCatalog([
+ { id: 'github', display_name: 'GitHub', category: 'developer' },
+ { id: 'notion', display_name: 'Notion', category: 'productivity', auth_mode: 'mcp_dcr' },
+ ]);
+ ctx.loadConnectors = vi.fn(async () => {});
+ ctx._renderConnectorsGrid();
+ grid.search('github');
+ grid.click('rnd');
+ ctx.document.createElement = (tag: string) => {
+ const card = makeElement(tag);
+ card.scrollIntoView = vi.fn(() => { revealed = card; });
+ return card;
+ };
+
+ expect(await ctx.window.openConnectorSetupById('notion')).toBe(true);
+ expect(grid.elements.get('connectors-search-input').value).toBe('');
+ expect(grid.active()).toBe('');
+ expect(revealed.focus).toHaveBeenCalledWith({ preventScroll: true });
+ expect(invoke).toHaveBeenCalledExactlyOnceWith('connectors.start_oauth', { catalog_id: 'notion' });
+ expect(ctx.__alerts).toEqual([]);
+ ctx.__advanceTimers(2000);
+ expect(ctx.document.querySelectorAll('.connector-card.is-highlighted').map((card: any) => card.dataset.id)).toEqual(['notion']);
+ ctx.__advanceTimers(500);
+ expect(ctx.document.querySelectorAll('.connector-card.is-highlighted')).toEqual([]);
+ ctx._renderConnectorsGrid();
+ expect(ctx.document.querySelectorAll('.connector-card.is-highlighted')).toEqual([]);
+ });
+
+ it('locates visible parent and bundle cards, and gives only the latest target a full highlight interval', async () => {
+ const ctx = loadConnectorsRenderer();
+ mountCategoryGrid(ctx);
+ ctx.__setCatalog([
+ { id: 'feishu', display_name: 'Lark' },
+ { id: 'lark', catalog_parent_id: 'feishu' },
+ { id: 'workspace', display_name: 'Workspace', bundle_member_ids: ['sheet'] },
+ { id: 'sheet', display_name: 'Sheet' },
+ ]);
+ ctx._renderConnectorsGrid();
+ const highlighted = () => ctx.document.querySelectorAll('.connector-card.is-highlighted').map((card: any) => card.dataset.id);
+ expect(await ctx.window.focusConnectorById('lark')).toBe(true);
+ expect(highlighted()).toEqual(['feishu']);
+ ctx.__advanceTimers(2000);
+ expect(await ctx.window.focusConnectorById('sheet')).toBe(true);
+ expect(highlighted()).toEqual(['workspace']);
+ ctx.__advanceTimers(500);
+ expect(highlighted()).toEqual(['workspace']);
+ ctx.__setInstances([{ id: 'sheet', status: { kind: 'connected' } }]);
+ ctx._renderConnectorsGrid();
+ expect(highlighted()).toEqual(['workspace']);
+ ctx.__advanceTimers(2000);
+ expect(highlighted()).toEqual([]);
+ expect(await ctx.window.focusConnectorById('missing')).toBe(false);
+ expect(highlighted()).toEqual([]);
+ });
+
it('makes every newly added OAuth service discoverable in exactly one category matching its purpose', async () => {
const { COMPOSIO_MANAGED_ENTRIES } = await import('../../src/main/features/connectors/catalog-managed');
// Purpose-based acceptance inventory for the 69-service expansion. Keep this independent
@@ -756,7 +873,7 @@ describe('connectors panel — degraded cards never claim 已连接', () => {
if (channel === 'connectors.list') return { ok: true, instances: [] };
return { ok: true };
});
- const card = { dataset: { id: 'github' }, setAttribute() {}, scrollIntoView() {}, focus() {} };
+ const card = { ...makeElement('div'), dataset: { id: 'github' } };
ctx.document.querySelectorAll = (selector: string) => (selector === '.connector-card[data-id]' ? [card] : []);
// Cold state: the first focus request has to load (and is held at the gate).
@@ -841,6 +958,25 @@ describe('connectors panel — degraded cards never claim 已连接', () => {
}
});
+ it('uses renderer-only descriptions while retaining regional tags and shared guidance fallback', () => {
+ const ctx = loadConnectorsRenderer();
+ const entry = { id: 'sample', description_en: 'English', description_ja: '日本語',
+ 'description_zh-tw': '繁體中文', 'description_pt-pt': 'Portugal', 'description_es-419': 'Latinoamérica',
+ instructions_en: 'Shared setup guidance' };
+ ctx.t = (key: string) => key;
+ for (const [lang, expected] of [['ja-JP', '日本語'], ['zh-TW', '繁體中文'], ['pt_PT', 'Portugal'], ['es-419', 'Latinoamérica']]) {
+ expect(ctx._connectorCopy(entry, 'description', lang)).toBe(expected);
+ }
+ ctx.getLang = () => 'vi';
+ ctx.t = (key: string) => key === 'connectors.catalog.sample.description' ? 'Mô tả' : key;
+ expect(ctx._connectorCopy(entry, 'description')).toBe('Mô tả');
+ expect(ctx._connectorCopy(entry, 'instructions')).toBe('Shared setup guidance');
+ expect(ctx._connectorCopy(entry, 'description', 'ja-JP')).toBe('日本語');
+ expect(ctx._connectorCopy({ ...entry, _custom: true }, 'description')).toBe('English');
+ expect(ctx._connectorCopy({ id: 'remote', description_en: 'Remote English' }, 'description')).toBe('Remote English');
+ expect(ctx._connectorCopy(null, 'description')).toBe('');
+ });
+
it('shows the detailed authorization result once without sending provider text to telemetry', () => {
const ctx = loadConnectorsRenderer();
const table = JSON.parse(fs.readFileSync(path.join(__dirname, '../../src/renderer/locales/zh.json'), 'utf8'));
@@ -1026,7 +1162,7 @@ describe('connectors panel — degraded cards never claim 已连接', () => {
const message = ctx._connectorActionMessage(info);
const details = ctx._connectorActionDetails(info);
- expect(message).toBe('connectors.action_confirm.connector: Shop\nconnectors.action_confirm.action: SHOP_DELETE_ORDER');
+ expect(message).toBe('connectors.action_confirm.connector: Shop\nconnectors.action_confirm.account: Store A\nconnectors.action_confirm.action: SHOP_DELETE_ORDER');
expect(details).toBe('{"order_id":"private-order-1"}');
});
@@ -1730,6 +1866,10 @@ describe('connectors panel — degraded cards never claim 已连接', () => {
expect(ctx._connectorMatchesSearch(workspace, query), query).toBe(true);
}
expect(ctx._connectorMatchesSearch(workspace, 'shopify')).toBe(false);
+ ctx.getLang = () => 'vi';
+ ctx.t = (key: string) => key === 'connectors.catalog.gmail.description' ? 'Đọc và gửi thư' : key;
+ expect(ctx._connectorMatchesSearch(gmail, 'gửi thư')).toBe(true);
+ expect(ctx._connectorMatchesSearch(workspace, 'gửi thư')).toBe(true);
});
it('filters the visible groups as the connector search input changes', () => {
diff --git a/test/renderer/connectors-render-cache.test.ts b/test/renderer/connectors-render-cache.test.ts
index 6557be96..14a6f171 100644
--- a/test/renderer/connectors-render-cache.test.ts
+++ b/test/renderer/connectors-render-cache.test.ts
@@ -194,4 +194,56 @@ describe('connectors renderer cache', () => {
expect(storage.has('orkas.connectors.renderCache.v4.u-cache')).toBe(true);
expect(storage.has('some.other.key')).toBe(true);
});
+ it('names chat configure cards from the render cache without hydrating Connectors page state', () => {
+ const { context, storage } = loadConnectorsRenderer();
+ context.sanitizeSvgIconHtml = (svg: string) => (svg ? `safe:${svg}` : '');
+ storage.set('orkas.connectors.renderCache.v4.u-cache', JSON.stringify({
+ version: 4,
+ updated_at: Date.now(),
+ catalog: [
+ { id: 'gmail', display_name: 'Gmail', icon_svg: '<svg id="gmail"/>' },
+ { id: 'feishu', display_name: 'Feishu', display_name_zh: '飞书', icon_svg: '<svg id="feishu"/>' },
+ // A hidden compatibility child opens its parent card, so it is labeled as that card.
+ { id: 'lark', display_name: 'Lark', catalog_parent_id: 'feishu' },
+ ],
+ instances: [],
+ }));
+
+ expect(context.window.connectorNavTarget('gmail')).toEqual({ name: 'Gmail', iconSvg: 'safe:<svg id="gmail"/>' });
+ expect(context.window.connectorNavTarget(' lark ')).toEqual({ name: '飞书', iconSvg: 'safe:<svg id="feishu"/>' });
+ expect(context.window.connectorNavTarget('unknown')).toBeNull();
+ expect(context.window.connectorNavTarget('')).toBeNull();
+ expect(vm.runInContext('_connectorsState.catalog.length', context)).toBe(0);
+ });
+
+ it('fetches the catalog once for chat card names and retries only after a failed fetch', async () => {
+ const { context } = loadConnectorsRenderer();
+ const requests: string[] = [];
+ let fail = true;
+ context.window.orkas.invoke = async (channel: string) => {
+ requests.push(channel);
+ if (fail) throw new Error('offline');
+ return { ok: true, catalog: [{ id: 'm365-mail', display_name: 'Microsoft 365 Mail' }] };
+ };
+
+ expect(await context.window.loadConnectorNavTarget('m365-mail')).toBeNull();
+ fail = false;
+ const [first, second, unknown] = await Promise.all([
+ context.window.loadConnectorNavTarget('m365-mail'),
+ context.window.loadConnectorNavTarget('m365-mail'),
+ context.window.loadConnectorNavTarget('unknown'),
+ ]);
+ expect(first).toEqual({ name: 'Microsoft 365 Mail', iconSvg: '' });
+ expect(second).toEqual(first);
+ expect(unknown).toBeNull();
+ expect(await context.window.loadConnectorNavTarget('unknown')).toBeNull();
+ expect(requests).toEqual(['connectors.catalog', 'connectors.catalog']);
+ expect(vm.runInContext('_connectorsState.catalog.length', context)).toBe(0);
+ });
+
+ it('prefers the loaded Connectors page catalog for chat card names', () => {
+ const { context } = loadConnectorsRenderer();
+ vm.runInContext(`_connectorsState.catalog = [{ id: 'gcal', display_name: 'Google Calendar' }];`, context);
+ expect(context.window.connectorNavTarget('gcal')).toEqual({ name: 'Google Calendar', iconSvg: '' });
+ });
});