Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(models): 支持 GPT-6 Astra 并修正推理与缓存计量 (#3938)

Dash2fd803a3fd37
diff --git a/AGENTS.md b/AGENTS.md
index 5885d60efc..0f1e064a7f 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -26,6 +26,9 @@
`docs/dev-rules/repo-map.md`。
- 首次安装、修复依赖或准备新 worktree 时,必须先读
`docs/dev-rules/environment-setup.md`。
+- 新增模型、更新模型窗口/价格/推理档位/默认值,或排查模型信息显示错误前,必须先读
+ `docs/dev-rules/model-catalog-maintenance.md`:先确认实际下发目录与数据归属;Server
+ 目录和客户端内置兜底需协调更新,不能只改本仓快照就认定线上已生效。
- 启动、调试或验证 Desktop 时,必须先读 `docs/dev-rules/desktop-development.md`。
- 修改 Desktop Renderer、preload、BrowserWindow、WebView、IPC、CSP、导航或 Electron
特权能力前,必须先读 `docs/dev-rules/electron-security-and-process-boundaries.md`。
diff --git a/apps/desktop/src/main/__tests__/sessionsListIncludePinned.test.ts b/apps/desktop/src/main/__tests__/sessionsListIncludePinned.test.ts
index 54ed9cd684..e99f52e096 100644
--- a/apps/desktop/src/main/__tests__/sessionsListIncludePinned.test.ts
+++ b/apps/desktop/src/main/__tests__/sessionsListIncludePinned.test.ts
@@ -174,6 +174,45 @@ function resolveReferencesHandler() {
}
describe('local-db:sessions:list includePinned', () => {
+ it('projects usage-history windows before stripping agent identity from the response', async () => {
+ const resolveContextWindow = vi.fn((row: { agentKind?: string | null }) =>
+ row.agentKind === 'codex' ? 272_000 : null,
+ );
+ registerSessionIpc(undefined, { resolveContextWindow });
+ const handler = h.ipcHandle.mock.calls.find(([name]) => name === 'local-db:sessions:list')![1];
+ h.queryResults.push([
+ sessionRow('codex', { agentKind: 'codex', contextWindow: 1_050_000, contextTokens: 140_500 }),
+ sessionRow('pi', { agentKind: 'pi', contextWindow: 872_000, contextTokens: 140_500 }),
+ ]);
+ const result = await handler({}, 20, 'all', { usageHistory: true });
+ expect(result[0]).toMatchObject({ contextWindow: 272_000, contextTokens: 140_500 });
+ expect(result[1]).toMatchObject({ contextWindow: 872_000, contextTokens: 140_500 });
+ expect(result[0]).not.toHaveProperty('agentKind');
+ expect(result[1]).not.toHaveProperty('agentKind');
+ });
+
+ it.each(['local-db:sessions:get', 'local-db:sessions:list'])(
+ '%s projects historical context using the stored route without writing it',
+ async (channel) => {
+ const resolveContextWindow = vi.fn(() => 272_000);
+ registerSessionIpc(undefined, { resolveContextWindow });
+ const handler = h.ipcHandle.mock.calls.find(([name]) => name === channel)![1];
+ const saved = listRow('old-astra', {
+ agentKind: 'codex', model: 'gpt-6-astra', providerId: 'openai',
+ contextTokens: 140_500, contextWindow: 1_050_000,
+ });
+ h.queryResults.push([saved]);
+ const result = channel.endsWith(':get')
+ ? await handler({}, 'old-astra')
+ : (await handler({}, 20, 'active'))[0];
+ expect(result).toMatchObject({ contextTokens: 140_500, contextWindow: 272_000 });
+ expect(resolveContextWindow).toHaveBeenCalledWith(expect.objectContaining({
+ agentKind: 'codex', model: 'gpt-6-astra', providerId: 'openai',
+ }));
+ expect(saved.session.contextWindow).toBe(1_050_000);
+ },
+ );
+
it('returns recent active rows plus missing active pinned rows without duplicates', async () => {
const handler = sessionsListHandler();
h.queryResults.push(
@@ -231,6 +270,7 @@ describe('local-db:sessions:list includePinned', () => {
'totalTokenUsage',
'contextTokens',
'contextWindow',
+ 'agentKind',
'userSendAt',
'updatedAt',
]);
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index e51ed7575d..71d0fcb5d1 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -333,6 +333,8 @@ import { cindyGhostSchemePrivilege } from './cindy-brain/runtime/electronSandbox
import { fetchReleaseNotes, fetchReleaseNotesIndex } from './releaseNotesService';
import { resolveWorkspacePathCached, resolveWorkspacePathBatchCached } from './pathResolver';
import { registerLocalDbIpc } from './localDb/ipc/registerAll';
+import { getActiveCatalog } from './maker-host/active-catalog';
+import { resolveSessionContextWindow } from '../shared/sessionContextWindow';
import {
getSessionRowSnapshot,
resumeDeletedPiSubagentCleanup,
@@ -8233,6 +8235,7 @@ app.on('ready', async () => {
// 保证 beforeEnsureReady 推送 confirm 态时 renderer 已能 invoke 确认通道。
registerLegacyMigrationIpc();
registerLocalDbIpc({
+ resolveContextWindow: (session) => resolveSessionContextWindow(getActiveCatalog(), session),
cancelSessionOperations: cancelIOSSimulatorSessionOperations,
cleanupRemovedSession: cleanupIOSSimulatorRemovedSession,
closeIdleSessionForMove: async (sessionId) => {
diff --git a/apps/desktop/src/main/localDb/ipc/registerAll.ts b/apps/desktop/src/main/localDb/ipc/registerAll.ts
index f0ce8d932d..b44dabeba9 100644
--- a/apps/desktop/src/main/localDb/ipc/registerAll.ts
+++ b/apps/desktop/src/main/localDb/ipc/registerAll.ts
@@ -13,6 +13,7 @@ import { closeDb, ensureReady, getCurrentUserId } from '../index';
import { getCurrentDbClientUserId, tryGetDbClient } from '../client/current';
import {
registerSessionIpc,
+ type RegisterSessionIpcOpts,
setSessionRemovalCancelOperations,
setSessionRemovalCleanup,
} from './sessions';
@@ -71,6 +72,7 @@ function startMediaRefCompensationReconcile(
}
export interface RegisterLocalDbIpcOpts {
+ resolveContextWindow?: RegisterSessionIpcOpts['resolveContextWindow'];
/** Current stable app-session owner. False makes queued/in-flight work stale. */
isOwnerCurrent?: (userId: string) => boolean;
/** Dispose any secondary DB client committed by a stale onReady callback. */
@@ -237,6 +239,7 @@ export function registerLocalDbIpc(opts: RegisterLocalDbIpcOpts = {}): void {
});
registerSessionIpc(getCurrentDbClientUserId, {
+ resolveContextWindow: opts.resolveContextWindow,
closeIdleSessionForMove: opts.closeIdleSessionForMove,
});
registerMessageIpc();
diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.ts
index 325a1e4fce..c24aa6d86d 100644
--- a/apps/desktop/src/main/localDb/ipc/sessions.ts
+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts
@@ -34,6 +34,10 @@ import { throwIpcError, requireString, requireObject } from '../../utils/ipcVali
import { bindDeletedPiSubagentCleanupCancel } from './piSubagentDeletion';
import { resolveBusinessSessionId } from '../../sessionIds';
import { normalizeDbAgentKind } from '../../../shared/agentKindConversion';
+import {
+ projectSessionContextWindow,
+ type ContextWindowSession,
+} from '../../../shared/sessionContextWindow';
import {
sessionToCamel,
sessionUsageToCamel,
@@ -125,6 +129,8 @@ export interface SessionRecycleScope {
}
export interface RegisterSessionIpcOpts {
+ /** Use the same live catalog as runtime usage, without writing during reads. */
+ resolveContextWindow?: (session: ContextWindowSession) => number | null;
/** Close a local Pi/Codex runtime only if its current turn is idle. */
closeIdleSessionForMove?: (sessionId: string) => Promise<boolean>;
}
@@ -1117,12 +1123,15 @@ export function registerSessionIpc(
scheduleSessionListProjectionBackfill(mergedRows);
return mergedRows.map((r) =>
- sessionToCamel({
- ...r.session,
- messageCount: r.messageCount,
- latestMessageExtract: r.latestMessageExtract,
- latestMessageRole: r.latestMessageRole,
- }),
+ projectSessionContextWindow(
+ sessionToCamel({
+ ...r.session,
+ messageCount: r.messageCount,
+ latestMessageExtract: r.latestMessageExtract,
+ latestMessageRole: r.latestMessageRole,
+ }),
+ opts.resolveContextWindow,
+ ),
);
};
const loadUsageHistoryRows = async () => {
@@ -1133,7 +1142,9 @@ export function registerSessionIpc(
const statusWhere = () =>
statusFilter ? eq(sessions.status, statusFilter) : ne(sessions.status, 'deleted');
const rows = await selectSessionUsageRows(db, and(sourceFilter, statusWhere()));
- return rows.map(sessionUsageToCamel);
+ return rows.map((row) =>
+ sessionUsageToCamel(projectSessionContextWindow(row, opts.resolveContextWindow)),
+ );
};
// key 用同一快照上的 userId + clientEpoch + 归一化参数。
// forceRefresh / status 重拉带 fresh,不并入写前那次查询。
@@ -1389,7 +1400,7 @@ export function registerSessionIpc(
const db = getDbClient().drizzle;
const row = await selectSessionWithCount(db, sid);
if (!row) throwIpcError('NOT_FOUND', 'Session 不存在');
- return sessionToCamel(row);
+ return projectSessionContextWindow(sessionToCamel(row), opts.resolveContextWindow);
});
/**
@@ -2351,6 +2362,7 @@ function selectSessionUsageRows(
| 'totalTokenUsage'
| 'contextTokens'
| 'contextWindow'
+ | 'agentKind'
| 'userSendAt'
| 'updatedAt'
>
@@ -2365,6 +2377,7 @@ function selectSessionUsageRows(
totalTokenUsage: sessions.totalTokenUsage,
contextTokens: sessions.contextTokens,
contextWindow: sessions.contextWindow,
+ agentKind: sessions.agentKind,
userSendAt: sessions.userSendAt,
updatedAt: sessions.updatedAt,
})
diff --git a/apps/desktop/src/main/maker-host/__tests__/activeCatalogDiscovery.test.ts b/apps/desktop/src/main/maker-host/__tests__/activeCatalogDiscovery.test.ts
index cd546813f2..0847c5d94a 100644
--- a/apps/desktop/src/main/maker-host/__tests__/activeCatalogDiscovery.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/activeCatalogDiscovery.test.ts
@@ -347,7 +347,7 @@ describe('active-catalog discovered augment', () => {
expect(xai?.videoModels).toEqual([]);
});
- it('bridge 投影剔除 max/ultra:codex 侧保留、claude-code 侧封顶 xhigh(issue #352)', () => {
+ it('bridge 投影保留上游声明的 max/ultra,由实际通道能力控制传参', () => {
setActiveCatalog(bundledWithoutRegistry());
setDiscoveredCodexModels([
{
@@ -364,9 +364,9 @@ describe('active-catalog discovered augment', () => {
// codex 侧完整保留(该模型确实支持 max/ultra)。
expect(codex?.efforts).toEqual(['low', 'medium', 'high', 'xhigh', 'max', 'ultra']);
expect(codex?.defaultEffort).toBe('ultra');
- // claude-code bridge 侧剔除 max/ultra,默认值随之回落到剩余最高档 xhigh。
- expect(bridge?.efforts).toEqual(['low', 'medium', 'high', 'xhigh']);
- expect(bridge?.defaultEffort).toBe('xhigh');
+ // bridge 已支持按模型能力传参,无需在目录层丢弃高档。
+ expect(bridge?.efforts).toEqual(['low', 'medium', 'high', 'xhigh', 'max', 'ultra']);
+ expect(bridge?.defaultEffort).toBe('ultra');
});
it('动态清单契约:注册表快照即清单本身(bundled 零静态,快照全量呈现)', () => {
diff --git a/apps/desktop/src/main/maker-host/__tests__/codex-smart-subagent-routing.test.ts b/apps/desktop/src/main/maker-host/__tests__/codex-smart-subagent-routing.test.ts
index 784c6de415..18a0fcc269 100644
--- a/apps/desktop/src/main/maker-host/__tests__/codex-smart-subagent-routing.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/codex-smart-subagent-routing.test.ts
@@ -71,6 +71,26 @@ const baseCatalog = {
};
describe('Codex smart Subagent catalog', () => {
+ it('preserves a newly discovered native v2 model including its larger maximum window', () => {
+ const astra = {
+ slug: 'gpt-6-astra',
+ multi_agent_version: 'v2',
+ context_window: 272_000,
+ max_context_window: 872_000,
+ supported_reasoning_levels: [{ effort: 'ultra', description: 'native delegation' }],
+ };
+ const built = buildCodexSmartModelCatalog({ models: [astra] }, [
+ { providerId: 'openai', model: model('gpt-6-astra', 'gpt') },
+ { providerId: 'xd', model: model('deepseek/deepseek-v4-flash') },
+ ]);
+ expect(built?.models[0]).toEqual(astra);
+ expect(built?.models[1]).toMatchObject({
+ slug: 'deepseek/deepseek-v4-flash',
+ context_window: 200_000,
+ max_context_window: 200_000,
+ });
+ });
+
it('keeps native Sol/Terra and selects additional connected Codex chat models', () => {
const candidates = selectCodexSmartSubagentCandidates(
[
diff --git a/apps/desktop/src/main/maker-host/__tests__/modelPlane.test.ts b/apps/desktop/src/main/maker-host/__tests__/modelPlane.test.ts
index b80071d7db..ebbe98fbcf 100644
--- a/apps/desktop/src/main/maker-host/__tests__/modelPlane.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/modelPlane.test.ts
@@ -139,7 +139,7 @@ describe('registry presence 实体化', () => {
expect('newSessionDefault' in claude!).toBe(false);
});
- it('bridge 在投影后应用目标端 perAgent,随后再执行 effort 硬约束', () => {
+ it('bridge 在投影后应用目标端 perAgent 的 effort 能力', () => {
setActiveCatalog(
baseCatalog([
gpt6Entry({
@@ -176,6 +176,17 @@ describe('registry presence 实体化', () => {
expect(models('openai', 'pi').find((m) => m.id === 'chatgpt/gpt-6')).toBeUndefined();
});
+ it('bridge preserves max and ultra when declared by the target consumer', () => {
+ setActiveCatalog(baseCatalog([gpt6Entry({
+ efforts: ['low', 'medium', 'high', 'xhigh', 'max', 'ultra'],
+ defaultEffort: 'ultra',
+ })]));
+ expect(models('openai', 'claude-code').find((m) => m.id === 'chatgpt/gpt-6')).toMatchObject({
+ efforts: ['low', 'medium', 'high', 'xhigh', 'max', 'ultra'],
+ defaultEffort: 'ultra',
+ });
+ });
+
it('同一 OpenAI modelId 的长上下文 Registry entry 只生成 Claude 独立选择', () => {
setActiveCatalog(
baseCatalog([
@@ -204,7 +215,7 @@ describe('registry presence 实体化', () => {
contextWindow: 1_000_000,
},
]);
- expect(models('openai', 'pi').some((m) => m.id.startsWith('chatgpt/gpt-6'))).toBe(false);
+ expect(models('openai', 'pi').some((m) => ['chatgpt/gpt-6', 'chatgpt/gpt-6[1m]'].includes(m.id))).toBe(false);
setLocalCatalogOverrides(
overridesOf({
patches: { 'openai:gpt-6[1m]': { base: { contextWindow: 900_000 } } },
diff --git a/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts b/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts
index 27367561b0..f7edbed571 100644
--- a/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts
@@ -217,6 +217,45 @@ describe('resolvePiCindyGatewayModelApi', () => {
});
describe('buildPiNativeProvidersFromConfigs', () => {
+ it.each([
+ { baseUrl: 'https://api.openai.com/v1', wireProtocol: 'openai-responses' as const, expected: true },
+ { baseUrl: 'https://private.example/v1', wireProtocol: 'openai-responses' as const, expected: false },
+ { baseUrl: 'https://api.openai.com/v1', wireProtocol: 'openai-chat' as const, expected: false },
+ ])('Astra API metadata requires the matching endpoint and protocol: $baseUrl $wireProtocol', ({ baseUrl, wireProtocol, expected }) => {
+ const { providers } = buildPiNativeProvidersFromConfigs([{
+ id: 'manual-openai', name: 'Manual OpenAI', auth: { method: 'apiKey' },
+ runtimes: { pi: piRuntime({ baseUrl, wireProtocol, models: [{ id: 'gpt-6-astra', name: 'Astra' }] }) },
+ }], () => 'test-key');
+ const model = providers[0]?.models[0];
+ if (expected) {
+ expect(model).toMatchObject({
+ contextWindow: 1_050_000, maxTokens: 128_000, reasoning: true,
+ input: ['text', 'image'], thinkingLevelMap: { off: 'low', max: 'max' },
+ cost: { input: 10, output: 50, cacheRead: 1, cacheWrite: 12.5 },
+ });
+ expect(model?.baseUrl).toBeUndefined();
+ } else {
+ expect(model?.thinkingLevelMap).toBeUndefined();
+ expect(model?.contextWindow).toBeUndefined();
+ }
+ });
+
+ it('adds missing Astra subscription metadata and preserves native transport compatibility', () => {
+ const catalog = structuredClone(BUNDLED_CATALOG);
+ const build = (native?: PiBundledModelInfo) => buildPiSubscriptionNativeProviders(
+ catalog, 'http://127.0.0.1:4567/',
+ new Map([['openai-codex', new Map(native ? [['gpt-6-astra', native]] : [])]]),
+ ).providers.find((provider) => provider.id === 'openai-codex')?.models.find((model) => model.wireId === 'gpt-6-astra');
+ expect(build()).toMatchObject({
+ id: 'chatgpt/gpt-6-astra', api: 'openai-codex-responses', catalogAddition: true,
+ contextWindow: 272_000, input: ['text', 'image'], thinkingLevelMap: { max: 'max' },
+ });
+ expect(build()?.baseUrl).toBeUndefined();
+ const native = piBundledModel('gpt-6-astra', 'openai-codex-responses', { compat: { supportsStore: false } });
+ expect(build(native)).toMatchObject({ api: 'openai-codex-responses', compat: { supportsStore: false } });
+ expect(build(native)?.catalogAddition).toBeUndefined();
+ });
+
it('keeps a legacy custom xai endpoint separate from the official SuperGrok provider', () => {
const { providers, env } = buildPiNativeProvidersFromConfigs(
[
diff --git a/apps/desktop/src/main/maker-host/anthropic-responses-bridge-host.ts b/apps/desktop/src/main/maker-host/anthropic-responses-bridge-host.ts
index bc690154b8..ecec72e212 100644
--- a/apps/desktop/src/main/maker-host/anthropic-responses-bridge-host.ts
+++ b/apps/desktop/src/main/maker-host/anthropic-responses-bridge-host.ts
@@ -31,6 +31,7 @@ import {
import { createResponsesHandler, type BridgeProviderConfig, type ResponsesBridgeHandler } from '@cindy/anthropic-responses-bridge';
import { createMakerLogger } from './logger-adapter.js';
+import { getActiveCatalog } from './active-catalog.js';
import { outboundFetch } from './outbound-fetch.js';
import { getGrokAccessToken } from './grok-oauth-login.js';
import { invalidateXaiBridgeAuth } from './xai-auth-invalidation-host.js';
@@ -288,6 +289,9 @@ function codexProviderConfig(): BridgeProviderConfig {
// Fast 模式:codex models_cache 的 service_tiers 声明 {id:'priority', name:'Fast'},
// handler 在 prefs.fast 时映射成 Responses 的 service_tier:'priority'。
fastServiceTier: 'priority',
+ supportedReasoningEfforts: (model) => getActiveCatalog().providers
+ .find((provider) => provider.id === 'openai')?.models['claude-code']
+ ?.find((entry) => entry.id === `${CHATGPT_MODEL_PREFIX}${model}`)?.efforts,
// codex 后端不支持 max_output_tokens(会 400),保持默认 false。
buildHeaders: async ({ sessionId }) => {
const { accessToken, accountId } = await getChatgptBridgeAuth();
diff --git a/apps/desktop/src/main/maker-host/catalog-to-descriptors.ts b/apps/desktop/src/main/maker-host/catalog-to-descriptors.ts
index 8241201a6d..ddfea7d942 100644
--- a/apps/desktop/src/main/maker-host/catalog-to-descriptors.ts
+++ b/apps/desktop/src/main/maker-host/catalog-to-descriptors.ts
@@ -245,25 +245,7 @@ export function resolvePiGatewayDescriptorProviderId(
*
* 返回 null 一律意味着「不收敛」,也就是改动前的行为(fail-safe)。
*/
-export function resolveVerifiedContextWindow(
- catalog: Catalog,
- agent: AgentKind,
- providerId: string | null | undefined,
- modelId: string,
-): number | null {
- const candidates: CatalogModel[] = [];
- for (const provider of catalog.providers) {
- if (provider.routing[agent]?.disabled === true) continue;
- if (providerId && provider.id !== providerId) continue;
- for (const m of provider.models[agent] ?? []) {
- if (m.id === modelId) candidates.push(m);
- }
- }
- if (candidates.length !== 1) return null;
- const only = candidates[0];
- if (only.contextWindowVerified !== true) return null;
- return only.contextWindow > 0 ? only.contextWindow : null;
-}
+export { resolveVerifiedContextWindow } from '../../shared/sessionContextWindow';
/**
* 自定义供应商上用户显式填写的 contextWindow。
diff --git a/apps/desktop/src/main/maker-host/codex-smart-subagent-routing.ts b/apps/desktop/src/main/maker-host/codex-smart-subagent-routing.ts
index ad94d061ed..7b5c2758eb 100644
--- a/apps/desktop/src/main/maker-host/codex-smart-subagent-routing.ts
+++ b/apps/desktop/src/main/maker-host/codex-smart-subagent-routing.ts
@@ -139,7 +139,8 @@ export function buildCodexSmartModelCatalog(
);
const template =
models.find((model) => model.slug === 'gpt-5.6-terra') ??
- models.find((model) => model.slug === 'gpt-5.6-sol');
+ models.find((model) => model.slug === 'gpt-5.6-sol') ??
+ models.find((model) => model.multi_agent_version === 'v2');
if (!template) return null;
const bySlug = new Map(models.map((model) => [model.slug, model]));
@@ -147,6 +148,9 @@ export function buildCodexSmartModelCatalog(
const nextModels = models.map((record) => {
const candidate = candidateBySlug.get(record.slug);
if (!candidate) return record;
+ // Native subscription models already carry their own multi-agent contract.
+ // In particular, max_context_window can exceed the default context_window.
+ if (candidate.providerId === 'openai' && record.multi_agent_version === 'v2') return record;
return {
...record,
display_name: candidate.model.name,
diff --git a/apps/desktop/src/main/maker-host/model-plane/modelPlanePolicy.ts b/apps/desktop/src/main/maker-host/model-plane/modelPlanePolicy.ts
index bd3126a42a..6c1a66b5be 100644
--- a/apps/desktop/src/main/maker-host/model-plane/modelPlanePolicy.ts
+++ b/apps/desktop/src/main/maker-host/model-plane/modelPlanePolicy.ts
@@ -114,26 +114,11 @@ type Effort = CatalogModel['efforts'][number];
/** Claude 的 OpenAI bridge 默认收起的旧型号;与既有目录行为保持一致。 */
const BRIDGE_DEFAULT_HIDDEN_SLUGS: ReadonlySet<string> = new Set(['gpt-5.4', 'gpt-5.4-mini']);
-/** anthropic-responses bridge 不会兑现的 GPT 思考档,投影时必须在客户端硬封顶。 */
-const CLAUDE_BRIDGE_UNSUPPORTED_EFFORTS: ReadonlySet<Effort> = new Set(['max', 'ultra']);
-
/** OpenAI Codex root → Claude bridge。 */
export function toChatgptBridgeModel(model: CatalogModel): CatalogModel {
- const bridgeEfforts = model.efforts.filter(
- (effort) => !CLAUDE_BRIDGE_UNSUPPORTED_EFFORTS.has(effort),
- );
- const cappedDefault: Effort | null =
- model.defaultEffort && CLAUDE_BRIDGE_UNSUPPORTED_EFFORTS.has(model.defaultEffort)
- ? bridgeEfforts.includes('xhigh')
- ? 'xhigh'
- : (bridgeEfforts[bridgeEfforts.length - 1] ?? null)
- : model.defaultEffort;
return {
...model,
id: `${CHATGPT_MODEL_PREFIX}${model.id}`,
- ...(bridgeEfforts.length !== model.efforts.length
- ? { efforts: bridgeEfforts, defaultEffort: cappedDefault }
- : {}),
...(BRIDGE_DEFAULT_HIDDEN_SLUGS.has(model.id) ? { defaultEnabled: false } : {}),
};
}
diff --git a/apps/desktop/src/main/maker-host/pi-gateway-model-catalog.ts b/apps/desktop/src/main/maker-host/pi-gateway-model-catalog.ts
index fc77c8e427..5d5b53bea2 100644
--- a/apps/desktop/src/main/maker-host/pi-gateway-model-catalog.ts
+++ b/apps/desktop/src/main/maker-host/pi-gateway-model-catalog.ts
@@ -37,6 +37,8 @@ const gatewayModelIdsByApi: Record<PiModelApi, ReadonlySet<string>> = {
'anthropic/claude-opus-5',
]),
'openai-responses': new Set([
+ 'gpt-6-astra',
+ 'codex/gpt-6-astra',
'gpt-5.4',
'gpt-5.4-mini',
'gpt-5.4-nano',
@@ -195,6 +197,7 @@ const gatewayCatalogIdentityOverrides = new Map<string, { provider: string; mode
'gpt-5.6-luna',
'gpt-5.6-sol',
'gpt-5.6-terra',
+ 'gpt-6-astra',
].flatMap((id) => [
[id, { provider: 'openai', modelId: id }] as const,
[`codex/${id}`, { provider: 'openai', modelId: id }] as const,
diff --git a/apps/desktop/src/main/maker-host/pi-host.ts b/apps/desktop/src/main/maker-host/pi-host.ts
index 884b0bfe71..921bec9ea4 100644
--- a/apps/desktop/src/main/maker-host/pi-host.ts
+++ b/apps/desktop/src/main/maker-host/pi-host.ts
@@ -536,6 +536,9 @@ export function buildPiSubscriptionNativeProviders(
const officialXaiById = new Map(
(officialPiModels('xai') ?? []).map((model) => [model.id, model]),
);
+ const officialOpenAiById = new Map(
+ (officialPiModels('openai-codex') ?? []).map((model) => [model.id, model]),
+ );
const env: Record<string, string> = {
[PI_OPENAI_PROXY_KEY_ENV]: piOpenaiProxyPlaceholderJwt(),
[PI_XAI_PROXY_API_KEY_ENV]: PI_PROVIDER_AUTH_PLACEHOLDER_KEY,
@@ -625,6 +628,16 @@ export function buildPiSubscriptionNativeProviders(
const listedIds =
listedModelIdsByProvider?.get(piProviderId)
?? listedPiModelIds(bundledModelsByProvider)?.get(piProviderId);
+ const officialOpenAi = officialOpenAiById.get(wireId);
+ if (sourceProviderId === 'openai' && !bundledModel && !listedIds?.has(wireId)
+ && officialOpenAi?.api === 'openai-codex-responses') {
+ return {
+ ...structuredClone(officialOpenAi),
+ id: model.id,
+ wireId,
+ catalogAddition: true,
+ };
+ }
const isKnownMissingXaiModel =
wireId === 'grok-4.6' || model.id === 'grok-4.6' || model.id.endsWith('/grok-4.6');
const isXaiCatalogAddition =
@@ -1261,8 +1274,18 @@ export function buildPiNativeProvidersFromConfigs(
? officialPiModels(rt.piCatalogProviderId)
: null;
const officialById = new Map((official ?? []).map((model) => [model.id, model]));
+ // The pinned binary predates Astra. Exact public API endpoint/protocol matches
+ // may use our catalog addition even when the user entered the endpoint by hand.
+ // Never lend subscription capabilities to an API key or another endpoint.
+ const openaiAddition = !rt.piCatalogProviderId &&
+ runtimeApi === 'openai-responses' &&
+ officialPiRouteMatches('openai', rt.baseUrl, rt.wireProtocol)
+ ? officialPiModels('openai')?.find((model) => model.id === 'gpt-6-astra')
+ : undefined;
const metadataModels = rt.models.map(
- (model, index) => bundledModels[index] ?? officialById.get(model.id),
+ (model, index) => bundledModels[index] ?? officialById.get(model.id) ??
+ (model.id === openaiAddition?.id && !model.route &&
+ (!model.piApi || model.piApi === openaiAddition.api) ? openaiAddition : undefined),
);
const modelApis = rt.models.map(
(model, index) =>
diff --git a/apps/desktop/src/main/usage/__tests__/modelPriceOverrideStore.test.ts b/apps/desktop/src/main/usage/__tests__/modelPriceOverrideStore.test.ts
index e04c6eb90d..45cbdf410f 100644
--- a/apps/desktop/src/main/usage/__tests__/modelPriceOverrideStore.test.ts
+++ b/apps/desktop/src/main/usage/__tests__/modelPriceOverrideStore.test.ts
@@ -1,6 +1,106 @@
import { describe, expect, it } from 'vitest';
+import { BUNDLED_CATALOG } from '@cindy/model-providers';
+import { providerReferencePriceQuote } from '../../../shared/modelPriceQuote';
+import type { ModelPriceQuote } from '../../../shared/regionalMoney';
import { __testing } from '../modelPriceOverrideStore';
+import { computeGatewayTurnCost } from '../turnCostCalculator';
+
+describe('standard overrides preserve independent Fast reference prices', () => {
+ const target = { providerId: 'openai', agent: 'pi' as const, modelId: 'gpt-6-astra' };
+ const reference = providerReferencePriceQuote(
+ 'openai',
+ target.modelId,
+ BUNDLED_CATALOG.modelRegistry,
+ {
+ at: '2026-09-04',
+ },
+ )!;
+ const savedBase = {
+ currency: reference.currency,
+ inputPerMtok: reference.inputPerMtok,
+ outputPerMtok: reference.outputPerMtok,
+ cacheReadPerMtok: reference.cacheReadPerMtok ?? null,
+ cacheCreatePerMtok: reference.cacheCreatePerMtok ?? null,
+ inputTokenPriceBands: reference.inputTokenPriceBands,
+ };
+ const tokens = {
+ inputTokens: 200_000,
+ outputTokens: 1_000,
+ cacheReadTokens: 0,
+ cacheCreateTokens: 0,
+ };
+
+ it('keeps Astra Fast prices and window bounds separate from saved standard edits', () => {
+ const merged = __testing.mergedQuote(
+ target,
+ reference,
+ {
+ inputPerMtok: 3,
+ outputPerMtok: 7,
+ cacheReadPerMtok: null,
+ cacheCreatePerMtok: null,
+ },
+ savedBase,
+ );
+ expect(merged).toMatchObject({ source: 'user-override', inputPerMtok: 3, outputPerMtok: 7 });
+ expect(merged?.priority).toEqual(reference.priority);
+ expect(computeGatewayTurnCost(tokens, merged, 'fast')).toBeCloseTo(4.1);
+ expect(computeGatewayTurnCost(tokens, merged)).toBeCloseTo(0.607);
+ expect(computeGatewayTurnCost({ ...tokens, inputTokens: 272_001 }, merged, 'fast')).toBeNull();
+ expect(__testing.mergedQuote(target, reference, undefined)).toBe(reference);
+ });
+
+ it.each([true, false])(
+ 'follows live Fast updates while standard reference bands exist: %s',
+ (keepBands) => {
+ const updated: ModelPriceQuote = {
+ ...reference,
+ outputPerMtok: 60,
+ inputTokenPriceBands: keepBands ? reference.inputTokenPriceBands : undefined,
+ priority: { inputPerMtok: 30, outputPerMtok: 120 },
+ };
+ const merged = __testing.mergedQuote(target, updated, { inputPerMtok: 3 }, savedBase);
+ expect(merged?.outputPerMtok).toBe(60);
+ expect(merged?.priority).toEqual(updated.priority);
+ expect(computeGatewayTurnCost(tokens, merged, 'fast')).toBeCloseTo(6.12);
+ expect(
+ computeGatewayTurnCost({ ...tokens, cacheCreateTokens: 1 }, merged, 'fast'),
+ ).toBeNull();
+ },
+ );
+
+ it('does not relabel USD Fast prices when the user enters CNY prices', () => {
+ const values = __testing.sparseValues(
+ { currency: 'CNY', inputPerMtok: 3, outputPerMtok: 7 },
+ savedBase,
+ );
+ const merged = __testing.mergedQuote(target, reference, values, savedBase);
+ expect(merged?.currency).toBe('CNY');
+ expect(merged?.priority).toBeUndefined();
+ expect(computeGatewayTurnCost(tokens, merged, 'fast')).toBeNull();
+ });
+
+ it.each(['currency-change', 'missing-reference', 'missing-fast'] as const)(
+ 'does not invent Fast prices after %s',
+ (scenario) => {
+ const live =
+ scenario === 'missing-reference'
+ ? undefined
+ : {
+ ...reference,
+ ...(scenario === 'currency-change'
+ ? { currency: 'CNY' as const }
+ : { priority: undefined }),
+ };
+ const merged = __testing.mergedQuote(target, live, { inputPerMtok: 3 }, savedBase);
+ expect(merged?.currency).toBe('USD');
+ expect(merged?.inputPerMtok).toBe(3);
+ expect(merged?.priority).toBeUndefined();
+ expect(computeGatewayTurnCost(tokens, merged, 'fast')).toBeNull();
+ },
+ );
+});
describe('model price override sparse persistence', () => {
it('keys overrides by provider instance, runtime, and exact model id', () => {
diff --git a/apps/desktop/src/main/usage/__tests__/turnCostCalculator.test.ts b/apps/desktop/src/main/usage/__tests__/turnCostCalculator.test.ts
index e1c86ef774..f24000e170 100644
--- a/apps/desktop/src/main/usage/__tests__/turnCostCalculator.test.ts
+++ b/apps/desktop/src/main/usage/__tests__/turnCostCalculator.test.ts
@@ -1,4 +1,6 @@
import { describe, expect, it } from 'vitest';
+import { BUNDLED_CATALOG } from '@cindy/model-providers';
+import { subscriptionDirectPriceQuote } from '../../../shared/modelPriceQuote';
import type { ModelUsageDeltaEntry } from '../modelUsageDelta';
import { __resetActiveLedgerCurrencyForTesting, setActiveLedgerCurrency } from '../ledgerCurrency';
@@ -44,6 +46,36 @@ const SUBSCRIPTION: TurnPricingContext = {
region: 'global',
};
+describe('Astra subscription reference estimates', () => {
+ const astra = subscriptionDirectPriceQuote(
+ 'chatgpt/gpt-6-astra', BUNDLED_CATALOG.modelRegistry, 'codex', '2026-09-04',
+ );
+ const tokens = { inputTokens: 50_000, outputTokens: 100, cacheReadTokens: 200_000, cacheCreateTokens: 22_000 };
+
+ it('uses the declared Fast tariff for native priority segments, including cache writes', () => {
+ expect(astra?.source).toBe('subscription-reference');
+ expect(computeGatewayTurnCost(tokens, astra)).toBeCloseTo(0.98);
+ expect(computeGatewayTurnCost(tokens, astra, 'priority')).toBeCloseTo(1.96);
+ expect(computeGatewayTurnCost(tokens, astra, 'fast')).toBeCloseTo(1.96);
+ expect(computeGatewaySegmentedTurnCost([
+ { ...tokens, priceVariant: 'standard' },
+ { ...tokens, priceVariant: 'priority' },
+ ], astra)).toBeCloseTo(2.94);
+ });
+
+ it('keeps the subscription reference window bound for both tariffs', () => {
+ const expanded = { ...tokens, inputTokens: tokens.inputTokens + 1 };
+ expect(computeGatewayTurnCost(expanded, astra)).toBeNull();
+ expect(computeGatewayTurnCost(expanded, astra, 'priority')).toBeNull();
+ });
+
+ it('does not borrow standard cache-write prices for an incomplete reference Fast tariff', () => {
+ expect(astra?.priority).toBeDefined();
+ const incomplete = { ...astra!, priority: { ...astra!.priority, cacheCreatePerMtok: undefined, inputTokenPriceBands: undefined } };
+ expect(computeGatewayTurnCost(tokens, incomplete, 'priority')).toBeNull();
+ });
+});
+
function quote(
modelId: string,
inputPerMtok: number,
diff --git a/apps/desktop/src/main/usage/modelPriceOverrideStore.ts b/apps/desktop/src/main/usage/modelPriceOverrideStore.ts
index 81bd960f63..6f50d16eb0 100644
--- a/apps/desktop/src/main/usage/modelPriceOverrideStore.ts
+++ b/apps/desktop/src/main/usage/modelPriceOverrideStore.ts
@@ -246,7 +246,7 @@ function mergedQuote(
baseReference?: ComparablePrice | null,
): ModelPriceQuote | undefined {
if (!values) return reference;
- const savedBaseQuote = baseReference
+ const savedBaseQuote: ModelPriceQuote | undefined = baseReference
? {
providerId: target.providerId,
modelId: target.modelId,
@@ -397,6 +397,10 @@ function mergedQuote(
...(inputTokenPriceBands ? { inputTokenPriceBands } : {}),
...(cacheReadPerMtok !== undefined ? { cacheReadPerMtok } : {}),
...(cacheCreatePerMtok !== undefined ? { cacheCreatePerMtok } : {}),
+ // Standard-price edits do not change the independent Fast tariff or its currency.
+ ...(mergeReference?.priority && mergeReference.currency === currency
+ ? { priority: mergeReference.priority }
+ : {}),
};
}
diff --git a/apps/desktop/src/main/usage/turnCostCalculator.ts b/apps/desktop/src/main/usage/turnCostCalculator.ts
index 0570470229..d0656e1ee7 100644
--- a/apps/desktop/src/main/usage/turnCostCalculator.ts
+++ b/apps/desktop/src/main/usage/turnCostCalculator.ts
@@ -176,7 +176,7 @@ export function computeGatewayTurnCost(
const cacheCreatePrice =
band?.cacheCreatePerMtok ??
tariff.cacheCreatePerMtok ??
- (priority ? price.cacheCreatePerMtok : undefined);
+ (priority && price.source === 'gateway' ? price.cacheCreatePerMtok : undefined);
if (
(tokens.inputTokens > 0 && inputPrice === undefined) ||
(tokens.outputTokens > 0 && outputPrice === undefined) ||
diff --git a/apps/desktop/src/renderer/__tests__/contextWindowDisplay.test.ts b/apps/desktop/src/renderer/__tests__/contextWindowDisplay.test.ts
index 17d7f154ea..30ad213b83 100644
--- a/apps/desktop/src/renderer/__tests__/contextWindowDisplay.test.ts
+++ b/apps/desktop/src/renderer/__tests__/contextWindowDisplay.test.ts
@@ -4,6 +4,28 @@ import { resolveDisplayContextWindow } from '@/lib/contextWindow';
import { makerChatStore } from '@/lib/makerChatStore';
describe('resolveDisplayContextWindow', () => {
+ it('replaces a restored large window only with verified route metadata', () => {
+ expect(resolveDisplayContextWindow({
+ sdkContextWindow: 1_050_000,
+ modelContextWindow: 272_000,
+ verifiedContextWindow: 272_000,
+ })).toBe(272_000);
+ expect(resolveDisplayContextWindow({
+ sdkContextWindow: 1_050_000,
+ modelContextWindow: 272_000,
+ })).toBe(1_050_000);
+ });
+
+ it('follows an explicit long window and ignores invalid verified values', () => {
+ expect(resolveDisplayContextWindow({
+ sdkContextWindow: 272_000,
+ verifiedContextWindow: 872_000,
+ })).toBe(872_000);
+ for (const verifiedContextWindow of [null, 0, -1, NaN, Infinity]) {
+ expect(resolveDisplayContextWindow({ sdkContextWindow: 872_000, verifiedContextWindow }))
+ .toBe(872_000);
+ }
+ });
it('prefers maker capability when SDK reports the unknown-model 200K default', () => {
expect(resolveDisplayContextWindow({
modelContextWindow: 992_000,
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
index ad8c1c09c0..b509afe2c5 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
@@ -219,6 +219,7 @@ import { useSessionHardwareTaskActions } from './lib/sessionHardwareTaskActions'
import { isRemoteSessionWriteBlocked } from './lib/remoteSessionWriteGuard';
import { getModelById, getDefaultModelForVendor, getModelsForVendor } from '@/lib/modelDefinitions';
import { resolveDisplayContextWindow } from '@/lib/contextWindow';
+import { resolveSessionContextWindow } from '../../../shared/sessionContextWindow';
import { formatRunningTokenCount, resolveRunningUsageMeta } from './lib/runningTokenUsage';
import { matchNavigationCommandName, tryHandleNavigationCommand } from '@/lib/navigationCommands';
import { extractIpcError } from '@/utils/ipcError';
@@ -3604,6 +3605,7 @@ export function CCAgentSessionView({
try {
const contextWindow = resolveDisplayContextWindow({
sdkContextWindow: agentStatus.contextWindow,
+ verifiedContextWindow: resolveSessionContextWindow({ providers }, sourceSession),
modelContextWindow: getModelContextWindow(
sourceSession.model,
sourceSession.agentKind ?? 'cc',
@@ -3685,6 +3687,7 @@ export function CCAgentSessionView({
compactRequestGuard,
compactSession,
confirmDialog,
+ providers,
remoteDeviceId,
session,
t,
@@ -5209,6 +5212,16 @@ export function CCAgentSessionView({
model={agentSwitchIntent?.model ?? session?.model ?? ''}
vendorKey={normalizeDbAgentKind(displayAgentKind)}
sdkContextWindow={agentStatus.contextWindow}
+ verifiedContextWindow={resolveSessionContextWindow(
+ { providers },
+ {
+ agentKind: normalizeDbAgentKind(displayAgentKind),
+ model: agentSwitchIntent?.model ?? session?.model,
+ providerId: agentSwitchIntent
+ ? agentSwitchIntent.providerId
+ : session?.providerId,
+ },
+ )}
deviceId={remoteDeviceId}
onCompact={
// 按 agent 能力分流(#1927/#1933 review):claude-code 走 inputCoordinator,
@@ -5721,6 +5734,7 @@ function ContextCapacityRing({
model,
vendorKey,
sdkContextWindow,
+ verifiedContextWindow,
deviceId,
onCompact,
}: {
@@ -5729,6 +5743,7 @@ function ContextCapacityRing({
vendorKey: 'cc' | 'codex' | 'pi';
/** SDK-reported context window; 0 = not yet known → use hardcoded fallback. */
sdkContextWindow: number;
+ verifiedContextWindow?: number | null;
/** device-link 远程会话所属被控端 id;按被控端能力查 contextWindow(本机会话 undefined,行为不变)。 */
deviceId?: string;
/** 提供时圆环可点击 — 点击后(经用户确认)向 agent 发送 /compact 压缩上下文。 */
@@ -5737,6 +5752,7 @@ function ContextCapacityRing({
const { t } = useTranslation();
const contextWindow = resolveDisplayContextWindow({
sdkContextWindow,
+ verifiedContextWindow,
modelContextWindow: getModelContextWindow(model, vendorKey, deviceId),
});
const pct =
diff --git a/apps/desktop/src/renderer/lib/contextWindow.ts b/apps/desktop/src/renderer/lib/contextWindow.ts
index 18d034a7d6..51f099f749 100644
--- a/apps/desktop/src/renderer/lib/contextWindow.ts
+++ b/apps/desktop/src/renderer/lib/contextWindow.ts
@@ -3,6 +3,7 @@ export const DEFAULT_CONTEXT_WINDOW = 200_000;
interface ResolveDisplayContextWindowOptions {
sdkContextWindow: number;
modelContextWindow?: number;
+ verifiedContextWindow?: number | null;
}
/**
@@ -15,7 +16,13 @@ interface ResolveDisplayContextWindowOptions {
export function resolveDisplayContextWindow({
sdkContextWindow,
modelContextWindow,
+ verifiedContextWindow,
}: ResolveDisplayContextWindowOptions): number {
+ // Restored snapshots and SDK values share this slot. Only route-verified
+ // metadata may supersede it, matching the host's runtime normalization.
+ if (Number.isFinite(verifiedContextWindow) && (verifiedContextWindow ?? 0) > 0) {
+ return Math.floor(verifiedContextWindow!);
+ }
const configured =
Number.isFinite(modelContextWindow) && (modelContextWindow ?? 0) > 0
? Math.floor(modelContextWindow!)
diff --git a/apps/desktop/src/shared/__tests__/modelPriceQuote.test.ts b/apps/desktop/src/shared/__tests__/modelPriceQuote.test.ts
index 2f7f76654b..2b322ae557 100644
--- a/apps/desktop/src/shared/__tests__/modelPriceQuote.test.ts
+++ b/apps/desktop/src/shared/__tests__/modelPriceQuote.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
-import type { ModelRegistry } from '@cindy/model-providers';
+import { BUNDLED_CATALOG, type ModelRegistry } from '@cindy/model-providers';
import type { ModelAccessGatewayModel } from '../modelAccess.js';
import {
@@ -115,6 +115,24 @@ describe('gatewayPricingCatalog', () => {
});
describe('registryPricingCatalog', () => {
+ it.each(['fast', 'priority'] as const)('projects declared %s prices without inventing unavailable tariffs', (variant) => {
+ const entry = structuredClone(BUNDLED_CATALOG.modelRegistry!.models.find((model) => model.id === 'openai/gpt-6-astra')!);
+ const prices = entry.routes[0]!.referencePrices!;
+ prices.find((price) => price.variant === 'fast')!.variant = variant;
+ const registry: ModelRegistry = { schemaVersion: 1, updatedAt: '2026-09-04T00:00:00Z', models: [entry] };
+ const getQuote = (at = '2026-09-04') => providerReferencePriceQuote('openai', 'gpt-6-astra', registry, { at });
+ expect(getQuote()).toMatchObject({ inputPerMtok: 10, priority: { inputPerMtok: 20, cacheCreatePerMtok: 25 } });
+
+ const fast = prices.find((price) => price.variant === variant)!;
+ fast.effectiveFrom = '2026-09-05';
+ expect(getQuote()?.priority).toBeUndefined();
+ expect(getQuote('2026-09-05')?.priority).toBeDefined();
+ fast.currency = 'CNY';
+ expect(getQuote('2026-09-05')?.priority).toBeUndefined();
+ entry.routes[0]!.referencePrices = prices.filter((price) => price.variant === 'standard');
+ expect(getQuote()?.priority).toBeUndefined();
+ });
+
it('preserves the bounds of a single reference-price interval', () => {
const registry: ModelRegistry = {
schemaVersion: 1,
diff --git a/apps/desktop/src/shared/__tests__/sessionContextWindow.test.ts b/apps/desktop/src/shared/__tests__/sessionContextWindow.test.ts
new file mode 100644
index 0000000000..ae688d4eb2
--- /dev/null
+++ b/apps/desktop/src/shared/__tests__/sessionContextWindow.test.ts
@@ -0,0 +1,76 @@
+import { describe, expect, it } from 'vitest';
+import type { Catalog, CatalogModel, Provider } from '@cindy/model-providers';
+import { projectSessionContextWindow, resolveSessionContextWindow } from '../sessionContextWindow';
+
+const model: CatalogModel = {
+ id: 'gpt-6-astra',
+ name: 'Astra',
+ contextWindow: 272_000,
+ contextWindowVerified: true,
+ efforts: ['medium'],
+ defaultEffort: 'medium',
+};
+function provider(id: string, row: CatalogModel = model): Provider {
+ return {
+ id,
+ name: id,
+ source: 'builtin',
+ agents: ['codex', 'claude-code', 'pi'],
+ auth: { method: 'oauth' },
+ routing: {},
+ models: { codex: [row], 'claude-code': [row], pi: [row] },
+ };
+}
+const session = {
+ agentKind: 'codex',
+ model: model.id,
+ providerId: 'openai',
+ contextTokens: 140_500,
+ contextWindow: 1_050_000,
+};
+const catalog: Pick<Catalog, 'providers'> = { providers: [provider('openai')] };
+
+describe('session context read projection', () => {
+ it.each(['cc', 'codex'])(
+ 'corrects %s history without mutating its stored snapshot',
+ (agentKind) => {
+ const saved = { ...session, agentKind };
+ const result = projectSessionContextWindow(saved, (row) =>
+ resolveSessionContextWindow(catalog, row),
+ );
+ expect(result).toEqual({ ...saved, contextWindow: 272_000 });
+ expect(saved.contextWindow).toBe(1_050_000);
+ expect(Math.round((result.contextTokens / result.contextWindow) * 100)).toBe(52);
+ },
+ );
+
+ it('uses the actual provider, preserving explicit long-window overrides', () => {
+ const routes = {
+ providers: [provider('openai'), provider('custom', { ...model, contextWindow: 872_000 })],
+ };
+ expect(resolveSessionContextWindow(routes, { ...session, providerId: 'custom' })).toBe(872_000);
+ expect(resolveSessionContextWindow(routes, session)).toBe(272_000);
+ expect(resolveSessionContextWindow(routes, { ...session, providerId: null })).toBeNull();
+ expect(resolveSessionContextWindow(routes, { ...session, providerId: 'missing' })).toBeNull();
+ });
+
+ it('preserves Pi runtime snapshots and unknown or unverified routes', () => {
+ for (const saved of [
+ { ...session, agentKind: 'pi' },
+ { ...session, model: '' },
+ ]) {
+ expect(
+ projectSessionContextWindow(saved, (row) => resolveSessionContextWindow(catalog, row)),
+ ).toBe(saved);
+ }
+ const unknown = { providers: [provider('openai', { ...model, contextWindowVerified: false })] };
+ expect(resolveSessionContextWindow(unknown, session)).toBeNull();
+ expect(resolveSessionContextWindow({ providers: [] }, session)).toBeNull();
+ });
+
+ it('follows catalog refresh without retaining an earlier result', () => {
+ const before = { providers: [provider('openai', { ...model, contextWindow: 1_050_000 })] };
+ expect(resolveSessionContextWindow(before, session)).toBe(1_050_000);
+ expect(resolveSessionContextWindow(catalog, session)).toBe(272_000);
+ });
+});
diff --git a/apps/desktop/src/shared/modelPriceQuote.ts b/apps/desktop/src/shared/modelPriceQuote.ts
index 85ab7a6d40..ee4eaab9ea 100644
--- a/apps/desktop/src/shared/modelPriceQuote.ts
+++ b/apps/desktop/src/shared/modelPriceQuote.ts
@@ -247,16 +247,40 @@ function referencePriceCalendarDate(value: string | Date | undefined): string {
return new Date().toISOString().slice(0, 10);
}
+/** Selects a dated provider reference tariff, optionally for a specific agent/input size. */
+interface ReferencePriceOptions {
+ agent?: AgentKind;
+ inputTokens?: number;
+ at?: string | Date;
+ variant?: 'standard' | 'priority' | 'batch' | 'fast';
+}
+
export function providerReferencePriceQuote(
providerId: string,
modelId: string,
registry: ModelRegistry | null | undefined,
- options: {
- agent?: AgentKind;
- inputTokens?: number;
- at?: string | Date;
- variant?: 'standard' | 'priority' | 'batch' | 'fast';
- } = {},
+ options: ReferencePriceOptions = {},
+): ModelPriceQuote | undefined {
+ const quote = referencePriceQuoteForVariant(providerId, modelId, registry, options);
+ if (!quote || (options.variant ?? 'standard') !== 'standard') return quote;
+ // Usage segments call Fast "priority". Keep the standard quote for display,
+ // and project the independently declared Fast tariff for the cost calculator.
+ const fast =
+ referencePriceQuoteForVariant(providerId, modelId, registry, { ...options, variant: 'fast' }) ??
+ referencePriceQuoteForVariant(providerId, modelId, registry, { ...options, variant: 'priority' });
+ if (!fast || fast.currency !== quote.currency) return quote;
+ const { inputPerMtok, outputPerMtok, cacheReadPerMtok, cacheCreatePerMtok, inputTokenPriceBands } = fast;
+ return {
+ ...quote,
+ priority: { inputPerMtok, outputPerMtok, cacheReadPerMtok, cacheCreatePerMtok, inputTokenPriceBands },
+ };
+}
+
+function referencePriceQuoteForVariant(
+ providerId: string,
+ modelId: string,
+ registry: ModelRegistry | null | undefined,
+ options: ReferencePriceOptions = {},
): ModelPriceQuote | undefined {
// 参考价 registry 的 agent 维度只有 claude-code / codex;Pi(动态 BYOM,按 provider/模型
// 路由)在此按 agent 无关的参考价解析 —— pi 一律降级为 undefined 传给协议函数。
diff --git a/apps/desktop/src/shared/regionalMoney.ts b/apps/desktop/src/shared/regionalMoney.ts
index 655407d2c9..0b046793b4 100644
--- a/apps/desktop/src/shared/regionalMoney.ts
+++ b/apps/desktop/src/shared/regionalMoney.ts
@@ -36,7 +36,7 @@ export interface ModelPriceQuote {
outputPerMtok: number;
cacheReadPerMtok?: number;
cacheCreatePerMtok?: number;
- /** Gateway fast/priority tariff. Missing fields make that request unpriceable. */
+ /** Declared fast/priority tariff. Missing fields make that request unpriceable. */
priority?: {
inputPerMtok?: number;
outputPerMtok?: number;
diff --git a/apps/desktop/src/shared/sessionContextWindow.ts b/apps/desktop/src/shared/sessionContextWindow.ts
new file mode 100644
index 0000000000..323b275cef
--- /dev/null
+++ b/apps/desktop/src/shared/sessionContextWindow.ts
@@ -0,0 +1,57 @@
+import type { AgentKind, Catalog, CatalogModel } from '@cindy/model-providers';
+import { dbToMakerAgentKind } from './agentKindConversion';
+
+/** Route identity carried by both persisted sessions and their renderer projection. */
+export interface ContextWindowSession {
+ agentKind?: string | null;
+ model?: string | null;
+ providerId?: string | null;
+}
+
+/**
+ * Shared with runtime usage normalization: only an unambiguous, verified route
+ * may replace a reported window. Never borrow a same-id model from another provider.
+ */
+export function resolveVerifiedContextWindow(
+ catalog: Pick<Catalog, 'providers'>,
+ agent: AgentKind,
+ providerId: string | null | undefined,
+ modelId: string,
+): number | null {
+ const candidates: CatalogModel[] = [];
+ for (const provider of catalog.providers) {
+ if (provider.routing[agent]?.disabled === true) continue;
+ if (providerId && provider.id !== providerId) continue;
+ for (const model of provider.models[agent] ?? []) {
+ if (model.id === modelId) candidates.push(model);
+ }
+ }
+ if (candidates.length !== 1) return null;
+ const only = candidates[0];
+ if (only.contextWindowVerified !== true) return null;
+ return Number.isFinite(only.contextWindow) && only.contextWindow > 0 ? only.contextWindow : null;
+}
+
+/** Pi's runtime window can differ from its catalog; preserve its saved snapshot. */
+export function resolveSessionContextWindow(
+ catalog: Pick<Catalog, 'providers'>,
+ session: ContextWindowSession,
+): number | null {
+ if (!session.model || session.agentKind === 'pi') return null;
+ return resolveVerifiedContextWindow(
+ catalog,
+ dbToMakerAgentKind(session.agentKind),
+ session.providerId,
+ session.model,
+ );
+}
+
+/** Read-only projection: retain token counts and storage, refresh only the denominator. */
+export function projectSessionContextWindow<
+ T extends ContextWindowSession & { contextWindow: number },
+>(session: T, resolve?: (session: ContextWindowSession) => number | null): T {
+ const window = resolve?.(session);
+ return window && Number.isFinite(window) && window > 0 && window !== session.contextWindow
+ ? { ...session, contextWindow: window }
+ : session;
+}
diff --git a/docs/README.md b/docs/README.md
index 9cc95804fe..0133a9a434 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -13,6 +13,7 @@
| [design-rules/DESIGN.md](design-rules/DESIGN.md) | 设计规范 | authoritative | Desktop 与 Mobile 的视觉语言、Token、组件和交互约定 | — |
| [dev-rules/README.md](./dev-rules/README.md) | 开发规则索引 | authoritative | Cindy 客户端工程规则 | — |
| [environment-setup.md](./dev-rules/environment-setup.md) | 开发环境 | authoritative | 公共依赖、submodule 与首次安装 | — |
+| [model-catalog-maintenance.md](./dev-rules/model-catalog-maintenance.md) | 模型目录维护 | authoritative | Server 发布目录、客户端兜底、模型能力与参考价更新及运行验收 | — |
| [desktop-development.md](./dev-rules/desktop-development.md) | Desktop 开发规则 | authoritative | Desktop 启动、重启与验证 | — |
| [electron-security-and-process-boundaries.md](./dev-rules/electron-security-and-process-boundaries.md) | Electron 安全规则 | authoritative | Renderer、preload、BrowserWindow、WebView、IPC、CSP 与进程边界 | — |
| [credentials-and-local-storage.md](./dev-rules/credentials-and-local-storage.md) | 本地数据安全规则 | authoritative | 凭证、用户持久数据、临时文件与测试目录 | — |
diff --git a/docs/dev-rules/README.md b/docs/dev-rules/README.md
index f1b2fdc89e..6b12290210 100644
--- a/docs/dev-rules/README.md
+++ b/docs/dev-rules/README.md
@@ -16,6 +16,8 @@
- [`repo-map.md`](repo-map.md):仓库地图——apps、packages 与顶层目录的定位导航。
- [`environment-setup.md`](environment-setup.md):公共开发环境、依赖安装与 submodule
准备。
+- [`model-catalog-maintenance.md`](model-catalog-maintenance.md):模型窗口、价格与能力的
+ Server/客户端数据归属、目录更新和运行验收。
- [`desktop-development.md`](desktop-development.md):Desktop 的 Agent 安全启动入口与
分层验证命令。
- [`electron-security-and-process-boundaries.md`](electron-security-and-process-boundaries.md):
diff --git a/docs/dev-rules/model-catalog-maintenance.md b/docs/dev-rules/model-catalog-maintenance.md
new file mode 100644
index 0000000000..95c7d39097
--- /dev/null
+++ b/docs/dev-rules/model-catalog-maintenance.md
@@ -0,0 +1,69 @@
+# 模型目录:数据归属、更新与验收
+
+> **状态**:权威开发规则(authoritative)
+> **读取时机**:新增模型,更新窗口、价格、推理档位、默认值,或排查模型信息显示错误之前
+
+新增模型的支持工作必须覆盖实际运行时的数据源。修改本仓内置 JSON、通过单元测试,
+都不能单独证明用户拿到的模型配置已更新。本规则描述客户端与 Server 的职责边界,
+不改变根 `AGENTS.md` 的跨仓修改边界。
+
+## 1. 先找数据归属
+
+| 内容 | 应维护的位置 | 客户端职责 |
+| --- | --- | --- |
+| 统一模型目录中的名称、窗口、最大输出、推理档位、参考价及默认标记 | `cindy-server` 的 `model-access-server/catalog/providers.json`;若部署配置了 `MODEL_CATALOG_URL`,还需核对那份远程完整快照 | 同步 `packages/model-providers/catalog/model-registry.json` 作为内置兜底,正确消费实际下发值 |
+| Gateway 的实际可用性、路由能力与实价 | Gateway/Server 对应控制面 | 保留实际路由与价格来源,不用 registry 参考价覆盖 Gateway 实价 |
+| 请求协议、SDK 字段兼容、能力透传与 token 计量 | 本仓对应 harness/bridge/host | 根据具体通道能力适配,测试最终请求与用量 |
+| Pi 原生模型元数据 | Pi 上游与本仓 `tools/pi/sync-model-catalog.mjs`、`catalog/pi-model-catalog.json` | 保留上游原生字段,区分公共 API 与订阅协议,遵守 `pi-harness.md` |
+| 旧任务的上下文占比 | 客户端历史读取与展示路径 | 正确区分历史快照、当前目录与运行数据;不能用显示特判掩盖源目录错误 |
+
+同一模型在公共 API、订阅、Gateway,以及不同 Agent 下的能力可能不同。先列出实际
+`provider + agent + model` 路由,再判断哪些字段共用、哪些需要 `perAgent` 或独立条目。
+公共 API 总窗口、Codex 默认工作窗口、可选最大窗口、有效窗口和压缩阈值不是同一个值。
+参考价也不等于订阅实际扣费;标准/Fast、缓存读/写、长输入分档需分别核实。
+
+## 2. 核对真实发布链路
+
+客户端入口是 `packages/model-providers/src/source.ts` 的 `loadCatalog`,Desktop 由
+`apps/desktop/src/main/maker-host/createDesktopProviderService.ts` 装载并刷新活动目录。
+公共目录接口为当前配置的 `modelAccessApiBaseUrl` 下的 `/api/model-catalog/catalog`;
+还可能存在本地覆盖、上一份有效缓存及旧 OSS 兼容来源。不要仅凭文件名或注释认定当前来源。
+
+- Server 仓库文件是随制品发布的基线。改文件不等于部署完成;配置了远程覆盖源时,
+ 还必须检查远程源是否会覆盖该基线。Server 的实际行为以其当前代码、部署配置和接口为准。
+- 客户端 registry 是带 `updatedAt` 的**完整快照**,不是字段级合并。
+ `selectNewerModelRegistry` 会保留较新的有效版本;同 revision 异内容属于冲突。
+ 新客户端内置快照较新时可以暂时胜出,但不能据此省略 Server 更新:下一份较新的
+ Server 快照若仍含错误数据,会再次覆盖回来。
+- 发布新快照时,`updatedAt` 必须递增且内容不可变;与本次协同发布的客户端内置版本
+ 一并核对。价格的 `effectiveFrom`/`verifiedAt` 表达价格生效与核实日期,不能为了
+ 提升目录 revision 随意改成发布时间。
+- 修模型数据时保留用户显式 override,不顺带更换默认模型或默认推理档位。
+
+## 3. 新模型或配置更新的工作顺序
+
+1. **核实通道事实**:查官方模型文档、定价和所用 harness 的实际发现结果;记录来源与
+ 核实时间,列出 API/订阅/Gateway 的差异。不要只从模型名猜协议或能力。
+2. **检查线上现状**:读取目标部署的公共目录,摘录模型条目与 registry revision;同时
+ 检查客户端活动目录来源、实际路由和 override。检查多个部署时分别记录结果。
+3. **分别修改责任侧**:Server 维护发布目录,客户端同步兜底及必要协议/计量适配。
+ 数据已能解决的问题不新增客户端硬编码;客户端协议缺口也不能靠改目录假装解决。
+ 需要跨仓配套时,在交付说明中列出对应变更与发布依赖。
+4. **做有区分力的回归**:覆盖不同路由窗口、标准与 Fast 价格、缓存与长输入分档,
+ 以及上游原生元数据优先。涉及显示时覆盖旧任务重新打开、目录刷新、新一轮上报、
+ 显式长窗口、缺失/歧义来源与 Pi 运行时窗口。
+5. **按运行结果验收**:确认部署后公共接口已返回目标条目,客户端实际接受目标 revision,
+ 再验证选择模型、请求参数和新旧任务显示。只跑本地 fixture、只成功启动登录页、或
+ 只通过 CI 时,明确记录尚未完成的运行验收,不宣称线上支持已闭环。
+
+## 4. 上下文显示错误的排查顺序
+
+先检查活动目录是否就写错了窗口,再检查当前路由的运行时上报与校正,最后检查旧任务
+持久化快照及显示优先级。数据库里同一个大窗口数值,可能来自过去的上报,也可能来自
+当前错误目录被当作 verified 写入;**仅凭旧任务或截图不能判断是哪一种**。
+
+修复显示时复用运行时已有的路由判定,保留数据来源边界。目录错误应回到 Server/发布
+源修正;不要把某个模型的正确数字硬编码进圆环,也不要用取最小值一律压掉显式长窗口。
+
+相关规则:[`configuration-and-overrides.md`](configuration-and-overrides.md)、
+[`pi-harness.md`](pi-harness.md)、[`remote-and-mobile-adaptation.md`](remote-and-mobile-adaptation.md)。
diff --git a/packages/anthropic-responses-bridge/src/__tests__/handler.test.ts b/packages/anthropic-responses-bridge/src/__tests__/handler.test.ts
index d66fbef41a..8063f9ef07 100644
--- a/packages/anthropic-responses-bridge/src/__tests__/handler.test.ts
+++ b/packages/anthropic-responses-bridge/src/__tests__/handler.test.ts
@@ -92,6 +92,21 @@ afterEach(() => {
});
describe('createResponsesHandler', () => {
+ it.each(['max', 'ultra'])('honors declared %s capability without changing legacy providers', async (effort) => {
+ const seen: Array<{ reasoning: { effort: string } }> = [];
+ vi.stubGlobal('fetch', vi.fn(async (_url: string, init: RequestInit) => {
+ seen.push(JSON.parse(String(init.body)));
+ return new Response(sse(OK_SSE), { headers: { 'content-type': 'text/event-stream' } });
+ }));
+ const capabilities = vi.fn((model: string) => model === 'gpt-6-astra'
+ ? ['low', 'medium', 'high', 'xhigh', 'max', 'ultra'] : ['low', 'high', 'xhigh']);
+ const handler = createResponsesHandler({ providers: [providerConfig({ supportedReasoningEfforts: capabilities })] });
+ await invoke(handler, { model: 'chatgpt/gpt-6-astra', messages: [] }, { prefs: { reasoningEffort: effort } });
+ await invoke(handler, { model: 'chatgpt/gpt-5.5', messages: [] }, { prefs: { reasoningEffort: effort } });
+ expect(capabilities).toHaveBeenCalledWith('gpt-6-astra');
+ expect(seen.map((body) => body.reasoning.effort)).toEqual([effort, 'xhigh']);
+ });
+
it('prefs.fast + effort → 上游请求体 service_tier / reasoning.effort;SSE 翻译写回', async () => {
const seen: Array<{ url: string; body: Record<string, unknown> }> = [];
vi.stubGlobal('fetch', vi.fn(async (url: string, init: RequestInit) => {
diff --git a/packages/anthropic-responses-bridge/src/__tests__/usage.test.ts b/packages/anthropic-responses-bridge/src/__tests__/usage.test.ts
new file mode 100644
index 0000000000..117052bb59
--- /dev/null
+++ b/packages/anthropic-responses-bridge/src/__tests__/usage.test.ts
@@ -0,0 +1,27 @@
+import { describe, expect, it } from 'vitest';
+import { mapUsage } from '../usage.js';
+
+describe('Responses cache accounting', () => {
+ it('keeps ordinary input, cache reads and cache writes disjoint', () => {
+ const usage = mapUsage({
+ input_tokens: 15_000,
+ input_tokens_details: { cached_tokens: 10_000, cache_write_tokens: 3_000 },
+ output_tokens: 200,
+ });
+ expect(usage).toEqual({
+ input_tokens: 2_000,
+ cache_read_input_tokens: 10_000,
+ cache_creation_input_tokens: 3_000,
+ output_tokens: 200,
+ });
+ expect(usage.input_tokens + usage.cache_read_input_tokens + usage.cache_creation_input_tokens).toBe(15_000);
+ });
+
+ it('preserves accounting for older providers without cache writes', () => {
+ expect(mapUsage({ input_tokens: 100, input_tokens_details: { cached_tokens: 30 } })).toMatchObject({
+ input_tokens: 70,
+ cache_read_input_tokens: 30,
+ cache_creation_input_tokens: 0,
+ });
+ });
+});
diff --git a/packages/anthropic-responses-bridge/src/handler.ts b/packages/anthropic-responses-bridge/src/handler.ts
index 9d793b2899..96c0a9ab55 100644
--- a/packages/anthropic-responses-bridge/src/handler.ts
+++ b/packages/anthropic-responses-bridge/src/handler.ts
@@ -31,12 +31,13 @@ import type {
} from './types.js';
/**
- * maker 的 effort 档(minimal/low/medium/high/xhigh/max)→ Responses 端点接受的 4 档。
- * Responses(codex / api.x.ai)只认 low/medium/high/xhigh:minimal 收敛到 low、max 收敛到 xhigh。
+ * Higher efforts require an explicit per-model capability; providers without one keep the
+ * historical xhigh ceiling. Codex subscription capabilities differ from the public API.
* 无输入 / 无法识别 → undefined(translateRequest 回退默认档)。
*/
-function normalizeReasoningEffort(raw: string | undefined): ResponsesReasoningEffort | undefined {
- switch ((raw ?? '').trim().toLowerCase()) {
+function normalizeReasoningEffort(raw: string | undefined, supported?: readonly string[]): ResponsesReasoningEffort | undefined {
+ const effort = (raw ?? '').trim().toLowerCase();
+ switch (effort) {
case 'minimal':
case 'low':
return 'low';
@@ -45,8 +46,11 @@ function normalizeReasoningEffort(raw: string | undefined): ResponsesReasoningEf
case 'high':
return 'high';
case 'xhigh':
+ return 'xhigh';
case 'max':
case 'ultra':
+ if (supported?.includes(effort)) return effort;
+ if (effort === 'ultra' && supported?.includes('max')) return 'max';
return 'xhigh';
default:
return undefined;
@@ -339,7 +343,7 @@ export function createResponsesHandler(opts: ResponsesHandlerOptions): Responses
// reasoning 档:host 经 prefs 闭包传入用户选定 effort(CC 不会把非 Anthropic 模型的 effort
// 放进请求体,由 host 从会话态解析);模型不支持 reasoning → 'none'。
const reasoningSupported = provider.supportsReasoning ? provider.supportsReasoning(realModel) : true;
- const prefEffort = normalizeReasoningEffort(prefs?.reasoningEffort);
+ const prefEffort = normalizeReasoningEffort(prefs?.reasoningEffort, provider.supportedReasoningEfforts?.(realModel));
const reasoningEffort = !reasoningSupported ? 'none' : prefEffort;
// Fast 模式:prefs.fast × provider.fastServiceTier(codex='priority')。
diff --git a/packages/anthropic-responses-bridge/src/translate-request.ts b/packages/anthropic-responses-bridge/src/translate-request.ts
index 2e4e451efc..088aeed16e 100644
--- a/packages/anthropic-responses-bridge/src/translate-request.ts
+++ b/packages/anthropic-responses-bridge/src/translate-request.ts
@@ -279,8 +279,8 @@ function resolveToolChoice(
return choice;
}
-/** Responses 端点接受的 reasoning effort 档(codex / api.x.ai 通用)。 */
-export type ResponsesReasoningEffort = 'low' | 'medium' | 'high' | 'xhigh';
+/** Responses reasoning effort 的并集;各通道只接受自身声明的档位。 */
+export type ResponsesReasoningEffort = 'low' | 'medium' | 'high' | 'xhigh' | 'max' | 'ultra';
export interface TranslateRequestOptions {
/** 发给上游的真实 model id(已 strip 掉 bridge 前缀)。 */
@@ -295,7 +295,7 @@ export interface TranslateRequestOptions {
maxOutputTokensSupported?: boolean;
/**
* reasoning 档控制:
- * - 具体档('low'|'medium'|'high'|'xhigh')→ 发 `reasoning: { effort, summary:'auto' }`(用户选的思维深度经此流入);
+ * - 具体档(由通道能力限定)→ 发 `reasoning: { effort, summary:'auto' }`(用户选的思维深度经此流入);
* - `'none'` → **完全不发** reasoning 字段(某些模型如 xAI grok-code-fast 会对 reasoningEffort 报 400);
* - 省略(undefined)→ 回退到按 thinking.budget_tokens 推断(默认 medium),与旧行为一致。
*/
diff --git a/packages/anthropic-responses-bridge/src/types.ts b/packages/anthropic-responses-bridge/src/types.ts
index bb17d50c60..0dc0982dff 100644
--- a/packages/anthropic-responses-bridge/src/types.ts
+++ b/packages/anthropic-responses-bridge/src/types.ts
@@ -128,7 +128,7 @@ export interface ResponsesRequest {
include?: string[];
prompt_cache_key?: string;
max_output_tokens?: number;
- reasoning?: { effort?: 'low' | 'medium' | 'high' | 'xhigh'; summary?: 'auto' | 'concise' | 'detailed' | 'none' };
+ reasoning?: { effort?: 'low' | 'medium' | 'high' | 'xhigh' | 'max' | 'ultra'; summary?: 'auto' | 'concise' | 'detailed' | 'none' };
/** Fast 模式:codex 后端的 'priority' tier(models_cache service_tiers 声明,UI 名 "Fast")。 */
service_tier?: string;
}
@@ -198,6 +198,8 @@ export interface BridgeProviderConfig {
* 对 reasoningEffort 报 400)bridge 将**完全不发** reasoning 字段。省略 = 全部支持。
*/
supportsReasoning?: (model: string) => boolean;
+ /** Final per-model route capabilities. Omitted providers retain the legacy xhigh ceiling. */
+ supportedReasoningEfforts?: (model: string) => readonly string[] | undefined;
/**
* 该(去前缀后的)model 是否启用 strict function-tool 约束解码。这是生产唯一控制面
* (不走环境变量)。开启后 translate 层仍**逐工具**做 strict 子集兼容检查
diff --git a/packages/anthropic-responses-bridge/src/usage.ts b/packages/anthropic-responses-bridge/src/usage.ts
index 42ffca037f..fcd673aa3c 100644
--- a/packages/anthropic-responses-bridge/src/usage.ts
+++ b/packages/anthropic-responses-bridge/src/usage.ts
@@ -8,7 +8,7 @@
* cache_read_input_tokens, cache_creation_input_tokens }
*
* 关键换算:Anthropic 的 input_tokens **不含** cache_read,而 Responses 的 input_tokens
- * **含** cached;所以 anthropic.input_tokens = responses.input_tokens - cached_tokens,
+ * **含** cached 与 cache write;所以普通输入要减去两类缓存 token,
* cache_read_input_tokens = cached_tokens。output_tokens 直接透传(已含 reasoning,正是要计费的)。
*/
@@ -28,12 +28,13 @@ export function mapUsage(responsesUsage: unknown): AnthropicUsage {
const inputTotal = num(u.input_tokens);
const inputDetails = (u.input_tokens_details ?? {}) as Record<string, unknown>;
const cached = num(inputDetails.cached_tokens);
+ const cacheWrite = num(inputDetails.cache_write_tokens);
const output = num(u.output_tokens);
return {
- input_tokens: Math.max(0, inputTotal - cached),
+ input_tokens: Math.max(0, inputTotal - cached - cacheWrite),
output_tokens: output,
cache_read_input_tokens: cached,
- // Responses 不区分 cache creation(它没有显式写缓存的概念);恒 0。
- cache_creation_input_tokens: 0,
+ // Older providers omit cache_write_tokens; keep their historical zero.
+ cache_creation_input_tokens: cacheWrite,
};
}
diff --git a/packages/maker-core/src/agents/codex/app-server/protocol.ts b/packages/maker-core/src/agents/codex/app-server/protocol.ts
index 5ebc36b0e6..6fb89d8326 100644
--- a/packages/maker-core/src/agents/codex/app-server/protocol.ts
+++ b/packages/maker-core/src/agents/codex/app-server/protocol.ts
@@ -908,6 +908,8 @@ export interface TokenUsageBreakdown {
totalTokens: number;
inputTokens: number;
cachedInputTokens: number;
+ /** Present in Codex 0.153.0; older app-server versions omit this subset. */
+ cacheWriteInputTokens?: number;
outputTokens: number;
reasoningOutputTokens: number;
}
diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.ts
index 35a49e1de6..90f80b189e 100644
--- a/packages/maker-core/src/agents/codex/index.test.ts
+++ b/packages/maker-core/src/agents/codex/index.test.ts
@@ -17092,7 +17092,7 @@ describe('CodexAgent MCP thread context hooks', () => {
}
});
- it('emits only monotonic request segments and keeps reasoning as a non-additive detail', async () => {
+ it.each([undefined, 20_000])('emits monotonic segments with cache-write subset %s and non-additive reasoning', async (cacheWriteInputTokens) => {
const agent = new CodexAgent(createDeps());
const host = installFakeHost(agent);
const handle = await agent.startSession({
@@ -17118,6 +17118,7 @@ describe('CodexAgent MCP thread context hooks', () => {
totalTokens: 60_007,
inputTokens: 60_000,
cachedInputTokens: 10_000,
+ cacheWriteInputTokens,
outputTokens: 7,
reasoningOutputTokens: 3,
},
@@ -17125,6 +17126,7 @@ describe('CodexAgent MCP thread context hooks', () => {
totalTokens: 60_007,
inputTokens: 60_000,
cachedInputTokens: 10_000,
+ cacheWriteInputTokens,
outputTokens: 7,
reasoningOutputTokens: 3,
},
@@ -17170,16 +17172,16 @@ describe('CodexAgent MCP thread context hooks', () => {
const done = events.find((event) => event.type === 'done');
expect((done?.data as { usage?: unknown }).usage).toMatchObject({
- promptTokens: 100_000,
+ promptTokens: 100_000 - (cacheWriteInputTokens ?? 0),
completionTokens: 11,
reasoningTokens: 5,
cachedTokens: 15_000,
segments: [
{
- inputTokens: 50_000,
+ inputTokens: 50_000 - (cacheWriteInputTokens ?? 0),
outputTokens: 7,
cacheReadTokens: 10_000,
- cacheCreateTokens: 0,
+ cacheCreateTokens: cacheWriteInputTokens ?? 0,
reasoningTokens: 3,
},
{
diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.ts
index 459ef7fd71..51eb8a187a 100644
--- a/packages/maker-core/src/agents/codex/index.ts
+++ b/packages/maker-core/src/agents/codex/index.ts
@@ -10698,8 +10698,9 @@ export class CodexAgent extends BaseAgent {
if (!last) return;
lastTurnTokenUsage = last;
const cached = last.cachedInputTokens ?? 0;
+ const cacheWrite = last.cacheWriteInputTokens ?? 0;
const totalInput = last.inputTokens ?? 0;
- const uncachedInput = Math.max(0, totalInput - cached);
+ const uncachedInput = Math.max(0, totalInput - cached - cacheWrite);
const cumulativeTotal = params.tokenUsage?.total;
if (!cumulativeTotal) return;
const previousCursor = acceptedUsageTotalByThread.get(params.threadId);
@@ -10708,6 +10709,7 @@ export class CodexAgent extends BaseAgent {
const hasBillableLast =
last.inputTokens > 0 ||
last.cachedInputTokens > 0 ||
+ cacheWrite > 0 ||
last.outputTokens > 0 ||
last.reasoningOutputTokens > 0;
// A lower cursor can be an out-of-order frame, so it is not sufficient
@@ -10732,7 +10734,7 @@ export class CodexAgent extends BaseAgent {
// reasoningOutputTokens again double-counts completion usage.
outputTokens: last.outputTokens ?? 0,
cacheReadTokens: cached,
- cacheCreateTokens: 0,
+ cacheCreateTokens: cacheWrite,
reasoningTokens: last.reasoningOutputTokens ?? 0,
model: turnOriginByTurnId.get(params.turnId)?.model ?? activeTurnModel ?? mutableModel,
priceVariant: isFastServiceTier(
diff --git a/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts b/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts
index 2d272a129e..8a5a96fd96 100644
--- a/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts
@@ -342,6 +342,32 @@ function loadBashTimeoutHelpers(): {
}
describe('cindy-bridge extension source', () => {
+ it('adapts Astra API payloads without changing other models or subscription requests', () => {
+ const start = CINDY_BRIDGE_EXTENSION_SOURCE.indexOf('function astraResponsesPayload(');
+ const end = CINDY_BRIDGE_EXTENSION_SOURCE.indexOf('export default async function cindyBridge');
+ const adapt = new Function(`${CINDY_BRIDGE_EXTENSION_SOURCE.slice(start, end)}; return astraResponsesPayload;`)();
+ const original = {
+ prompt_cache_retention: '24h',
+ prompt_cache_options: { mode: 'explicit' },
+ temperature: 0.5, top_p: 1, top_logprobs: 2,
+ include: ['reasoning.encrypted_content', 'message.output_text.logprobs'],
+ reasoning: { effort: 'none', summary: 'auto' },
+ input: [{ role: 'user', content: 'hello' }],
+ };
+ const model = { id: 'gpt-6-astra', api: 'openai-responses' };
+ expect(adapt(original, model)).toEqual({
+ prompt_cache_options: { ttl: '30m', mode: 'explicit' },
+ include: ['reasoning.encrypted_content'],
+ reasoning: { effort: 'low', summary: 'auto' },
+ input: original.input,
+ });
+ expect(original.reasoning.effort).toBe('none');
+ expect(original.prompt_cache_retention).toBe('24h');
+ expect(adapt({ reasoning: { effort: 'max' } }, model).reasoning.effort).toBe('max');
+ expect(adapt(original, { ...model, id: 'gpt-5.5' })).toBeUndefined();
+ expect(adapt(original, { ...model, api: 'openai-codex-responses' })).toBeUndefined();
+ });
+
it('is valid standalone TypeScript for the Pi runtime to load', () => {
const result = ts.transpileModule(CINDY_BRIDGE_EXTENSION_SOURCE, {
compilerOptions: {
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts
index 86b6f11d1e..bdd26ad55b 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts
@@ -129,7 +129,13 @@ function anthropicStreamBody(text: string): string {
}
/** 最小完整的 OpenAI Responses SSE 流:供 Pi 原生 Responses BYOM 回归使用。 */
-function responsesStreamBody(text: string, model: string): string {
+function responsesStreamBody(text: string, model: string, usage = {
+ input_tokens: 1,
+ input_tokens_details: { cached_tokens: 0, cache_write_tokens: 0 },
+ output_tokens: 1,
+ output_tokens_details: { reasoning_tokens: 0 },
+ total_tokens: 2,
+}): string {
const responseId = 'resp_byom_reasoning_1';
const item = {
id: 'msg_byom_reasoning_1',
@@ -159,13 +165,7 @@ function responsesStreamBody(text: string, model: string): string {
tools: [],
top_p: 1,
truncation: 'disabled',
- usage: {
- input_tokens: 1,
- input_tokens_details: { cached_tokens: 0 },
- output_tokens: 1,
- output_tokens_details: { reasoning_tokens: 0 },
- total_tokens: 2,
- },
+ usage,
metadata: {},
};
return sse([
@@ -1486,10 +1486,13 @@ describe.skipIf(!piAvailable)('PiAgent integration (real pi binary + fake gatewa
},
);
- it(
- 'BYOM Responses: an explicit Pi effort reaches the upstream reasoning.effort request field',
+ it.each([
+ { model: 'byom-reasoner', effort: 'xhigh' as const },
+ { model: 'gpt-6-astra', effort: 'max' as const },
+ ])(
+ 'BYOM Responses: $model sends $effort with compatible cache parameters',
{ timeout: 60_000 },
- async () => {
+ async ({ model, effort }) => {
const nativeSeen: Array<{
url: string;
auth: string | undefined;
@@ -1510,7 +1513,13 @@ describe.skipIf(!piAvailable)('PiAgent integration (real pi binary + fake gatewa
'content-type': 'text/event-stream',
'cache-control': 'no-cache',
});
- res.end(responsesStreamBody('pong from Responses', 'byom-reasoner'));
+ res.end(responsesStreamBody('pong from Responses', model, {
+ input_tokens: 300_000,
+ input_tokens_details: { cached_tokens: 200_000, cache_write_tokens: 50_000 },
+ output_tokens: 100,
+ output_tokens_details: { reasoning_tokens: 0 },
+ total_tokens: 300_100,
+ }));
});
});
await new Promise<void>((resolve) => nativeServer.listen(0, '127.0.0.1', resolve));
@@ -1540,16 +1549,21 @@ describe.skipIf(!piAvailable)('PiAgent integration (real pi binary + fake gatewa
apiKeyEnvVar: 'CINDY_PI_KEY_LOCALRESPONSES',
models: [
{
- id: 'byom-reasoner',
+ id: model,
name: 'BYOM Reasoner',
reasoning: true,
+ contextWindow: 1_050_000,
+ cost: {
+ input: 10, output: 50, cacheRead: 1, cacheWrite: 12.5,
+ tiers: [{ inputTokensAbove: 272_000, input: 20, output: 75, cacheRead: 2, cacheWrite: 25 }],
+ },
thinkingLevelMap: {
minimal: null,
low: 'low',
medium: null,
high: 'high',
xhigh: 'xhigh',
- max: null,
+ max: model === 'gpt-6-astra' ? 'max' : null,
},
},
],
@@ -1566,24 +1580,40 @@ describe.skipIf(!piAvailable)('PiAgent integration (real pi binary + fake gatewa
sessionId: 'byom-responses-session',
workingDir,
providerId: 'localresponses',
- model: 'byom-reasoner',
- effort: 'xhigh',
+ model,
+ effort,
});
const done = (async () => {
for await (const event of handle!.events()) {
- if (event.type === 'done') break;
+ if (event.type === 'done') return event;
}
})();
await handle.send({ type: 'user', content: 'reason carefully' });
- await done;
+ const completed = await done;
+ expect(completed?.data).toMatchObject({
+ status: 'completed',
+ usage: {
+ inputTokens: 50_000, outputTokens: 100,
+ cacheReadTokens: 200_000, cacheCreationTokens: 50_000,
+ segments: [expect.objectContaining({ cacheCreateTokens: 50_000, costUsd: expect.closeTo(2.6575, 10) })],
+ },
+ });
expect(nativeSeen).toHaveLength(1);
expect(nativeSeen[0]?.url).toMatch(/\/responses(?:\?|$)/);
expect(nativeSeen[0]?.auth).toContain('responses-secret-key');
expect(JSON.parse(nativeSeen[0]?.body ?? '{}')).toMatchObject({
- model: 'byom-reasoner',
- reasoning: { effort: 'xhigh' },
- });
+ model,
+ reasoning: { effort },
+ });
+ const payload = JSON.parse(nativeSeen[0]?.body ?? '{}');
+ if (model === 'gpt-6-astra') {
+ expect(payload.prompt_cache_retention).toBeUndefined();
+ expect(payload.prompt_cache_options).toEqual({ ttl: '30m' });
+ } else {
+ expect(payload.prompt_cache_retention).toBe('24h');
+ expect(payload.prompt_cache_options).toBeUndefined();
+ }
expect(seenRequests.length).toBe(gatewayBefore);
} finally {
await handle?.close();
diff --git a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts b/packages/maker-core/src/agents/pi/cindy-bridge-source.ts
index 098873faee..f95e5d1402 100644
--- a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts
+++ b/packages/maker-core/src/agents/pi/cindy-bridge-source.ts
@@ -3059,7 +3059,29 @@ function rgGlob(
});
}
+// Astra's public Responses contract differs from older Pi serializers. Keep this at the
+// native pre-request hook so BYOM, gateway and subagent calls share the same wire correction.
+function astraResponsesPayload(payload, model) {
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) return undefined;
+ if (!model || model.api !== 'openai-responses') return undefined;
+ if (!/(^|\/)gpt-6-astra(?:\[1m\])?$/.test(model.id ?? '')) return undefined;
+ const out = { ...payload };
+ delete out.prompt_cache_retention;
+ out.prompt_cache_options = { ttl: '30m', ...out.prompt_cache_options };
+ delete out.temperature;
+ delete out.top_p;
+ delete out.top_logprobs;
+ if (Array.isArray(out.include)) {
+ out.include = out.include.filter((entry) => entry !== 'message.output_text.logprobs');
+ }
+ if (out.reasoning?.effort === 'none' || out.reasoning?.effort === 'minimal') {
+ out.reasoning = { ...out.reasoning, effort: 'low' };
+ }
+ return out;
+}
+
export default async function cindyBridge(pi: any) {
+ pi.on('before_provider_request', (event, ctx) => astraResponsesPayload(event.payload, ctx.model));
const mcpGateway = new CindyMcpGateway();
// bash 隔离 home 经 resolveBashPackageHome 解析(首次加载读删 + 防篡改 stash,
// 扩展重载(#3070)经双重验证取回,而不是拿到 undefined 让 bash 永久 fail-closed)。
diff --git a/packages/model-providers/AGENTS.md b/packages/model-providers/AGENTS.md
new file mode 100644
index 0000000000..d11bfd8e58
--- /dev/null
+++ b/packages/model-providers/AGENTS.md
@@ -0,0 +1,8 @@
+# 模型目录维护入口
+
+新增模型或修改窗口、价格、推理档位、默认值之前,先读
+[`../../docs/dev-rules/model-catalog-maintenance.md`](../../docs/dev-rules/model-catalog-maintenance.md)。
+
+本包的内置目录是客户端兜底,不能替代 Cindy Server 的发布目录。先核对公共目录接口、
+当前生效的 registry revision 与实际路由,再决定应修改 Server 数据、客户端兼容代码,
+还是两者都改。Pi 原生目录有独立来源,不从订阅 registry 推导公共 API 配置。
diff --git a/packages/model-providers/catalog/model-registry.json b/packages/model-providers/catalog/model-registry.json
index 97251e3951..9a55ddadf8 100644
--- a/packages/model-providers/catalog/model-registry.json
+++ b/packages/model-providers/catalog/model-registry.json
@@ -1,6 +1,6 @@
{
"schemaVersion": 1,
- "updatedAt": "2026-08-17T00:00:00.000Z",
+ "updatedAt": "2026-09-04T21:38:48.000Z",
"models": [
{
"id": "openai/gpt-5.6-sol",
@@ -1730,6 +1730,90 @@
"agents": ["claude-code", "codex"]
}
]
+ },
+ {
+ "id": "openai/gpt-6-astra",
+ "name": "GPT-6 Astra",
+ "status": "active",
+ "group": "gpt",
+ "contextWindow": 1050000,
+ "maxOutputTokens": 128000,
+ "efforts": [
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "defaultEffort": "medium",
+ "sortOrder": 22,
+ "supportsFastMode": true,
+ "perAgent": {
+ "claude-code": {
+ "contextWindow": 272000,
+ "efforts": [
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max",
+ "ultra"
+ ]
+ },
+ "codex": {
+ "contextWindow": 272000,
+ "efforts": [
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max",
+ "ultra"
+ ]
+ }
+ },
+ "routes": [
+ {
+ "providerId": "openai",
+ "modelId": "gpt-6-astra",
+ "agents": [
+ "claude-code",
+ "codex"
+ ],
+ "referencePrices": [
+ {
+ "currency": "USD",
+ "variant": "standard",
+ "inputPerMtok": 10,
+ "outputPerMtok": 50,
+ "cacheReadPerMtok": 1,
+ "cacheWritePerMtok": 12.5,
+ "maxInputTokens": 272001,
+ "effectiveFrom": "2026-09-04",
+ "source": {
+ "kind": "provider-official",
+ "url": "https://developers.openai.com/api/docs/models/gpt-6-astra",
+ "verifiedAt": "2026-09-04"
+ }
+ },
+ {
+ "currency": "USD",
+ "variant": "fast",
+ "inputPerMtok": 20,
+ "outputPerMtok": 100,
+ "cacheReadPerMtok": 2,
+ "cacheWritePerMtok": 25,
+ "maxInputTokens": 272001,
+ "effectiveFrom": "2026-09-04",
+ "source": {
+ "kind": "provider-official",
+ "url": "https://developers.openai.com/api/docs/models/gpt-6-astra",
+ "verifiedAt": "2026-09-04"
+ }
+ }
+ ]
+ }
+ ]
}
]
}
diff --git a/packages/model-providers/catalog/pi-model-catalog.json b/packages/model-providers/catalog/pi-model-catalog.json
index 72eb6700c3..0cc3faffd8 100644
--- a/packages/model-providers/catalog/pi-model-catalog.json
+++ b/packages/model-providers/catalog/pi-model-catalog.json
@@ -1,5 +1,5 @@
{
- "generatedAt": "2026-09-03T10:41:11.000Z",
+ "generatedAt": "2026-09-04T21:38:48.000Z",
"providers": {
"anthropic": [
{
@@ -1562,6 +1562,44 @@
"supportsAdditionalTools": true,
"supportsToolSearch": true
}
+ },
+ {
+ "id": "gpt-6-astra",
+ "name": "GPT-6 Astra",
+ "provider": "openai-codex",
+ "api": "openai-codex-responses",
+ "baseUrl": "https://chatgpt.com/backend-api",
+ "reasoning": true,
+ "input": [
+ "text",
+ "image"
+ ],
+ "cost": {
+ "input": 10,
+ "output": 50,
+ "cacheRead": 1,
+ "cacheWrite": 12.5,
+ "tiers": [
+ {
+ "inputTokensAbove": 272000,
+ "input": 20,
+ "output": 75,
+ "cacheRead": 2,
+ "cacheWrite": 25
+ }
+ ]
+ },
+ "contextWindow": 272000,
+ "maxTokens": 128000,
+ "thinkingLevelMap": {
+ "off": "low",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ }
}
],
"qwen-token-plan-cn": [
@@ -2906,6 +2944,46 @@
"contextWindow": 200000,
"maxTokens": 131072
}
+ ],
+ "openai": [
+ {
+ "id": "gpt-6-astra",
+ "name": "GPT-6 Astra",
+ "provider": "openai",
+ "api": "openai-responses",
+ "baseUrl": "https://api.openai.com/v1",
+ "reasoning": true,
+ "input": [
+ "text",
+ "image"
+ ],
+ "cost": {
+ "input": 10,
+ "output": 50,
+ "cacheRead": 1,
+ "cacheWrite": 12.5,
+ "tiers": [
+ {
+ "inputTokensAbove": 272000,
+ "input": 20,
+ "output": 75,
+ "cacheRead": 2,
+ "cacheWrite": 25
+ }
+ ]
+ },
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "thinkingLevelMap": {
+ "off": "low",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ }
+ }
]
}
}
diff --git a/packages/model-providers/src/__tests__/catalog.test.ts b/packages/model-providers/src/__tests__/catalog.test.ts
index 63a946a838..ad3a8ffb5c 100644
--- a/packages/model-providers/src/__tests__/catalog.test.ts
+++ b/packages/model-providers/src/__tests__/catalog.test.ts
@@ -143,7 +143,7 @@ describe('bundled catalog validity (dynamic-first contract)', () => {
}
});
- it('ships only Pi-native subscription models and does not invent GPT-6 from Registry', () => {
+ it('ships Pi-native subscription models plus explicit Astra support, independent of Registry', () => {
expect(provider('openai').models.pi?.map((model) => model.id)).toEqual([
'chatgpt/gpt-5.3-codex-spark',
'chatgpt/gpt-5.4',
@@ -152,9 +152,10 @@ describe('bundled catalog validity (dynamic-first contract)', () => {
'chatgpt/gpt-5.6-luna',
'chatgpt/gpt-5.6-sol',
'chatgpt/gpt-5.6-terra',
+ 'chatgpt/gpt-6-astra',
]);
expect(
- provider('openai').models.pi?.some((model) => model.id.startsWith('chatgpt/gpt-6')),
+ provider('openai').models.pi?.some((model) => model.id === 'chatgpt/gpt-6'),
).toBe(false);
expect(provider('anthropic').models.pi).toHaveLength(14);
});
diff --git a/packages/model-providers/src/__tests__/modelRegistry.test.ts b/packages/model-providers/src/__tests__/modelRegistry.test.ts
index b07962ee20..9b38dd9a12 100644
--- a/packages/model-providers/src/__tests__/modelRegistry.test.ts
+++ b/packages/model-providers/src/__tests__/modelRegistry.test.ts
@@ -10,6 +10,19 @@ import {
const registry = BUNDLED_CATALOG.modelRegistry;
describe("model registry", () => {
+ it.each([
+ { variant: "standard" as const, inputPerMtok: 10, cacheWritePerMtok: 12.5 },
+ { variant: "fast" as const, inputPerMtok: 20, cacheWritePerMtok: 25 },
+ ])("Astra $variant prices are available on the verified UTC day", ({ variant, inputPerMtok, cacheWritePerMtok }) => {
+ // September 5 in Auckland is still September 4 UTC: pricing uses the UTC day.
+ const options = { at: new Date("2026-09-04T21:00:00Z"), variant, inputTokens: 272_000 };
+ expect(resolveModelReferencePrice(registry, "openai", "gpt-6-astra", options)?.price)
+ .toMatchObject({ inputPerMtok, cacheWritePerMtok });
+ expect(resolveModelReferencePrice(registry, "openai", "gpt-6-astra", {
+ ...options, inputTokens: 272_001,
+ })).toBeUndefined();
+ });
+
it("compares revision instants with normalized timestamps before checking content", () => {
if (!registry) throw new Error("missing bundled registry");
const current = { ...registry, updatedAt: "2026-08-02T02:00:00.000Z" };
diff --git a/packages/model-providers/src/__tests__/piCatalogCorrections.test.ts b/packages/model-providers/src/__tests__/piCatalogCorrections.test.ts
index ad49fd71a9..439490e8f4 100644
--- a/packages/model-providers/src/__tests__/piCatalogCorrections.test.ts
+++ b/packages/model-providers/src/__tests__/piCatalogCorrections.test.ts
@@ -4,6 +4,7 @@ import {
applyKnownXaiCorrections,
preferredDefaultEffort,
} from '../../../../tools/pi/xai-catalog-corrections.mjs';
+import { applyAstraCatalogAdditions } from '../../../../tools/pi/openai-catalog-corrections.mjs';
import piCatalog from '../../catalog/pi-model-catalog.json';
import { BUNDLED_CATALOG } from '../catalog.js';
@@ -60,3 +61,20 @@ describe('Pi xAI catalog corrections', () => {
);
});
});
+
+describe('Pi Astra catalog additions', () => {
+ it('regenerates separate API and subscription profiles and yields to upstream metadata', () => {
+ const providers = applyAstraCatalogAdditions({});
+ expect(providers.openai[0]).toMatchObject({
+ api: 'openai-responses', contextWindow: 1_050_000,
+ thinkingLevelMap: { off: 'low', max: 'max' },
+ cost: { cacheWrite: 12.5, tiers: [{ inputTokensAbove: 272_000, cacheWrite: 25 }] },
+ });
+ expect(providers['openai-codex'][0]).toMatchObject({ api: 'openai-codex-responses', contextWindow: 272_000 });
+ const native = { id: 'gpt-6-astra', contextWindow: 872_000, upstreamField: true };
+ expect(applyAstraCatalogAdditions({ openai: [native] }).openai).toEqual([native]);
+ expect(applyAstraCatalogAdditions(providers)).toEqual(providers);
+ expect(piCatalog.providers.openai).toEqual(providers.openai);
+ expect(piCatalog.providers['openai-codex'].find((model) => model.id === 'gpt-6-astra')).toEqual(providers['openai-codex'][0]);
+ });
+});
diff --git a/packages/model-providers/src/__tests__/piCatalogSync.test.ts b/packages/model-providers/src/__tests__/piCatalogSync.test.ts
new file mode 100644
index 0000000000..52892e31ed
--- /dev/null
+++ b/packages/model-providers/src/__tests__/piCatalogSync.test.ts
@@ -0,0 +1,95 @@
+import { execFileSync } from "node:child_process";
+import {
+ cpSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { fileURLToPath, pathToFileURL } from "node:url";
+import { describe, expect, it } from "vitest";
+
+import piCatalog from "../../catalog/pi-model-catalog.json";
+
+const root = fileURLToPath(new URL("../../../../", import.meta.url));
+
+describe("Pi catalog sync upstream precedence", () => {
+ it.each(["input", "online"] as const)(
+ "reads native public API Astra metadata through the %s sync path",
+ (source) => {
+ const temporary = mkdtempSync(
+ path.join(tmpdir(), "cindy-pi-catalog-sync #-"),
+ );
+ try {
+ const catalogDirectory = path.join(
+ temporary,
+ "packages/model-providers/catalog",
+ );
+ mkdirSync(catalogDirectory, { recursive: true });
+ const scriptsDirectory = path.join(temporary, "tools/pi");
+ mkdirSync(scriptsDirectory, { recursive: true });
+ for (const script of [
+ "sync-model-catalog.mjs",
+ "openai-catalog-corrections.mjs",
+ "xai-catalog-corrections.mjs",
+ ]) {
+ cpSync(
+ path.join(root, "tools/pi", script),
+ path.join(scriptsDirectory, script),
+ );
+ }
+ cpSync(
+ path.join(root, "packages/model-providers/catalog/providers.json"),
+ path.join(catalogDirectory, "providers.json"),
+ );
+ const native = {
+ ...piCatalog.providers.openai[0],
+ name: "Native Astra",
+ contextWindow: 1_060_000,
+ compat: { supportsStore: false },
+ upstreamField: "preserve-native-metadata",
+ };
+ const input = { ...piCatalog.providers, openai: [native] };
+ const inputPath = path.join(temporary, "input.json");
+ writeFileSync(inputPath, JSON.stringify(input));
+ const args: string[] = [];
+ if (source === "online") {
+ const mockFetchPath = path.join(temporary, "mock-fetch.mjs");
+ writeFileSync(
+ mockFetchPath,
+ `
+ import { readFileSync } from 'node:fs';
+ const providers = JSON.parse(readFileSync(new URL('./input.json', import.meta.url), 'utf8'));
+ globalThis.fetch = async (url) => {
+ const provider = decodeURIComponent(new URL(url).pathname.split('/').at(-1));
+ if (!(provider in providers)) throw new Error('Unexpected provider: ' + provider);
+ return new Response(JSON.stringify(providers[provider]));
+ };
+ `,
+ );
+ args.push("--import", pathToFileURL(mockFetchPath).href);
+ }
+ args.push(path.join(temporary, "tools/pi/sync-model-catalog.mjs"));
+ if (source === "input") args.push("--input", inputPath);
+ args.push("--generated-at", "2026-09-04T21:38:48Z");
+ execFileSync(process.execPath, args, {
+ cwd: temporary,
+ timeout: 10_000,
+ });
+ const result = JSON.parse(
+ readFileSync(
+ path.join(catalogDirectory, "pi-model-catalog.json"),
+ "utf8",
+ ),
+ );
+ expect(result.providers.openai).toEqual([native]);
+ expect(result.providers["openai-codex"]).toEqual(input["openai-codex"]);
+ } finally {
+ rmSync(temporary, { recursive: true, force: true });
+ }
+ },
+ );
+});
diff --git a/tools/pi/openai-catalog-corrections.d.mts b/tools/pi/openai-catalog-corrections.d.mts
new file mode 100644
index 0000000000..f3b14fbbe4
--- /dev/null
+++ b/tools/pi/openai-catalog-corrections.d.mts
@@ -0,0 +1,8 @@
+export interface AstraCatalogRow {
+ id: string;
+ [key: string]: unknown;
+}
+
+export function applyAstraCatalogAdditions(
+ providers: Record<string, AstraCatalogRow[]>,
+): Record<string, AstraCatalogRow[]>;
diff --git a/tools/pi/openai-catalog-corrections.mjs b/tools/pi/openai-catalog-corrections.mjs
new file mode 100644
index 0000000000..1e5edbb575
--- /dev/null
+++ b/tools/pi/openai-catalog-corrections.mjs
@@ -0,0 +1,25 @@
+// Explicit Astra support for the pinned Pi runtime, verified 2026-09-05.
+// API contract: https://developers.openai.com/api/docs/models/gpt-6-astra
+// Subscription window: Codex 0.153.0 model metadata (272K default, 872K maximum).
+// Keep the transports separate; public API cache compatibility lives in cindy-bridge.
+export function applyAstraCatalogAdditions(providers) {
+ const cost = {
+ input: 10, output: 50, cacheRead: 1, cacheWrite: 12.5,
+ tiers: [{ inputTokensAbove: 272000, input: 20, output: 75, cacheRead: 2, cacheWrite: 25 }],
+ };
+ for (const [provider, api, baseUrl, contextWindow] of [
+ ['openai', 'openai-responses', 'https://api.openai.com/v1', 1050000],
+ ['openai-codex', 'openai-codex-responses', 'https://chatgpt.com/backend-api', 272000],
+ ]) {
+ const rows = providers[provider] ?? [];
+ // Newer upstream metadata wins when the native catalog learns this model.
+ if (rows.some((model) => model.id === 'gpt-6-astra')) continue;
+ providers[provider] = [...rows, {
+ id: 'gpt-6-astra', name: 'GPT-6 Astra', provider, api, baseUrl,
+ reasoning: true, input: ['text', 'image'], cost: structuredClone(cost),
+ contextWindow, maxTokens: 128000,
+ thinkingLevelMap: { off: 'low', minimal: null, low: 'low', medium: 'medium', high: 'high', xhigh: 'xhigh', max: 'max' },
+ }];
+ }
+ return providers;
+}
diff --git a/tools/pi/sync-model-catalog.mjs b/tools/pi/sync-model-catalog.mjs
index 451d26187e..fac656a47c 100644
--- a/tools/pi/sync-model-catalog.mjs
+++ b/tools/pi/sync-model-catalog.mjs
@@ -5,6 +5,7 @@ import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { applyKnownXaiCorrections, preferredDefaultEffort } from './xai-catalog-corrections.mjs';
+import { applyAstraCatalogAdditions } from './openai-catalog-corrections.mjs';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
const CATALOG_PATH = path.join(ROOT, 'packages/model-providers/catalog/providers.json');
@@ -35,6 +36,8 @@ const PROVIDER_IDS = [...new Set([
// be copied from Cindy's separately discovered Claude Code or Codex catalogs.
'anthropic',
'openai-codex',
+ // Read public API metadata too, so Astra additions yield to native upstream entries.
+ 'openai',
'xai',
])].sort();
@@ -172,6 +175,7 @@ async function main() {
}
}
if (providers.xai) providers.xai = applyKnownXaiCorrections(providers.xai);
+ applyAstraCatalogAdditions(providers);
const catalog = JSON.parse(await fs.readFile(CATALOG_PATH, 'utf8'));
for (const preset of catalog.presets ?? []) {