Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(pi): 补齐国产模型官方元数据 (#2572)
Chris Zhang9c212821bd5c
diff --git a/apps/desktop/drizzle/0090_distinguish_xai_provider_provenance.sql b/apps/desktop/drizzle/0090_distinguish_xai_provider_provenance.sqlnew file mode 100644index 0000000000..e0ac49d1ec--- /dev/null+++ b/apps/desktop/drizzle/0090_distinguish_xai_provider_provenance.sql@@ -0,0 +1 @@+SELECT 1;diff --git a/apps/desktop/drizzle/meta/0090_snapshot.json b/apps/desktop/drizzle/meta/0090_snapshot.jsonnew file mode 100644index 0000000000..344d20f63b--- /dev/null+++ b/apps/desktop/drizzle/meta/0090_snapshot.json@@ -0,0 +1,4246 @@+{+ "id": "9b947440-3e27-474b-93c1-dc62b1bc9c35",+ "prevId": "36f4dec3-66f7-4a85-b5ec-eb2212ca69c6",+ "version": "6",+ "dialect": "sqlite",+ "tables": {+ "account_usage_snapshots": {+ "name": "account_usage_snapshots",+ "columns": {+ "agent_kind": {+ "name": "agent_kind",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "snapshot": {+ "name": "snapshot",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "agent_input_queue_snapshots": {+ "name": "agent_input_queue_snapshots",+ "columns": {+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "payload": {+ "name": "payload",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "agent_input_queue_snapshots_session_id_sessions_id_fk": {+ "name": "agent_input_queue_snapshots_session_id_sessions_id_fk",+ "tableFrom": "agent_input_queue_snapshots",+ "columnsFrom": [+ "session_id"+ ],+ "tableTo": "sessions",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "custom_mcp_servers": {+ "name": "custom_mcp_servers",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "transport": {+ "name": "transport",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "url": {+ "name": "url",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "headers": {+ "name": "headers",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'{}'"+ },+ "sort_order": {+ "name": "sort_order",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_custom_mcp_servers_sort_order": {+ "name": "idx_custom_mcp_servers_sort_order",+ "columns": [+ "sort_order"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "custom_providers": {+ "name": "custom_providers",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "runtimes": {+ "name": "runtimes",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'{}'"+ },+ "auth": {+ "name": "auth",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "sort_order": {+ "name": "sort_order",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_custom_providers_sort_order": {+ "name": "idx_custom_providers_sort_order",+ "columns": [+ "sort_order"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "daily_model_usage": {+ "name": "daily_model_usage",+ "columns": {+ "day": {+ "name": "day",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "agent_kind": {+ "name": "agent_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "model": {+ "name": "model",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "cost_usd": {+ "name": "cost_usd",+ "type": "real",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "cost_amount": {+ "name": "cost_amount",+ "type": "real",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "cost_currency": {+ "name": "cost_currency",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'USD'"+ },+ "cost_is_approximate": {+ "name": "cost_is_approximate",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "input_tokens": {+ "name": "input_tokens",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "output_tokens": {+ "name": "output_tokens",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "cache_read_tokens": {+ "name": "cache_read_tokens",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "cache_create_tokens": {+ "name": "cache_create_tokens",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "daily_model_usage_day_agent_kind_model_cost_currency_pk": {+ "columns": [+ "day",+ "agent_kind",+ "model",+ "cost_currency"+ ],+ "name": "daily_model_usage_day_agent_kind_model_cost_currency_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "daily_spend": {+ "name": "daily_spend",+ "columns": {+ "day": {+ "name": "day",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "cost_usd": {+ "name": "cost_usd",+ "type": "real",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "cost_amount": {+ "name": "cost_amount",+ "type": "real",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "cost_currency": {+ "name": "cost_currency",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'USD'"+ },+ "cost_is_approximate": {+ "name": "cost_is_approximate",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "daily_spend_day_cost_currency_pk": {+ "columns": [+ "day",+ "cost_currency"+ ],+ "name": "daily_spend_day_cost_currency_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "device_link_ownership": {+ "name": "device_link_ownership",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "owner_id": {+ "name": "owner_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "owner_pid": {+ "name": "owner_pid",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "owner_label": {+ "name": "owner_label",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "heartbeat_at": {+ "name": "heartbeat_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "embedding_jobs": {+ "name": "embedding_jobs",+ "columns": {+ "rowid": {+ "name": "rowid",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": true+ },+ "source": {+ "name": "source",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "source_id": {+ "name": "source_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "chunk_index": {+ "name": "chunk_index",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "model_id": {+ "name": "model_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "vec_table": {+ "name": "vec_table",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'pending'"+ },+ "attempts": {+ "name": "attempts",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "last_error": {+ "name": "last_error",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "scheduled_at": {+ "name": "scheduled_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "locked_at": {+ "name": "locked_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "uniq_embedding_jobs_natural": {+ "name": "uniq_embedding_jobs_natural",+ "columns": [+ "source",+ "source_id",+ "chunk_index",+ "model_id"+ ],+ "isUnique": true+ },+ "idx_embedding_jobs_status_scheduled": {+ "name": "idx_embedding_jobs_status_scheduled",+ "columns": [+ "status",+ "scheduled_at"+ ],+ "isUnique": false+ },+ "idx_embedding_jobs_source_id": {+ "name": "idx_embedding_jobs_source_id",+ "columns": [+ "source",+ "source_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "embedding_meta": {+ "name": "embedding_meta",+ "columns": {+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "value": {+ "name": "value",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "ghost_cards": {+ "name": "ghost_cards",+ "columns": {+ "call_id": {+ "name": "call_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "ghost_id": {+ "name": "ghost_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "html": {+ "name": "html",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "height": {+ "name": "height",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "v": {+ "name": "v",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 1+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "ghost_cards_updated_at_idx": {+ "name": "ghost_cards_updated_at_idx",+ "columns": [+ "updated_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "hook_group_context_cursors": {+ "name": "hook_group_context_cursors",+ "columns": {+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "cursor_key": {+ "name": "cursor_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "cursor_id": {+ "name": "cursor_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "hook_group_context_cursors_updated_at_idx": {+ "name": "hook_group_context_cursors_updated_at_idx",+ "columns": [+ "updated_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "hook_group_context_cursors_provider_cursor_key_pk": {+ "columns": [+ "provider",+ "cursor_key"+ ],+ "name": "hook_group_context_cursors_provider_cursor_key_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "hook_group_message_stats": {+ "name": "hook_group_message_stats",+ "columns": {+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "row_count": {+ "name": "row_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "text_bytes": {+ "name": "text_bytes",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "hook_group_messages": {+ "name": "hook_group_messages",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": true+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "chat_id": {+ "name": "chat_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "thread_id": {+ "name": "thread_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ },+ "message_id": {+ "name": "message_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "chat_name": {+ "name": "chat_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "author": {+ "name": "author",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "is_bot": {+ "name": "is_bot",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "text": {+ "name": "text",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "file_names": {+ "name": "file_names",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "sent_at": {+ "name": "sent_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "hook_group_messages_msg_idx": {+ "name": "hook_group_messages_msg_idx",+ "columns": [+ "provider",+ "chat_id",+ "thread_id",+ "message_id"+ ],+ "isUnique": true+ },+ "hook_group_messages_window_idx": {+ "name": "hook_group_messages_window_idx",+ "columns": [+ "provider",+ "chat_id",+ "thread_id",+ "id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "im_bindings": {+ "name": "im_bindings",+ "columns": {+ "channel": {+ "name": "channel",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "bot_context_id": {+ "name": "bot_context_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "scope_key": {+ "name": "scope_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ },+ "target_session_id": {+ "name": "target_session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "attached_at": {+ "name": "attached_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "attached_via_card_message_id": {+ "name": "attached_via_card_message_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_im_bindings_target": {+ "name": "idx_im_bindings_target",+ "columns": [+ "target_session_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "im_bindings_target_session_id_sessions_id_fk": {+ "name": "im_bindings_target_session_id_sessions_id_fk",+ "tableFrom": "im_bindings",+ "columnsFrom": [+ "target_session_id"+ ],+ "tableTo": "sessions",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {+ "im_bindings_channel_bot_context_id_user_id_scope_key_pk": {+ "columns": [+ "channel",+ "bot_context_id",+ "user_id",+ "scope_key"+ ],+ "name": "im_bindings_channel_bot_context_id_user_id_scope_key_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "media_blobs": {+ "name": "media_blobs",+ "columns": {+ "hash": {+ "name": "hash",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "ext": {+ "name": "ext",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "mime_type": {+ "name": "mime_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "bytes": {+ "name": "bytes",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "is_cache": {+ "name": "is_cache",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "last_access_at": {+ "name": "last_access_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "media_refs": {+ "name": "media_refs",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "hash": {+ "name": "hash",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "ref_kind": {+ "name": "ref_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "ref_id": {+ "name": "ref_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "origin_session_id": {+ "name": "origin_session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "origin_kind": {+ "name": "origin_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "origin_id": {+ "name": "origin_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "label": {+ "name": "label",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "media_refs_hash_idx": {+ "name": "media_refs_hash_idx",+ "columns": [+ "hash"+ ],+ "isUnique": false+ },+ "media_refs_ref_idx": {+ "name": "media_refs_ref_idx",+ "columns": [+ "ref_kind",+ "ref_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "media_refs_hash_media_blobs_hash_fk": {+ "name": "media_refs_hash_media_blobs_hash_fk",+ "tableFrom": "media_refs",+ "columnsFrom": [+ "hash"+ ],+ "tableTo": "media_blobs",+ "columnsTo": [+ "hash"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "messages": {+ "name": "messages",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "client_id": {+ "name": "client_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "tool_use_id": {+ "name": "tool_use_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "agent_meta": {+ "name": "agent_meta",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "agent_kind": {+ "name": "agent_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "rewind_at": {+ "name": "rewind_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "uniq_messages_session_client": {+ "name": "uniq_messages_session_client",+ "columns": [+ "session_id",+ "client_id"+ ],+ "isUnique": true+ },+ "idx_messages_session_created": {+ "name": "idx_messages_session_created",+ "columns": [+ "session_id",+ "created_at"+ ],+ "isUnique": false+ },+ "idx_messages_created_at": {+ "name": "idx_messages_created_at",+ "columns": [+ "created_at",+ "id"+ ],+ "isUnique": false+ },+ "idx_messages_rewind_at": {+ "name": "idx_messages_rewind_at",+ "columns": [+ "rewind_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "messages_session_id_sessions_id_fk": {+ "name": "messages_session_id_sessions_id_fk",+ "tableFrom": "messages",+ "columnsFrom": [+ "session_id"+ ],+ "tableTo": "sessions",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "migration_history": {+ "name": "migration_history",+ "columns": {+ "seq": {+ "name": "seq",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "file_name": {+ "name": "file_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "content_hash": {+ "name": "content_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "applied_at": {+ "name": "applied_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "migration_meta": {+ "name": "migration_meta",+ "columns": {+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "value": {+ "name": "value",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "orca_teams": {+ "name": "orca_teams",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "lead_session_id": {+ "name": "lead_session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'active'"+ },+ "completed_at": {+ "name": "completed_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "uniq_active_team_per_lead": {+ "name": "uniq_active_team_per_lead",+ "columns": [+ "lead_session_id"+ ],+ "where": "\"orca_teams\".\"status\" = 'active'",+ "isUnique": true+ },+ "idx_orca_teams_status": {+ "name": "idx_orca_teams_status",+ "columns": [+ "status"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "orca_teams_lead_session_id_sessions_id_fk": {+ "name": "orca_teams_lead_session_id_sessions_id_fk",+ "tableFrom": "orca_teams",+ "columnsFrom": [+ "lead_session_id"+ ],+ "tableTo": "sessions",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "orca_worker_creation_reservations": {+ "name": "orca_worker_creation_reservations",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "team_id": {+ "name": "team_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "label": {+ "name": "label",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "uniq_orca_worker_creation_reservations_team_label": {+ "name": "uniq_orca_worker_creation_reservations_team_label",+ "columns": [+ "team_id",+ "lower(\"label\")"+ ],+ "isUnique": true+ },+ "idx_orca_worker_creation_reservations_expires_at": {+ "name": "idx_orca_worker_creation_reservations_expires_at",+ "columns": [+ "expires_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "orca_worker_creation_reservations_team_id_orca_teams_id_fk": {+ "name": "orca_worker_creation_reservations_team_id_orca_teams_id_fk",+ "tableFrom": "orca_worker_creation_reservations",+ "columnsFrom": [+ "team_id"+ ],+ "tableTo": "orca_teams",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "orca_workers": {+ "name": "orca_workers",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "team_id": {+ "name": "team_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'idle'"+ },+ "label": {+ "name": "label",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "worktree_branch": {+ "name": "worktree_branch",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'developer'"+ },+ "focused": {+ "name": "focused",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "idle_since": {+ "name": "idle_since",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "uniq_orca_workers_session_id": {+ "name": "uniq_orca_workers_session_id",+ "columns": [+ "session_id"+ ],+ "isUnique": true+ },+ "uniq_orca_workers_team_label": {+ "name": "uniq_orca_workers_team_label",+ "columns": [+ "team_id",+ "lower(\"label\")"+ ],+ "isUnique": true+ },+ "uniq_orca_workers_focused_per_team": {+ "name": "uniq_orca_workers_focused_per_team",+ "columns": [+ "team_id"+ ],+ "where": "\"orca_workers\".\"focused\" = true",+ "isUnique": true+ },+ "idx_orca_workers_team_id": {+ "name": "idx_orca_workers_team_id",+ "columns": [+ "team_id"+ ],+ "isUnique": false+ },+ "idx_orca_workers_status": {+ "name": "idx_orca_workers_status",+ "columns": [+ "status"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "orca_workers_team_id_orca_teams_id_fk": {+ "name": "orca_workers_team_id_orca_teams_id_fk",+ "tableFrom": "orca_workers",+ "columnsFrom": [+ "team_id"+ ],+ "tableTo": "orca_teams",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ },+ "orca_workers_session_id_sessions_id_fk": {+ "name": "orca_workers_session_id_sessions_id_fk",+ "tableFrom": "orca_workers",+ "columnsFrom": [+ "session_id"+ ],+ "tableTo": "sessions",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "project_aliases": {+ "name": "project_aliases",+ "columns": {+ "project_key": {+ "name": "project_key",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "alias": {+ "name": "alias",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_project_aliases_updated_at": {+ "name": "idx_project_aliases_updated_at",+ "columns": [+ "updated_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "project_automation_consents": {+ "name": "project_automation_consents",+ "columns": {+ "working_dir": {+ "name": "working_dir",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "consented_at": {+ "name": "consented_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "config_hash": {+ "name": "config_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "recent_workdirs": {+ "name": "recent_workdirs",+ "columns": {+ "path": {+ "name": "path",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "last_used_at": {+ "name": "last_used_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_recent_workdirs_last_used_at": {+ "name": "idx_recent_workdirs_last_used_at",+ "columns": [+ "last_used_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "right_sidebar_tabs": {+ "name": "right_sidebar_tabs",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "is_active": {+ "name": "is_active",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "state": {+ "name": "state",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'{}'"+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "right_sidebar_tabs_session_idx": {+ "name": "right_sidebar_tabs_session_idx",+ "columns": [+ "session_id",+ "position"+ ],+ "isUnique": false+ },+ "right_sidebar_tabs_subagents_singleton_idx": {+ "name": "right_sidebar_tabs_subagents_singleton_idx",+ "columns": [+ "session_id"+ ],+ "where": "\"right_sidebar_tabs\".\"kind\" = 'subagents'",+ "isUnique": true+ }+ },+ "foreignKeys": {+ "right_sidebar_tabs_session_id_sessions_id_fk": {+ "name": "right_sidebar_tabs_session_id_sessions_id_fk",+ "tableFrom": "right_sidebar_tabs",+ "columnsFrom": [+ "session_id"+ ],+ "tableTo": "sessions",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "schedule_runs": {+ "name": "schedule_runs",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "schedule_id": {+ "name": "schedule_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "fired_at": {+ "name": "fired_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "finished_at": {+ "name": "finished_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "error_msg": {+ "name": "error_msg",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "cost_usd": {+ "name": "cost_usd",+ "type": "real",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "estimated_value_usd": {+ "name": "estimated_value_usd",+ "type": "real",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "cost_amount": {+ "name": "cost_amount",+ "type": "real",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "estimated_value_amount": {+ "name": "estimated_value_amount",+ "type": "real",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "cost_currency": {+ "name": "cost_currency",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "cost_is_approximate": {+ "name": "cost_is_approximate",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "cost_attribution": {+ "name": "cost_attribution",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'legacy'"+ },+ "result_text": {+ "name": "result_text",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "pre_run_hook_result": {+ "name": "pre_run_hook_result",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "read_at": {+ "name": "read_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "heartbeat_at": {+ "name": "heartbeat_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_schedule_runs_schedule": {+ "name": "idx_schedule_runs_schedule",+ "columns": [+ "schedule_id",+ "fired_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "schedule_runs_schedule_id_schedules_id_fk": {+ "name": "schedule_runs_schedule_id_schedules_id_fk",+ "tableFrom": "schedule_runs",+ "columnsFrom": [+ "schedule_id"+ ],+ "tableTo": "schedules",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ },+ "schedule_runs_session_id_sessions_id_fk": {+ "name": "schedule_runs_session_id_sessions_id_fk",+ "tableFrom": "schedule_runs",+ "columnsFrom": [+ "session_id"+ ],+ "tableTo": "sessions",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "set null"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "schedules": {+ "name": "schedules",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "prompt": {+ "name": "prompt",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "job_type": {+ "name": "job_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'prompt'"+ },+ "job_config": {+ "name": "job_config",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "execution_mode": {+ "name": "execution_mode",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'agent'"+ },+ "script_config": {+ "name": "script_config",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "source": {+ "name": "source",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "'user'"+ },+ "project_config_id": {+ "name": "project_config_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "legacy_session_fallback": {+ "name": "legacy_session_fallback",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'cron'"+ },+ "cron_expr": {+ "name": "cron_expr",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "timezone": {+ "name": "timezone",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "recurring": {+ "name": "recurring",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": true+ },+ "manual": {+ "name": "manual",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "interval_ms": {+ "name": "interval_ms",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "agent_kind": {+ "name": "agent_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "model": {+ "name": "model",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "provider_id": {+ "name": "provider_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "effort": {+ "name": "effort",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "fast_mode": {+ "name": "fast_mode",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "working_dir": {+ "name": "working_dir",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "workspace_kind": {+ "name": "workspace_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'project'"+ },+ "use_worktree": {+ "name": "use_worktree",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "target_session_id": {+ "name": "target_session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "persistent_session": {+ "name": "persistent_session",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "silent_when_idle": {+ "name": "silent_when_idle",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "pre_run_hook_command": {+ "name": "pre_run_hook_command",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "pre_run_hook_timeout_ms": {+ "name": "pre_run_hook_timeout_ms",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "skip_log_session_id": {+ "name": "skip_log_session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "notify_desktop": {+ "name": "notify_desktop",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": true+ },+ "notify_feishu": {+ "name": "notify_feishu",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "notify_wecom_group": {+ "name": "notify_wecom_group",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'active'"+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "last_fired_at": {+ "name": "last_fired_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_finished_at": {+ "name": "last_finished_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "next_fire_at": {+ "name": "next_fire_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "expire_at": {+ "name": "expire_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_schedules_active_next": {+ "name": "idx_schedules_active_next",+ "columns": [+ "status",+ "next_fire_at"+ ],+ "isUnique": false+ },+ "idx_schedules_target_session": {+ "name": "idx_schedules_target_session",+ "columns": [+ "target_session_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "schedules_target_session_id_sessions_id_fk": {+ "name": "schedules_target_session_id_sessions_id_fk",+ "tableFrom": "schedules",+ "columnsFrom": [+ "target_session_id"+ ],+ "tableTo": "sessions",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "set null"+ },+ "schedules_skip_log_session_id_sessions_id_fk": {+ "name": "schedules_skip_log_session_id_sessions_id_fk",+ "tableFrom": "schedules",+ "columnsFrom": [+ "skip_log_session_id"+ ],+ "tableTo": "sessions",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "set null"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "session_goals": {+ "name": "session_goals",+ "columns": {+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "objective": {+ "name": "objective",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'active'"+ },+ "budget_tokens": {+ "name": "budget_tokens",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "max_turns": {+ "name": "max_turns",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "no_progress_limit": {+ "name": "no_progress_limit",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "turns_used": {+ "name": "turns_used",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "tokens_used": {+ "name": "tokens_used",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "no_progress_streak": {+ "name": "no_progress_streak",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "usage_reset_at": {+ "name": "usage_reset_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_reason": {+ "name": "last_reason",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "agent_kind": {+ "name": "agent_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "started_at": {+ "name": "started_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_session_goals_status": {+ "name": "idx_session_goals_status",+ "columns": [+ "status"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "session_goals_session_id_sessions_id_fk": {+ "name": "session_goals_session_id_sessions_id_fk",+ "tableFrom": "session_goals",+ "columnsFrom": [+ "session_id"+ ],+ "tableTo": "sessions",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "session_pr_refs": {+ "name": "session_pr_refs",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "owner": {+ "name": "owner",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "repo": {+ "name": "repo",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "pr_number": {+ "name": "pr_number",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "url": {+ "name": "url",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "first_seen_at": {+ "name": "first_seen_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "last_seen_at": {+ "name": "last_seen_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "uniq_session_pr_refs": {+ "name": "uniq_session_pr_refs",+ "columns": [+ "session_id",+ "owner",+ "repo",+ "pr_number"+ ],+ "isUnique": true+ },+ "idx_session_pr_refs_session_last_seen": {+ "name": "idx_session_pr_refs_session_last_seen",+ "columns": [+ "session_id",+ "last_seen_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "session_pr_refs_session_id_sessions_id_fk": {+ "name": "session_pr_refs_session_id_sessions_id_fk",+ "tableFrom": "session_pr_refs",+ "columnsFrom": [+ "session_id"+ ],+ "tableTo": "sessions",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "sessions": {+ "name": "sessions",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'New Maker'"+ },+ "working_dir": {+ "name": "working_dir",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "workspace_kind": {+ "name": "workspace_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'project'"+ },+ "model": {+ "name": "model",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'claude-sonnet-4-6'"+ },+ "effort": {+ "name": "effort",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'high'"+ },+ "permission_mode": {+ "name": "permission_mode",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'ask'"+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'active'"+ },+ "sdk_session_id": {+ "name": "sdk_session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "total_token_usage": {+ "name": "total_token_usage",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "total_cost_usd": {+ "name": "total_cost_usd",+ "type": "real",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "total_cost_amount": {+ "name": "total_cost_amount",+ "type": "real",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "total_cost_currency": {+ "name": "total_cost_currency",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "total_cost_is_approximate": {+ "name": "total_cost_is_approximate",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "context_tokens": {+ "name": "context_tokens",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "context_window": {+ "name": "context_window",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "fast_mode": {+ "name": "fast_mode",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "plan_mode_enabled": {+ "name": "plan_mode_enabled",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "cleared_at": {+ "name": "cleared_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "pinned_at": {+ "name": "pinned_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "summary": {+ "name": "summary",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "provider_id": {+ "name": "provider_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "user_send_at": {+ "name": "user_send_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "agent_kind": {+ "name": "agent_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'cc'"+ },+ "orca_role": {+ "name": "orca_role",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "parent_session_id": {+ "name": "parent_session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "forked_at_message_id": {+ "name": "forked_at_message_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "worktree_path": {+ "name": "worktree_path",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "source": {+ "name": "source",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'desktop'"+ },+ "feishu_open_id": {+ "name": "feishu_open_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "feishu_bot_app_id": {+ "name": "feishu_bot_app_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "im_bot_context_id": {+ "name": "im_bot_context_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "im_user_id": {+ "name": "im_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "used_project_context": {+ "name": "used_project_context",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "codex_history_has_product_prompt": {+ "name": "codex_history_has_product_prompt",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "extra_dirs": {+ "name": "extra_dirs",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'[]'"+ },+ "remote_host_id": {+ "name": "remote_host_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "active_turn_started_at": {+ "name": "active_turn_started_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "active_turn_pid": {+ "name": "active_turn_pid",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_turn_ended_at": {+ "name": "last_turn_ended_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_sessions_updated_at": {+ "name": "idx_sessions_updated_at",+ "columns": [+ "updated_at"+ ],+ "isUnique": false+ },+ "idx_sessions_user_send_at": {+ "name": "idx_sessions_user_send_at",+ "columns": [+ "user_send_at"+ ],+ "isUnique": false+ },+ "idx_sessions_sdk_session_id": {+ "name": "idx_sessions_sdk_session_id",+ "columns": [+ "sdk_session_id"+ ],+ "isUnique": false+ },+ "idx_sessions_workdir_created": {+ "name": "idx_sessions_workdir_created",+ "columns": [+ "working_dir",+ "created_at",+ "id"+ ],+ "isUnique": false+ },+ "idx_sessions_created_at": {+ "name": "idx_sessions_created_at",+ "columns": [+ "created_at",+ "id"+ ],+ "isUnique": false+ },+ "idx_sessions_workspace_kind": {+ "name": "idx_sessions_workspace_kind",+ "columns": [+ "workspace_kind"+ ],+ "isUnique": false+ },+ "idx_sessions_parent_session_id": {+ "name": "idx_sessions_parent_session_id",+ "columns": [+ "parent_session_id"+ ],+ "isUnique": false+ },+ "idx_sessions_orca_role": {+ "name": "idx_sessions_orca_role",+ "columns": [+ "orca_role"+ ],+ "isUnique": false+ },+ "idx_sessions_worktree_path": {+ "name": "idx_sessions_worktree_path",+ "columns": [+ "worktree_path"+ ],+ "isUnique": false+ },+ "idx_sessions_feishu_lookup": {+ "name": "idx_sessions_feishu_lookup",+ "columns": [+ "source",+ "feishu_bot_app_id",+ "feishu_open_id"+ ],+ "isUnique": false+ },+ "idx_sessions_im_lookup": {+ "name": "idx_sessions_im_lookup",+ "columns": [+ "source",+ "im_bot_context_id",+ "im_user_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "sessions_parent_session_id_sessions_id_fk": {+ "name": "sessions_parent_session_id_sessions_id_fk",+ "tableFrom": "sessions",+ "columnsFrom": [+ "parent_session_id"+ ],+ "tableTo": "sessions",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "set null"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "skill_usage_exposures": {+ "name": "skill_usage_exposures",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "analyzer_version": {+ "name": "analyzer_version",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'6'"+ },+ "raw_file_path": {+ "name": "raw_file_path",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "raw_line_no": {+ "name": "raw_line_no",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "sdk_session_id": {+ "name": "sdk_session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "agent_kind": {+ "name": "agent_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "skill_name": {+ "name": "skill_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "skill_path": {+ "name": "skill_path",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "skill_document_hash": {+ "name": "skill_document_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "exposure_content_hash": {+ "name": "exposure_content_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "document_hash_source": {+ "name": "document_hash_source",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "source": {+ "name": "source",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "tool_use_id": {+ "name": "tool_use_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "seen_at": {+ "name": "seen_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "tool_call_count": {+ "name": "tool_call_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "repeated_tool_call_count": {+ "name": "repeated_tool_call_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "tool_error_count": {+ "name": "tool_error_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "command_call_count": {+ "name": "command_call_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "command_failure_count": {+ "name": "command_failure_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ }+ },+ "indexes": {+ "idx_skill_usage_exposures_skill_document_version": {+ "name": "idx_skill_usage_exposures_skill_document_version",+ "columns": [+ "analyzer_version",+ "skill_name",+ "skill_document_hash"+ ],+ "isUnique": false+ },+ "idx_skill_usage_exposures_session": {+ "name": "idx_skill_usage_exposures_session",+ "columns": [+ "session_id"+ ],+ "isUnique": false+ },+ "idx_skill_usage_exposures_raw_file": {+ "name": "idx_skill_usage_exposures_raw_file",+ "columns": [+ "raw_file_path"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "skill_usage_exposures_raw_file_path_skill_usage_sources_raw_file_path_fk": {+ "name": "skill_usage_exposures_raw_file_path_skill_usage_sources_raw_file_path_fk",+ "tableFrom": "skill_usage_exposures",+ "columnsFrom": [+ "raw_file_path"+ ],+ "tableTo": "skill_usage_sources",+ "columnsTo": [+ "raw_file_path"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "skill_usage_sources": {+ "name": "skill_usage_sources",+ "columns": {+ "raw_file_path": {+ "name": "raw_file_path",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "analyzer_version": {+ "name": "analyzer_version",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'6'"+ },+ "agent_kind": {+ "name": "agent_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "sdk_session_id": {+ "name": "sdk_session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "mtime_ms": {+ "name": "mtime_ms",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "size_bytes": {+ "name": "size_bytes",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "last_scanned_at": {+ "name": "last_scanned_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'ok'"+ },+ "error": {+ "name": "error",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_skill_usage_sources_session": {+ "name": "idx_skill_usage_sources_session",+ "columns": [+ "session_id"+ ],+ "isUnique": false+ },+ "idx_skill_usage_sources_sdk_session": {+ "name": "idx_skill_usage_sources_sdk_session",+ "columns": [+ "sdk_session_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "subagent_run_aliases": {+ "name": "subagent_run_aliases",+ "columns": {+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "alias": {+ "name": "alias",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "run_id": {+ "name": "run_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "subagent_run_aliases_lookup_idx": {+ "name": "subagent_run_aliases_lookup_idx",+ "columns": [+ "session_id",+ "provider",+ "alias",+ "created_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "subagent_run_aliases_session_id_sessions_id_fk": {+ "name": "subagent_run_aliases_session_id_sessions_id_fk",+ "tableFrom": "subagent_run_aliases",+ "columnsFrom": [+ "session_id"+ ],+ "tableTo": "sessions",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ },+ "subagent_run_aliases_run_id_subagent_runs_id_fk": {+ "name": "subagent_run_aliases_run_id_subagent_runs_id_fk",+ "tableFrom": "subagent_run_aliases",+ "columnsFrom": [+ "run_id"+ ],+ "tableTo": "subagent_runs",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {+ "subagent_run_aliases_run_id_alias_pk": {+ "columns": [+ "run_id",+ "alias"+ ],+ "name": "subagent_run_aliases_run_id_alias_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "subagent_runs": {+ "name": "subagent_runs",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "logical_agent_id": {+ "name": "logical_agent_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "parent_tool_use_id": {+ "name": "parent_tool_use_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "aliases": {+ "name": "aliases",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'[]'"+ },+ "provider_run_ids": {+ "name": "provider_run_ids",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'[]'"+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'running'"+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "summary": {+ "name": "summary",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "model": {+ "name": "model",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "reasoning_effort": {+ "name": "reasoning_effort",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "total_tokens": {+ "name": "total_tokens",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "tool_uses": {+ "name": "tool_uses",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "duration_ms": {+ "name": "duration_ms",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "capabilities": {+ "name": "capabilities",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'{}'"+ },+ "activity": {+ "name": "activity",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'[]'"+ },+ "started_at": {+ "name": "started_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "ended_at": {+ "name": "ended_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "rewind_at": {+ "name": "rewind_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "deleted_at": {+ "name": "deleted_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "subagent_runs_logical_idx": {+ "name": "subagent_runs_logical_idx",+ "columns": [+ "session_id",+ "provider",+ "logical_agent_id"+ ],+ "isUnique": false+ },+ "subagent_runs_session_idx": {+ "name": "subagent_runs_session_idx",+ "columns": [+ "session_id",+ "rewind_at",+ "deleted_at",+ "started_at"+ ],+ "isUnique": false+ },+ "subagent_runs_parent_tool_use_idx": {+ "name": "subagent_runs_parent_tool_use_idx",+ "columns": [+ "session_id",+ "parent_tool_use_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "subagent_runs_session_id_sessions_id_fk": {+ "name": "subagent_runs_session_id_sessions_id_fk",+ "tableFrom": "subagent_runs",+ "columnsFrom": [+ "session_id"+ ],+ "tableTo": "sessions",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "vec_table_meta": {+ "name": "vec_table_meta",+ "columns": {+ "vec_table": {+ "name": "vec_table",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "source": {+ "name": "source",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "model_id": {+ "name": "model_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "dim": {+ "name": "dim",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "registered_at": {+ "name": "registered_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "notes": {+ "name": "notes",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "wechat_file_attachments": {+ "name": "wechat_file_attachments",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "binding_epoch": {+ "name": "binding_epoch",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "abs_path": {+ "name": "abs_path",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "original_name": {+ "name": "original_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "mime_type": {+ "name": "mime_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "bytes": {+ "name": "bytes",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'staged'"+ },+ "promoted_at": {+ "name": "promoted_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_wechat_file_attachments_task": {+ "name": "idx_wechat_file_attachments_task",+ "columns": [+ "binding_epoch",+ "task_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "wechat_file_attachments_binding_epoch_wechat_sync_state_binding_epoch_fk": {+ "name": "wechat_file_attachments_binding_epoch_wechat_sync_state_binding_epoch_fk",+ "tableFrom": "wechat_file_attachments",+ "columnsFrom": [+ "binding_epoch"+ ],+ "tableTo": "wechat_sync_state",+ "columnsTo": [+ "binding_epoch"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ },+ "wechat_file_attachments_task_id_wechat_inbox_id_fk": {+ "name": "wechat_file_attachments_task_id_wechat_inbox_id_fk",+ "tableFrom": "wechat_file_attachments",+ "columnsFrom": [+ "task_id"+ ],+ "tableTo": "wechat_inbox",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ },+ "wechat_file_attachments_session_id_sessions_id_fk": {+ "name": "wechat_file_attachments_session_id_sessions_id_fk",+ "tableFrom": "wechat_file_attachments",+ "columnsFrom": [+ "session_id"+ ],+ "tableTo": "sessions",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "set null"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "wechat_inbox": {+ "name": "wechat_inbox",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "binding_epoch": {+ "name": "binding_epoch",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "platform_message_id": {+ "name": "platform_message_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "platform_seq": {+ "name": "platform_seq",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "peer_id": {+ "name": "peer_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "received_at": {+ "name": "received_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "platform_created_at": {+ "name": "platform_created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'pending'"+ },+ "lease_until": {+ "name": "lease_until",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "conversation_epoch": {+ "name": "conversation_epoch",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "payload_json": {+ "name": "payload_json",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "context_nonce": {+ "name": "context_nonce",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "context_ciphertext": {+ "name": "context_ciphertext",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "context_tag": {+ "name": "context_tag",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "attempts": {+ "name": "attempts",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "last_error_code": {+ "name": "last_error_code",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "uniq_wechat_inbox_platform_message": {+ "name": "uniq_wechat_inbox_platform_message",+ "columns": [+ "binding_epoch",+ "platform_message_id"+ ],+ "isUnique": true+ },+ "idx_wechat_inbox_queue": {+ "name": "idx_wechat_inbox_queue",+ "columns": [+ "binding_epoch",+ "status",+ "received_at"+ ],+ "isUnique": false+ },+ "idx_wechat_inbox_lease": {+ "name": "idx_wechat_inbox_lease",+ "columns": [+ "binding_epoch",+ "lease_until"+ ],+ "isUnique": false+ },+ "idx_wechat_inbox_conversation": {+ "name": "idx_wechat_inbox_conversation",+ "columns": [+ "binding_epoch",+ "peer_id",+ "conversation_epoch"+ ],+ "isUnique": false+ },+ "uniq_wechat_inbox_running_session": {+ "name": "uniq_wechat_inbox_running_session",+ "columns": [+ "binding_epoch",+ "session_id"+ ],+ "where": "\"wechat_inbox\".\"session_id\" IS NOT NULL AND \"wechat_inbox\".\"status\" IN ('dispatching', 'accepted_running', 'waiting_desktop', 'delivery_pending')",+ "isUnique": true+ }+ },+ "foreignKeys": {+ "wechat_inbox_binding_epoch_wechat_sync_state_binding_epoch_fk": {+ "name": "wechat_inbox_binding_epoch_wechat_sync_state_binding_epoch_fk",+ "tableFrom": "wechat_inbox",+ "columnsFrom": [+ "binding_epoch"+ ],+ "tableTo": "wechat_sync_state",+ "columnsTo": [+ "binding_epoch"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ },+ "wechat_inbox_session_id_sessions_id_fk": {+ "name": "wechat_inbox_session_id_sessions_id_fk",+ "tableFrom": "wechat_inbox",+ "columnsFrom": [+ "session_id"+ ],+ "tableTo": "sessions",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "set null"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "wechat_outbox": {+ "name": "wechat_outbox",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "binding_epoch": {+ "name": "binding_epoch",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "client_id": {+ "name": "client_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "chunk_index": {+ "name": "chunk_index",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "text": {+ "name": "text",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "media_json": {+ "name": "media_json",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'[]'"+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'pending'"+ },+ "attempts": {+ "name": "attempts",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "next_retry_at": {+ "name": "next_retry_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "delivered_at": {+ "name": "delivered_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "uniq_wechat_outbox_client_id": {+ "name": "uniq_wechat_outbox_client_id",+ "columns": [+ "binding_epoch",+ "client_id"+ ],+ "isUnique": true+ },+ "idx_wechat_outbox_delivery": {+ "name": "idx_wechat_outbox_delivery",+ "columns": [+ "binding_epoch",+ "status",+ "next_retry_at"+ ],+ "isUnique": false+ },+ "idx_wechat_outbox_task": {+ "name": "idx_wechat_outbox_task",+ "columns": [+ "binding_epoch",+ "task_id",+ "chunk_index"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "wechat_outbox_binding_epoch_wechat_sync_state_binding_epoch_fk": {+ "name": "wechat_outbox_binding_epoch_wechat_sync_state_binding_epoch_fk",+ "tableFrom": "wechat_outbox",+ "columnsFrom": [+ "binding_epoch"+ ],+ "tableTo": "wechat_sync_state",+ "columnsTo": [+ "binding_epoch"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ },+ "wechat_outbox_task_id_wechat_inbox_id_fk": {+ "name": "wechat_outbox_task_id_wechat_inbox_id_fk",+ "tableFrom": "wechat_outbox",+ "columnsFrom": [+ "task_id"+ ],+ "tableTo": "wechat_inbox",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "wechat_sync_state": {+ "name": "wechat_sync_state",+ "columns": {+ "binding_epoch": {+ "name": "binding_epoch",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "is_active": {+ "name": "is_active",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "sync_cursor": {+ "name": "sync_cursor",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ },+ "last_poll_at": {+ "name": "last_poll_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_error_code": {+ "name": "last_error_code",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "uniq_wechat_sync_active": {+ "name": "uniq_wechat_sync_active",+ "columns": [+ "is_active"+ ],+ "where": "\"wechat_sync_state\".\"is_active\" = 1",+ "isUnique": true+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ }+ },+ "views": {},+ "enums": {},+ "_meta": {+ "columns": {},+ "schemas": {},+ "tables": {}+ },+ "internal": {+ "indexes": {+ "uniq_orca_worker_creation_reservations_team_label": {+ "columns": {+ "lower(\"label\")": {+ "isExpression": true+ }+ }+ },+ "uniq_orca_workers_team_label": {+ "columns": {+ "lower(\"label\")": {+ "isExpression": true+ }+ }+ }+ }+ }+}\ No newline at end of filediff --git a/apps/desktop/drizzle/meta/_journal.json b/apps/desktop/drizzle/meta/_journal.jsonindex 7b10d90b09..8d3be3074f 100644--- a/apps/desktop/drizzle/meta/_journal.json+++ b/apps/desktop/drizzle/meta/_journal.json@@ -631,6 +631,13 @@"when": 1786257834139,"tag": "0089_rich_power_pack","breakpoints": true+ },+ {+ "idx": 90,+ "version": "6",+ "when": 1786726026223,+ "tag": "0090_distinguish_xai_provider_provenance",+ "breakpoints": true}]-}+}\ No newline at end of filediff --git a/apps/desktop/drizzle/scripts/0090_distinguish_xai_provider_provenance.ts b/apps/desktop/drizzle/scripts/0090_distinguish_xai_provider_provenance.tsnew file mode 100644index 0000000000..40e5b63fed--- /dev/null+++ b/apps/desktop/drizzle/scripts/0090_distinguish_xai_provider_provenance.ts@@ -0,0 +1,45 @@+import type Database from 'better-sqlite3';++interface TableInfoRow {+ name: string;+}++const OFFICIAL_PI_XAI_INTRODUCED_AT_MS = 1_785_540_089_000;++function tableHasColumns(+ db: Database.Database,+ tableName: string,+ requiredColumns: string[],+): boolean {+ const columns = new Set(+ (db.prepare(`PRAGMA table_info('${tableName}')`).all() as TableInfoRow[]).map(+ (row) => row.name,+ ),+ );+ return requiredColumns.every((column) => columns.has(column));+}++function run(db: Database.Database): void {+ db.transaction(() => {+ if (tableHasColumns(db, 'sessions', ['agent_kind', 'provider_id', 'created_at'])) {+ db.exec(`+ UPDATE sessions+ SET provider_id = 'custom:xai'+ WHERE agent_kind = 'pi'+ AND provider_id = 'xai'+ AND created_at < ${OFFICIAL_PI_XAI_INTRODUCED_AT_MS}+ `);+ }+ if (tableHasColumns(db, 'schedules', ['agent_kind', 'provider_id', 'created_at'])) {+ db.exec(`+ UPDATE schedules+ SET provider_id = 'custom:xai'+ WHERE agent_kind = 'pi'+ AND provider_id = 'xai'+ AND created_at < ${OFFICIAL_PI_XAI_INTRODUCED_AT_MS}+ `);+ }+ })();+}++module.exports = { run };diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex ca5860a164..b9cca600ef 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -458,6 +458,12 @@ import {refreshAnthropicModelsFromHttp,clearAnthropicDiscoveredModels,} from './maker-host/model-discovery/anthropic.js';+import {+ clearXaiDiscoveredModels,+ discardXaiModelsDiskCache,+ loadXaiModelsFromDiskCache,+ refreshXaiModelsFromHttp,+} from './maker-host/model-discovery/xai.js';import { refreshCustomMcpProviders } from './mcp-integrations/custom-mcp-registry.js';import { clearXaiRateLimitSnapshot } from './usageBroadcaster.js';import {@@ -3764,6 +3770,7 @@ const registerIpcHandlers = () => {// 限流快照),否则用户会停在「显示已连接、请求连环 403」的假状态。setXaiAuthInvalidatedHandler(() => {resetProviderModelAutoRefreshCooldowns('xai');+ clearXaiDiscoveredModels();clearXaiMediaModels();clearXaiRateLimitSnapshot();broadcastXaiAuthStateChanged();@@ -3777,6 +3784,10 @@ const registerIpcHandlers = () => {const result = await runGrokOAuthLogin();if (result.ok) {resetProviderModelAutoRefreshCooldowns('xai');+ // 登录可直接覆盖旧 SuperGrok 账号:先清旧世代内存,再直接读新账号官方清单。+ // 这里不能先恢复同一 Cindy owner 的磁盘 LKG,否则 A→B 重登会短暂展示 A 的成员。+ clearXaiDiscoveredModels();+ await discardXaiModelsDiskCache();// 登录可直接覆盖旧账号凭证。先跨授权边界清掉旧账号发现快照,再补拉新账号;// 旧在途请求由 discovery generation + owner scope 双重守卫作废。clearXaiMediaModels();@@ -3785,6 +3796,7 @@ const registerIpcHandlers = () => {// 限流快照是账号级的:重登可能换账号,旧快照一并清掉(等新账号首个 xai/ 轮自然补上)。clearXaiRateLimitSnapshot();broadcastXaiAuthStateChanged();+ void refreshXaiModelsFromHttp();void refreshProviderModelsManually('xai').catch((error) => {createLogger('xai-model-refresh').warn('xAI models refresh after login failed', {error: error instanceof Error ? error.message : String(error),@@ -3798,6 +3810,7 @@ const registerIpcHandlers = () => {try {logoutGrok();resetProviderModelAutoRefreshCooldowns('xai');+ clearXaiDiscoveredModels();clearXaiMediaModels();} catch (err) {throwIpcError(@@ -6984,6 +6997,7 @@ app.on('ready', async () => {await refreshProviderModelsAfterAccountReady({restartCodex: restartCodexAfterAuthModeChange,shutdownCodexEnvironment,+ loadXaiLkg: loadXaiModelsFromDiskCache,refreshProviderModels: requestProviderModelAutoRefresh,log: accountSwitchLog,});diff --git a/apps/desktop/src/main/localDb/__tests__/xaiProviderProvenanceMigration.test.ts b/apps/desktop/src/main/localDb/__tests__/xaiProviderProvenanceMigration.test.tsnew file mode 100644index 0000000000..f0337990e4--- /dev/null+++ b/apps/desktop/src/main/localDb/__tests__/xaiProviderProvenanceMigration.test.ts@@ -0,0 +1,104 @@+import Database from 'better-sqlite3';+import { describe, expect, it } from 'vitest';++// Migration companion scripts intentionally use CommonJS so the runtime loader can replay them.+const { default: migration0090 } = (await import(+ '../../../../drizzle/scripts/0090_distinguish_xai_provider_provenance'+)) as { default: { run(db: Database.Database): void } };++describe('0090 xAI provider provenance migration', () => {+ it('namespaces only Pi xai rows that predate official SuperGrok support', () => {+ const db = new Database(':memory:');+ try {+ db.exec(`+ CREATE TABLE sessions (+ id TEXT PRIMARY KEY NOT NULL,+ agent_kind TEXT NOT NULL,+ provider_id TEXT,+ created_at INTEGER NOT NULL+ );+ CREATE TABLE schedules (+ id TEXT PRIMARY KEY NOT NULL,+ agent_kind TEXT NOT NULL,+ provider_id TEXT,+ created_at INTEGER NOT NULL+ );+ INSERT INTO sessions (id, agent_kind, provider_id, created_at) VALUES+ ('pi-legacy-custom', 'pi', 'xai', 1785540088999),+ ('pi-official-boundary', 'pi', 'xai', 1785540089000),+ ('pi-official-later', 'pi', 'xai', 1785540089001),+ ('pi-already-namespaced', 'pi', 'custom:xai', 1785540088999),+ ('pi-unspecified', 'pi', NULL, 1785540088999),+ ('claude-official', 'claude-code', 'xai', 1785540088999),+ ('codex-official', 'codex', 'xai', 1785540088999);+ INSERT INTO schedules (id, agent_kind, provider_id, created_at) VALUES+ ('schedule-pi-legacy-custom', 'pi', 'xai', 1785540088999),+ ('schedule-pi-official', 'pi', 'xai', 1785540089000),+ ('schedule-pi-already-namespaced', 'pi', 'custom:xai', 1785540088999),+ ('schedule-claude-official', 'claude-code', 'xai', 1785540088999);+ `);++ migration0090.run(db);++ expect(db.prepare('SELECT id, provider_id FROM sessions ORDER BY id').all()).toEqual([+ { id: 'claude-official', provider_id: 'xai' },+ { id: 'codex-official', provider_id: 'xai' },+ { id: 'pi-already-namespaced', provider_id: 'custom:xai' },+ { id: 'pi-legacy-custom', provider_id: 'custom:xai' },+ { id: 'pi-official-boundary', provider_id: 'xai' },+ { id: 'pi-official-later', provider_id: 'xai' },+ { id: 'pi-unspecified', provider_id: null },+ ]);+ expect(db.prepare('SELECT id, provider_id FROM schedules ORDER BY id').all()).toEqual([+ { id: 'schedule-claude-official', provider_id: 'xai' },+ { id: 'schedule-pi-already-namespaced', provider_id: 'custom:xai' },+ { id: 'schedule-pi-legacy-custom', provider_id: 'custom:xai' },+ { id: 'schedule-pi-official', provider_id: 'xai' },+ ]);+ } finally {+ db.close();+ }+ });++ it('is safe for partial legacy replay schemas and reruns', () => {+ const db = new Database(':memory:');+ try {+ db.exec(`+ CREATE TABLE sessions (+ id TEXT PRIMARY KEY NOT NULL,+ agent_kind TEXT NOT NULL,+ provider_id TEXT,+ created_at INTEGER NOT NULL+ );+ INSERT INTO sessions (id, agent_kind, provider_id, created_at)+ VALUES ('pi-legacy-custom', 'pi', 'xai', 1);+ `);++ expect(() => migration0090.run(db)).not.toThrow();+ expect(() => migration0090.run(db)).not.toThrow();+ expect(db.prepare('SELECT provider_id FROM sessions').pluck().get()).toBe('custom:xai');+ } finally {+ db.close();+ }+ });++ it('leaves ambiguous rows untouched when a partial schema lacks creation time', () => {+ const db = new Database(':memory:');+ try {+ db.exec(`+ CREATE TABLE sessions (+ id TEXT PRIMARY KEY NOT NULL,+ agent_kind TEXT NOT NULL,+ provider_id TEXT+ );+ INSERT INTO sessions (id, agent_kind, provider_id)+ VALUES ('pi-ambiguous', 'pi', 'xai');+ `);++ expect(() => migration0090.run(db)).not.toThrow();+ expect(db.prepare('SELECT provider_id FROM sessions').pluck().get()).toBe('xai');+ } finally {+ db.close();+ }+ });+});diff --git a/apps/desktop/src/main/maker-host/__tests__/accountProviderModelRefresh.test.ts b/apps/desktop/src/main/maker-host/__tests__/accountProviderModelRefresh.test.tsindex c28eaa3a81..488a0a92fe 100644--- a/apps/desktop/src/main/maker-host/__tests__/accountProviderModelRefresh.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/accountProviderModelRefresh.test.ts@@ -22,6 +22,10 @@ describe('refreshProviderModelsAfterAccountReady', () => {shutdownCodexEnvironment: async () => {events.push('shutdown');},+ loadXaiLkg: async () => {+ events.push('xai-lkg');+ return true;+ },refreshProviderModels: async (trigger, providerIds) => {events.push(`refresh:${trigger}:${providerIds?.join(',')}`);await (providerIds?.includes('anthropic')@@ -39,6 +43,7 @@ describe('refreshProviderModelsAfterAccountReady', () => {expect(events).toEqual(['restart','shutdown',+ 'xai-lkg','refresh:startup:xd,openai,xai','refresh:startup:anthropic',]),@@ -64,6 +69,7 @@ describe('refreshProviderModelsAfterAccountReady', () => {throw new Error('restart unavailable');},shutdownCodexEnvironment: vi.fn(async () => {}),+ loadXaiLkg: vi.fn(async () => false),refreshProviderModels,log: { warn },}),@@ -82,6 +88,7 @@ describe('refreshProviderModelsAfterAccountReady', () => {refreshProviderModelsAfterAccountReady({restartCodex: vi.fn(async () => {}),shutdownCodexEnvironment: vi.fn(async () => {}),+ loadXaiLkg: vi.fn(async () => false),refreshProviderModels: async () => {throw new Error('discovery unavailable');},@@ -96,4 +103,27 @@ describe('refreshProviderModelsAfterAccountReady', () => {error: 'discovery unavailable',});});++ it('loads the current owner xAI LKG before starting account refreshes', async () => {+ const releaseLkg = deferred();+ const events: string[] = [];+ const operation = refreshProviderModelsAfterAccountReady({+ restartCodex: async () => {},+ shutdownCodexEnvironment: async () => {},+ loadXaiLkg: async () => {+ events.push('lkg:start');+ await releaseLkg.promise;+ events.push('lkg:end');+ return true;+ },+ refreshProviderModels: async () => {+ events.push('refresh');+ },+ log: { warn: vi.fn() },+ });+ await vi.waitFor(() => expect(events).toEqual(['lkg:start']));+ releaseLkg.resolve();+ await operation;+ expect(events).toEqual(['lkg:start', 'lkg:end', 'refresh', 'refresh']);+ });});diff --git a/apps/desktop/src/main/maker-host/__tests__/activeCatalogDiscovery.test.ts b/apps/desktop/src/main/maker-host/__tests__/activeCatalogDiscovery.test.tsindex 402d4872f5..b12fb7aadb 100644--- a/apps/desktop/src/main/maker-host/__tests__/activeCatalogDiscovery.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/activeCatalogDiscovery.test.ts@@ -22,6 +22,7 @@ import {setActiveCatalog,setAnthropicDiscoveredModels,setDiscoveredCodexModels,+ setXaiDiscoveredModels,setDiscoveredProviderMediaModels,} from '../active-catalog.js';@@ -90,6 +91,7 @@ describe('active-catalog discovered augment', () => {// 复位全局状态,避免测试间串扰setActiveCatalog(BUNDLED_CATALOG);setDiscoveredCodexModels([]);+ setXaiDiscoveredModels(null);setDiscoveredProviderMediaModels('xai', null);});@@ -101,12 +103,49 @@ describe('active-catalog discovered augment', () => {expect(openaiIds('pi')).toContain('chatgpt/gpt-5.7');});- it('SuperGrok 静态清单投影到独立 Pi 通道', () => {+ it('SuperGrok fallback keeps namespaced roots but projects bare Pi ids', () => {setActiveCatalog(BUNDLED_CATALOG);const xai = getActiveCatalog().providers.find((provider) => provider.id === 'xai');expect(xai?.agents).toContain('pi');- expect(xai?.routing.pi?.modelPrefixes).toEqual(['xai/']);- expect(xai?.models.pi).toEqual(xai?.models['claude-code']);+ expect(xai?.routing.pi?.upstream).toBe('https://api.x.ai/v1');+ expect(xai?.models.pi?.map((model) => model.id)).toEqual([+ 'grok-4.3',+ 'grok-4.5',+ 'grok-4.6',+ 'grok-build-0.1',+ ]);+ expect(xai?.models.pi).not.toEqual(xai?.models['claude-code']);+ });++ it('xAI account snapshot is authoritative and projects canonical ids per harness', () => {+ setActiveCatalog(BUNDLED_CATALOG);+ setXaiDiscoveredModels([+ { id: 'xai/grok-4.5' },+ { id: 'xai/grok-4.6' },+ ]);+ const xai = getActiveCatalog().providers.find((provider) => provider.id === 'xai');+ expect(xai?.models['claude-code']?.map((model) => model.id)).toEqual([+ 'xai/grok-4.5',+ 'xai/grok-4.6',+ ]);+ expect(xai?.models.codex?.map((model) => model.id)).toEqual([+ 'xai/grok-4.5',+ 'xai/grok-4.6',+ ]);+ expect(xai?.models.pi?.map((model) => model.id)).toEqual(['grok-4.5', 'grok-4.6']);+ expect(xai?.models.pi?.find((model) => model.id === 'grok-4.6')).toMatchObject({+ contextWindow: 500_000,+ supportsImageInput: true,+ });+ });++ it('xAI successful empty snapshot stays empty and does not leak static membership', () => {+ setActiveCatalog(BUNDLED_CATALOG);+ setXaiDiscoveredModels([]);+ const xai = getActiveCatalog().providers.find((provider) => provider.id === 'xai');+ expect(xai?.models['claude-code']).toEqual([]);+ expect(xai?.models.codex).toEqual([]);+ expect(xai?.models.pi).toEqual([]);});it('xAI 媒体发现按官方存在性收敛,静态同 id 保持 first-wins', () => {diff --git a/apps/desktop/src/main/maker-host/__tests__/activeCatalogRevision.test.ts b/apps/desktop/src/main/maker-host/__tests__/activeCatalogRevision.test.tsindex 7c423a99c7..0e2e2e2c1d 100644--- a/apps/desktop/src/main/maker-host/__tests__/activeCatalogRevision.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/activeCatalogRevision.test.ts@@ -9,7 +9,9 @@ import {setActiveCatalog,setActiveCatalogChangedListener,setAnthropicDiscoveredModels,+ setCustomProviderConfigs,setDiscoveredCodexModels,+ setXaiDiscoveredModels,} from '../active-catalog.js';describe('active catalog revision', () => {@@ -18,6 +20,8 @@ describe('active catalog revision', () => {setActiveCatalog(BUNDLED_CATALOG);setAnthropicDiscoveredModels([]);setDiscoveredCodexModels([]);+ setXaiDiscoveredModels(null);+ setCustomProviderConfigs([]);});it('invalidates the merged catalog before notifying one monotonic revision', () => {@@ -45,6 +49,35 @@ describe('active catalog revision', () => {expect(listener.mock.results[0]?.value.ids).toContain('gpt-next-live');});+ it('keeps legacy custom xai isolated across catalog refresh and owner config reload', () => {+ setCustomProviderConfigs([+ {+ id: 'xai',+ name: 'Private xAI-compatible endpoint',+ runtimes: {+ codex: {+ baseUrl: 'https://private-xai.example/v1',+ models: [{ id: 'private-grok', name: 'Private Grok' }],+ },+ },+ },+ ]);+ setActiveCatalog(structuredClone(BUNDLED_CATALOG));++ const active = getActiveCatalog();+ expect(active.providers.find((provider) => provider.id === 'xai')?.source).toBe('builtin');+ expect(active.providers.find((provider) => provider.id === 'custom:xai')).toMatchObject({+ source: 'user',+ routing: { codex: { upstream: 'https://private-xai.example/v1' } },+ });++ setCustomProviderConfigs([]);+ expect(getActiveCatalog().providers.some((provider) => provider.id === 'custom:xai')).toBe(+ false,+ );+ expect(getActiveCatalog().providers.some((provider) => provider.id === 'xai')).toBe(true);+ });+it('routes Anthropic discovery through the same revision listener', () => {const start = getActiveCatalogRevision();const listener = vi.fn((revision: number) => ({@@ -70,8 +103,10 @@ describe('active catalog revision', () => {expect(listener.mock.results[0]?.value.ids).toContain('claude-opus-next');});- it('refreshes one provider model snapshot without replacing live routing or other providers', () => {- // registry-free 克隆:本用例只验「换模型快照不换路由」机制,隔离 registry 实体化层。+ it('refreshes xAI catalog metadata and routing without replacing other providers', () => {+ // registry-free 克隆:server Catalog 可更新 xAI routing/metadata;账号快照只在+ // computeMerged 阶段决定 membership。这里隔离 registry 实体化层,只验证 provider+ // plane 更新不会连带替换其他 provider。const current = structuredClone(BUNDLED_CATALOG);delete (current as { modelRegistry?: unknown }).modelRegistry;const incoming = structuredClone(current);@@ -117,7 +152,7 @@ describe('active catalog revision', () => {incomingXai.models.codex,);expect(active.providers.find((provider) => provider.id === 'xai')?.routing.codex).toEqual(- currentXai.routing.codex,+ incomingXai.routing.codex,);expect(active.providers.find((provider) => provider.id === 'openai')?.models.codex).toEqual(currentOpenAi.models.codex,diff --git a/apps/desktop/src/main/maker-host/__tests__/catalogDerivedModels.test.ts b/apps/desktop/src/main/maker-host/__tests__/catalogDerivedModels.test.tsindex fcb9050cbb..a3018ee2e2 100644--- a/apps/desktop/src/main/maker-host/__tests__/catalogDerivedModels.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/catalogDerivedModels.test.ts@@ -3,9 +3,9 @@** 历史:本文件曾是「迁移前硬编码清单的逐字快照」守卫(规则 10 no-break)。统一重构后* 静态清单**按设计**退役——anthropic/openai/xd 的清单运行时动态注入(SDK 发现 /- * codex 注册表 / 网关下发,见 active-catalog + model-discovery),bundled 只剩 xai。+ * codex 注册表 / 网关下发,见 active-catalog + model-discovery),bundled 的 xai 仅作离线 fallback。* 冻结快照随之退役;本守卫改为守派生机制本身的契约:- * 1. bundled 派生 = 仅 xai 静态清单(动态供应商零静态模型,不用假数据冒充);+ * 1. bundled 派生 = xai 离线 fallback(账号发现成功后由账号快照收缩成员);* 2. 注入后的目录按 provider 序 flatMap + id 首见去重,per-agent 分叉字段透传;* 3. refreshCatalogDerivedModels 原地 splice(已建会话持引用可见新目录)。*/@@ -61,10 +61,11 @@ function injectedCatalog(): Catalog {}describe('deriveAvailableModels — dynamic-first catalog contract', () => {- it('adds native minimal thinking to reasoning-capable Pi models only', () => {+ it('publishes Pi effort controls only when the official catalog has an explicit thinking map', () => {const pi = deriveAvailableModels(BUNDLED_CATALOG, 'pi');- expect(pi.find((m) => m.id === 'xai/grok-4.3')?.efforts[0]).toBe('minimal');- expect(pi.find((m) => m.id === 'xai/grok-code-fast')?.efforts).toEqual([]);+ expect(pi.find((m) => m.id === 'grok-4.3')?.efforts).toEqual([]);+ expect(pi.find((m) => m.id === 'grok-4.5')?.efforts).toEqual(['minimal', 'low', 'medium', 'high']);+ expect(pi.find((m) => m.id === 'grok-4.6')?.efforts).toEqual([]);});it('preserves the explicit effort subset of a Pi BYOM model in remote capabilities', () => {@@ -114,13 +115,13 @@ describe('deriveAvailableModels — dynamic-first catalog contract', () => {wireProtocol: 'openai-responses',models: [{- id: 'xai/grok-4.3',+ id: 'grok-4.3',name: 'Grok 4.3 through BYOM',reasoning: true,reasoningEfforts: ['low'],},{- id: 'xai/grok-4.5',+ id: 'grok-4.5',name: 'Grok 4.5 without declared reasoning',},],@@ -130,25 +131,25 @@ describe('deriveAvailableModels — dynamic-first catalog contract', () => {);const flatModels = deriveAvailableModels(catalog, 'pi');- const flat = flatModels.filter((m) => m.id === 'xai/grok-4.3');+ const flat = flatModels.filter((m) => m.id === 'grok-4.3');expect(flat).toHaveLength(1);expect(flat[0]).toMatchObject({- efforts: ['low'],- defaultEffort: 'low',+ efforts: [],+ defaultEffort: null,});expect(- resolvePiRuntimeModelDescriptor(catalog, 'colliding-reasoning', 'xai/grok-4.3'),+ resolvePiRuntimeModelDescriptor(catalog, 'colliding-reasoning', 'grok-4.3'),).toMatchObject({efforts: ['low'],defaultEffort: 'low',});- expect(flatModels.find((m) => m.id === 'xai/grok-4.5')).toMatchObject({+ expect(flatModels.find((m) => m.id === 'grok-4.5')).toMatchObject({efforts: [],defaultEffort: null,});});- it('resolves the cindy gateway descriptor from built-ins when a non-reasoning BYOM claims the same id first', () => {+ it('resolves the native xAI descriptor when a non-reasoning BYOM claims the same id first', () => {const catalog = structuredClone(BUNDLED_CATALOG);catalog.providers.unshift(buildUserProvider({@@ -159,22 +160,22 @@ describe('deriveAvailableModels — dynamic-first catalog contract', () => {pi: {baseUrl: 'http://127.0.0.1:11434/v1',wireProtocol: 'openai-responses',- models: [{ id: 'xai/grok-4.5', name: 'Grok 4.5 without reasoning' }],+ models: [{ id: 'grok-4.5', name: 'Grok 4.5 without reasoning' }],},},}),);- expect(deriveAvailableModels(catalog, 'pi').find((m) => m.id === 'xai/grok-4.5')).toMatchObject({+ expect(deriveAvailableModels(catalog, 'pi').find((m) => m.id === 'grok-4.5')).toMatchObject({efforts: [],defaultEffort: null,});expect(- resolvePiRuntimeModelDescriptor(catalog, 'colliding-non-reasoning', 'xai/grok-4.5'),+ resolvePiRuntimeModelDescriptor(catalog, 'colliding-non-reasoning', 'grok-4.5'),).toMatchObject({ efforts: [], defaultEffort: null });- expect(resolvePiRuntimeModelDescriptor(catalog, 'cindy', 'xai/grok-4.5')).toMatchObject({+ expect(resolvePiRuntimeModelDescriptor(catalog, 'xai', 'grok-4.5')).toMatchObject({efforts: ['minimal', 'low', 'medium', 'high'],- defaultEffort: 'high',+ defaultEffort: 'medium',});});@@ -227,7 +228,7 @@ describe('deriveAvailableModels — dynamic-first catalog contract', () => {);});- it('bundled(未注入)派生 = 仅 xai 静态清单,动态供应商不贡献任何条目', () => {+ it('bundled(未注入)派生 = xai 离线 fallback,其它动态供应商不贡献条目', () => {const cc = deriveAvailableModels(BUNDLED_CATALOG, 'claude-code');const codex = deriveAvailableModels(BUNDLED_CATALOG, 'codex');expect(cc.map((m) => m.id)).toEqual([diff --git a/apps/desktop/src/main/maker-host/__tests__/claudeProxyScopeGate.test.ts b/apps/desktop/src/main/maker-host/__tests__/claudeProxyScopeGate.test.tsindex f9cc9176d6..f0b04e1c31 100644--- a/apps/desktop/src/main/maker-host/__tests__/claudeProxyScopeGate.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/claudeProxyScopeGate.test.ts@@ -55,6 +55,7 @@ import {} from '../claude-session-route-registry';import { setPendingCredentialSwitchReader, setProviderOAuthTokenReader } from '../provider-route';import {+ authenticatePiProxySession,registerPiProxySession,resetPiProxySessionsForTest,} from '../pi-proxy-session-auth';@@ -185,6 +186,17 @@ describe('pi routingTransform — xdt session header selects the Pi provider rouresetPiProxySessionsForTest();});+ it('an old disposer cannot remove a replacement registration with the same stable token', () => {+ const disposeOld = registerPiProxySession('sess-pi', 'stable-secret');+ const disposeReplacement = registerPiProxySession('sess-pi', 'stable-secret');++ disposeOld();+ expect(authenticatePiProxySession('sess-pi', 'stable-secret')).toBe(true);++ disposeReplacement();+ expect(authenticatePiProxySession('sess-pi', 'stable-secret')).toBe(false);+ });+it('routes an Anthropic Pi request with host-managed OAuth and strips Pi placeholder auth', async () => {setClaudeProxyGatewayKeyReader(() => 'sk-gw');setSessionProvider('sess-pi', 'anthropic');diff --git a/apps/desktop/src/main/maker-host/__tests__/codexAuthBindingClaim.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexAuthBindingClaim.test.tsindex 2e5e812b2f..06cffb1cb5 100644--- a/apps/desktop/src/main/maker-host/__tests__/codexAuthBindingClaim.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/codexAuthBindingClaim.test.ts@@ -55,7 +55,12 @@ vi.mock('../../appSessionState.js', async (importOriginal) => {};});-function fixture(): { codexHome: string; systemAuth: string; localAuth: string; bindingFile: string } {+function fixture(): {+ codexHome: string;+ systemAuth: string;+ localAuth: string;+ bindingFile: string;+} {const root = fs.mkdtempSync(path.join(os.tmpdir(), 'xdt-codex-binding-claim-'));dirs.push(root);h.userDataDir = path.join(root, 'user-data');@@ -120,6 +125,9 @@ describe('codex OAuth binding auto-claim on reconcile', () => {identity: '[email protected]',});expect(readBindingFile(bindingFile)).toMatchObject({ openai: 'owner-a' });+ expect(readBindingFile(bindingFile)).toMatchObject({+ sources: { openai: 'native-harness-inherited' },+ });await expect(adapter.getAccessToken()).resolves.toBe('system-token');});@@ -166,9 +174,8 @@ describe('codex OAuth binding auto-claim on reconcile', () => {const { codexHome, systemAuth, localAuth, bindingFile } = fixture();fs.mkdirSync(codexHome, { recursive: true });fs.copyFileSync(systemAuth, localAuth);- const { CODEX_USER_DISCONNECT_REASON, writeInvalidatedSystemCodexAuthMarker } = await import(- '../codex-auth-invalidation.js'- );+ const { CODEX_USER_DISCONNECT_REASON, writeInvalidatedSystemCodexAuthMarker } =+ await import('../codex-auth-invalidation.js');expect(writeInvalidatedSystemCodexAuthMarker(codexHome,diff --git a/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.tsindex 3afac8ebe6..879e8bb785 100644--- a/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts@@ -3863,7 +3863,11 @@ describe('codex proxy host', () => {it('normalizes implicit-source xAI Codex requests before forwarding', async () => {const host = await freshCodexProxyHost();+ const { BUNDLED_CATALOG } = await import('@cindy/model-providers');+ const { setActiveCatalog, setXaiDiscoveredModels } = await import('../active-catalog.js');const { clearSessionProvider } = await import('../session-provider-store.js');+ setActiveCatalog(BUNDLED_CATALOG);+ setXaiDiscoveredModels([{ id: 'xai/grok-code-fast' }]);mockState.createAnthropicCompatProxy.mockResolvedValueOnce({url: 'http://127.0.0.1:43210',dispose: vi.fn(async () => undefined),@@ -3872,33 +3876,38 @@ describe('codex proxy host', () => {host.registerComposed('session-xai-implicit', 'thread-xai-implicit', 'PRODUCT_PROMPT');clearSessionProvider('session-xai-implicit');- const transforms = mockState.createAnthropicCompatProxy.mock.calls[0]?.[0]?.transformRequest ?? [];- let current: unknown = {- model: 'xai/grok-code-fast',- instructions: 'BASE_PROMPT\n\nPRODUCT_PROMPT',- reasoning: { effort: 'high', summary: 'auto' },- input: [- { type: 'reasoning', encrypted_content: 'gAAA' },- { role: 'user', content: 'hello' },- ],- };- const ctx = {- method: 'POST',- url: '/responses',- headers: { 'thread-id': 'thread-xai-implicit' },- };- for (const transform of transforms) {- const next = transform(current, ctx);- if (next !== null && next !== undefined) current = next;- }+ try {+ const transforms = mockState.createAnthropicCompatProxy.mock.calls[0]?.[0]?.transformRequest ?? [];+ let current: unknown = {+ model: 'xai/grok-code-fast',+ instructions: 'BASE_PROMPT\n\nPRODUCT_PROMPT',+ reasoning: { effort: 'high', summary: 'auto' },+ input: [+ { type: 'reasoning', encrypted_content: 'gAAA' },+ { role: 'user', content: 'hello' },+ ],+ };+ const ctx = {+ method: 'POST',+ url: '/responses',+ headers: { 'thread-id': 'thread-xai-implicit' },+ };+ for (const transform of transforms) {+ const next = transform(current, ctx);+ if (next !== null && next !== undefined) current = next;+ }- expect(current).toEqual({- model: 'grok-code-fast',- input: [- { type: 'message', role: 'system', content: 'BASE_PROMPT\n\nPRODUCT_PROMPT' },- { type: 'message', role: 'user', content: 'hello' },- ],- });+ expect(current).toEqual({+ model: 'grok-code-fast',+ input: [+ { type: 'message', role: 'system', content: 'BASE_PROMPT\n\nPRODUCT_PROMPT' },+ { type: 'message', role: 'user', content: 'hello' },+ ],+ });+ } finally {+ setXaiDiscoveredModels(null);+ setActiveCatalog(BUNDLED_CATALOG);+ }});it('leaves non-xai/ bodies untouched in explicit xAI sessions (transform 与路由 scope 门同源, #890 review)', async () => {diff --git a/apps/desktop/src/main/maker-host/__tests__/custom-provider-store.test.ts b/apps/desktop/src/main/maker-host/__tests__/custom-provider-store.test.tsindex 800e34f52a..98ee718639 100644--- a/apps/desktop/src/main/maker-host/__tests__/custom-provider-store.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/custom-provider-store.test.ts@@ -92,6 +92,10 @@ describe('validateCustomProviderConfig (per-runtime)', () => {it('rejects bad / reserved ids', () => {expect(validateCustomProviderConfig({ ...valid, id: 'Bad Id' }).ok).toBe(false);expect(validateCustomProviderConfig({ ...valid, id: 'xd' }).ok).toBe(false);+ expect(validateCustomProviderConfig({ ...valid, id: 'xai' }).ok).toBe(false);+ expect(validateCustomProviderConfig({ ...valid, id: 'xai' }, { allowLegacyXai: true }).ok).toBe(+ true,+ );// 'cindy' 撞 pi 网关 provider id,必须保留expect(validateCustomProviderConfig({ ...valid, id: 'cindy' }).ok).toBe(false);});@@ -195,6 +199,7 @@ describe('validateCustomProviderConfig (per-runtime)', () => {config({reasoning: true,reasoningEfforts: ['low', 'high', 'xhigh'],+ reasoningDefaultEffort: 'high',}),),).toEqual({ ok: true });@@ -216,6 +221,11 @@ describe('validateCustomProviderConfig (per-runtime)', () => {).ok,).toBe(false);expect(validateCustomProviderConfig(config({ reasoningEfforts: ['high'] })).ok).toBe(false);+ expect(validateCustomProviderConfig(config({+ reasoning: true,+ reasoningEfforts: ['low', 'high'],+ reasoningDefaultEffort: 'max',+ })).ok).toBe(false);expect(validateCustomProviderConfig(config(@@ -360,6 +370,199 @@ describe('custom-provider-store CRUD (per-runtime)', () => {]);});+ it('round-trips the Pi official catalog provider id without adding it to other runtimes', async () => {+ mountDb();+ await createCustomProvider({+ id: 'official-pi',+ name: 'Official Pi',+ runtimes: {+ pi: {+ baseUrl: 'https://api.deepseek.com',+ piCatalogProviderId: 'deepseek',+ models: [{ id: 'deepseek-v4-pro', name: 'DeepSeek V4 Pro' }],+ },+ },+ });+ expect((await getCustomProvider('official-pi'))?.runtimes.pi?.piCatalogProviderId).toBe('deepseek');+ expect(validateCustomProviderConfig({+ id: 'bad-catalog-runtime',+ name: 'Bad',+ runtimes: {+ codex: {+ baseUrl: 'https://api.example/v1',+ piCatalogProviderId: 'deepseek',+ models: [{ id: 'm', name: 'M' }],+ },+ },+ }).ok).toBe(false);+ });++ it('clears the Pi catalog marker when any write path changes saved model metadata', async () => {+ mountDb();+ const original = await createCustomProvider({+ id: 'official-pi-edited',+ name: 'Official Pi',+ runtimes: {+ pi: {+ baseUrl: 'https://api.deepseek.com',+ wireProtocol: 'openai-chat',+ piCatalogProviderId: 'deepseek',+ models: [{+ id: 'deepseek-v4-pro',+ name: 'DeepSeek V4 Pro',+ contextWindow: 1_000_000,+ reasoning: true,+ reasoningEfforts: ['high', 'max'],+ reasoningDefaultEffort: 'high',+ }],+ },+ },+ });+ const edited: CustomProviderConfig = {+ ...original,+ runtimes: {+ ...original.runtimes,+ pi: {+ ...original.runtimes.pi!,+ models: [{+ ...original.runtimes.pi!.models[0]!,+ name: 'My DeepSeek',+ contextWindow: 64_000,+ supportsImageInput: true,+ reasoningEfforts: ['low'],+ reasoningDefaultEffort: 'low',+ }],+ },+ },+ };+ expect((await updateCustomProvider('official-pi-edited', {+ ...original,+ name: 'Renamed provider only',+ }))?.runtimes.pi?.piCatalogProviderId).toBe('deepseek');+ const defaultProtocolRoundTrip: CustomProviderConfig = {+ ...original,+ runtimes: {+ ...original.runtimes,+ pi: { ...original.runtimes.pi!, wireProtocol: undefined },+ },+ };+ expect((await updateCustomProvider('official-pi-edited', defaultProtocolRoundTrip))+ ?.runtimes.pi?.piCatalogProviderId).toBe('deepseek');+ expect((await updateCustomProvider('official-pi-edited', {+ ...defaultProtocolRoundTrip,+ runtimes: {+ ...defaultProtocolRoundTrip.runtimes,+ pi: {+ ...defaultProtocolRoundTrip.runtimes.pi!,+ wireProtocol: 'anthropic-messages',+ },+ },+ }))?.runtimes.pi).not.toHaveProperty('piCatalogProviderId');++ await updateCustomProvider('official-pi-edited', original);+ expect((await updateCustomProvider('official-pi-edited', edited))?.runtimes.pi)+ .not.toHaveProperty('piCatalogProviderId');++ const second = await createCustomProvider({+ ...original,+ id: 'official-pi-discovered',+ });+ expect(await updateCustomProviderIfUnchanged(+ second.id,+ second,+ {+ ...second,+ runtimes: {+ ...second.runtimes,+ pi: {+ ...second.runtimes.pi!,+ models: [+ ...second.runtimes.pi!.models,+ { id: 'new-from-models-url', name: 'New model' },+ ],+ },+ },+ },+ )).toBe(true);+ expect((await getCustomProvider(second.id))?.runtimes.pi?.piCatalogProviderId)+ .toBe('deepseek');++ const replaced = await createCustomProvider({+ ...original,+ id: 'official-pi-replaced',+ });+ expect((await updateCustomProvider(replaced.id, {+ ...replaced,+ runtimes: {+ ...replaced.runtimes,+ pi: {+ ...replaced.runtimes.pi!,+ models: [{+ id: 'deepseek-v4-flash',+ name: 'My Flash Model',+ contextWindow: 64_000,+ supportsImageInput: true,+ reasoning: true,+ reasoningEfforts: ['low'],+ reasoningDefaultEffort: 'low',+ }],+ },+ },+ }))?.runtimes.pi).not.toHaveProperty('piCatalogProviderId');+ expect((await getCustomProvider(replaced.id))?.runtimes.pi).toMatchObject({+ models: [{+ id: 'deepseek-v4-flash',+ name: 'My Flash Model',+ contextWindow: 64_000,+ supportsImageInput: true,+ reasoning: true,+ reasoningEfforts: ['low'],+ reasoningDefaultEffort: 'low',+ }],+ });++ const deleted = await createCustomProvider({+ ...original,+ id: 'official-pi-deleted',+ });+ expect((await updateCustomProvider(deleted.id, {+ ...deleted,+ runtimes: {+ ...deleted.runtimes,+ pi: { ...deleted.runtimes.pi!, models: [] },+ },+ }))?.runtimes.pi).not.toHaveProperty('piCatalogProviderId');+ const deletedSnapshot = await getCustomProvider(deleted.id);+ expect((await updateCustomProvider(deleted.id, {+ ...deletedSnapshot!,+ runtimes: {+ ...deletedSnapshot!.runtimes,+ pi: {+ ...deletedSnapshot!.runtimes.pi!,+ models: deleted.runtimes.pi!.models,+ },+ },+ }))?.runtimes.pi).not.toHaveProperty('piCatalogProviderId');++ const duplicate = await createCustomProvider({+ ...original,+ id: 'official-pi-duplicate',+ });+ expect((await updateCustomProvider(duplicate.id, {+ ...duplicate,+ runtimes: {+ ...duplicate.runtimes,+ pi: {+ ...duplicate.runtimes.pi!,+ models: [+ { ...duplicate.runtimes.pi!.models[0]!, name: 'Edited first duplicate' },+ duplicate.runtimes.pi!.models[0]!,+ ],+ },+ },+ }))?.runtimes.pi).not.toHaveProperty('piCatalogProviderId');+ });+it('round-trips only an explicitly enabled Pi reasoning capability', async () => {mountDb();await createCustomProvider({@@ -375,6 +578,7 @@ describe('custom-provider-store CRUD (per-runtime)', () => {name: 'Reasoner',reasoning: true,reasoningEfforts: ['low', 'high', 'xhigh'],+ reasoningDefaultEffort: 'xhigh',},{ id: 'legacy', name: 'Legacy' },{ id: 'explicit-off', name: 'Explicit off', reasoning: false },@@ -388,6 +592,7 @@ describe('custom-provider-store CRUD (per-runtime)', () => {name: 'Reasoner',reasoning: true,reasoningEfforts: ['low', 'high', 'xhigh'],+ reasoningDefaultEffort: 'xhigh',},{ id: 'legacy', name: 'Legacy' },{ id: 'explicit-off', name: 'Explicit off' },diff --git a/apps/desktop/src/main/maker-host/__tests__/modelPlane.test.ts b/apps/desktop/src/main/maker-host/__tests__/modelPlane.test.tsindex 4ea3cc6bd7..8a6dc32013 100644--- a/apps/desktop/src/main/maker-host/__tests__/modelPlane.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/modelPlane.test.ts@@ -22,6 +22,7 @@ import {setAnthropicDiscoveredModels,setDiscoveredCodexModels,setLocalCatalogOverrides,+ setXaiDiscoveredModels,setXdGatewayModels,} from '../active-catalog.js';import {@@ -88,12 +89,13 @@ afterEach(() => {setActiveCatalog(BUNDLED_CATALOG);setDiscoveredCodexModels([]);setAnthropicDiscoveredModels([]);+ setXaiDiscoveredModels(null);setXdGatewayModels([]);setLocalCatalogOverrides(EMPTY_MODEL_CATALOG_OVERRIDES);});describe('registry presence 实体化', () => {- it('bundled xAI 离线快照与同仓 Registry 投影逐字节一致,禁止发布期人工漂移', () => {+ it('a loaded legacy Catalog keeps its own xAI fallback membership instead of importing Pi members', () => {const expected = BUNDLED_CATALOG.providers.find((provider) => provider.id === 'xai');if (!expected) throw new Error('bundled catalog missing xai');const generatedCatalog = structuredClone(BUNDLED_CATALOG);@@ -105,6 +107,9 @@ describe('registry presence 实体化', () => {setActiveCatalog(generatedCatalog);expect(models('xai', 'claude-code')).toEqual(expected.models['claude-code']);expect(models('xai', 'codex')).toEqual(expected.models.codex);+ expect(models('xai', 'pi').map((model) => model.id)).toEqual(+ expected.models['claude-code']?.map((model) => model.id.slice('xai/'.length)),+ );});it('远端宣告 GPT-6(status+能力自洽)→ 免发现进入 codex root,并自动派生 claude/pi bridge', () => {@@ -524,7 +529,7 @@ describe('本地 override(local 永远最高)', () => {expect(models('xai', 'codex').map((model) => model.id)).toEqual(xaiOrder);});- it('一条 perAgent.codex patch 只修 xAI Codex 档位,claude root 与 pi 镜像不动', () => {+ it('一条 perAgent.codex patch 只修 xAI Codex 档位,claude root 与 Pi 官方目录不动', () => {setActiveCatalog(baseCatalog([grokEntry()]));setLocalCatalogOverrides(overridesOf({@@ -541,8 +546,10 @@ describe('本地 override(local 永远最高)', () => {});const claude = models('xai', 'claude-code').find((m) => m.id === 'xai/grok-test');expect(claude).toMatchObject({ efforts: ['low', 'medium', 'high', 'xhigh'] });- // Pi 恒定镜像 claude-code root,拿满 root 档位。- expect(models('xai', 'pi').find((m) => m.id === 'xai/grok-test')).toEqual(claude);+ expect(models('xai', 'pi').find((m) => m.id === 'grok-test')).toMatchObject({+ efforts: ['low', 'medium', 'high', 'xhigh'],+ });+ expect(models('xai', 'pi').some((m) => m.id === 'grok-4.6')).toBe(false);});it('本地 perAgent 也在 bridge 目标端生效,且不能写展示/status 字段', () => {diff --git a/apps/desktop/src/main/maker-host/__tests__/nativeProviderAuthBinding.test.ts b/apps/desktop/src/main/maker-host/__tests__/nativeProviderAuthBinding.test.tsindex 9c7a72e490..bc5132804b 100644--- a/apps/desktop/src/main/maker-host/__tests__/nativeProviderAuthBinding.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/nativeProviderAuthBinding.test.ts@@ -22,6 +22,7 @@ vi.mock('../../appSessionState.js', () => ({import {bindNativeProviderAuth,claimDetectedNativeProviderAuth,+ getNativeProviderAuthSource,isNativeProviderAuthBound,isNativeProviderAuthRevoked,isNativeProviderAuthSelfAuthorized,@@ -51,11 +52,15 @@ describe('native provider auth legacy binding', () => {expect(JSON.parse(fs.readFileSync(bindingFile, 'utf8'))).toMatchObject({anthropic: 'owner-a',legacyClaimOwner: 'owner-a',+ sources: { anthropic: 'native-harness-inherited' },});});- it('does not reclaim a legacy credential after logout', () => {+ it('migrates an old Cindy xAI token as explicit provider OAuth, never CLI inheritance', () => {migrateLegacyNativeProviderAuthBindings('owner-a', { xai: true });+ expect(getNativeProviderAuthSource('xai')).toBe('explicit-provider-oauth');+ expect(isNativeProviderAuthSelfAuthorized('xai')).toBe(true);+unbindNativeProviderAuth('xai');session.dataOwnerId = 'owner-b';migrateLegacyNativeProviderAuthBindings('owner-b', { xai: true });@@ -119,12 +124,12 @@ describe('claimDetectedNativeProviderAuth', () => {expect(claimDetectedNativeProviderAuth('anthropic', () => true)).toBe(true);});- it('claims anthropic and xai on the same terms as openai', () => {- // 三家 native provider 共用一套认领口径:凭证在场 + 名额未被占 → 绑给当前 owner。+ it('claims only native Harness credentials and records their inherited source', () => {expect(claimDetectedNativeProviderAuth('anthropic', () => true)).toBe(true);- expect(claimDetectedNativeProviderAuth('xai', () => true)).toBe(true);+ expect(claimDetectedNativeProviderAuth('openai', () => true)).toBe(true);expect(isNativeProviderAuthBound('anthropic')).toBe(true);- expect(isNativeProviderAuthBound('xai')).toBe(true);+ expect(getNativeProviderAuthSource('anthropic')).toBe('native-harness-inherited');+ expect(getNativeProviderAuthSource('openai')).toBe('native-harness-inherited');session.dataOwnerId = 'owner-b';expect(isNativeProviderAuthBound('anthropic')).toBe(false);@@ -172,15 +177,13 @@ describe('claimDetectedNativeProviderAuth', () => {expect(isNativeProviderAuthBound('xai')).toBe(true);});- it('用户再次显式授权即清除撤销标记,恢复自动继承语义', () => {+ it('xAI 再次显式授权清除撤销标记,但仍保持 provider OAuth 来源', () => {unbindNativeProviderAuth('xai', { revoked: true });- expect(claimDetectedNativeProviderAuth('xai', () => true)).toBe(false);bindNativeProviderAuth('xai');expect(isNativeProviderAuthBound('xai')).toBe(true);- unbindNativeProviderAuth('xai');- // 上一次的撤销标记已随显式授权作废,这次(非显式登出)不该再挡。- expect(claimDetectedNativeProviderAuth('xai', () => true)).toBe(true);+ expect(getNativeProviderAuthSource('xai')).toBe('explicit-provider-oauth');+ expect(JSON.parse(fs.readFileSync(bindingFile, 'utf8'))).not.toHaveProperty('revoked.xai');});it('凭证失效(非用户登出)不留标记 —— 本机重新登录后仍按设计自动继承', () => {@@ -233,7 +236,9 @@ describe('claimDetectedNativeProviderAuth', () => {expect(() => claimDetectedNativeProviderAuth('anthropic', () => true)).not.toThrow();expect(claimDetectedNativeProviderAuth('anthropic', () => true)).toBe(false);expect(() => unbindNativeProviderAuth('anthropic', { revoked: true })).not.toThrow();- expect(() => migrateLegacyNativeProviderAuthBindings('owner-a', { anthropic: true })).not.toThrow();+ expect(() =>+ migrateLegacyNativeProviderAuthBindings('owner-a', { anthropic: true }),+ ).not.toThrow();expect(fs.readFileSync(bindingFile, 'utf8')).toBe(bad); // 一律不改写}@@ -271,7 +276,7 @@ describe('claimDetectedNativeProviderAuth', () => {// 坏掉的 revoked 无从得知谁被撤销过,不能直接丢弃(丢弃 = 给所有残留凭证放行)。expect(after.revoked).toMatchObject({ openai: 'owner-a', xai: 'owner-a' });expect(after.revoked).not.toHaveProperty('anthropic');- expect(claimDetectedNativeProviderAuth('xai', () => true)).toBe(false);+ expect(isNativeProviderAuthBound('xai')).toBe(false);// 本次授权的这家不受抑制,且 owner-b 的 openai 依然轮不到 owner-a。expect(isNativeProviderAuthBound('anthropic')).toBe(true);expect(isNativeProviderAuthBound('openai')).toBe(false);@@ -344,9 +349,11 @@ describe('凭证来路(selfAuthorized)—— 显式授权 vs 自动继承', () =it('显式授权记下来路,自动认领不记', () => {bindNativeProviderAuth('anthropic');expect(isNativeProviderAuthSelfAuthorized('anthropic')).toBe(true);+ expect(getNativeProviderAuthSource('anthropic')).toBe('explicit-provider-oauth');expect(claimDetectedNativeProviderAuth('openai', () => true)).toBe(true);expect(isNativeProviderAuthSelfAuthorized('openai')).toBe(false);+ expect(getNativeProviderAuthSource('openai')).toBe('native-harness-inherited');});it('来路按 provider 分别记账,不互相串味', () => {diff --git a/apps/desktop/src/main/maker-host/__tests__/nativeProviderConnectionClaim.test.ts b/apps/desktop/src/main/maker-host/__tests__/nativeProviderConnectionClaim.test.tsindex a131feac58..e26a8371e4 100644--- a/apps/desktop/src/main/maker-host/__tests__/nativeProviderConnectionClaim.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/nativeProviderConnectionClaim.test.ts@@ -20,7 +20,9 @@ const h = vi.hoisted(() => ({catalog: null as Catalog | null,claudeCredentialPresent: true,grokCredentialPresent: true,- refreshAnthropicModels: vi.fn(),+ refreshAnthropicModels: vi.fn(async () => true),+ refreshXaiModels: vi.fn(async () => true),+ loadXaiDiskCache: vi.fn(async () => false),refreshXaiMediaModels: vi.fn(async () => true),loadAnthropicDiskCache: vi.fn(async () => {}),codexLoginWithSideEffects: vi.fn(async () => false),@@ -43,6 +45,7 @@ vi.mock('../../appSessionState.js', () => ({dataOwnerId: h.dataOwnerId,generation: h.generation,}),+ activeOwnerScopeKey: () => `local:${h.dataOwnerId ?? 'none'}:${h.generation}`,isAppSessionBoundaryPending: () => false,// model-disable-store(经 createDesktopProviderService 引入)按 owner 定位 override// 文件;指到本用例的临时 userData 即可(store 是惰性读,文件缺席 = 全启用)。@@ -53,13 +56,13 @@ vi.mock('../../appSessionState.js', () => ({// 与真实实现(readClaudeAiOAuth / hasGrokOAuthLogin)的分层一致。vi.mock('../claude-credentials-store.js', () => ({hasClaudeAiOAuthUnbound: () => h.claudeCredentialPresent,- hasClaudeAiOAuth: () =>- h.claudeCredentialPresent && isBoundToCurrentOwner('anthropic'),+ hasClaudeAiOAuth: () => h.claudeCredentialPresent && isBoundToCurrentOwner('anthropic'),}));vi.mock('../grok-oauth-login.js', () => ({hasGrokOAuthLoginUnbound: () => h.grokCredentialPresent,hasGrokOAuthLogin: () => h.grokCredentialPresent && isBoundToCurrentOwner('xai'),getGrokAccessToken: () => null,+ peekGrokAccessToken: () => null,resetGrokOAuthMemoryCache: () => {},}));@@ -68,6 +71,11 @@ vi.mock('../model-discovery/anthropic.js', () => ({refreshAnthropicModelsFromHttp: h.refreshAnthropicModels,getAnthropicModelDiscoveryFailure: () => h.anthropicDiscoveryFailure,}));+vi.mock('../model-discovery/xai.js', () => ({+ clearXaiDiscoveredModels: vi.fn(),+ loadXaiModelsFromDiskCache: h.loadXaiDiskCache,+ refreshXaiModelsFromHttp: h.refreshXaiModels,+}));vi.mock('../model-discovery/xai-media.js', () => ({refreshXaiMediaModels: h.refreshXaiMediaModels,clearXaiMediaModels: vi.fn(),@@ -93,11 +101,21 @@ vi.mock('../auth-adapters.js', () => ({},}));-vi.mock('../../authManager.js', () => ({ getAuthState: () => ({ mode: 'local' as const, user: null }) }));-vi.mock('../../appCapabilities.js', () => ({ getAppCapabilities: () => ({ canUseCindyGateway: false }) }));+vi.mock('../../authManager.js', () => ({+ getAuthState: () => ({ mode: 'local' as const, user: null }),+}));+vi.mock('../../appCapabilities.js', () => ({+ getAppCapabilities: () => ({ canUseCindyGateway: false }),+}));vi.mock('../../ownerNamespaceMigration.js', () => ({ hasLegacyOwnerNamespaceClaim: () => false }));-vi.mock('../../manifestService.js', () => ({ isDev: () => true, getBaseUrl: () => 'https://example.invalid' }));-vi.mock('../../clientEndpointsService.js', () => ({ getBuildClientEndpoint: () => 'https://example.invalid', getClientEndpoint: () => 'https://example.invalid' }));+vi.mock('../../manifestService.js', () => ({+ isDev: () => true,+ getBaseUrl: () => 'https://example.invalid',+}));+vi.mock('../../clientEndpointsService.js', () => ({+ getBuildClientEndpoint: () => 'https://example.invalid',+ getClientEndpoint: () => 'https://example.invalid',+}));vi.mock('../../secrets/providerSecretStore.js', () => ({genericOAuthSecretIo: {},setProviderSecretsClearedListener: () => {},@@ -112,7 +130,11 @@ import {getDesktopProviderService,setNativeProviderClaimListener,} from '../createDesktopProviderService.js';-import { isNativeProviderAuthBound } from '../nativeProviderAuthBinding.js';+import {+ bindNativeProviderAuth,+ getNativeProviderAuthSource,+ isNativeProviderAuthBound,+} from '../nativeProviderAuthBinding.js';function isBoundToCurrentOwner(provider: 'anthropic' | 'xai'): boolean {return isNativeProviderAuthBound(provider);@@ -136,6 +158,8 @@ beforeEach(() => {h.grokCredentialPresent = true;h.anthropicDiscoveryFailure = null;h.refreshAnthropicModels.mockClear();+ h.refreshXaiModels.mockClear();+ h.loadXaiDiskCache.mockClear();h.refreshXaiMediaModels.mockClear();h.loadAnthropicDiskCache.mockClear();h.codexLoginWithSideEffects.mockClear();@@ -152,6 +176,7 @@ describe('native provider connection claim on read', () => {expect((await connectedMap()).anthropic).toBe(true);expect(isNativeProviderAuthBound('anthropic')).toBe(true);+ expect(getNativeProviderAuthSource('anthropic')).toBe('native-harness-inherited');// 绑定刚建立 —— 启动期那次发现早被登录态 gate 掉,必须在这里补一次。expect(h.refreshAnthropicModels).toHaveBeenCalledTimes(1);// 磁盘缓存同样要补:启动期那次 load 也因未绑定而早退了。不先摆出上次成功的清单,@@ -318,21 +343,29 @@ describe('native provider connection claim on read', () => {expect(secondProviders.find((provider) => provider.id === 'anthropic')?.connected).toBe(true);});- it('认领本机 xai 凭证后后台补拉媒体模型', async () => {+ it('不把 Cindy 存在的 xAI token 当本机 CLI 凭证自动认领', async () => {+ expect((await connectedMap()).xai).toBe(false);+ expect(isNativeProviderAuthBound('xai')).toBe(false);+ expect(h.refreshXaiModels).not.toHaveBeenCalled();+ expect(h.loadXaiDiskCache).not.toHaveBeenCalled();++ bindNativeProviderAuth('xai');expect((await connectedMap()).xai).toBe(true);- expect(isNativeProviderAuthBound('xai')).toBe(true);- expect(h.refreshXaiMediaModels).toHaveBeenCalledTimes(1);+ expect(getNativeProviderAuthSource('xai')).toBe('explicit-provider-oauth');+ expect(h.refreshXaiModels).not.toHaveBeenCalled();+ // Explicit OAuth/login owns discovery refresh. Merely reading connection state after+ // a durable binding must stay side-effect free and must not re-run media discovery.+ expect(h.refreshXaiMediaModels).not.toHaveBeenCalled();});it('认领成功要广播:其它窗口与 device-link 对端只认这条推送来失效快照', async () => {- // xai 的自愈没有清单拉取顺带广播那条路,不显式通知就只有触发这次读取的调用方看到- // 「已连接」,配对的手机会一直留着 connected:false 的缓存(PR #548 review)。+ // Claude 本机凭证自愈后要广播;xAI 不走本机凭证认领。+ h.grokCredentialPresent = false;const onClaimed = vi.fn();setNativeProviderClaimListener(onClaimed);try {- h.claudeCredentialPresent = false; // 只让 xai 认领,避免与 anthropic 混淆计数- await connectedMap();- expect(isNativeProviderAuthBound('xai')).toBe(true);+ await listProviders(true, true);+ expect(isNativeProviderAuthBound('anthropic')).toBe(true);expect(onClaimed).toHaveBeenCalledTimes(1);// 已绑定后不再重复广播。@@ -348,10 +381,16 @@ describe('native provider connection claim on read', () => {let releaseCache!: () => void;let releaseRefresh!: () => void;h.loadAnthropicDiskCache.mockImplementationOnce(- () => new Promise<void>((resolve) => { releaseCache = resolve; }),+ () =>+ new Promise<void>((resolve) => {+ releaseCache = resolve;+ }),);h.refreshAnthropicModels.mockImplementationOnce(- () => new Promise<boolean>((resolve) => { releaseRefresh = () => resolve(true); }),+ () =>+ new Promise<boolean>((resolve) => {+ releaseRefresh = () => resolve(true);+ }),);const onClaimed = vi.fn();setNativeProviderClaimListener(onClaimed);@@ -374,8 +413,8 @@ describe('native provider connection claim on read', () => {throw new Error('broadcast boom');});try {- await expect(connectedMap()).resolves.toMatchObject({ xai: true });- expect(isNativeProviderAuthBound('xai')).toBe(true);+ await expect(connectedMap()).resolves.toMatchObject({ anthropic: true });+ expect(isNativeProviderAuthBound('anthropic')).toBe(true);} finally {setNativeProviderClaimListener(null);}@@ -445,4 +484,17 @@ describe('native provider connection claim on read', () => {expect(connected.anthropic).toBe(false);expect(h.refreshAnthropicModels).not.toHaveBeenCalled();});++ it('durable disconnect 后即使本机 Claude 凭证仍在,也不绑定、不发现、不回灌', async () => {+ fs.writeFileSync(+ path.join(h.userDataDir, 'native-provider-auth.json'),+ JSON.stringify({ revoked: { anthropic: 'owner-a' } }),+ );++ const connected = await connectedMap();+ expect(connected.anthropic).toBe(false);+ expect(isNativeProviderAuthBound('anthropic')).toBe(false);+ expect(h.loadAnthropicDiskCache).not.toHaveBeenCalled();+ expect(h.refreshAnthropicModels).not.toHaveBeenCalled();+ });});diff --git a/apps/desktop/src/main/maker-host/__tests__/pi-remote-provider-forward.test.ts b/apps/desktop/src/main/maker-host/__tests__/pi-remote-provider-forward.test.tsnew file mode 100644index 0000000000..10599fa1f3--- /dev/null+++ b/apps/desktop/src/main/maker-host/__tests__/pi-remote-provider-forward.test.ts@@ -0,0 +1,33 @@+import { describe, expect, it, vi } from 'vitest';+import type { RemoteForward } from '@cindy/maker-remote-ssh';++import { createPiRemoteProviderForwardLease } from '../pi-remote-provider-forward';++describe('Pi remote provider forward lease', () => {+ it('gives overlapping transport wrappers independent handles for the same tunnel', async () => {+ const closeOld = vi.fn(async () => undefined);+ const closeReplacement = vi.fn(async () => undefined);+ const handles: RemoteForward[] = [+ { remotePort: 43121, close: closeOld },+ { remotePort: 43121, close: closeReplacement },+ ];+ const ensureRemoteForward = vi.fn(async () => handles.shift()!);+ const oldLease = createPiRemoteProviderForwardLease(ensureRemoteForward);+ const replacementLease = createPiRemoteProviderForwardLease(ensureRemoteForward);+ const spec = { localUrl: 'http://127.0.0.1:43120', remotePort: 43121 };++ await oldLease.ensure(spec);+ await replacementLease.ensure(spec);+ expect(ensureRemoteForward).toHaveBeenCalledTimes(2);++ await oldLease.releaseAll();+ expect(closeOld).toHaveBeenCalledTimes(1);+ expect(closeReplacement).not.toHaveBeenCalled();++ await replacementLease.ensure(spec);+ expect(ensureRemoteForward).toHaveBeenCalledTimes(2);+ await replacementLease.releaseAll();+ await replacementLease.releaseAll();+ expect(closeReplacement).toHaveBeenCalledTimes(1);+ });+});diff --git a/apps/desktop/src/main/maker-host/__tests__/piAuthEnv.test.ts b/apps/desktop/src/main/maker-host/__tests__/piAuthEnv.test.tsindex 60892be9c3..a3b2492a86 100644--- a/apps/desktop/src/main/maker-host/__tests__/piAuthEnv.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/piAuthEnv.test.ts@@ -1,10 +1,12 @@/*** DesktopPiAuthAdapter.getAuthEnv —— 会话级网关 key(CINDY_PI_API_KEY)注入规则。- * 关键不变量:只有订阅 OAuth provider(anthropic/openai/xai)写占位符(真凭证由 compat- * proxy 注入);BYOM/自定义 provider 及网关本身都拿真网关 key,否则网关块被毒化,- * BYOM 会话中途切回网关模型会 401。+ * 关键不变量:只有共用 cindy provider 的订阅 OAuth 路由(anthropic/openai)写占位符;+ * xAI/BYOM 原生 provider 使用独立 env,CINDY_PI_API_KEY 保留真网关 key,否则+ * 会话中途切回网关模型会 401。*/-import { describe, expect, it, vi } from 'vitest';+import { beforeEach, describe, expect, it, vi } from 'vitest';++const h = vi.hoisted(() => ({ gatewayKey: 'REAL-GATEWAY-KEY' as string | null }));vi.mock('electron', () => ({app: {@@ -15,7 +17,7 @@ vi.mock('electron', () => ({}));vi.mock('../auth-adapters.js', () => ({- readClaudeApiKey: () => 'REAL-GATEWAY-KEY',+ readClaudeApiKey: () => h.gatewayKey,desktopCodexAuthAdapter: { getState: async () => ({ authenticated: false }) },}));vi.mock('../custom-provider-header-secrets.js', () => ({@@ -44,13 +46,25 @@ const PI_API_KEY_ENV = 'CINDY_PI_API_KEY';const PLACEHOLDER = 'cindy-pi-provider-auth-placeholder';describe('DesktopPiAuthAdapter.getAuthEnv', () => {- it('writes placeholder only for OAuth subscription providers', async () => {- for (const providerId of ['anthropic', 'openai', 'xai']) {+ beforeEach(() => {+ h.gatewayKey = 'REAL-GATEWAY-KEY';+ });++ it('writes the gateway placeholder only for shared cindy OAuth routes', async () => {+ for (const providerId of ['anthropic', 'openai']) {const env = await desktopPiAuthAdapter.getAuthEnv({ providerId });expect(env[PI_API_KEY_ENV]).toBe(PLACEHOLDER);}});+ it('preserves the gateway key for xAI sessions and falls back when no gateway exists', async () => {+ expect((await desktopPiAuthAdapter.getAuthEnv({ providerId: 'xai' }))[PI_API_KEY_ENV])+ .toBe('REAL-GATEWAY-KEY');+ h.gatewayKey = null;+ expect((await desktopPiAuthAdapter.getAuthEnv({ providerId: 'xai' }))[PI_API_KEY_ENV])+ .toBe(PLACEHOLDER);+ });+it('gives BYOM / custom provider ids the real gateway key (no gateway-block poisoning)', async () => {for (const providerId of ['my-vllm', 'ollama-local', 'some_custom']) {const env = await desktopPiAuthAdapter.getAuthEnv({ providerId });diff --git a/apps/desktop/src/main/maker-host/__tests__/piByomNoCindyAuth.test.ts b/apps/desktop/src/main/maker-host/__tests__/piByomNoCindyAuth.test.tsindex 6a8b801cb3..4a66cac45b 100644--- a/apps/desktop/src/main/maker-host/__tests__/piByomNoCindyAuth.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/piByomNoCindyAuth.test.ts@@ -1,4 +1,6 @@-import { describe, expect, it, vi } from 'vitest';+import { beforeEach, describe, expect, it, vi } from 'vitest';++const grokOAuth = vi.hoisted(() => ({ loggedIn: false }));vi.mock('electron', () => ({app: {@@ -19,13 +21,32 @@ vi.mock('../custom-provider-header-secrets.js', () => ({auth: { method: 'none' },runtimes: { pi: { baseUrl: 'http://127.0.0.1:11434/v1', models: [{ id: 'local-model' }] } },},+ {+ id: 'xai',+ name: 'Legacy custom xAI',+ auth: { method: 'apiKey' },+ runtimes: {+ pi: {+ baseUrl: 'https://private-xai.example/v1',+ models: [{ id: 'private-grok' }, { id: 'grok-4.6' }],+ },+ },+ },],}));-vi.mock('../../secrets/providerSecretStore.js', () => ({ readCustomProviderKey: () => null }));+vi.mock('../../secrets/providerSecretStore.js', () => ({+ readCustomProviderKey: (providerId: string) =>+ providerId === 'xai' ? 'legacy-custom-key' : null,+}));+vi.mock('../grok-oauth-login.js', () => ({ hasGrokOAuthLogin: () => grokOAuth.loggedIn }));-import { desktopPiAuthAdapter } from '../pi-host.js';+import { desktopPiAuthAdapter, resolvePiNativeProviders } from '../pi-host.js';describe('Pi pure BYOM auth without a Cindy account', () => {+ beforeEach(() => {+ grokOAuth.loggedIn = false;+ });+it('authenticates the native provider and only uses an inert gateway placeholder', async () => {expect(await desktopPiAuthAdapter.getState({ providerId: 'local-keyless' })).toMatchObject({authenticated: true,@@ -39,4 +60,57 @@ describe('Pi pure BYOM auth without a Cindy account', () => {errorReason: 'cindy_gateway_key_unavailable',});});++ it('keeps a legacy custom xai credential usable without a SuperGrok login', async () => {+ expect(await desktopPiAuthAdapter.getState({ providerId: 'custom:xai' })).toMatchObject({+ authenticated: true,+ identity: 'Legacy custom xAI',+ });+ expect(await desktopPiAuthAdapter.getState({ providerId: 'xai' })).toEqual({+ authenticated: false,+ errorReason: 'xai_oauth_unavailable',+ });+ });++ it('keeps an official xai resume on SuperGrok when a custom provider has the same model', async () => {+ grokOAuth.loggedIn = true;+ const resolved = await resolvePiNativeProviders({+ workingDir: '/tmp/project',+ providerId: 'xai',+ model: 'grok-4.6',+ resumeSessionId: '/tmp/pi/official-session.jsonl',+ });++ expect(resolved.providers).toContainEqual(+ expect.objectContaining({+ id: 'xai',+ baseUrl: expect.not.stringContaining('private-xai.example'),+ }),+ );+ expect(resolved.providers).toContainEqual(+ expect.objectContaining({+ id: 'custom:xai',+ baseUrl: 'https://private-xai.example/v1',+ }),+ );+ });++ it('restores a migrated custom:xai session from its saved endpoint after SuperGrok is connected', async () => {+ grokOAuth.loggedIn = true;+ const resolved = await resolvePiNativeProviders({+ workingDir: '/tmp/project',+ providerId: 'custom:xai',+ model: 'private-grok',+ resumeSessionId: '/tmp/pi/legacy-custom-session.jsonl',+ });++ expect(resolved.providers).toContainEqual(+ expect.objectContaining({+ id: 'custom:xai',+ baseUrl: 'https://private-xai.example/v1',+ models: expect.arrayContaining([expect.objectContaining({ id: 'private-grok' })]),+ }),+ );+ expect(Object.values(resolved.env)).toContain('legacy-custom-key');+ });});diff --git a/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts b/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.tsindex 265fb0028c..9fb6e2344c 100644--- a/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts@@ -6,6 +6,14 @@ import { describe, expect, it, vi } from 'vitest';import { derivePiRuntimeFromClaudeRuntime } from '../../../shared/piRuntimeInitialization.js';+vi.mock('../grok-oauth-login.js', () => ({+ hasGrokOAuthLogin: () => true,+}));++vi.mock('../anthropic-compat-proxy-host.js', () => ({+ getClaudeEndpoint: () => 'http://127.0.0.1:18765',+}));+vi.mock('electron', () => ({app: {isPackaged: false,@@ -14,7 +22,13 @@ vi.mock('electron', () => ({},}));-import { buildPiNativeProvidersFromConfigs, piNativeKeyEnvVar } from '../pi-host.js';+import {+ buildXaiPiNativeProvider,+ buildPiNativeProvidersFromConfigs,+ PI_XAI_COMPAT_FORWARD_PORT,+ piNativeKeyEnvVar,+ piNativeModelId,+} from '../pi-host.js';type Cfg = Parameters<typeof buildPiNativeProvidersFromConfigs>[0][number];@@ -25,6 +39,214 @@ const piRuntime = (over: Partial<NonNullable<Cfg['runtimes']['pi']>> = {}) => ({});describe('buildPiNativeProvidersFromConfigs', () => {+ it('keeps a legacy custom xai endpoint separate from the official SuperGrok provider', () => {+ const { providers, env } = buildPiNativeProvidersFromConfigs(+ [{+ id: 'xai',+ name: 'Private xAI-compatible endpoint',+ auth: { method: 'apiKey' },+ runtimes: {+ pi: piRuntime({+ baseUrl: 'https://private-xai.example/v1',+ models: [{ id: 'private-grok', name: 'Private Grok' }],+ }),+ },+ }],+ (providerId) => (providerId === 'xai' ? 'legacy-custom-key' : null),+ );+ expect(providers).toEqual([+ expect.objectContaining({+ id: 'custom:xai',+ baseUrl: 'https://private-xai.example/v1',+ models: [expect.objectContaining({ id: 'private-grok' })],+ }),+ ]);+ expect(Object.values(env)).toContain('legacy-custom-key');+ });++ it('reuses exact Pi official metadata and preserves unmatched configured models', () => {+ const { providers } = buildPiNativeProvidersFromConfigs(+ [{+ id: 'deepseek-local',+ name: 'DeepSeek Local',+ auth: { method: 'apiKey' },+ runtimes: {+ pi: piRuntime({+ baseUrl: 'https://api.deepseek.com',+ piCatalogProviderId: 'deepseek',+ models: [+ { id: 'deepseek-v4-pro', name: 'DeepSeek V4 Pro' },+ { id: 'models-url-only', name: 'Models URL Only', contextWindow: 64_000 },+ ],+ }),+ },+ }],+ () => 'secret',+ );+ expect(providers[0]).toMatchObject({ id: 'deepseek-local', baseUrl: 'https://api.deepseek.com' });+ expect(providers[0]?.models[0]).toMatchObject({+ id: 'deepseek-v4-pro',+ api: 'openai-completions',+ contextWindow: 1_000_000,+ maxTokens: 384_000,+ reasoning: true,+ thinkingLevelMap: { low: null, high: 'high', max: 'max' },+ });+ expect(providers[0]?.models[1]).toEqual({+ id: 'models-url-only',+ name: 'Models URL Only',+ contextWindow: 64_000,+ });+ });++ it('does not apply official per-model routing after the user changes endpoint or protocol', () => {+ const { providers } = buildPiNativeProvidersFromConfigs(+ [{+ id: 'deepseek-proxy',+ name: 'DeepSeek Proxy',+ auth: { method: 'none' },+ runtimes: {+ pi: piRuntime({+ baseUrl: 'https://proxy.example/anthropic',+ wireProtocol: 'anthropic-messages',+ piCatalogProviderId: 'deepseek',+ models: [{ id: 'deepseek-v4-pro', name: 'Proxy DeepSeek', contextWindow: 64_000 }],+ }),+ },+ }],+ () => null,+ );+ expect(providers[0]).toMatchObject({+ baseUrl: 'https://proxy.example/anthropic',+ api: 'anthropic-messages',+ models: [{ id: 'deepseek-v4-pro', name: 'Proxy DeepSeek', contextWindow: 64_000 }],+ });+ expect(providers[0]?.models[0]).not.toHaveProperty('thinkingLevelMap');+ });++ it('preserves per-model headers from the official Pi catalog', () => {+ const { providers } = buildPiNativeProvidersFromConfigs(+ [{+ id: 'kimi-coding-local',+ name: 'Kimi Coding Local',+ auth: { method: 'apiKey' },+ runtimes: {+ pi: piRuntime({+ baseUrl: 'https://api.kimi.com/coding',+ wireProtocol: 'anthropic-messages',+ piCatalogProviderId: 'kimi-coding',+ models: [{ id: 'k3', name: 'Kimi K3' }],+ }),+ },+ }],+ () => 'secret',+ );+ expect(providers[0]?.models[0]).toMatchObject({+ id: 'k3',+ headers: { 'User-Agent': 'KimiCLI/1.5' },+ });+ });++ it('preserves explicit overrides for an exact official model after the catalog marker is cleared', () => {+ const { providers } = buildPiNativeProvidersFromConfigs(+ [{+ id: 'deepseek-customized',+ name: 'DeepSeek Customized',+ auth: { method: 'apiKey' },+ runtimes: {+ pi: piRuntime({+ baseUrl: 'https://api.deepseek.com',+ wireProtocol: 'openai-chat',+ models: [{+ id: 'deepseek-v4-flash',+ name: 'My DeepSeek Flash',+ contextWindow: 64_000,+ supportsImageInput: true,+ reasoning: true,+ reasoningEfforts: ['low'],+ }],+ }),+ },+ }],+ () => 'secret',+ );+ expect(providers[0]?.models[0]).toEqual({+ id: 'deepseek-v4-flash',+ name: 'My DeepSeek Flash',+ contextWindow: 64_000,+ input: ['text', 'image'],+ reasoning: true,+ thinkingLevelMap: {+ minimal: null,+ low: 'low',+ medium: null,+ high: null,+ xhigh: null,+ max: null,+ },+ });+ });++ it('maps historical xAI namespaced ids to Pi official bare ids', () => {+ expect(piNativeModelId('xai', 'xai/grok-4.6')).toBe('grok-4.6');+ expect(piNativeModelId('xai', 'grok-4.6')).toBe('grok-4.6');+ expect(piNativeModelId('deepseek', 'xai/grok-4.6')).toBe('xai/grok-4.6');+ });++ it('builds Grok 4.6 from the Pi official xAI catalog without losing protocol metadata', async () => {+ const { providers, env } = await buildXaiPiNativeProvider('xai/grok-4.6');+ expect(providers).toHaveLength(1);+ expect(providers[0]).toMatchObject({+ id: 'xai',+ baseUrl: 'http://127.0.0.1:18765',+ api: 'anthropic-messages',+ apiKeyEnvVar: 'CINDY_PI_XAI_PROXY_API_KEY',+ headers: {+ 'x-cindy-pi-session-id': '$CINDY_PI_SESSION_ID',+ 'x-cindy-pi-session-token': '$CINDY_PI_SESSION_TOKEN',+ },+ modelIdAliases: { 'grok-4.6': 'xai/grok-4.6' },+ });+ expect(providers[0]?.models.find((model) => model.id === 'xai/grok-4.6')).toMatchObject({+ api: 'anthropic-messages',+ contextWindow: 500_000,+ maxTokens: 500_000,+ input: ['text', 'image'],+ reasoning: true,+ compat: {+ supportsStore: false,+ supportsDeveloperRole: false,+ supportsReasoningEffort: false,+ },+ });+ expect(env).toEqual({+ CINDY_PI_XAI_PROXY_API_KEY: 'cindy-pi-provider-auth-placeholder',+ });+ });++ it('projects remote xAI through an exact SSH reverse-forward to the Desktop compat proxy', async () => {+ const { providers } = await buildXaiPiNativeProvider('grok-4.6', false, true);+ expect(providers[0]).toMatchObject({+ id: 'xai',+ baseUrl: `http://127.0.0.1:${PI_XAI_COMPAT_FORWARD_PORT}`,+ api: 'anthropic-messages',+ hostProxyForward: {+ localUrl: 'http://127.0.0.1:18765',+ remotePort: PI_XAI_COMPAT_FORWARD_PORT,+ },+ });+ });++ it('adds a private conservative xAI descriptor only when resuming a historical namespaced id', async () => {+ await expect(buildXaiPiNativeProvider('xai/grok-retired')).rejects.toThrow(/does not contain/);+ const { providers } = await buildXaiPiNativeProvider('xai/grok-retired', true);+ expect(providers[0]?.models.find((model) => model.id === 'xai/grok-retired')).toEqual({+ id: 'xai/grok-retired',+ name: 'xai/grok-retired',+ api: 'anthropic-messages',+ });+ expect(providers[0]?.modelIdAliases?.['grok-retired']).toBe('xai/grok-retired');+ });it('turns a Claude-derived wizard runtime and copied Pi key into a callable native provider', () => {const derived = derivePiRuntimeFromClaudeRuntime({baseUrl: 'https://api.example/anthropic',@@ -249,4 +471,28 @@ describe('buildPiNativeProvidersFromConfigs', () => {{ id: 'legacy', name: 'Legacy', contextWindow: undefined },]);});++ it.each([+ ['deepseek-v4-pro', 'DeepSeek V4 Pro', false],+ ['kimi-k3', 'Kimi K3', true],+ ] as const)('maps %s exact reasoning levels and image capability into Pi', (id, name, visual) => {+ const { providers } = buildPiNativeProvidersFromConfigs(+ [{+ id: 'cn-provider', name: 'CN Provider', auth: { method: 'none' },+ runtimes: { pi: piRuntime({ models: [{+ id, name, ...(visual ? { supportsImageInput: true } : {}),+ reasoning: true, reasoningEfforts: ['low', 'high', 'max'],+ }] }) },+ }],+ () => null,+ );+ expect(providers[0].models[0]).toEqual({+ id, name, contextWindow: undefined,+ ...(visual ? { input: ['text', 'image'] } : {}),+ reasoning: true,+ thinkingLevelMap: {+ minimal: null, low: 'low', medium: null, high: 'high', xhigh: null, max: 'max',+ },+ });+ });});diff --git a/apps/desktop/src/main/maker-host/__tests__/piProxySessionToken.test.ts b/apps/desktop/src/main/maker-host/__tests__/piProxySessionToken.test.tsnew file mode 100644index 0000000000..38d7539697--- /dev/null+++ b/apps/desktop/src/main/maker-host/__tests__/piProxySessionToken.test.ts@@ -0,0 +1,73 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const h = vi.hoisted(() => ({+ persistedKey: null as string | null,+ clearListeners: [] as Array<() => void>,+ failWrites: 0,+ writes: 0,+}));++vi.mock('../../secrets/providerSecretStore.js', () => ({+ readPiProxyDerivationKey: vi.fn(() => h.persistedKey),+ writePiProxyDerivationKey: vi.fn((value: string) => {+ if (h.failWrites > 0) {+ h.failWrites -= 1;+ return false;+ }+ h.persistedKey = value;+ h.writes += 1;+ return true;+ }),+ addProviderSecretsClearedListener: vi.fn((listener: () => void) => {+ h.clearListeners.push(listener);+ return () => undefined;+ }),+}));++import {+ derivePiProxySessionToken,+ resetPiProxyDerivationKeyCacheForTests,+} from '../pi-proxy-session-token.js';++describe('Pi remote proxy session token derivation', () => {+ beforeEach(() => {+ h.persistedKey = null;+ h.clearListeners.length = 0;+ h.failWrites = 0;+ h.writes = 0;+ resetPiProxyDerivationKeyCacheForTests();+ });++ it('keeps the same session token across a Desktop restart and isolates other sessions', () => {+ const first = derivePiProxySessionToken('session-a');+ expect(first).toMatch(/^[A-Za-z0-9_-]{40,}$/);+ expect(h.writes).toBe(1);++ resetPiProxyDerivationKeyCacheForTests();+ const afterRestart = derivePiProxySessionToken('session-a');+ const otherSession = derivePiProxySessionToken('session-b');++ expect(afterRestart).toBe(first);+ expect(otherSession).not.toBe(first);+ expect(h.writes).toBe(1);+ });++ it('rotates after the owner secret boundary is cleared', () => {+ const first = derivePiProxySessionToken('session-a');+ h.persistedKey = null;+ for (const listener of h.clearListeners) listener();++ expect(derivePiProxySessionToken('session-a')).not.toBe(first);+ expect(h.writes).toBe(2);+ });++ it('retries secure persistence after a transient write failure', () => {+ h.failWrites = 1;++ expect(() => derivePiProxySessionToken('session-a')).toThrow(+ 'PI_PROXY_DERIVATION_KEY_UNAVAILABLE',+ );+ expect(derivePiProxySessionToken('session-a')).toMatch(/^[A-Za-z0-9_-]{40,}$/);+ expect(h.writes).toBe(1);+ });+});diff --git a/apps/desktop/src/main/maker-host/__tests__/providerCatalogRealmReload.test.ts b/apps/desktop/src/main/maker-host/__tests__/providerCatalogRealmReload.test.tsindex ff9ac67b94..260af588ec 100644--- a/apps/desktop/src/main/maker-host/__tests__/providerCatalogRealmReload.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/providerCatalogRealmReload.test.ts@@ -18,6 +18,8 @@ const h = vi.hoisted(() => ({resolve: (result: unknown) => void;}>,customProviderRead: vi.fn(),+ getGrokAccessToken: vi.fn(),+ recoverGrokAuthAfterRejection: vi.fn(),warn: vi.fn(),}));@@ -66,6 +68,7 @@ vi.mock('../../authManager.js', () => ({}));vi.mock('../../appSessionState.js', () => ({getActiveAppSession: () => ({ mode: 'signed-out', dataOwnerId: h.owner }),+ activeOwnerScopeKey: () => `signed-out:${h.owner ?? 'none'}`,ownerScopedUserDataPath: (...segments: string[]) =>path.join(os.tmpdir(), 'provider-catalog-realm-reload', h.owner, ...segments),}));@@ -88,9 +91,11 @@ vi.mock('../claude-credentials-store.js', () => ({hasClaudeAiOAuthUnbound: () => false,}));vi.mock('../grok-oauth-login.js', () => ({- getGrokAccessToken: () => null,+ getGrokAccessToken: h.getGrokAccessToken,+ peekGrokAccessToken: () => null,hasGrokOAuthLogin: () => false,hasGrokOAuthLoginUnbound: () => false,+ recoverGrokAuthAfterRejection: h.recoverGrokAuthAfterRejection,resetGrokOAuthMemoryCache: () => undefined,}));vi.mock('../generic-oauth.js', () => ({@@ -136,8 +141,10 @@ import {} from '@cindy/model-providers';import {getActiveCatalog,+ commitModelPlaneFromCatalog,setActiveCatalog,setActiveCatalogChangedListener,+ setCustomProviderConfigs,setCustomProviders,} from '../active-catalog.js';import {@@ -166,6 +173,48 @@ function activeMarker(): string | undefined {}describe('provider catalog realm reload', () => {+ it('passes xAI rejection context into forced recovery and never replays the stale token', async () => {+ h.getGrokAccessToken.mockReset();+ h.recoverGrokAuthAfterRejection.mockReset();++ h.getGrokAccessToken.mockResolvedValueOnce('ordinary-token');+ await expect(__testing.readXaiProviderOAuthToken()).resolves.toBe('ordinary-token');+ expect(h.recoverGrokAuthAfterRejection).not.toHaveBeenCalled();++ h.recoverGrokAuthAfterRejection.mockResolvedValueOnce('refreshed');+ h.getGrokAccessToken.mockResolvedValueOnce('fresh-token');+ await expect(+ __testing.readXaiProviderOAuthToken({+ forceRefresh: true,+ staleToken: 'rejected-token',+ }),+ ).resolves.toBe('fresh-token');+ expect(h.recoverGrokAuthAfterRejection).toHaveBeenLastCalledWith('rejected-token');++ h.recoverGrokAuthAfterRejection.mockResolvedValueOnce('unchanged');+ await expect(+ __testing.readXaiProviderOAuthToken({+ forceRefresh: true,+ staleToken: 'rejected-token',+ }),+ ).resolves.toBeNull();+ expect(h.getGrokAccessToken).toHaveBeenCalledTimes(2);++ h.recoverGrokAuthAfterRejection.mockResolvedValueOnce('superseded');+ h.getGrokAccessToken.mockResolvedValueOnce('replacement-token');+ await expect(+ __testing.readXaiProviderOAuthToken({+ forceRefresh: true,+ staleToken: 'rejected-token',+ }),+ ).resolves.toBe('replacement-token');++ await expect(+ __testing.readXaiProviderOAuthToken({ forceRefresh: true }),+ ).resolves.toBeNull();+ expect(h.recoverGrokAuthAfterRejection).toHaveBeenCalledTimes(3);+ });+it('drops a stale owner custom-provider read and clears the current snapshot on failure', async () => {const provider: CustomProviderConfig = {id: 'owner-a-provider',@@ -202,6 +251,115 @@ describe('provider catalog realm reload', () => {h.customProviderRead.mockReset();});+ it('reprojects custom efforts once on Registry refresh and preserves the custom route', async () => {+ const current = structuredClone(catalogNamed('custom-before', '2026-08-12T10:00:00.000Z'));+ const currentEntry = current.modelRegistry?.models.find(+ (entry) => entry.id === 'openai/gpt-5.6-sol',+ );+ if (!currentEntry) throw new Error('expected gpt-5.6-sol Registry entry');+ currentEntry.perAgent = { ...currentEntry.perAgent, codex: { efforts: ['high'] } };+ setActiveCatalog(current);++ const config: CustomProviderConfig = {+ id: 'registry-relay',+ name: 'Registry Relay',+ runtimes: {+ codex: {+ baseUrl: 'https://relay.example/v1',+ models: [{ id: 'gpt-5.6-sol', name: 'GPT-5.6-Sol' }],+ },+ },+ };+ setCustomProviderConfigs([config]);++ const next = structuredClone(catalogNamed('custom-after', '2026-08-12T11:00:00.000Z'));+ const nextEntry = next.modelRegistry?.models.find(+ (entry) => entry.id === 'openai/gpt-5.6-sol',+ );+ if (!nextEntry) throw new Error('expected gpt-5.6-sol Registry entry');+ nextEntry.perAgent = {+ ...nextEntry.perAgent,+ codex: { efforts: ['high', 'max', 'ultra'], defaultEffort: 'ultra' },+ };++ const events: number[] = [];+ setActiveCatalogChangedListener((revision) => events.push(revision));+ try {+ setActiveCatalog(next);+ const provider = getActiveCatalog().providers.find((entry) => entry.id === config.id);+ expect(provider).toMatchObject({+ id: config.id,+ routing: { codex: { upstream: 'https://relay.example/v1' } },+ });+ expect(provider?.models.codex?.[0]).toMatchObject({+ id: 'gpt-5.6-sol',+ efforts: ['high', 'max', 'ultra'],+ defaultEffort: 'ultra',+ });+ expect(events).toHaveLength(1);+ } finally {+ setActiveCatalogChangedListener(null);+ setCustomProviders([]);+ }+ });++ it('keeps the current custom projection when full or model-plane catalogs omit Registry', () => {+ const current = structuredClone(catalogNamed('registry-bearing', '2026-08-12T12:00:00.000Z'));+ const entry = current.modelRegistry?.models.find(+ (candidate) => candidate.id === 'openai/gpt-5.6-sol',+ );+ if (!entry) throw new Error('expected gpt-5.6-sol Registry entry');+ entry.perAgent = {+ ...entry.perAgent,+ codex: { efforts: ['minimal', 'max'], defaultEffort: 'max' },+ };+ setActiveCatalog(current);+ const config: CustomProviderConfig = {+ id: 'registry-relay',+ name: 'Registry Relay',+ runtimes: {+ codex: {+ baseUrl: 'https://relay.example/v1',+ models: [{ id: 'gpt-5.6-sol', name: 'GPT-5.6-Sol' }],+ },+ },+ };+ setCustomProviderConfigs([config]);++ const withoutRegistry = structuredClone(current);+ delete withoutRegistry.modelRegistry;+ setActiveCatalog(withoutRegistry);+ expect(+ getActiveCatalog().providers.find((provider) => provider.id === config.id)?.models.codex?.[0],+ ).toMatchObject({ efforts: ['minimal', 'max'], defaultEffort: 'max' });+ expect(getActiveCatalog().modelRegistry).toBeUndefined();++ setActiveCatalog(current);+ commitModelPlaneFromCatalog(withoutRegistry);+ expect(+ getActiveCatalog().providers.find((provider) => provider.id === config.id)?.models.codex?.[0],+ ).toMatchObject({ efforts: ['minimal', 'max'], defaultEffort: 'max' });+ expect(getActiveCatalog().modelRegistry?.updatedAt).toBe('2026-08-12T12:00:00.000Z');+ setCustomProviders([]);+ });++ it('does not revive cleared owner configs on a later Registry refresh', () => {+ const config: CustomProviderConfig = {+ id: 'old-owner-relay',+ name: 'Old owner relay',+ runtimes: {+ codex: {+ baseUrl: 'https://old-owner.example/v1',+ models: [{ id: 'gpt-5.6-sol', name: 'GPT-5.6-Sol' }],+ },+ },+ };+ setCustomProviderConfigs([config]);+ setCustomProviders([]);+ setActiveCatalog(catalogNamed('next-owner-catalog', '2026-08-12T13:00:00.000Z'));+ expect(getActiveCatalog().providers.some((provider) => provider.id === config.id)).toBe(false);+ });+it('persists only a digest of a catalog scope that may contain URL credentials', () => {const scope = 'https://catalog.example/models?access_token=do-not-persist';const envelope = __testing.catalogLkgEnvelope(scope, '{"schemaVersion":1}');diff --git a/apps/desktop/src/main/maker-host/__tests__/providerModelAutoRefresh.test.ts b/apps/desktop/src/main/maker-host/__tests__/providerModelAutoRefresh.test.tsindex da06709cf1..181a3ed988 100644--- a/apps/desktop/src/main/maker-host/__tests__/providerModelAutoRefresh.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/providerModelAutoRefresh.test.ts@@ -61,7 +61,7 @@ describe('provider model auto-refresh coordinator', () => {expect(refreshCatalog).toHaveBeenCalledOnce();});- it('refreshes connected xAI media separately from the shared Catalog', async () => {+ it('refreshes xAI account membership and media independently after shared Catalog metadata', async () => {let now = 1_000;const refreshCatalog = vi.fn(async () => undefined);const refreshProvider = vi.fn(async () => undefined);@@ -73,7 +73,7 @@ describe('provider model auto-refresh coordinator', () => {log: { debug: vi.fn(), warn: vi.fn() },});- // Splash already loaded the public Catalog, but account-scoped media discovery still runs.+ // Splash already loaded the public Catalog; startup still reads the connected account list.await coordinator.requestAutoRefresh('startup');expect(refreshCatalog).not.toHaveBeenCalled();expect(refreshProvider).toHaveBeenCalledOnce();@@ -82,10 +82,9 @@ describe('provider model auto-refresh coordinator', () => {now += PROVIDER_MODEL_AUTO_REFRESH_FAILURE_COOLDOWN_MS;await coordinator.requestAutoRefresh('foreground');expect(refreshCatalog).toHaveBeenCalledOnce();- // provider 自己的上次成功快照仍在 30 分钟冷却内,不重复打 xAI 账号端点。expect(refreshProvider).toHaveBeenCalledOnce();- // Manual xAI refresh updates both the shared Catalog and account-scoped media snapshot.+ // Manual xAI refresh updates the public Catalog plus both account-scoped model sources.await coordinator.refreshManually('xai');expect(refreshCatalog).toHaveBeenCalledTimes(2);expect(refreshProvider).toHaveBeenCalledTimes(2);diff --git a/apps/desktop/src/main/maker-host/__tests__/providerModelRefresh.test.ts b/apps/desktop/src/main/maker-host/__tests__/providerModelRefresh.test.tsindex 9234abfe4a..c17b5499cf 100644--- a/apps/desktop/src/main/maker-host/__tests__/providerModelRefresh.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/providerModelRefresh.test.ts@@ -12,6 +12,7 @@ function deps(refreshXd: vi.fn(async () => {}),refreshAnthropic: vi.fn(async () => true),refreshOpenAi: vi.fn(async () => true),+ refreshXai: vi.fn(async () => true),refreshXaiMedia: vi.fn(async () => true),...overrides,};@@ -22,11 +23,12 @@ describe('refreshBuiltinProviderModels', () => {['xd', 'refreshXd'],['anthropic', 'refreshAnthropic'],['openai', 'refreshOpenAi'],- ['xai', 'refreshXaiMedia'],+ ['xai', 'refreshXai'],] as const)('dispatches %s to its existing refresh source', async (providerId, method) => {const d = deps();await refreshBuiltinProviderModels(providerId, d);expect(d[method]).toHaveBeenCalledOnce();+ if (providerId === 'xai') expect(d.refreshXaiMedia).toHaveBeenCalledOnce();});it('rejects stale or unapplied dynamic snapshots', async () => {@@ -36,6 +38,9 @@ describe('refreshBuiltinProviderModels', () => {await expect(refreshBuiltinProviderModels('openai', deps({ refreshOpenAi: async () => false })),).rejects.toThrow(/OpenAI model discovery/);+ await expect(+ refreshBuiltinProviderModels('xai', deps({ refreshXai: async () => false })),+ ).rejects.toThrow(/xAI account model discovery/);await expect(refreshBuiltinProviderModels('xai', deps({ refreshXaiMedia: async () => false })),).rejects.toThrow(/xAI media model discovery/);diff --git a/apps/desktop/src/main/maker-host/__tests__/providerRoute.test.ts b/apps/desktop/src/main/maker-host/__tests__/providerRoute.test.tsindex fbe68a15f6..a44bbe2a76 100644--- a/apps/desktop/src/main/maker-host/__tests__/providerRoute.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/providerRoute.test.ts@@ -761,6 +761,35 @@ describe('resolveSessionRouteDecision — 自定义供应商(resolve 时注入 k});});+ it('routes a legacy custom xai row independently from the built-in SuperGrok source', () => {+ setCustomProviders([+ buildUserProvider({+ id: 'xai',+ name: 'Private xAI-compatible endpoint',+ runtimes: {+ codex: {+ baseUrl: 'https://private-xai.example/v1',+ models: [{ id: 'private-grok', name: 'Private Grok' }],+ },+ },+ }),+ ]);+ setCustomProviderKeyReader((id, agent) =>+ id === 'xai' && agent === 'codex' ? 'legacy-custom-key' : null,+ );+ setSessionProvider('s-user', 'custom:xai');++ expect(getActiveCatalog().providers.some((provider) => provider.id === 'xai')).toBe(true);+ expect(getActiveCatalog().providers.some((provider) => provider.id === 'custom:xai')).toBe(+ true,+ );+ expect(resolveSessionRouteDecision('s-user', 'codex', KEY)).toEqual({+ headerOverride: { authorization: 'Bearer legacy-custom-key' },+ upstreamOverride: 'https://private-xai.example/v1',+ headerDelete: CODEX_ACCOUNT_HEADER_DELETE,+ });+ });+it('跨供应商切换 pending 时不把目标模型发给旧供应商', async () => {setCustomProviders([buildUserProvider({@@ -921,7 +950,6 @@ describe('resolveSessionRouteDecision — 自定义供应商(resolve 时注入 k});expect(resolveSessionRouteDecision('s-user', 'codex', KEY, 'gpt-5.5')).toBeNull();});-it('blocks new routes while endpoint and key switch as one logical mutation', async () => {setCustomProviders([buildUserProvider({diff --git a/apps/desktop/src/main/maker-host/__tests__/xaiModelDiscovery.test.ts b/apps/desktop/src/main/maker-host/__tests__/xaiModelDiscovery.test.tsnew file mode 100644index 0000000000..d996a84ddf--- /dev/null+++ b/apps/desktop/src/main/maker-host/__tests__/xaiModelDiscovery.test.ts@@ -0,0 +1,350 @@+import fsp from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';++import { afterEach, describe, expect, it, vi } from 'vitest';++import {+ discardXaiModelsDiskCache,+ loadXaiModelsFromDiskCache,+ parseXaiAccountModels,+ refreshXaiModelsFromHttp,+ resetXaiDiscoveryForTest,+ waitForXaiDiscoveryIdleForTest,+ XAI_ACCOUNT_MODELS_URL,+ XAI_ACCOUNT_USER_URL,+ XAI_GROK_CLIENT_VERSION,+} from '../model-discovery/xai.js';++function jsonResponse(body: unknown, status = 200): Response {+ return new Response(JSON.stringify(body), {+ status,+ headers: { 'content-type': 'application/json' },+ });+}++const tempDirs: string[] = [];++afterEach(async () => {+ resetXaiDiscoveryForTest();+ await waitForXaiDiscoveryIdleForTest();+ await Promise.all(tempDirs.splice(0).map((dir) => fsp.rm(dir, { recursive: true, force: true })));+});++describe('xAI account model discovery', () => {+ it('normalizes membership without inventing missing capabilities', () => {+ expect(+ parseXaiAccountModels({+ data: [+ {+ model: 'grok-4.5',+ name: 'Grok 4.5',+ contextWindow: 500_000,+ maxCompletionTokens: 64_000,+ reasoningEfforts: ['low', { value: 'high', default: true }],+ },+ { modelId: 'grok-4.6', supportedInApi: false },+ { model: 'hidden-model', hidden: true },+ { model: 'grok-4.5' },+ ],+ }),+ ).toEqual([+ {+ id: 'xai/grok-4.5',+ name: 'Grok 4.5',+ contextWindow: 500_000,+ contextWindowVerified: true,+ maxOutput: 64_000,+ efforts: ['low', 'high'],+ defaultEffort: 'high',+ },+ { id: 'xai/grok-4.6' },+ ]);+ });++ it('persists a successful empty table and reloads it as an authoritative LKG', async () => {+ const dir = await fsp.mkdtemp(path.join(os.tmpdir(), 'cindy-xai-models-'));+ tempDirs.push(dir);+ const cacheFile = path.join(dir, 'xai-models.json');+ const applySnapshot = vi.fn();+ const fetchImpl = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {+ const headers = new Headers(init?.headers);+ expect(headers.get('authorization')).toBe('Bearer token-a');+ expect(headers.get('x-xai-token-auth')).toBe('xai-grok-cli');+ expect(headers.get('x-grok-client-version')).toBe(XAI_GROK_CLIENT_VERSION);+ if (String(input) === XAI_ACCOUNT_USER_URL) return jsonResponse({ userId: 'user-a' });+ expect(String(input)).toBe(XAI_ACCOUNT_MODELS_URL);+ expect(headers.get('x-userid')).toBe('user-a');+ return jsonResponse({ data: [] });+ });+ const deps = {+ fetchImpl: fetchImpl as typeof fetch,+ getAccessToken: async () => 'token-a',+ peekAccessToken: () => 'token-a',+ hasLogin: () => true,+ getConnectionSource: () => 'explicit-provider-oauth' as const,+ getScopeKey: () => 'owner-a:1',+ cacheFilePath: () => cacheFile,+ applySnapshot,+ invalidateAuth: vi.fn(),+ log: { info: vi.fn(), warn: vi.fn() },+ };++ await expect(refreshXaiModelsFromHttp(deps)).resolves.toBe(true);+ expect(applySnapshot).toHaveBeenLastCalledWith([]);+ applySnapshot.mockClear();+ await expect(loadXaiModelsFromDiskCache(deps)).resolves.toBe(true);+ expect(applySnapshot).toHaveBeenCalledWith([]);+ });++ it('keeps the current snapshot on temporary failure and never applies late account results', async () => {+ const applySnapshot = vi.fn();+ await expect(+ refreshXaiModelsFromHttp({+ fetchImpl: (async () => {+ throw new Error('offline');+ }) as typeof fetch,+ getAccessToken: async () => 'token-a',+ peekAccessToken: () => 'token-a',+ hasLogin: () => true,+ getConnectionSource: () => 'explicit-provider-oauth' as const,+ getScopeKey: () => 'owner-a:1',+ cacheFilePath: () => '/unused',+ applySnapshot,+ invalidateAuth: vi.fn(),+ log: { info: vi.fn(), warn: vi.fn() },+ }),+ ).resolves.toBe(false);+ expect(applySnapshot).not.toHaveBeenCalled();++ let scope = 'owner-a:1';+ await expect(+ refreshXaiModelsFromHttp({+ fetchImpl: (async (input: RequestInfo | URL) => {+ if (String(input) === XAI_ACCOUNT_USER_URL) return jsonResponse({ userId: 'user-a' });+ scope = 'owner-b:2';+ return jsonResponse({ data: [{ model: 'grok-4.6' }] });+ }) as typeof fetch,+ getAccessToken: async () => 'token-a',+ peekAccessToken: () => 'token-a',+ hasLogin: () => true,+ getConnectionSource: () => 'explicit-provider-oauth' as const,+ getScopeKey: () => scope,+ cacheFilePath: () => '/unused',+ applySnapshot,+ invalidateAuth: vi.fn(),+ log: { info: vi.fn(), warn: vi.fn() },+ }),+ ).resolves.toBe(false);+ expect(applySnapshot).not.toHaveBeenCalled();+ });++ it('drops a queued disk-cache deletion after the active owner scope changes', async () => {+ let scope = 'owner-a:1';+ const ownerACache = '/owner-a/xai-models.json';+ const ownerBCache = '/owner-b/xai-models.json';+ const cacheFilePath = vi.fn(() => (scope === 'owner-a:1' ? ownerACache : ownerBCache));+ let releaseFirstRemoval!: () => void;+ const firstRemovalReleased = new Promise<void>((resolve) => {+ releaseFirstRemoval = resolve;+ });+ let firstRemovalStarted!: () => void;+ const firstRemovalStartedPromise = new Promise<void>((resolve) => {+ firstRemovalStarted = resolve;+ });+ const rmSpy = vi.spyOn(fsp, 'rm').mockImplementation(async () => {+ firstRemovalStarted();+ await firstRemovalReleased;+ });+ const deps = {+ getScopeKey: () => scope,+ cacheFilePath,+ log: { info: vi.fn(), warn: vi.fn() },+ };++ try {+ const firstRemoval = discardXaiModelsDiskCache(deps);+ await firstRemovalStartedPromise;+ const queuedRemoval = discardXaiModelsDiskCache(deps);+ expect(cacheFilePath).toHaveBeenCalledTimes(2);++ scope = 'owner-b:2';+ releaseFirstRemoval();+ await Promise.all([firstRemoval, queuedRemoval]);++ expect(rmSpy).toHaveBeenCalledTimes(1);+ expect(rmSpy).toHaveBeenCalledWith(ownerACache, { force: true });+ expect(rmSpy).not.toHaveBeenCalledWith(ownerBCache, expect.anything());+ } finally {+ releaseFirstRemoval();+ rmSpy.mockRestore();+ }+ });++ it('does not reuse an older account flight when the token changes under the same owner scope', async () => {+ let token = 'token-a';+ let releaseAUser!: () => void;+ const aUserReleased = new Promise<void>((resolve) => {+ releaseAUser = resolve;+ });+ let aUserStarted!: () => void;+ const aUserStartedPromise = new Promise<void>((resolve) => {+ aUserStarted = resolve;+ });+ const applySnapshot = vi.fn();+ const fetchImpl = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {+ const auth = new Headers(init?.headers).get('authorization');+ if (String(input) === XAI_ACCOUNT_USER_URL && auth === 'Bearer token-a') {+ aUserStarted();+ await aUserReleased;+ return jsonResponse({ userId: 'user-a' });+ }+ if (String(input) === XAI_ACCOUNT_USER_URL && auth === 'Bearer token-b') {+ return jsonResponse({ userId: 'user-b' });+ }+ if (String(input) === XAI_ACCOUNT_MODELS_URL && auth === 'Bearer token-b') {+ return jsonResponse({ data: [{ model: 'grok-4.6' }] });+ }+ throw new Error(`unexpected request ${String(input)} ${auth}`);+ });+ const deps = {+ fetchImpl: fetchImpl as typeof fetch,+ getAccessToken: async () => token,+ peekAccessToken: () => token,+ hasLogin: () => true,+ getConnectionSource: () => 'explicit-provider-oauth' as const,+ getScopeKey: () => 'owner-a:1',+ cacheFilePath: () => '/unused',+ applySnapshot,+ invalidateAuth: vi.fn(),+ log: { info: vi.fn(), warn: vi.fn() },+ };++ const accountA = refreshXaiModelsFromHttp(deps);+ await aUserStartedPromise;+ token = 'token-b';+ const accountB = refreshXaiModelsFromHttp({+ ...deps,+ getAccessToken: async () => token,+ peekAccessToken: () => token,+ });+ await expect(accountB).resolves.toBe(true);+ expect(applySnapshot).toHaveBeenCalledWith([{ id: 'xai/grok-4.6' }]);++ releaseAUser();+ await expect(accountA).resolves.toBe(false);+ expect(applySnapshot).toHaveBeenCalledTimes(1);+ });++ it('joins startup refresh after getAccessToken rotates the same account token', async () => {+ let token = 'token-old';+ let releaseUser!: () => void;+ const userReleased = new Promise<void>((resolve) => {+ releaseUser = resolve;+ });+ let userStarted!: () => void;+ const userStartedPromise = new Promise<void>((resolve) => {+ userStarted = resolve;+ });+ const applySnapshot = vi.fn();+ const fetchImpl = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {+ const auth = new Headers(init?.headers).get('authorization');+ expect(auth).toBe('Bearer token-new');+ if (String(input) === XAI_ACCOUNT_USER_URL) {+ userStarted();+ await userReleased;+ return jsonResponse({ userId: 'user-a' });+ }+ return jsonResponse({ data: [{ model: 'grok-4.6' }] });+ });+ const deps = {+ fetchImpl: fetchImpl as typeof fetch,+ getAccessToken: async () => {+ token = 'token-new';+ return token;+ },+ peekAccessToken: () => token,+ hasLogin: () => true,+ getConnectionSource: () => 'explicit-provider-oauth' as const,+ getScopeKey: () => 'owner-a:1',+ cacheFilePath: () => '/unused',+ applySnapshot,+ invalidateAuth: vi.fn(),+ log: { info: vi.fn(), warn: vi.fn() },+ };++ const splashRefresh = refreshXaiModelsFromHttp(deps);+ await userStartedPromise;+ const readinessRefresh = refreshXaiModelsFromHttp(deps);+ releaseUser();++ await expect(Promise.all([splashRefresh, readinessRefresh])).resolves.toEqual([true, true]);+ expect(fetchImpl).toHaveBeenCalledTimes(2);+ expect(applySnapshot).toHaveBeenCalledTimes(1);+ });++ it('refreshes a rejected token once and restarts the user-model chain', async () => {+ let token = 'token-old';+ const applySnapshot = vi.fn();+ const invalidateAuth = vi.fn(async () => {+ token = 'token-new';+ return 'refreshed' as const;+ });+ const fetchImpl = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {+ const auth = new Headers(init?.headers).get('authorization');+ if (auth === 'Bearer token-old') {+ return jsonResponse(+ {+ code: 'unauthenticated:bad-credentials',+ error: 'The OAuth2 access token could not be validated.',+ },+ 403,+ );+ }+ if (String(input) === XAI_ACCOUNT_USER_URL) return jsonResponse({ userId: 'user-new' });+ return jsonResponse({ data: [{ model: 'grok-4.6' }] });+ });+ await expect(+ refreshXaiModelsFromHttp({+ fetchImpl: fetchImpl as typeof fetch,+ getAccessToken: async () => token,+ peekAccessToken: () => token,+ hasLogin: () => true,+ getConnectionSource: () => 'explicit-provider-oauth' as const,+ getScopeKey: () => 'owner-a:1',+ cacheFilePath: () => path.join(os.tmpdir(), 'unused-xai-models.json'),+ applySnapshot,+ invalidateAuth,+ log: { info: vi.fn(), warn: vi.fn() },+ }),+ ).resolves.toBe(true);+ expect(invalidateAuth).toHaveBeenCalledWith(+ expect.objectContaining({ status: 403, failedAccessToken: 'token-old' }),+ );+ expect(applySnapshot).toHaveBeenCalledWith([{ id: 'xai/grok-4.6' }]);+ });++ it('拒绝任何 inherited-local-cli 来源,不读取 token 也不发账号请求', async () => {+ const getAccessToken = vi.fn(async () => 'must-not-read');+ const fetchImpl = vi.fn();+ const applySnapshot = vi.fn();++ await expect(+ refreshXaiModelsFromHttp({+ fetchImpl: fetchImpl as typeof fetch,+ getAccessToken,+ peekAccessToken: () => 'must-not-read',+ hasLogin: () => true,+ getConnectionSource: () => null,+ getScopeKey: () => 'owner-a:1',+ cacheFilePath: () => '/unused',+ applySnapshot,+ invalidateAuth: vi.fn(),+ log: { info: vi.fn(), warn: vi.fn() },+ }),+ ).resolves.toBe(false);+ expect(getAccessToken).not.toHaveBeenCalled();+ expect(fetchImpl).not.toHaveBeenCalled();+ expect(applySnapshot).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/main/maker-host/account-provider-model-refresh.ts b/apps/desktop/src/main/maker-host/account-provider-model-refresh.tsindex ab5aa0f60d..f1230f81b0 100644--- a/apps/desktop/src/main/maker-host/account-provider-model-refresh.ts+++ b/apps/desktop/src/main/maker-host/account-provider-model-refresh.ts@@ -10,6 +10,7 @@ interface AccountProviderModelRefreshLogger {export interface AccountProviderModelRefreshDeps {restartCodex(): Promise<void>;shutdownCodexEnvironment(): Promise<void>;+ loadXaiLkg(): Promise<boolean>;refreshProviderModels(trigger: ProviderModelAutoRefreshTrigger,providerIds?: readonly BuiltinRefreshableProviderId[],@@ -49,6 +50,17 @@ export async function refreshProviderModelsAfterAccountReady(}}+ try {+ // Account readiness is also the owner boundary. Restore this owner's authoritative xAI LKG+ // before the HTTP refresh so an offline/timeout result never exposes the generic fallback in+ // place of a previously verified account snapshot.+ await deps.loadXaiLkg();+ } catch (error) {+ deps.log.warn('xAI owner LKG load failed; continuing with network discovery', {+ error: error instanceof Error ? error.message : String(error),+ });+ }+const backgroundRefresh = deps.refreshProviderModels('startup', ['xd', 'openai', 'xai']).catch((error) => {diff --git a/apps/desktop/src/main/maker-host/active-catalog.ts b/apps/desktop/src/main/maker-host/active-catalog.tsindex 71e12d1784..b8952b834c 100644--- a/apps/desktop/src/main/maker-host/active-catalog.ts+++ b/apps/desktop/src/main/maker-host/active-catalog.ts@@ -26,10 +26,12 @@import {BUNDLED_CATALOG,+ buildUserProvider,findModelRegistryRoute,type AgentKind,type Catalog,type CatalogModel,+ type CustomProviderConfig,type Provider,type ProviderWireProtocol,} from '@cindy/model-providers';@@ -56,8 +58,12 @@ import {/** OSS / bundled 加载来的基础目录;null = 尚未加载(回落 BUNDLED_CATALOG)。 */let base: Catalog | null = null;+/** Last trusted Registry used only to re-project user configs; it never changes catalog membership. */+let trustedCustomProviderRegistry: Catalog['modelRegistry'] = BUNDLED_CATALOG.modelRegistry;/** 用户自定义供应商(已 buildUserProvider 展开的标准 Provider),追加在 base 之后。 */let custom: Provider[] = [];+/** 当前 owner 的原始配置;仅用于 Registry 热更新后的运行时重投影。 */+let customConfigs: CustomProviderConfig[] | null = null;/*** codex cache 派生的规范化模型快照(原始 slug,不带 chatgpt/ 前缀)。先 augment 到* openai.codex,再从生效后的 codex 列表投影 openai.claude-code bridge,确保两边名称和排序同源。@@ -70,6 +76,26 @@ let discoveredCodex: CatalogModel[] = [];* 空/坏数据绝不抹掉静态兜底。由 generic-oauth 的 models 发现流程写入。*/const discoveredByProvider = new Map<string, Partial<Record<AgentKind, CatalogModel[]>>>();++/**+ * xAI 订阅账号从官方 `/v1/user` → `/v1/models` 读到的权威成员清单。+ *+ * `null` = 当前 owner 尚无成功账号快照,允许公共 Catalog / bundled 只作为启动救急;+ * `[]` = 上游明确返回空清单,仍是权威结果。成员保存为 canonical `xai/grok-*`,+ * Claude/Codex 原样消费,Pi 在投影时去掉 `xai/`。+ */+export interface XaiDiscoveredModel {+ id: string;+ name?: string;+ description?: string;+ contextWindow?: number;+ contextWindowVerified?: boolean;+ maxOutput?: number;+ efforts?: CatalogModel['efforts'];+ defaultEffort?: CatalogModel['defaultEffort'];+}++let xaiDiscoveredModels: XaiDiscoveredModel[] | null = null;/*** 供应商媒体模型动态发现快照。成功快照决定当前账号的型号存在性,静态/远端* 同 id 条目只提供 first-wins 展示元数据;发现失败不写本 Map,完整回落静态目录。@@ -364,7 +390,11 @@ function projectCodexModelsToBridges(}/** 静态段被淘汰的供应商:先清空 providers.models,再由 discovery + Registry/local root 装配。 */-const DYNAMIC_LIST_PROVIDER_IDS: ReadonlySet<string> = new Set(['anthropic', 'openai', 'xd']);+const DYNAMIC_LIST_PROVIDER_IDS: ReadonlySet<string> = new Set([+ 'anthropic',+ 'openai',+ 'xd',+]);/*** Anthropic discovery 映射阶段读取的 Registry 字段子集:上游缺字段时先用它补齐,@@ -390,10 +420,10 @@ function modelRegistryMetaFields(agent: AgentKind,modelId: string,): RegistryMetaFields | undefined {- const catalog = base ?? BUNDLED_CATALOG;// 模型 registry 的路由与 perAgent 覆盖只按 claude-code / codex 建键;Pi 是动态 BYOM,// 无 registry per-agent 覆盖,按 agent 无关处理(取条目基线元数据)。const registryAgent = agent === 'pi' ? undefined : agent;+ const catalog = base ?? BUNDLED_CATALOG;const matched = findModelRegistryRoute(catalog.modelRegistry, providerId, modelId, registryAgent);if (!matched) return undefined;const { entry } = matched;@@ -520,6 +550,130 @@ function assembleRoot(return preserveDeclarationOrder ? out : sortModelsByOrder(out);}+/** Registry / local override 只能补账号已返回的条目,不能重新实体化账号没有的成员。 */+function assembleAuthoritativeRoot(+ providerId: string,+ agent: RootAgentKind,+ models: readonly CatalogModel[],+ plan: ModelPlaneRegistryPlan,+): CatalogModel[] {+ const memberIds = new Set(models.map((model) => model.id));+ return assembleRoot(providerId, agent, models, plan, true).filter((model) =>+ memberIds.has(model.id),+ );+}++function xaiCatalogModelById(+ provider: Provider,+ id: string,+ agent: AgentKind,+): CatalogModel | undefined {+ const bundled = BUNDLED_CATALOG.providers.find((entry) => entry.id === 'xai');+ if (agent === 'pi') {+ const bare = id.startsWith('xai/') ? id.slice('xai/'.length) : id;+ return (+ provider.models.pi?.find((model) => model.id === bare)+ ?? bundled?.models.pi?.find((model) => model.id === bare)+ );+ }+ return (+ provider.models[agent]?.find((model) => model.id === id)+ ?? bundled?.models[agent]?.find((model) => model.id === id)+ );+}++function materializeXaiAccountModels(+ provider: Provider,+ agent: RootAgentKind,+ discovered: readonly XaiDiscoveredModel[],+): CatalogModel[] {+ return discovered.map((entry, index) => {+ const catalogModel =+ xaiCatalogModelById(provider, entry.id, agent)+ ?? xaiCatalogModelById(provider, entry.id, 'pi');+ const registry = modelRegistryMetaFields('xai', agent, entry.id);+ const efforts = entry.efforts+ ? [...entry.efforts]+ : [...(registry?.efforts ?? catalogModel?.efforts ?? [])];+ const requestedDefault =+ entry.defaultEffort !== undefined+ ? entry.defaultEffort+ : (registry?.defaultEffort ?? catalogModel?.defaultEffort ?? null);+ const defaultEffort =+ requestedDefault !== null && efforts.includes(requestedDefault)+ ? requestedDefault+ : efforts.includes('high')+ ? 'high'+ : (efforts[efforts.length - 1] ?? null);+ const contextWindow =+ entry.contextWindow ?? registry?.contextWindow ?? catalogModel?.contextWindow ?? 200_000;+ const contextWindowVerified =+ entry.contextWindow !== undefined+ ? (entry.contextWindowVerified ?? true)+ : registry?.contextWindow !== undefined || catalogModel?.contextWindowVerified === true;+ return {+ ...catalogModel,+ id: entry.id,+ name: entry.name ?? registry?.name ?? catalogModel?.name ?? entry.id.slice('xai/'.length),+ ...(entry.description !== undefined+ ? { description: entry.description }+ : registry?.description !== undefined+ ? { description: registry.description }+ : {}),+ group: registry?.group ?? catalogModel?.group ?? 'grok',+ sortOrder: registry?.sortOrder ?? catalogModel?.sortOrder ?? 1_000 + index,+ contextWindow,+ ...(contextWindowVerified ? { contextWindowVerified: true } : {}),+ ...(entry.maxOutput !== undefined+ ? { maxOutput: entry.maxOutput }+ : registry?.maxOutput !== undefined+ ? { maxOutput: registry.maxOutput }+ : catalogModel?.maxOutput !== undefined+ ? { maxOutput: catalogModel.maxOutput }+ : {}),+ efforts,+ defaultEffort,+ ...(registry?.supportsFastMode !== undefined+ ? { supportsFastMode: registry.supportsFastMode }+ : {}),+ status: registry?.status ?? catalogModel?.status ?? 'active',+ defaultEnabled: registry?.defaultEnabled ?? catalogModel?.defaultEnabled ?? true,+ };+ });+}++function bundledXaiFallbackMembers(provider: Provider): XaiDiscoveredModel[] {+ return (provider.models.pi ?? []).map((model) => ({+ id: model.id.startsWith('xai/') ? model.id : `xai/${model.id}`,+ }));+}++function projectXaiPiModel(+ provider: Provider,+ model: CatalogModel,+): CatalogModel {+ const bareId = model.id.startsWith('xai/') ? model.id.slice('xai/'.length) : model.id;+ const piMetadata = xaiCatalogModelById(provider, model.id, 'pi');+ return {+ ...model,+ ...piMetadata,+ id: bareId,+ name: model.name,+ description: model.description,+ group: model.group,+ sortOrder: model.sortOrder,+ contextWindow: model.contextWindow,+ ...(model.contextWindowVerified !== undefined+ ? { contextWindowVerified: model.contextWindowVerified }+ : {}),+ ...(model.maxOutput !== undefined ? { maxOutput: model.maxOutput } : {}),+ efforts: model.efforts,+ defaultEffort: model.defaultEffort,+ status: model.status,+ defaultEnabled: model.defaultEnabled,+ };+}+/** 把 provider 的全部 per-agent 模型清单清零(保留身份卡);已为空则原样返回。 */function withEmptyModels(p: Provider): Provider {const entries = Object.entries(p.models) as [AgentKind, CatalogModel[]][];@@ -538,23 +692,11 @@ function computeMerged(): Catalog {// XD Provider 使用随客户端发布的固定壳,远端 Catalog 只能管理非 XD Provider。// `/models` 会在下方重建固定壳的全部模型,Catalog 缺失、刷新或异常都不能改变 XD。const builtinXd = BUNDLED_CATALOG.providers.find((provider) => provider.id === 'xd');+ const bundledXai = BUNDLED_CATALOG.providers.find((provider) => provider.id === 'xai');const remoteXdIndex = b.providers.findIndex((provider) => provider.id === 'xd');const providerSources = b.providers.filter((provider) => provider.id !== 'xd');if (builtinXd) providerSources.splice(Math.max(0, remoteXdIndex), 0, builtinXd);- let providers: Provider[] = providerSources.map((provider): Provider => {- if (provider.id !== 'xai') return provider;- const claudeRoute = provider.routing['claude-code'];- const claudeModels = provider.models['claude-code'] ?? [];- if (!claudeRoute) return provider;- return {- ...provider,- agents: provider.agents.includes('pi')- ? provider.agents- : [...provider.agents, 'pi' as AgentKind],- routing: { ...provider.routing, pi: provider.routing.pi ?? claudeRoute },- models: { ...provider.models, pi: provider.models.pi ?? claudeModels },- };- });+ let providers: Provider[] = providerSources;// 先清零已退役的静态 providers.models 段:无论目录来自 bundled 还是远端,// OpenAI/Anthropic 的 root 都只由 discovery 证据 + Registry presence + local@@ -661,22 +803,48 @@ function computeMerged(): Catalog {return { ...p, models: { ...p.models, 'claude-code': root, codex: codexBridge, pi: root } };}if (p.id === 'xai') {- const claudeRoot = assembleRoot(- 'xai',- 'claude-code',- p.models['claude-code'] ?? [],- plan,- true,- );- const codexRoot = assembleRoot('xai', 'codex', p.models.codex ?? [], plan, true);+ const useAccountMembership = xaiDiscoveredModels !== null;+ const accountModels = xaiDiscoveredModels ?? [];+ // The bundled-only fallback uses Pi's official list as its membership seed because it is+ // the freshest packaged xAI list (and currently carries Grok 4.6). A loaded server Catalog+ // remains the preceding fallback and keeps its own legacy static membership for old server+ // compatibility. Any successful account snapshot, including [], overrides both.+ const authoritativeMembers = useAccountMembership+ ? accountModels+ : b === BUNDLED_CATALOG || p === bundledXai+ ? bundledXaiFallbackMembers(p)+ : null;+ const claudeSeed = authoritativeMembers+ ? materializeXaiAccountModels(p, 'claude-code', authoritativeMembers)+ : (p.models['claude-code'] ?? []);+ const codexSeed = authoritativeMembers+ ? materializeXaiAccountModels(p, 'codex', authoritativeMembers)+ : (p.models.codex ?? []);+ const claudeRoot = authoritativeMembers+ ? assembleAuthoritativeRoot('xai', 'claude-code', claudeSeed, plan)+ : assembleRoot('xai', 'claude-code', claudeSeed, plan, true);+ const codexRoot = authoritativeMembers+ ? assembleAuthoritativeRoot('xai', 'codex', codexSeed, plan)+ : assembleRoot('xai', 'codex', codexSeed, plan, true);+ const piModels = claudeRoot.map((model) => projectXaiPiModel(p, model));return {...p,+ agents: p.agents.includes('pi') ? p.agents : [...p.agents, 'pi' as AgentKind],+ routing: {+ ...p.routing,+ ...(p.routing.pi+ ? {}+ : bundledXai?.routing.pi+ ? {+ pi: bundledXai.routing.pi,+ }+ : {}),+ },models: {...p.models,'claude-code': claudeRoot,codex: codexRoot,- // Pi 恒定镜像 claude-code root(拿满 root 能力,如 grok-4.20 的 xhigh 档)。- ...(p.agents.includes('pi') ? { pi: claudeRoot } : {}),+ pi: piModels,},};}@@ -792,7 +960,16 @@ export function getCatalogModelContextWindow(/** 由 host 的目录加载器(ensureActiveCatalogLoaded)在拉取成功后写入基础目录。 */export function setActiveCatalog(catalog: Catalog): void {+ const previous = base ?? BUNDLED_CATALOG;+ const projectionRegistry =+ catalog.modelRegistry ?? previous.modelRegistry ?? trustedCustomProviderRegistry;+ trustedCustomProviderRegistry = projectionRegistry;base = catalog;+ if (customConfigs) {+ custom = customConfigs.map((config) =>+ buildUserProvider(config, { modelRegistry: projectionRegistry }),+ );+ }markChanged();}@@ -810,14 +987,20 @@ export function commitModelPlaneFromCatalog(catalog: Catalog): void {const providers =incomingXai && current.providers.some((provider) => provider.id === 'xai')? current.providers.map((provider) =>- provider.id === 'xai' ? { ...provider, models: incomingXai.models } : provider,+ provider.id === 'xai' ? incomingXai : provider,): current.providers;+ if (catalog.modelRegistry) trustedCustomProviderRegistry = catalog.modelRegistry;base = {...current,providers,...(catalog.modelRegistry ? { modelRegistry: catalog.modelRegistry } : {}),};+ if (customConfigs) {+ custom = customConfigs.map((config) =>+ buildUserProvider(config, { modelRegistry: trustedCustomProviderRegistry }),+ );+ }markChanged();}@@ -840,10 +1023,23 @@ export function getModelPlaneWarnings(): readonly ModelPlaneWarning[] {* 传入的是已 `buildUserProvider` 展开的标准 `Provider[]`(**不含 API key**)。*/export function setCustomProviders(providers: Provider[]): void {+ customConfigs = null;custom = [...providers];markChanged();}+/**+ * 保存当前 owner 的原始配置并按生效 Registry 展开。配置本身不改写、不持久化;目录刷新时+ * 可在同一个 revision 内重算 effort 投影。+ */+export function setCustomProviderConfigs(configs: CustomProviderConfig[]): void {+ customConfigs = [...configs];+ custom = customConfigs.map((config) =>+ buildUserProvider(config, { modelRegistry: trustedCustomProviderRegistry }),+ );+ markChanged();+}+/*** 注入 codex cache 派生的规范化模型快照。由 ensureActiveCatalogLoaded 在目录加载后调用。* 传空数组 = 有效空快照(回到静态兜底);读取失败时调用方不应调用本 setter,以保留现值。@@ -868,6 +1064,12 @@ export function setDiscoveredProviderModels(markChanged();}+/** 成功空数组同样是权威成员快照;null 仅表示当前 owner 尚无成功快照。 */+export function setXaiDiscoveredModels(models: readonly XaiDiscoveredModel[] | null): void {+ xaiDiscoveredModels = models === null ? null : models.map((model) => ({ ...model }));+ markChanged();+}+/*** 原子注入供应商图片/视频发现快照。成功快照决定存在性,同 id 静态元数据优先;* 传 null 清空该供应商账号态快照,回到当前diff --git a/apps/desktop/src/main/maker-host/createDesktopProviderService.ts b/apps/desktop/src/main/maker-host/createDesktopProviderService.tsindex 98605e47eb..407d893934 100644--- a/apps/desktop/src/main/maker-host/createDesktopProviderService.ts+++ b/apps/desktop/src/main/maker-host/createDesktopProviderService.ts@@ -23,13 +23,13 @@ import path from 'node:path';import {BUNDLED_CATALOG,- buildUserProvider,compareModelRegistryRevisions,decideModelRegistrySnapshot,DEFAULT_REMOTE_CATALOG_BUDGET_MS,loadCatalog,loadCatalogWithSource,parseCatalog,+ storedCustomProviderId,type Catalog,type CatalogIO,type CatalogSourceConfig,@@ -44,6 +44,7 @@ import {getActiveCatalog,getModelPlaneWarnings,setActiveCatalog,+ setCustomProviderConfigs,setCustomProviders,setDiscoveredCodexModels,setLocalCatalogOverrides,@@ -58,6 +59,11 @@ import {loadAnthropicModelsFromDiskCache,refreshAnthropicModelsFromHttp,} from './model-discovery/anthropic.js';+import {+ clearXaiDiscoveredModels,+ loadXaiModelsFromDiskCache,+ refreshXaiModelsFromHttp,+} from './model-discovery/xai.js';import { createProviderService, type ProviderService } from './provider-service.js';import { readModelDisableOverrides } from './model-disable-store.js';import { listCustomProvidersWithSecureHeaders } from './custom-provider-header-secrets.js';@@ -66,6 +72,7 @@ import {setOAuthTokenReader,setProviderOAuthTokenReader,setProviderViewsReader,+ type ProviderOAuthTokenReadOptions,} from './provider-route.js';import { setDiagnosticsKeyReader, setDiagnosticsOAuthTokenReader } from './provider-diagnostics.js';import {@@ -85,10 +92,10 @@ import { getValidClaudeAiOAuth } from './claude-oauth-refresh.js';import {getGrokAccessToken,hasGrokOAuthLogin,- hasGrokOAuthLoginUnbound,+ recoverGrokAuthAfterRejection,resetGrokOAuthMemoryCache,} from './grok-oauth-login.js';-import { clearXaiMediaModels, refreshXaiMediaModels } from './model-discovery/xai-media.js';+import { clearXaiMediaModels } from './model-discovery/xai-media.js';import { getAuthState } from '../authManager.js';import { getActiveAppSession } from '../appSessionState.js';import {@@ -385,10 +392,30 @@ let endpointReloadInflight: {promise: Promise<Catalog>;} | null = null;+async function readXaiProviderOAuthToken(+ options?: ProviderOAuthTokenReadOptions,+): Promise<string | null> {+ if (!options?.forceRefresh) return getGrokAccessToken();++ // A forced retry must stay bound to the exact bearer rejected upstream. Without that+ // baseline we cannot safely decide which account generation to refresh.+ const staleToken = options.staleToken;+ if (!staleToken) return null;++ const outcome = await recoverGrokAuthAfterRejection(staleToken);+ if (outcome !== 'refreshed' && outcome !== 'superseded') return null;++ // `superseded` means another request/login already replaced the rejected credential.+ // Return that newer token, but never replay the bearer which caused the 401/403.+ const token = await getGrokAccessToken();+ return token !== staleToken ? token : null;+}+/** Set 用稳定函数引用去重,ensureActiveCatalogLoaded 的幂等调用不会重复注册清理副作用。 */function handleProviderSecretsCleared(): void {resetGenericOAuthMemoryCache();resetGrokOAuthMemoryCache();+ clearXaiDiscoveredModels();clearXaiMediaModels();}@@ -402,7 +429,7 @@ export function ensureActiveCatalogLoaded(): Promise<Catalog> {// 这里在路由发生前(splash 早于任何 turn)把真实 safeStorage 读取接进去。setCustomProviderKeyReader(readCustomProviderKey);setProviderOAuthTokenReader((providerId, agent, options) => {- if (providerId === 'xai') return getGrokAccessToken();+ if (providerId === 'xai') return readXaiProviderOAuthToken(options);// Codex and Pi processes do not carry Claude Code's native OAuth credential.// Their Anthropic bridges read the host-owned Claude.ai token and allow the// existing refresher to rotate it when needed.@@ -427,7 +454,9 @@ export function ensureActiveCatalogLoaded(): Promise<Catalog> {addProviderSecretsClearedListener(handleProviderSecretsCleared);const readOAuthToken = (providerId: string): string | null => {const provider = getActiveCatalog().providers.find((p) => p.id === providerId);- return readCachedGenericOAuthAccessToken(providerId, provider?.auth.oauth);+ const storageProviderId =+ provider?.source === 'user' ? storedCustomProviderId(providerId) : providerId;+ return readCachedGenericOAuthAccessToken(storageProviderId, provider?.auth.oauth);};setOAuthTokenReader(readOAuthToken);setDiagnosticsOAuthTokenReader(readOAuthToken);@@ -474,6 +503,10 @@ export function ensureActiveCatalogLoaded(): Promise<Catalog> {// 不阻塞 splash(失败保留现值,语义见 model-discovery/anthropic.ts)。await loadAnthropicModelsFromDiskCache();void refreshAnthropicModelsFromHttp();+ // xAI 账号成员同样先恢复当前 owner 的成功 LKG,再后台读官方账号清单。+ // 无 LKG / 刷新失败时 active-catalog 才继续使用 server Catalog → bundled 救急。+ await loadXaiModelsFromDiskCache();+ void refreshXaiModelsFromHttp();activeLoaded = true;return catalog;})@@ -685,7 +718,7 @@ export async function refreshCustomProvidersIntoCatalog(log.info('discarded stale custom provider catalog refresh');return;}- setCustomProviders(configs.map((c) => buildUserProvider(c)));+ setCustomProviderConfigs(configs);log.info('custom providers merged into active catalog', { count: configs.length });} catch (err) {if (!shouldApply()) {@@ -702,15 +735,15 @@ export async function refreshCustomProvidersIntoCatalog(}/**- * 连接态读取路径上的绑定自愈(同步凭证的两家:anthropic / xai)。+ * 连接态读取路径上的原生 Harness 绑定自愈。** 写失败绝不抛穿:connection 回调服务于 listProviders,抛出会让整份供应商列表取不到,* 比「这一次没认领上」严重得多 —— 下一次读取还会再试。Codex 的同款自愈挂在异步* reconcile 收口(见 auth-adapters.claimDetectedCodexOAuthBinding),因为它的凭证是- * 惰性物化的;这两家的凭证同步可读,在读连接态时就地认领即可。+ * 惰性物化的;Claude 凭证同步可读,在读连接态时就地认领即可。*/async function claimNativeProviderAuthOnRead(- provider: 'anthropic' | 'xai',+ provider: 'anthropic',hasCredential: () => boolean,onClaimed?: () => void | Promise<void>,waitForClaimed = false,@@ -838,7 +871,9 @@ export function getDesktopProviderService(): ProviderService {migrateLegacyNativeProviderAuthBindings(ownerId, {anthropic: hasClaudeAiOAuthUnbound(),openai: desktopCodexAuthAdapter.hasCodexOAuthLoginUnbound(),- xai: hasGrokOAuthLoginUnbound(),+ // 这是升级迁移,不是 CLI 自动发现:旧 xAI blob 只可能由 Cindy OAuth 写入,+ // nativeProviderAuthBinding 会把它记为 explicit-provider-oauth。+ xai: getProviderSecretStore().has('xai'),});}if (singleton) return singleton;@@ -846,10 +881,8 @@ export function getDesktopProviderService(): ProviderService {getCatalog: getDesktopSelectableCatalog,connection: {xd: () => getAppCapabilities().canUseCindyGateway && readClaudeApiKey() != null,- // 三家 native provider 统一口径:先跑一次绑定自愈,再读「绑定 + 凭证」的连接态。- // hasClaudeAiOAuth / hasCodexOAuthLogin / hasGrokOAuthLogin 内部都已校验绑定,- // 所以这里不再前置 isNativeProviderAuthBound —— 前置短路是纯冗余,而且会把- // listProviders 挡在自愈之前,正是「设置页已连接 / 聊天无来源」假报的成因(#294)。+ // Claude/Codex 是原生 Harness,可继承本机 CLI 凭证;xAI 是下游 provider,+ // 只能读取已经由 Cindy OAuth 明确绑定的 token,禁止在连接态读取时自动认领。anthropic: async ({ allowSideEffects, waitForDiscovery }) => {// 自愈会写绑定文件、读凭证作用域缓存并发起带凭证的上游请求。listProviders 这条通道// 同时服务 device-link 与可能不受信的渲染上下文,所以副作用只在本机主页面发起时@@ -886,17 +919,13 @@ export function getDesktopProviderService(): ProviderService {allowSideEffects? desktopCodexAuthAdapter.hasCodexOAuthLogin(): desktopCodexAuthAdapter.hasCodexOAuthLoginReadOnly(),- xai: async ({ allowSideEffects }) => {- if (allowSideEffects) {- await claimNativeProviderAuthOnRead('xai', hasGrokOAuthLoginUnbound, () =>- refreshXaiMediaModels().then(() => undefined),- );- }- return hasGrokOAuthLogin();- },+ // xAI is a downstream provider, not a native Harness. Its connection state+ // only reflects a Cindy OAuth binding (or the explicit legacy migration above);+ // reading the provider list must never auto-claim an arbitrary local token.+ xai: () => hasGrokOAuthLogin(),},// 通用 OAuth 供应商(目录 auth.oauth 描述符驱动):连接态 = 本机凭证 blob 是否存在。- genericOAuthConnected: (providerId) => hasGenericOAuthLogin(providerId),+ genericOAuthConnected: (providerId) => hasGenericOAuthLogin(storedCustomProviderId(providerId)),// 内置 API-key 供应商(如 gemini 图像来源):连接态 = key 已存(providerSecretStore)。builtinApiKeyConnected: (providerId) =>providerId === 'gemini' ? Boolean(getProviderSecretStore().get('gemini')?.trim()) : false,@@ -921,6 +950,7 @@ export const __testing = {catalogLkgTemporaryPath,readCatalogLkg,replaceCatalogLkgFile,+ readXaiProviderOAuthToken,selectCatalogLkgSnapshot,serializeCatalogLkgWrite,writeCatalogLkg,diff --git a/apps/desktop/src/main/maker-host/custom-provider-store.ts b/apps/desktop/src/main/maker-host/custom-provider-store.tsindex 13307a80c5..92eb6ff39e 100644--- a/apps/desktop/src/main/maker-host/custom-provider-store.ts+++ b/apps/desktop/src/main/maker-host/custom-provider-store.ts@@ -24,10 +24,12 @@ import type {ProviderRuntimeModelConfig,} from '@cindy/model-providers';import {+ effectivePiWireProtocol,findReservedOAuthExtraParam,isLoopbackProviderUrl,isProviderRequestPath,PI_REASONING_EFFORTS,+ preservesPiCatalogModels,} from '@cindy/model-providers';import { getDbClient } from '../localDb/client/current.js';@@ -38,7 +40,7 @@ export const CUSTOM_PROVIDER_ID_RE = /^[a-z0-9_-]+$/;/** 不可占用的内置来源 id。 */// 'cindy' 是 pi models.json 里网关 provider 的保留 id;自定义 provider 撞名会让其模型// 既被排除出网关块又不写入原生块 → --model 校验失败,故一并保留。-const RESERVED_IDS = new Set(['anthropic', 'openai', 'xd', 'cindy']);+const RESERVED_IDS = new Set(['anthropic', 'openai', 'xai', 'xd', 'cindy']);const VALID_AGENTS: readonly AgentKind[] = ['claude-code', 'codex', 'pi'];const MAX_ID_LEN = 40;const MAX_NAME_LEN = 60;@@ -74,7 +76,15 @@ function parseStoredPiReasoningCapability() {return {};}- return { reasoning: true, reasoningEfforts: efforts };+ const defaultEffort = isPiReasoningEffort(model.reasoningDefaultEffort)+ && efforts.includes(model.reasoningDefaultEffort)+ ? model.reasoningDefaultEffort+ : undefined;+ return {+ reasoning: true,+ reasoningEfforts: efforts,+ ...(defaultEffort ? { reasoningDefaultEffort: defaultEffort } : {}),+ };}function validateNoAuthLoopbackBoundary(@@ -143,7 +153,10 @@ function validateRuntime(agent: string, rt: unknown): ValidationResult {if (mm.supportsImageInput !== undefined && typeof mm.supportsImageInput !== 'boolean') {return invalid(`runtime '${agent}' model.supportsImageInput must be a boolean`);}- const hasReasoningCapability = mm.reasoning !== undefined || mm.reasoningEfforts !== undefined;+ const hasReasoningCapability =+ mm.reasoning !== undefined+ || mm.reasoningEfforts !== undefined+ || mm.reasoningDefaultEffort !== undefined;if (hasReasoningCapability && agent !== 'pi') {return invalid(`runtime '${agent}' reasoning capability is only supported for pi models`);}@@ -160,8 +173,17 @@ function validateRuntime(agent: string, rt: unknown): ValidationResult {) {return invalid(`runtime '${agent}' model.reasoningEfforts invalid`);}- } else if (mm.reasoningEfforts !== undefined) {- return invalid(`runtime '${agent}' model.reasoningEfforts requires reasoning=true`);+ if (+ mm.reasoningDefaultEffort !== undefined+ && (+ !isPiReasoningEffort(mm.reasoningDefaultEffort)+ || !mm.reasoningEfforts.includes(mm.reasoningDefaultEffort)+ )+ ) {+ return invalid(`runtime '${agent}' model.reasoningDefaultEffort invalid`);+ }+ } else if (mm.reasoningEfforts !== undefined || mm.reasoningDefaultEffort !== undefined) {+ return invalid(`runtime '${agent}' reasoning metadata requires reasoning=true`);}}if (r.wireProtocol !== undefined) {@@ -197,6 +219,16 @@ function validateRuntime(agent: string, rt: unknown): ValidationResult {return invalid(`runtime '${agent}' modelsUrl is not a valid URL`);}}+ if (+ r.piCatalogProviderId !== undefined+ && (+ agent !== 'pi'+ || typeof r.piCatalogProviderId !== 'string'+ || !/^[a-z0-9-]+$/.test(r.piCatalogProviderId)+ )+ ) {+ return invalid(`runtime '${agent}' piCatalogProviderId invalid`);+ }return { ok: true };}@@ -332,14 +364,19 @@ function validateAuthSection(auth: unknown): ValidationResult {}/** 纯函数:校验一份自定义供应商配置的结构合法性(per-runtime)。 */-export function validateCustomProviderConfig(config: unknown): ValidationResult {+export function validateCustomProviderConfig(+ config: unknown,+ options: { allowLegacyXai?: boolean } = {},+): ValidationResult {if (!config || typeof config !== 'object') return invalid('config must be an object');const c = config as Record<string, unknown>;if (typeof c.id !== 'string' || c.id.length === 0) return invalid('id required');if (c.id.length > MAX_ID_LEN) return invalid(`id too long (max ${MAX_ID_LEN})`);if (!CUSTOM_PROVIDER_ID_RE.test(c.id)) return invalid('id must match /^[a-z0-9_-]+$/');- if (RESERVED_IDS.has(c.id)) return invalid(`id '${c.id}' is reserved`);+ if (RESERVED_IDS.has(c.id) && !(c.id === 'xai' && options.allowLegacyXai === true)) {+ return invalid(`id '${c.id}' is reserved`);+ }if (typeof c.name !== 'string' || c.name.trim().length === 0) return invalid('name required');if (c.name.length > MAX_NAME_LEN) return invalid(`name too long (max ${MAX_NAME_LEN})`);@@ -380,7 +417,13 @@ function normalizeRuntime(...(m.defaultEnabled === false ? { defaultEnabled: false } : {}),...(m.supportsImageInput === true ? { supportsImageInput: true } : {}),...(agent === 'pi' && m.reasoning === true && m.reasoningEfforts?.length- ? { reasoning: true, reasoningEfforts: [...m.reasoningEfforts] }+ ? {+ reasoning: true,+ reasoningEfforts: [...m.reasoningEfforts],+ ...(m.reasoningDefaultEffort+ ? { reasoningDefaultEffort: m.reasoningDefaultEffort }+ : {}),+ }: {}),})).filter((m) => {@@ -394,6 +437,7 @@ function normalizeRuntime(out.requestPath = rt.requestPath.trim();}if (rt.modelsUrl && rt.modelsUrl.trim()) out.modelsUrl = rt.modelsUrl.trim();+ if (agent === 'pi' && rt.piCatalogProviderId) out.piCatalogProviderId = rt.piCatalogProviderId;return out;}@@ -441,6 +485,33 @@ function normalizeConfig(config: CustomProviderConfig): CustomProviderConfig {return out;}+/**+ * 官方目录标记只适用于用户尚未改写的预设快照。所有写入口都在 main 再比一次旧值,+ * 避免非当前设置页(移动端、旧 renderer、异步发现)改了路由或模型后仍保留 marker,+ * 继而在 Pi 启动时用官方模型整条覆盖用户显式配置。+ */+function invalidateEditedPiCatalogMarker(+ previous: CustomProviderConfig,+ next: CustomProviderConfig,+): CustomProviderConfig {+ const previousPi = previous.runtimes.pi;+ const nextPi = next.runtimes.pi;+ if (+ !previousPi?.piCatalogProviderId+ || !nextPi?.piCatalogProviderId+ || previousPi.piCatalogProviderId !== nextPi.piCatalogProviderId+ ) return next;+ const normalizeBaseUrl = (value: string) => value.trim().replace(/\/+$/, '');+ const unchanged = normalizeBaseUrl(previousPi.baseUrl) === normalizeBaseUrl(nextPi.baseUrl)+ && effectivePiWireProtocol(previousPi.wireProtocol)+ === effectivePiWireProtocol(nextPi.wireProtocol)+ && preservesPiCatalogModels(previousPi.models, nextPi.models);+ if (unchanged) return next;+ const pi = { ...nextPi };+ delete pi.piCatalogProviderId;+ return { ...next, runtimes: { ...next.runtimes, pi } };+}+/*** 把授权后自动发现的模型 additions-only 合并进自定义供应商配置的指定 runtime(纯函数)。* 已有 id first-wins(用户手填 / 上次发现的条目不被覆盖);无新增返回 null(调用方免写库)。@@ -544,6 +615,13 @@ function parseRuntimes(raw: string): Partial<Record<AgentKind, CustomProviderRunentry.headers = r.headers as Record<string, string>;}if (typeof r.modelsUrl === 'string' && r.modelsUrl.length > 0) entry.modelsUrl = r.modelsUrl;+ if (+ agent === 'pi'+ && typeof r.piCatalogProviderId === 'string'+ && /^[a-z0-9-]+$/.test(r.piCatalogProviderId)+ ) {+ entry.piCatalogProviderId = r.piCatalogProviderId;+ }out[agent] = entry;}return out;@@ -618,10 +696,13 @@ export async function updateCustomProvider(config: CustomProviderConfig,now: number = Date.now(),): Promise<CustomProviderConfig | null> {- const c = normalizeConfig({ ...config, id });const db = getDbClient().drizzle;const existing = await db.select().from(customProviders).where(eq(customProviders.id, id)).get();if (!existing) return null;+ const c = invalidateEditedPiCatalogMarker(+ rowToConfig(existing),+ normalizeConfig({ ...config, id }),+ );await db.update(customProviders).set({@@ -645,7 +726,10 @@ export async function updateCustomProviderIfUnchanged(now: number = Date.now(),): Promise<boolean> {const expectedConfig = normalizeConfig({ ...expected, id });- const nextConfig = normalizeConfig({ ...config, id });+ const nextConfig = invalidateEditedPiCatalogMarker(+ expectedConfig,+ normalizeConfig({ ...config, id }),+ );const db = getDbClient().drizzle;const existing = await db.select().from(customProviders).where(eq(customProviders.id, id)).get();if (!existing) return false;diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.tsindex fd5a52527a..13c2fbe771 100644--- a/apps/desktop/src/main/maker-host/index.ts+++ b/apps/desktop/src/main/maker-host/index.ts@@ -89,6 +89,7 @@ import {resolveRemotePiBinaryPath,} from './pi-remote-transport.js';import { ensurePiManagerInstalled } from './pi-manager-client.js';+import { createPiRemoteProviderForwardLease } from './pi-remote-provider-forward.js';import { openCcManagerSession } from './cc-manager-client.js';import { routeInjectedRemoteMcpApprovalsThroughCindy } from './remote-claude-permission-mode.js';import { getRemoteClaudeBinaryPath } from '../remote-ssh/cc-manager-install.js';@@ -1760,7 +1761,19 @@ export function getMaker(): Maker {// transport — SSH 连接复用 ConnectionPool (remote-ssh feature 起的),// 这里包一层 RemoteHost + SshPiTransport (execStream 直桥远端 pi --mode rpc)。// 远端机器没在 pool / 未连接 → 抛错, PiAgent 把它当 startSession 失败传上去。- getRemotePiTransport: async (remoteHostId, { binaryPath: _localBinaryPath, remoteBinaryPath: providedRemoteBinaryPath, args, cwd, env, logger, sessionId }) => {+ getRemotePiTransport: async (+ remoteHostId,+ {+ binaryPath: _localBinaryPath,+ remoteBinaryPath: providedRemoteBinaryPath,+ args,+ cwd,+ env,+ logger,+ sessionId,+ hostProxyForwards,+ },+ ) => {const remoteHost = getRemoteSshPool().get(remoteHostId);if (!remoteHost) {throw new Error(`remote SSH host "${remoteHostId}" not found in pool — connect it first under Settings → Remote`);@@ -1799,15 +1812,53 @@ export function getMaker(): Maker {});}});- return createSshPiDaemonTransport({- remoteHost,- binaryPath: remoteBinaryPath,- args,- cwd,- env,- logger,- daemonSessionId: sessionId ?? undefined,- });+ const providerForwardLease = createPiRemoteProviderForwardLease(+ (spec) => remoteHost.ensureRemoteForward(spec),+ );+ try {+ for (const spec of hostProxyForwards ?? []) {+ await providerForwardLease.ensure(spec);+ }+ } catch (error) {+ await Promise.allSettled([providerForwardLease.releaseAll()]);+ throw error;+ }+ let transport;+ try {+ transport = createSshPiDaemonTransport({+ remoteHost,+ binaryPath: remoteBinaryPath,+ args,+ cwd,+ env,+ logger,+ daemonSessionId: sessionId ?? undefined,+ });+ } catch (error) {+ await providerForwardLease.releaseAll();+ throw error;+ }+ transport.ensureHostProxyForward = providerForwardLease.ensure;+ if (transport.killRemoteSession) {+ const killRemoteSession = transport.killRemoteSession.bind(transport);+ transport.killRemoteSession = async () => {+ try {+ await killRemoteSession();+ } finally {+ await providerForwardLease.releaseAll();+ }+ };+ } else {+ const close = transport.close.bind(transport);+ transport.close = async (reason?: string) => {+ try {+ await close(reason);+ } finally {+ await providerForwardLease.releaseAll();+ }+ };+ }+ return transport;},// 远端 Pi 的 agentHome 文件操作:models.json / extensions / perm / subagent 快照 /// resume stat 都落到远端机器(pi 进程在远端读)。经 SSH stdin 管道写文件(cat > 原子diff --git a/apps/desktop/src/main/maker-host/model-discovery/connection-source.ts b/apps/desktop/src/main/maker-host/model-discovery/connection-source.tsnew file mode 100644index 0000000000..35e272c486--- /dev/null+++ b/apps/desktop/src/main/maker-host/model-discovery/connection-source.ts@@ -0,0 +1,43 @@+/**+ * 模型连接自发现分两段:先确定经过授权的凭证来源并绑定 owner,再用该来源读取账号模型。+ *+ * 授权来源不能被供应商刷新总线抹平:Claude Code / Codex 是 Cindy 支持的原生 Harness,+ * 可以继承各自 CLI 已登录凭证;xAI 是下游 provider,只能使用用户在 Cindy 内明确完成的+ * OAuth;API-key provider 同样只接受用户明确保存的 key。授权完成后,三者才共同进入+ * authoritative account snapshot → Harness projection → metadata overlay。+ */+export type ConnectionSourceKind =+ 'native-harness-inherited' | 'explicit-provider-oauth' | 'explicit-api-key';++export type NativeProviderId = 'anthropic' | 'openai' | 'xai';+export type NativeHarnessInheritedProviderId = 'anthropic' | 'openai';++export const NATIVE_PROVIDER_CONNECTION_SOURCE = {+ anthropic: 'native-harness-inherited',+ openai: 'native-harness-inherited',+ xai: 'explicit-provider-oauth',+} as const satisfies Record<NativeProviderId, ConnectionSourceKind>;++export function isNativeHarnessInheritedProvider(+ provider: NativeProviderId,+): provider is NativeHarnessInheritedProviderId {+ return NATIVE_PROVIDER_CONNECTION_SOURCE[provider] === 'native-harness-inherited';+}++export function isConnectionSourceKind(value: unknown): value is ConnectionSourceKind {+ return (+ value === 'native-harness-inherited' ||+ value === 'explicit-provider-oauth' ||+ value === 'explicit-api-key'+ );+}++/**+ * 账号模型发现的公共提交形态。成功空表同样是 authoritative,调用方不得用静态目录复活成员。+ * 各 provider 可以保留自己的授权刷新与上游协议 adapter,但成员语义从这里开始一致。+ */+export interface AuthoritativeAccountModelSnapshot<TModel> {+ source: ConnectionSourceKind;+ authoritative: true;+ models: readonly TModel[];+}diff --git a/apps/desktop/src/main/maker-host/model-discovery/xai.ts b/apps/desktop/src/main/maker-host/model-discovery/xai.tsnew file mode 100644index 0000000000..3844d05b6e--- /dev/null+++ b/apps/desktop/src/main/maker-host/model-discovery/xai.ts@@ -0,0 +1,444 @@+/** xAI SuperGrok account model discovery and owner-scoped last-known-good snapshot. */++import fsp from 'node:fs/promises';+import path from 'node:path';++import type { Effort } from '@cindy/model-providers';++import { activeOwnerScopeKey, ownerScopedUserDataPath } from '../../appSessionState.js';+import { createLogger, type Logger } from '../../logger.js';+import { setXaiDiscoveredModels, type XaiDiscoveredModel } from '../active-catalog.js';+import { getGrokAccessToken, hasGrokOAuthLogin, peekGrokAccessToken } from '../grok-oauth-login.js';+import { outboundFetch } from '../outbound-fetch.js';+import { invalidateXaiBridgeAuth } from '../xai-auth-invalidation-host.js';+import type {+ XaiBridgeAuthFailure,+ XaiBridgeAuthInvalidationResult,+} from '../xai-bridge-auth-invalidation.js';+import type { AuthoritativeAccountModelSnapshot } from './connection-source.js';+import { getNativeProviderAuthSource } from '../nativeProviderAuthBinding.js';++export const XAI_ACCOUNT_USER_URL = 'https://cli-chat-proxy.grok.com/v1/user?include=subscription';+export const XAI_ACCOUNT_MODELS_URL = 'https://cli-chat-proxy.grok.com/v1/models';+export const XAI_GROK_CLIENT_VERSION = '1.0.3';++const HTTP_TIMEOUT_MS = 15_000;+const MAX_ERROR_BODY_BYTES = 8 * 1024;+const VALID_EFFORTS: ReadonlySet<string> = new Set([+ 'minimal',+ 'low',+ 'medium',+ 'high',+ 'xhigh',+ 'max',+ 'ultra',+]);+const log = createLogger('model-discovery:xai');+let cacheMutationQueue: Promise<void> = Promise.resolve();+let cacheTempSequence = 0;+let refreshInflight: Promise<boolean> | null = null;+let refreshInflightScope: string | number | null = null;+let refreshInflightToken: string | null = null;++export interface XaiModelDiscoveryDeps {+ fetchImpl: typeof fetch;+ getAccessToken(): Promise<string>;+ peekAccessToken(): string | null;+ hasLogin(): boolean;+ getConnectionSource(): 'explicit-provider-oauth' | null;+ getScopeKey(): string | number;+ cacheFilePath(): string;+ applySnapshot(models: readonly XaiDiscoveredModel[]): void;+ invalidateAuth(failure: XaiBridgeAuthFailure): Promise<XaiBridgeAuthInvalidationResult>;+ log: Pick<Logger, 'info' | 'warn'>;+}++const DEFAULT_DEPS: XaiModelDiscoveryDeps = {+ fetchImpl: outboundFetch,+ getAccessToken: getGrokAccessToken,+ peekAccessToken: peekGrokAccessToken,+ hasLogin: hasGrokOAuthLogin,+ getConnectionSource: () =>+ getNativeProviderAuthSource('xai') === 'explicit-provider-oauth'+ ? 'explicit-provider-oauth'+ : null,+ getScopeKey: activeOwnerScopeKey,+ cacheFilePath: () => ownerScopedUserDataPath('model-discovery', 'xai-models.json'),+ applySnapshot: setXaiDiscoveredModels,+ invalidateAuth: invalidateXaiBridgeAuth,+ log,+};++interface XaiUserIdentity {+ userId: string;+ email?: string;+}++class XaiDiscoveryHttpError extends Error {+ constructor(+ readonly stage: 'user' | 'models',+ readonly status: number,+ readonly responseBody: string,+ ) {+ super(`xAI account model discovery ${stage} request failed (${status})`);+ }+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return value !== null && typeof value === 'object' && !Array.isArray(value);+}++function stringField(record: Record<string, unknown>, ...keys: string[]): string | undefined {+ for (const key of keys) {+ const value = record[key];+ if (typeof value === 'string' && value.trim()) return value.trim();+ }+ return undefined;+}++function positiveIntegerField(+ record: Record<string, unknown>,+ ...keys: string[]+): number | undefined {+ for (const key of keys) {+ const value = record[key];+ if (typeof value === 'number' && Number.isSafeInteger(value) && value > 0) return value;+ }+ return undefined;+}++function effort(value: unknown): Effort | undefined {+ return typeof value === 'string' && VALID_EFFORTS.has(value) ? (value as Effort) : undefined;+}++function parseReasoningEfforts(raw: unknown): { efforts?: Effort[]; declaredDefault?: Effort } {+ if (!Array.isArray(raw)) return {};+ const efforts: Effort[] = [];+ let declaredDefault: Effort | undefined;+ for (const item of raw) {+ const value = effort(typeof item === 'string' ? item : isRecord(item) ? item.value : undefined);+ if (!value || efforts.includes(value)) continue;+ efforts.push(value);+ if (isRecord(item) && item.default === true) declaredDefault = value;+ }+ return { efforts, declaredDefault };+}++function canonicalModelId(raw: string): string {+ return raw.startsWith('xai/') ? raw : `xai/${raw}`;+}++/** Parse membership without guessing missing capability fields. */+export function parseXaiAccountModels(payload: unknown): XaiDiscoveredModel[] {+ if (!isRecord(payload) || !Array.isArray(payload.data)) {+ throw new Error('xAI account model discovery returned an invalid models payload');+ }+ const seen = new Set<string>();+ const models: XaiDiscoveredModel[] = [];+ for (const value of payload.data) {+ if (!isRecord(value)) continue;+ const meta = isRecord(value._meta) ? value._meta : {};+ if (value.hidden === true || meta.hidden === true) continue;+ const rawId =+ stringField(value, 'model', 'modelId', 'id') ?? stringField(meta, 'model', 'modelId');+ if (!rawId) continue;+ const id = canonicalModelId(rawId);+ if (seen.has(id)) continue;+ seen.add(id);+ const contextWindow =+ positiveIntegerField(value, 'contextWindow', 'context_window') ??+ positiveIntegerField(meta, 'contextWindow', 'totalContextTokens');+ const maxOutput = positiveIntegerField(value, 'maxCompletionTokens', 'max_completion_tokens');+ const parsedEfforts = parseReasoningEfforts(+ value.reasoningEfforts ?? value.reasoning_efforts ?? meta.reasoningEfforts,+ );+ const declaredDefault =+ parsedEfforts.declaredDefault ??+ effort(value.reasoningEffort ?? value.reasoning_effort ?? meta.reasoningEffort);+ let efforts = parsedEfforts.efforts;+ if (value.supportsReasoningEffort === false || value.supports_reasoning_effort === false) {+ efforts = [];+ } else if (efforts === undefined && declaredDefault) {+ efforts = [declaredDefault];+ } else if (efforts && declaredDefault && !efforts.includes(declaredDefault)) {+ efforts = [...efforts, declaredDefault];+ }+ const name = stringField(value, 'name');+ const description = stringField(value, 'description');+ models.push({+ id,+ ...(name ? { name } : {}),+ ...(description ? { description } : {}),+ ...(contextWindow !== undefined ? { contextWindow, contextWindowVerified: true } : {}),+ ...(maxOutput !== undefined ? { maxOutput } : {}),+ ...(efforts !== undefined ? { efforts } : {}),+ ...(declaredDefault !== undefined ? { defaultEffort: declaredDefault } : {}),+ });+ }+ return models;+}++function parseCachedModels(payload: unknown): XaiDiscoveredModel[] | null {+ if (!isRecord(payload) || !Array.isArray(payload.models)) return null;+ const out: XaiDiscoveredModel[] = [];+ const seen = new Set<string>();+ for (const value of payload.models) {+ if (!isRecord(value) || typeof value.id !== 'string') return null;+ const id = canonicalModelId(value.id);+ if (seen.has(id)) continue;+ seen.add(id);+ const efforts =+ value.efforts === undefined ? undefined : parseReasoningEfforts(value.efforts).efforts;+ const defaultEffort = effort(value.defaultEffort);+ if (value.efforts !== undefined && efforts === undefined) return null;+ out.push({+ id,+ ...(typeof value.name === 'string' ? { name: value.name } : {}),+ ...(typeof value.description === 'string' ? { description: value.description } : {}),+ ...(positiveIntegerField(value, 'contextWindow') !== undefined+ ? {+ contextWindow: positiveIntegerField(value, 'contextWindow'),+ ...(value.contextWindowVerified === true ? { contextWindowVerified: true } : {}),+ }+ : {}),+ ...(positiveIntegerField(value, 'maxOutput') !== undefined+ ? { maxOutput: positiveIntegerField(value, 'maxOutput') }+ : {}),+ ...(efforts !== undefined ? { efforts } : {}),+ ...(defaultEffort !== undefined ? { defaultEffort } : {}),+ });+ }+ return out;+}++function enqueueCacheMutation(+ task: () => Promise<void>,+ deps: XaiModelDiscoveryDeps,+): Promise<void> {+ cacheMutationQueue = cacheMutationQueue.then(task).catch((error) => {+ deps.log.warn('xAI models cache mutation failed', { error: String(error) });+ });+ return cacheMutationQueue;+}++function isCurrent(deps: XaiModelDiscoveryDeps, scopeKey: string | number, token: string): boolean {+ return deps.getScopeKey() === scopeKey && deps.hasLogin() && deps.peekAccessToken() === token;+}++async function persistSnapshot(+ deps: XaiModelDiscoveryDeps,+ scopeKey: string | number,+ token: string,+ models: readonly XaiDiscoveredModel[],+): Promise<void> {+ const payload = JSON.stringify({ fetchedAt: new Date().toISOString(), models }, null, 2);+ await enqueueCacheMutation(async () => {+ if (!isCurrent(deps, scopeKey, token)) return;+ const file = deps.cacheFilePath();+ const temp = `${file}.${process.pid}.${(cacheTempSequence += 1)}.tmp`;+ try {+ await fsp.mkdir(path.dirname(file), { recursive: true });+ await fsp.writeFile(temp, payload, 'utf-8');+ if (!isCurrent(deps, scopeKey, token)) return;+ await fsp.rename(temp, file);+ } finally {+ await fsp.rm(temp, { force: true }).catch(() => undefined);+ }+ }, deps);+}++export async function loadXaiModelsFromDiskCache(+ injected: Partial<XaiModelDiscoveryDeps> = {},+): Promise<boolean> {+ const deps = { ...DEFAULT_DEPS, ...injected };+ if (!deps.hasLogin() || deps.getConnectionSource() !== 'explicit-provider-oauth') return false;+ const scopeKey = deps.getScopeKey();+ const token = deps.peekAccessToken();+ if (!token) return false;+ try {+ const parsed = parseCachedModels(JSON.parse(await fsp.readFile(deps.cacheFilePath(), 'utf-8')));+ if (parsed === null || !isCurrent(deps, scopeKey, token)) return false;+ deps.applySnapshot(parsed);+ return true;+ } catch {+ return false;+ }+}++async function readErrorBody(response: Response): Promise<string> {+ const text = await response.text().catch(() => '');+ return text.slice(0, MAX_ERROR_BODY_BYTES);+}++async function fetchJson(+ deps: XaiModelDiscoveryDeps,+ stage: 'user' | 'models',+ url: string,+ headers: Record<string, string>,+): Promise<unknown> {+ let response: Response;+ try {+ response = await deps.fetchImpl(url, {+ method: 'GET',+ headers,+ signal: AbortSignal.timeout(HTTP_TIMEOUT_MS),+ });+ } catch {+ throw new Error(`xAI account model discovery ${stage} request failed`);+ }+ if (!response.ok)+ throw new XaiDiscoveryHttpError(stage, response.status, await readErrorBody(response));+ try {+ return await response.json();+ } catch {+ throw new Error(`xAI account model discovery ${stage} returned invalid JSON`);+ }+}++function baseHeaders(accessToken: string): Record<string, string> {+ return {+ Authorization: `Bearer ${accessToken}`,+ 'X-XAI-Token-Auth': 'xai-grok-cli',+ 'x-grok-client-version': XAI_GROK_CLIENT_VERSION,+ 'x-grok-client-mode': 'interactive',+ };+}++function parseUserIdentity(payload: unknown): XaiUserIdentity {+ if (!isRecord(payload))+ throw new Error('xAI account model discovery returned an invalid user payload');+ const userId = stringField(payload, 'userId');+ if (!userId) throw new Error('xAI account model discovery user payload omitted userId');+ const email = stringField(payload, 'email');+ return { userId, ...(email ? { email } : {}) };+}++async function discoverOnce(+ deps: XaiModelDiscoveryDeps,+ scopeKey: string | number,+ token: string,+): Promise<XaiDiscoveredModel[] | null> {+ const identity = parseUserIdentity(+ await fetchJson(deps, 'user', XAI_ACCOUNT_USER_URL, baseHeaders(token)),+ );+ if (!isCurrent(deps, scopeKey, token)) return null;+ const models = await fetchJson(deps, 'models', XAI_ACCOUNT_MODELS_URL, {+ ...baseHeaders(token),+ 'x-userid': identity.userId,+ ...(identity.email ? { 'x-email': identity.email } : {}),+ });+ if (!isCurrent(deps, scopeKey, token)) return null;+ return parseXaiAccountModels(models);+}++async function runRefresh(+ deps: XaiModelDiscoveryDeps,+ onAccessTokenResolved?: (token: string) => void,+): Promise<boolean> {+ const connectionSource = deps.getConnectionSource();+ if (connectionSource !== 'explicit-provider-oauth') return false;+ const scopeKey = deps.getScopeKey();+ let token = await deps.getAccessToken();+ onAccessTokenResolved?.(token);+ if (!isCurrent(deps, scopeKey, token)) return false;+ for (let attempt = 0; attempt < 2; attempt += 1) {+ try {+ const models = await discoverOnce(deps, scopeKey, token);+ if (models === null || !isCurrent(deps, scopeKey, token)) return false;+ const snapshot: AuthoritativeAccountModelSnapshot<XaiDiscoveredModel> = {+ source: connectionSource,+ authoritative: true,+ models,+ };+ deps.applySnapshot(snapshot.models);+ await persistSnapshot(deps, scopeKey, token, models);+ deps.log.info('xAI account model discovery applied', { modelCount: models.length });+ return true;+ } catch (error) {+ if (!(error instanceof XaiDiscoveryHttpError) || attempt > 0) {+ deps.log.warn('xAI account model discovery failed; keeping current/LKG snapshot', {+ error: error instanceof Error ? error.message : String(error),+ });+ return false;+ }+ if (error.status !== 401 && error.status !== 403) return false;+ const outcome = await deps.invalidateAuth({+ status: error.status,+ body: error.responseBody,+ failedAccessToken: token,+ });+ if (outcome !== 'refreshed' && outcome !== 'superseded') return false;+ if (deps.getScopeKey() !== scopeKey || !deps.hasLogin()) return false;+ token = await deps.getAccessToken();+ if (!isCurrent(deps, scopeKey, token)) return false;+ }+ }+ return false;+}++export async function refreshXaiModelsFromHttp(+ injected: Partial<XaiModelDiscoveryDeps> = {},+): Promise<boolean> {+ const deps = { ...DEFAULT_DEPS, ...injected };+ const scopeKey = deps.getScopeKey();+ // The owner scope remains stable across an xAI account switch. Only reuse a+ // flight when it belongs to the same currently-bound access token; otherwise+ // the new account must start its own discovery immediately. The old flight+ // is still guarded by isCurrent and cannot apply or persist its late result.+ const currentToken = deps.peekAccessToken();+ if (+ refreshInflight &&+ currentToken &&+ refreshInflightScope === scopeKey &&+ refreshInflightToken === currentToken+ ) {+ return refreshInflight;+ }+ let flight!: Promise<boolean>;+ flight = runRefresh(deps, (resolvedToken) => {+ // getAccessToken may rotate an expired token before the first network request.+ // Re-key the active flight to that resolved token so a concurrent startup/+ // readiness refresh joins it instead of duplicating the same account discovery.+ // A real account switch still has a different current token and starts a new flight.+ if (refreshInflight === flight) refreshInflightToken = resolvedToken;+ }).finally(() => {+ if (refreshInflight === flight) {+ refreshInflight = null;+ refreshInflightScope = null;+ refreshInflightToken = null;+ }+ });+ refreshInflight = flight;+ refreshInflightScope = scopeKey;+ refreshInflightToken = currentToken;+ return flight;+}++/** Clear process membership on logout/account switch, but retain the owner's disk LKG. */+export function clearXaiDiscoveredModels(): void {+ setXaiDiscoveredModels(null);+}++/** Explicit re-login may replace the SuperGrok account under the same Cindy owner. */+export async function discardXaiModelsDiskCache(+ injected: Partial<XaiModelDiscoveryDeps> = {},+): Promise<void> {+ const deps = { ...DEFAULT_DEPS, ...injected };+ const scopeKey = deps.getScopeKey();+ const file = deps.cacheFilePath();+ await enqueueCacheMutation(async () => {+ if (deps.getScopeKey() !== scopeKey) return;+ await fsp.rm(file, { force: true });+ }, deps);+}++export function waitForXaiDiscoveryIdleForTest(): Promise<void> {+ return cacheMutationQueue;+}++export function resetXaiDiscoveryForTest(): void {+ refreshInflight = null;+ refreshInflightScope = null;+ refreshInflightToken = null;+ cacheMutationQueue = Promise.resolve();+}diff --git a/apps/desktop/src/main/maker-host/nativeProviderAuthBinding.ts b/apps/desktop/src/main/maker-host/nativeProviderAuthBinding.tsindex 34a0feb3c9..e557041e00 100644--- a/apps/desktop/src/main/maker-host/nativeProviderAuthBinding.ts+++ b/apps/desktop/src/main/maker-host/nativeProviderAuthBinding.ts@@ -3,9 +3,19 @@ import fs from 'node:fs';import path from 'node:path';import { getActiveAppSession, isAppSessionBoundaryPending } from '../appSessionState.js';+import {+ isConnectionSourceKind,+ NATIVE_PROVIDER_CONNECTION_SOURCE,+ type ConnectionSourceKind,+ type NativeHarnessInheritedProviderId,+ type NativeProviderId,+} from './model-discovery/connection-source.js';-type NativeProviderId = 'anthropic' | 'openai' | 'xai';-const NATIVE_PROVIDER_IDS = ['anthropic', 'openai', 'xai'] as const satisfies readonly NativeProviderId[];+const NATIVE_PROVIDER_IDS = [+ 'anthropic',+ 'openai',+ 'xai',+] as const satisfies readonly NativeProviderId[];type BindingFile = Partial<Record<NativeProviderId, string>> & {legacyClaimOwner?: string;/**@@ -33,6 +43,8 @@ type BindingFile = Partial<Record<NativeProviderId, string>> & {* 就存在」。登出时清除(那之后的凭证若还在,就回到「可被继承」的语义)。*/selfAuthorized?: Partial<Record<NativeProviderId, string>>;+ /** 授权来源审计;旧文件缺失时继续由 selfAuthorized / provider 迁移语义兼容。 */+ sources?: Partial<Record<NativeProviderId, ConnectionSourceKind>>;};function bindingPath(): string {@@ -78,7 +90,10 @@ function readBindingsOrFail(): BindingRead {// 只修 revoked、保住其余归属 —— 否则一次「修复」会把别人的 owner 抹掉,反倒开出新的// 误认领口子(PR #548 review)。const revoked = (value as { revoked?: unknown }).revoked;- if (revoked !== undefined && (typeof revoked !== 'object' || revoked === null || Array.isArray(revoked))) {+ if (+ revoked !== undefined &&+ (typeof revoked !== 'object' || revoked === null || Array.isArray(revoked))+ ) {const { revoked: _bad, ...rest } = value as BindingFile;return { ok: false, reason: 'badRevoked', bindings: rest };}@@ -136,6 +151,10 @@ export function bindNativeProviderAuth(provider: NativeProviderId): void {writeBindings({...bindings,selfAuthorized: { ...bindings.selfAuthorized, [provider]: owner },+ sources: {+ ...bindings.sources,+ [provider]: 'explicit-provider-oauth',+ },[provider]: owner,});return;@@ -161,6 +180,10 @@ export function bindNativeProviderAuth(provider: NativeProviderId): void {...salvaged,revoked: suppressed,selfAuthorized: { ...salvaged.selfAuthorized, [provider]: owner },+ sources: {+ ...salvaged.sources,+ [provider]: 'explicit-provider-oauth',+ },[provider]: owner,});}@@ -173,7 +196,24 @@ export function bindNativeProviderAuth(provider: NativeProviderId): void {export function isNativeProviderAuthSelfAuthorized(provider: NativeProviderId): boolean {const read = readBindingsOrFail();if (!read.ok && read.reason === 'unreadable') return true;- return read.bindings.selfAuthorized?.[provider] !== undefined;+ return (+ read.bindings.sources?.[provider] === 'explicit-provider-oauth' ||+ read.bindings.selfAuthorized?.[provider] !== undefined+ );+}++/** 返回当前 owner 绑定的授权来源;归属不明或旧文件未记录时返回 null。 */+export function getNativeProviderAuthSource(+ provider: NativeProviderId,+): ConnectionSourceKind | null {+ if (!isNativeProviderAuthBound(provider)) return null;+ const read = readBindingsOrFail();+ if (!read.ok) return null;+ const explicit = read.bindings.sources?.[provider];+ if (isConnectionSourceKind(explicit)) return explicit;+ if (read.bindings.selfAuthorized?.[provider] !== undefined) return 'explicit-provider-oauth';+ // 旧版 xAI token 只可能由 Cindy 的浏览器 OAuth 写入;不得把缺少来源字段误报成 CLI 继承。+ return NATIVE_PROVIDER_CONNECTION_SOURCE[provider];}/**@@ -209,6 +249,11 @@ export function unbindNativeProviderAuth(delete selfAuthorized[provider];bindings.selfAuthorized = selfAuthorized;}+ if (bindings.sources?.[provider] !== undefined) {+ const sources = { ...bindings.sources };+ delete sources[provider];+ bindings.sources = sources;+ }if (marking) bindings.revoked = { ...(bindings.revoked ?? {}), [provider]: owner as string };writeBindings(bindings);}@@ -234,7 +279,17 @@ export function migrateLegacyNativeProviderAuthBindings(// 显式登出过的 provider 一律跳过:这条一次性迁移同样不能把用户弃用掉的残留凭证// 认领回来(PR #548 review)。if (bindings.revoked && provider in bindings.revoked) continue;- if (available[provider] && !next[provider]) next[provider] = ownerId;+ if (available[provider] && !next[provider]) {+ next[provider] = ownerId;+ next.sources = {+ ...next.sources,+ [provider]: NATIVE_PROVIDER_CONNECTION_SOURCE[provider],+ };+ // xAI 的旧 safeStorage blob 也是 Cindy 自己完成的 OAuth,不是本机 CLI 继承。+ if (provider === 'xai') {+ next.selfAuthorized = { ...next.selfAuthorized, xai: ownerId };+ }+ }}writeBindings(next);}@@ -242,16 +297,18 @@ export function migrateLegacyNativeProviderAuthBindings(/*** Claim an auto-detected local CLI credential for the current owner.*- * Applies to every native provider, not just Codex. Two independent holes make+ * Applies only to Cindy's native Harness providers (Claude Code and Codex). Two independent holes make* the intended first-owner auto-connect strand forever without this repair:* - the one-shot legacy migration above can consume `legacyClaimOwner` while a* credential is not visible yet (the Codex ~/.codex reconcile hardlink is* created after startup, so its probe reads false);* - the migration only runs for cloud owners that hold the legacy namespace* claim, so local-mode owners — and cloud owners whose claim marker is- * absent — never get a chance to inherit at all, no matter how visible the- * credential is. Anthropic and xAI read their credential synchronously and- * are therefore immune to the first hole but not to the second.+ * absent — never get a chance to inherit at all, no matter how visible the credential is.+ *+ * xAI is deliberately excluded: it is a downstream provider, not a Cindy Harness. Its token may+ * only be bound by Cindy's explicit OAuth flow (or the one-time migration of a token that Cindy+ * itself stored in an older version), never by generic local-CLI detection.** This repairs exactly that: only when the slot has no owner, the credential* exists, and no OTHER account won the legacy claim. An existing binding is@@ -259,7 +316,7 @@ export function migrateLegacyNativeProviderAuthBindings(* migrateLegacyNativeProviderAuthBindings.*/export function claimDetectedNativeProviderAuth(- provider: NativeProviderId,+ provider: NativeHarnessInheritedProviderId,hasCredential: () => boolean,): boolean {const owner = getActiveAppSession().dataOwnerId;@@ -284,7 +341,11 @@ export function claimDetectedNativeProviderAuth(// 的口子。解除只有「用户再次显式授权」一条路(PR #548 review)。if (bindings.revoked && provider in bindings.revoked) return false;if (!hasCredential()) return false;- writeBindings({ ...bindings, [provider]: owner });+ writeBindings({+ ...bindings,+ sources: { ...bindings.sources, [provider]: 'native-harness-inherited' },+ [provider]: owner,+ });return true;}@@ -295,7 +356,7 @@ export function claimDetectedNativeProviderAuth(* that owner, while account switches and explicit revocation still fail closed.*/export function restoreNativeProviderAuthForRecovery(- provider: NativeProviderId,+ provider: NativeHarnessInheritedProviderId,expectedOwner: string,hasCredential: () => boolean,): boolean {@@ -307,6 +368,10 @@ export function restoreNativeProviderAuthForRecovery(if (bindings.revoked && provider in bindings.revoked) return false;if (!hasCredential()) return false;if (provider in bindings) return bindings[provider] === expectedOwner;- writeBindings({ ...bindings, [provider]: expectedOwner });+ writeBindings({+ ...bindings,+ sources: { ...bindings.sources, [provider]: 'native-harness-inherited' },+ [provider]: expectedOwner,+ });return true;}diff --git a/apps/desktop/src/main/maker-host/pi-host.ts b/apps/desktop/src/main/maker-host/pi-host.tsindex 4293c5ef37..5c1c3a47fe 100644--- a/apps/desktop/src/main/maker-host/pi-host.ts+++ b/apps/desktop/src/main/maker-host/pi-host.ts@@ -25,11 +25,21 @@ import type {AuthAdapterOptions,PiMcpServerRef,PiNativeApi,+ PiNativeModelSpec,PiNativeProviderSpec,PiNativeProvidersResult,} from '@cindy/maker-core';-import { PI_REASONING_EFFORTS } from '@cindy/model-providers';-import type { PiReasoningEffort, ProviderWireProtocol } from '@cindy/model-providers';+import {+ PI_REASONING_EFFORTS,+ runtimeCustomProviderId,+ storedCustomProviderId,+} from '@cindy/model-providers';+import piModelCatalogJson from '@cindy/model-providers/pi-model-catalog' with { type: 'json' };+import type {+ CustomProviderConfig,+ PiReasoningEffort,+ ProviderWireProtocol,+} from '@cindy/model-providers';import { getReadyBinaryPath } from '../agent-binaries/index.js';import { getPiExtraSpawnConfig } from '../mcp-integrations/piEnvironment.js';@@ -44,25 +54,31 @@ import piSystemPrompt from './pi-system-prompt.md?raw';import { createLogger } from '../logger.js';import { readMemorySettings } from './memory-settings-store.js';import { registerPiProxySession } from './pi-proxy-session-auth.js';+import { derivePiProxySessionToken } from './pi-proxy-session-token.js';import {getDesktopMcpToolApprovalPolicy,getDesktopMcpToolApprovalPresentation,} from './mcp-tool-approval-policy.js';import { getRipgrepBinaryPath, claudeUpstreamEndpoint } from './runtime-configs.js';-import { resolveXdPiGatewayWireProtocol } from './active-catalog.js';+import { getActiveCatalog, resolveXdPiGatewayWireProtocol } from './active-catalog.js';const log = createLogger('pi-host');const PI_API_KEY_ENV = 'CINDY_PI_API_KEY';+const PI_XAI_PROXY_API_KEY_ENV = 'CINDY_PI_XAI_PROXY_API_KEY';+const PI_SESSION_ID_ENV = 'CINDY_PI_SESSION_ID';+const PI_SESSION_TOKEN_ENV = 'CINDY_PI_SESSION_TOKEN';const PI_PROVIDER_AUTH_PLACEHOLDER_KEY = 'cindy-pi-provider-auth-placeholder';+/** Dedicated exact remote port for the Desktop-owned xAI compat proxy. */+export const PI_XAI_COMPAT_FORWARD_PORT = 47989;/*** 订阅 OAuth provider:网关 `cindy` 块经 compat proxy 用安全存储里的 OAuth 服务这些模型,* models.json 的 $CINDY_PI_API_KEY 只需占位(真凭证由 proxy 按 session-id 注入)。- * 自定义 BYOM provider **不在此列** —— 它们走各自原生块 + 独立 key,而网关块仍需真网关 key- * 以便会话中途切回网关模型可用,故 BYOM 会话不能写占位符毒化网关块。+ * xAI/BYOM provider **不在此列** —— 它们走各自原生块 + 独立 key,而网关块仍需真网关 key+ * 以便会话中途切回网关模型可用,故原生 provider 会话不能写占位符毒化网关块。*/-const PI_OAUTH_SUBSCRIPTION_PROVIDERS = new Set(['anthropic', 'openai', 'xai']);+const PI_OAUTH_SUBSCRIPTION_PROVIDERS = new Set(['anthropic', 'openai']);/*** 解析 pi 主执行文件绝对路径;找不到返回 null(pi 为可选实验 agent,不阻塞启动)。@@ -93,9 +109,10 @@ class DesktopPiAuthAdapter implements AuthAdapter {: { authenticated: false, errorReason: 'xai_oauth_unavailable' };}if (providerId) {+ const storageProviderId = storedCustomProviderId(providerId);try {const custom = (await listCustomProvidersWithSecureHeaders()).find(- (provider) => provider.id === providerId && provider.runtimes.pi,+ (provider) => provider.id === storageProviderId && provider.runtimes.pi,);if (custom) {const method = custom.auth?.method ?? 'apiKey';@@ -106,7 +123,7 @@ class DesktopPiAuthAdapter implements AuthAdapter {}if (method === 'apiKey') {const hasHeaderCredential = Object.keys(custom.runtimes.pi?.headers ?? {}).length > 0;- return readCustomProviderKey(providerId, 'pi') || hasHeaderCredential+ return readCustomProviderKey(storageProviderId, 'pi') || hasHeaderCredential? { authenticated: true, identity: custom.name, authSource: 'api-key' }: { authenticated: false, errorReason: 'pi_native_api_key_unavailable' };}@@ -136,13 +153,14 @@ class DesktopPiAuthAdapter implements AuthAdapter {}async getAuthEnv(options?: AuthAdapterOptions): Promise<Record<string, string>> {- // 订阅 OAuth provider 用占位符(真凭证由 compat proxy 注入)。+ // 共用 cindy provider 的订阅 OAuth 路由用占位符(真凭证由 compat proxy 注入)。if (options?.providerId && PI_OAUTH_SUBSCRIPTION_PROVIDERS.has(options.providerId)) {return { [PI_API_KEY_ENV]: PI_PROVIDER_AUTH_PLACEHOLDER_KEY };}const key = readClaudeApiKey();- // 纯 BYOM 不依赖 Cindy 登录。models.json 始终包含 gateway `cindy` 块,Pi 启动- // 会解析它,所以无网关 key 时给不可用占位值;当前原生 provider 使用独立 key。+ // xAI/BYOM 不依赖 Cindy 登录。models.json 始终包含 gateway `cindy` 块,+ // 有网关 key 就保留给会话内切回 Cindy/XD;无 key 时才用不可用占位值。+ // xAI 原生块自身使用 PI_XAI_PROXY_API_KEY_ENV,不再与网关块争用此变量。return { [PI_API_KEY_ENV]: key ?? PI_PROVIDER_AUTH_PLACEHOLDER_KEY };}}@@ -251,6 +269,87 @@ export function piNativeKeyEnvVar(providerId: string): string {return `CINDY_PI_KEY_${providerId.toUpperCase().replace(/[^A-Z0-9]+/g, '_')}`;}+interface PiCatalogModel extends PiNativeModelSpec {+ provider: string;+ baseUrl: string;+}++const piModelCatalog = piModelCatalogJson as unknown as {+ generatedAt: string;+ providers: Record<string, PiCatalogModel[]>;+};++/** Keep Cindy's historical xai/ ids while Pi's official native provider uses bare model ids. */+export function piNativeModelId(providerId: string, model: string): string {+ return providerId === 'xai' && model.startsWith('xai/')+ ? model.slice('xai/'.length)+ : model;+}++function officialPiModels(providerId: string): PiNativeModelSpec[] | null {+ const models = piModelCatalog.providers[providerId];+ if (!models) return null;+ return models.map((model) => ({+ id: model.id,+ name: model.name,+ ...(model.headers && Object.keys(model.headers).length > 0 ? { headers: model.headers } : {}),+ api: model.api,+ reasoning: model.reasoning,+ thinkingLevelMap: model.thinkingLevelMap,+ input: model.input,+ cost: model.cost,+ contextWindow: model.contextWindow,+ maxTokens: model.maxTokens,+ compat: model.compat,+ samplingParams: model.samplingParams,+ }));+}++function officialPiRouteMatches(+ providerId: string,+ baseUrl: string,+ wireProtocol: ProviderWireProtocol | undefined,+): boolean {+ const models = piModelCatalog.providers[providerId];+ if (!models?.length) return false;+ const baseUrls = new Set(models.map((model) => model.baseUrl.replace(/\/+$/, '')));+ const apis = new Set(models.map((model) => model.api));+ return baseUrls.size === 1+ && baseUrls.has(baseUrl.trim().replace(/\/+$/, ''))+ && apis.size === 1+ && apis.has(wireProtocolToPiApi(wireProtocol));+}++function configuredPiModel(model: {+ id: string;+ name?: string;+ contextWindow?: number;+ supportsImageInput?: boolean;+ reasoning?: boolean;+ reasoningEfforts?: PiReasoningEffort[];+}): PiNativeModelSpec {+ const supportedEfforts = new Set(model.reasoningEfforts ?? []);+ return {+ id: model.id,+ name: model.name,+ contextWindow: model.contextWindow,+ ...(model.supportsImageInput === true+ ? { input: ['text', 'image'] as Array<'text' | 'image'> }+ : {}),+ ...(model.reasoning === true+ ? {+ reasoning: true,+ thinkingLevelMap: Object.fromEntries(+ PI_REASONING_EFFORTS.map((effort) => [+ effort,+ supportedEfforts.has(effort) ? effort : null,+ ]),+ ),+ }+ : {}),+ };+}+/*** 纯映射:自定义 provider 配置(含 pi runtime)→ pi 原生 provider spec + env。* key 读取经 `readKey` 注入(便于单测)。规则:@@ -271,6 +370,7 @@ export function buildPiNativeProvidersFromConfigs(baseUrl: string;wireProtocol?: ProviderWireProtocol;headers?: Record<string, string>;+ piCatalogProviderId?: string;models: Array<{id: string;name?: string;@@ -335,54 +435,122 @@ export function buildPiNativeProvidersFromConfigs(}}providers.push({- id: cfg.id,+ id: runtimeCustomProviderId(cfg.id),name: cfg.name,baseUrl: rt.baseUrl,api: wireProtocolToPiApi(rt.wireProtocol),apiKeyEnvVar,...(headers && Object.keys(headers).length > 0 ? { headers } : {}),- models: rt.models.map((m) => {- const supportedEfforts = new Set(m.reasoningEfforts ?? []);- return {- id: m.id,- name: m.name,- contextWindow: m.contextWindow,- ...(m.supportsImageInput === true- ? { input: ['text', 'image'] as Array<'text' | 'image'> }- : {}),- ...(m.reasoning === true- ? {- reasoning: true,- thinkingLevelMap: Object.fromEntries(- PI_REASONING_EFFORTS.map((effort) => [- effort,- supportedEfforts.has(effort) ? effort : null,- ]),- ),- }- : {}),- };- }),+ models: (() => {+ const official = rt.piCatalogProviderId+ && officialPiRouteMatches(rt.piCatalogProviderId, rt.baseUrl, rt.wireProtocol)+ ? officialPiModels(rt.piCatalogProviderId)+ : null;+ const officialById = new Map((official ?? []).map((model) => [model.id, model]));+ // The catalog marker proves metadata only for exact matches. Models added by the user,+ // returned by modelsUrl, or retained from an older snapshot keep their saved fields.+ return rt.models.map((model) => officialById.get(model.id) ?? configuredPiModel(model));+ })(),});}return { providers, env };}+export async function buildXaiPiNativeProvider(+ model?: string,+ allowHistoricalResume = false,+ remote = false,+): Promise<PiNativeProvidersResult> {+ const catalogModels =+ getActiveCatalog().providers.find((provider) => provider.id === 'xai')?.models.pi ?? [];+ const officialById = new Map((officialPiModels('xai') ?? []).map((candidate) => [candidate.id, candidate]));+ const models = catalogModels.map((catalogModel) => ({+ ...(officialById.get(catalogModel.id) ?? configuredPiModel({+ id: catalogModel.id,+ name: catalogModel.name,+ contextWindow: catalogModel.contextWindowVerified ? catalogModel.contextWindow : undefined,+ supportsImageInput:+ catalogModel.supportsImageInput === true+ || catalogModel.modalities?.input.includes('image') === true,+ reasoning: catalogModel.efforts.length > 0,+ reasoningEfforts: catalogModel.efforts.filter(+ (effort): effort is PiReasoningEffort => effort !== 'ultra',+ ),+ })),+ id: `xai/${catalogModel.id}`,+ // Keep the xai/ prefix on the wire so the existing compat proxy selects its Responses+ // bridge, which refreshes OAuth per request, recovers 401/403, and injects x_search.+ api: 'anthropic-messages' as const,+ }));+ const aliases = Object.fromEntries(+ catalogModels.flatMap((candidate) => [+ [candidate.id, `xai/${candidate.id}`],+ [`xai/${candidate.id}`, `xai/${candidate.id}`],+ ]),+ );+ if (model) {+ const namespacedModel = model.startsWith('xai/') ? model : `xai/${model}`;+ if (!models.some((candidate) => candidate.id === namespacedModel)) {+ if (!allowHistoricalResume) {+ throw new Error(`Pi official xAI catalog does not contain model '${model}'`);+ }+ // Resume compatibility only: preserve the historical id and route it through the same+ // proxy without asserting unverified vision/reasoning capabilities or publishing it.+ models.push({ id: namespacedModel, name: namespacedModel, api: 'anthropic-messages' });+ aliases[model] = namespacedModel;+ aliases[piNativeModelId('xai', model)] = namespacedModel;+ }+ }+ return {+ providers: [{+ id: 'xai',+ name: 'xAI',+ baseUrl: remote+ ? (() => {+ const endpoint = new URL(getClaudeEndpoint());+ endpoint.hostname = '127.0.0.1';+ endpoint.port = String(PI_XAI_COMPAT_FORWARD_PORT);+ return endpoint.toString().replace(/\/$/, '');+ })()+ : getClaudeEndpoint(),+ api: 'anthropic-messages',+ apiKeyEnvVar: PI_XAI_PROXY_API_KEY_ENV,+ headers: {+ 'x-cindy-pi-session-id': `$${PI_SESSION_ID_ENV}`,+ 'x-cindy-pi-session-token': `$${PI_SESSION_TOKEN_ENV}`,+ },+ models,+ modelIdAliases: aliases,+ ...(remote+ ? {+ hostProxyForward: {+ localUrl: getClaudeEndpoint(),+ remotePort: PI_XAI_COMPAT_FORWARD_PORT,+ },+ }+ : {}),+ }],+ env: { [PI_XAI_PROXY_API_KEY_ENV]: PI_PROVIDER_AUTH_PLACEHOLDER_KEY },+ };+}+/** BYOM:读 DB 自定义 provider + safeStorage key → pi 原生 provider spec。IO 外壳,逻辑在上面。 */-async function resolvePiNativeProviders(ctx?: {- workingDir?: string;+export async function resolvePiNativeProviders(ctx: {+ workingDir: string;remoteHostId?: string | null;+ providerId?: string | null;+ model: string;+ resumeSessionId?: string;}): Promise<PiNativeProvidersResult> {- let configs;+ let configs: CustomProviderConfig[] = [];try {configs = await listCustomProvidersWithSecureHeaders();} catch (err) {- log.warn('resolvePiNativeProviders: listCustomProviders failed, gateway-only', {+ log.warn('resolvePiNativeProviders: listCustomProviders failed, continuing without custom providers', {message: err instanceof Error ? err.message : String(err),});- return { providers: [], env: {} };}- const isRemote = Boolean(ctx?.remoteHostId);+ const isRemote = Boolean(ctx.remoteHostId);// 远端会话:本地 loopback 端点(本机 Ollama/vLLM)远端够不到。// 轮 42 P2(codex-connector):**不再 pre-filter 掉** —— 让 PiAgent 的// [REMOTE_LOCAL_ONLY_PROVIDER] guard 显式拒绝, 用户才能拿到带行动指引的@@ -399,9 +567,26 @@ async function resolvePiNativeProviders(ctx?: {}}}- return buildPiNativeProvidersFromConfigs(configs, readCustomProviderKey, (id, reason) => {- log.warn('resolvePiNativeProviders: skipped custom provider', { id, reason });- });++ const custom = buildPiNativeProvidersFromConfigs(+ configs,+ readCustomProviderKey,+ (id, reason) =>+ log.warn('resolvePiNativeProviders: skipped custom provider', { id, reason }),+ );+ // `xai` is exclusively the official SuperGrok identity. Historical custom connections are+ // migrated to the runtime-only `custom:xai` id, so resume/login/model overlap must never infer+ // provenance or relabel a user endpoint as official (or vice versa).+ if (ctx.providerId === 'xai' || hasGrokOAuthLogin()) {+ const selectedXaiModel = ctx.providerId === 'xai'+ || (!ctx.providerId && ctx.model.startsWith('xai/'))+ ? ctx.model+ : undefined;+ const xai = await buildXaiPiNativeProvider(selectedXaiModel, !!ctx.resumeSessionId, isRemote);+ custom.providers.push(...xai.providers);+ Object.assign(custom.env, xai.env);+ }+ return custom;}/** baseUrl 是否指向本机 loopback(与本机 proxy 同判定,远端会话不可达)。@@ -435,6 +620,7 @@ export function buildPiAgent(opts: BuildPiAgentOpts): PiAgent | null {logger: opts.logger,turnChangeCapture: opts.turnChangeCapture,registerLocalAgentProcess: opts.registerLocalAgentProcess,+ derivePiProxySessionToken,capabilityAdditions: opts.capabilityAdditions,reviewAutoPermissionAction: opts.reviewAutoPermissionAction,mcpProviders: opts.mcpProviders,diff --git a/apps/desktop/src/main/maker-host/pi-proxy-session-auth.ts b/apps/desktop/src/main/maker-host/pi-proxy-session-auth.tsindex 6ef57baf6c..bcd55cab03 100644--- a/apps/desktop/src/main/maker-host/pi-proxy-session-auth.ts+++ b/apps/desktop/src/main/maker-host/pi-proxy-session-auth.ts@@ -9,18 +9,25 @@import { timingSafeEqual } from 'node:crypto';-const activeTokens = new Map<string, string>();+interface PiProxySessionRegistration {+ token: string;+}++const activeRegistrations = new Map<string, PiProxySessionRegistration>();export function registerPiProxySession(sessionId: string, token: string): () => void {if (!sessionId || !token) throw new Error('Pi proxy session registration requires an id and token');- activeTokens.set(sessionId, token);+ const registration = { token };+ activeRegistrations.set(sessionId, registration);return () => {- if (activeTokens.get(sessionId) === token) activeTokens.delete(sessionId);+ if (activeRegistrations.get(sessionId) === registration) {+ activeRegistrations.delete(sessionId);+ }};}export function authenticatePiProxySession(sessionId: string, candidate: string | null): boolean {- const expected = activeTokens.get(sessionId);+ const expected = activeRegistrations.get(sessionId)?.token;if (!expected || !candidate) return false;const expectedBytes = Buffer.from(expected);const candidateBytes = Buffer.from(candidate);@@ -30,5 +37,5 @@ export function authenticatePiProxySession(sessionId: string, candidate: string/** Test isolation only. */export function resetPiProxySessionsForTest(): void {- activeTokens.clear();+ activeRegistrations.clear();}diff --git a/apps/desktop/src/main/maker-host/pi-proxy-session-token.ts b/apps/desktop/src/main/maker-host/pi-proxy-session-token.tsnew file mode 100644index 0000000000..597aacd83e--- /dev/null+++ b/apps/desktop/src/main/maker-host/pi-proxy-session-token.ts@@ -0,0 +1,57 @@+/**+ * Restart-stable remote Pi proxy authentication.+ *+ * The HMAC key is owner-scoped and encrypted by Electron safeStorage. Only a+ * derived per-session token is passed to the remote Pi daemon; the host key+ * never leaves Desktop. Account-boundary secret clearing rotates the key and+ * invalidates the process cache so an old owner's daemon cannot authenticate.+ */+import { createHmac, randomBytes } from 'node:crypto';++import {+ addProviderSecretsClearedListener,+ readPiProxyDerivationKey,+ writePiProxyDerivationKey,+} from '../secrets/providerSecretStore.js';++const KEY_RE = /^[a-f0-9]{64}$/;+let cachedKey: string | null | undefined;+let unregisterClearListener: (() => void) | null = null;++function ensureClearListener(): void {+ if (unregisterClearListener) return;+ unregisterClearListener = addProviderSecretsClearedListener(() => {+ cachedKey = undefined;+ });+}++function getOrCreateDerivationKey(): string | null {+ ensureClearListener();+ if (cachedKey !== undefined) return cachedKey;+ const existing = readPiProxyDerivationKey();+ if (existing && KEY_RE.test(existing)) {+ cachedKey = existing;+ return existing;+ }+ const created = randomBytes(32).toString('hex');+ if (!writePiProxyDerivationKey(created)) return null;+ cachedKey = created;+ return created;+}++export function derivePiProxySessionToken(sessionId: string): string {+ const key = getOrCreateDerivationKey();+ if (!key) {+ throw new Error(+ '[PI_PROXY_DERIVATION_KEY_UNAVAILABLE] Cannot persist remote Pi proxy authentication; reconnect after secure storage becomes available.',+ );+ }+ return createHmac('sha256', key).update(sessionId).digest('base64url');+}++/** Test-only process restart simulation; does not delete the persisted key. */+export function resetPiProxyDerivationKeyCacheForTests(): void {+ cachedKey = undefined;+ unregisterClearListener?.();+ unregisterClearListener = null;+}diff --git a/apps/desktop/src/main/maker-host/pi-remote-provider-forward.ts b/apps/desktop/src/main/maker-host/pi-remote-provider-forward.tsnew file mode 100644index 0000000000..e24cbe40bd--- /dev/null+++ b/apps/desktop/src/main/maker-host/pi-remote-provider-forward.ts@@ -0,0 +1,82 @@+import type { RemoteForward, RemoteForwardSpec } from '@cindy/maker-remote-ssh';++interface ProviderForwardEntry {+ pending: Promise<RemoteForward>;+ handle?: RemoteForward;+}++export interface PiRemoteProviderForwardLease {+ ensure(spec: { localUrl: string; remotePort: number }): Promise<void>;+ releaseAll(): Promise<void>;+}++/**+ * Owns the remote-forward handles acquired by one Pi transport wrapper.+ * RemoteHost deduplicates the tunnel but returns one ref-counted handle per+ * call, so an old reattach wrapper cannot release its replacement's handle.+ */+export function createPiRemoteProviderForwardLease(+ ensureRemoteForward: (spec: RemoteForwardSpec) => Promise<RemoteForward>,+): PiRemoteProviderForwardLease {+ const entries = new Map<string, ProviderForwardEntry>();+ let released = false;++ const releaseEntry = async ({ pending, handle }: ProviderForwardEntry): Promise<void> => {+ let resolved = handle;+ if (!resolved) {+ try {+ resolved = await pending;+ } catch {+ return;+ }+ }+ await resolved.close();+ };++ return {+ async ensure(spec) {+ if (released) {+ throw new Error('pi host proxy forward cannot be established after transport cleanup');+ }+ const local = new URL(spec.localUrl);+ const localHost = local.hostname.replace(/^\[|\]$/g, '');+ const localPort = Number(local.port);+ if (+ !['127.0.0.1', '::1', 'localhost'].includes(localHost) ||+ !Number.isInteger(localPort) ||+ localPort <= 0+ ) {+ throw new Error(`pi host proxy forward requires an explicit loopback port: ${spec.localUrl}`);+ }+ const entryId = [`${localHost}:${localPort}`, String(spec.remotePort)].join('\0');+ const existing = entries.get(entryId);+ if (existing) {+ await existing.pending;+ return;+ }++ const pending = ensureRemoteForward({+ localHost,+ localPort,+ preferredRemotePort: spec.remotePort,+ exactRemotePort: true,+ });+ const entry = { pending, handle: undefined as RemoteForward | undefined };+ entries.set(entryId, entry);+ try {+ entry.handle = await pending;+ } catch (error) {+ if (entries.get(entryId) === entry) entries.delete(entryId);+ throw error;+ }+ },++ async releaseAll() {+ if (released) return;+ released = true;+ const ownedEntries = Array.from(entries.values());+ entries.clear();+ await Promise.all(ownedEntries.map(releaseEntry));+ },+ };+}diff --git a/apps/desktop/src/main/maker-host/provider-model-auto-refresh.ts b/apps/desktop/src/main/maker-host/provider-model-auto-refresh.tsindex ada68f3471..84780c92ef 100644--- a/apps/desktop/src/main/maker-host/provider-model-auto-refresh.ts+++ b/apps/desktop/src/main/maker-host/provider-model-auto-refresh.ts@@ -292,6 +292,8 @@ export function createProviderModelRefreshCoordinator(}const requestedIds = providerIds ?? BUILTIN_REFRESHABLE_PROVIDER_IDS;+ // Public Catalog refreshes metadata; each connected account still refreshes its own+ // authoritative membership independently, including xAI `/user` → `/models`.const ids = requestedIds.filter((id) => connectedIds.has(id));// 启动期无视冷却(见 `'startup'` trigger 注释);in-flight 合并仍生效,所以并发的// 启动触发与手动刷新不会各起一次 codex app-server。diff --git a/apps/desktop/src/main/maker-host/provider-model-refresh.ts b/apps/desktop/src/main/maker-host/provider-model-refresh.tsindex 331c4a0776..d6fc81343f 100644--- a/apps/desktop/src/main/maker-host/provider-model-refresh.ts+++ b/apps/desktop/src/main/maker-host/provider-model-refresh.ts@@ -11,6 +11,7 @@ export interface BuiltinProviderModelRefreshDeps {refreshXd(): Promise<void>;refreshAnthropic(): Promise<boolean>;refreshOpenAi(): Promise<boolean>;+ refreshXai(): Promise<boolean>;refreshXaiMedia(): Promise<boolean>;}@@ -33,8 +34,12 @@ export async function refreshBuiltinProviderModels(}return;case 'xai':+ if (!(await deps.refreshXai())) {+ throw new Error('xAI account model discovery did not apply to the current runtime');+ }if (!(await deps.refreshXaiMedia())) {throw new Error('xAI media model discovery did not produce a current snapshot');}+ return;}}diff --git a/apps/desktop/src/main/maker-host/provider-route.ts b/apps/desktop/src/main/maker-host/provider-route.tsindex 842f00e9f9..c69243af02 100644--- a/apps/desktop/src/main/maker-host/provider-route.ts+++ b/apps/desktop/src/main/maker-host/provider-route.ts@@ -21,6 +21,8 @@import {actualSourceIdForModel,+ runtimeCustomProviderId,+ storedCustomProviderId,type AgentKind,type Provider,type ProviderView,@@ -59,6 +61,7 @@ export function setCustomProviderKeyReader(reader: CustomProviderKeyReader): voi* mutation 之间不会短暂恢复路由。*/export function beginProviderRouteMutation(providerId: string): () => void {+ providerId = runtimeCustomProviderId(providerId);providerRouteMutationCounts.set(providerId,(providerRouteMutationCounts.get(providerId) ?? 0) + 1,@@ -74,7 +77,7 @@ export function beginProviderRouteMutation(providerId: string): () => void {}export function isProviderRouteMutationInProgress(providerId: string): boolean {- return providerRouteMutationCounts.has(providerId);+ return providerRouteMutationCounts.has(runtimeCustomProviderId(providerId));}/**@@ -95,7 +98,7 @@ export function setOAuthTokenReader(reader: OAuthTokenReader): void {/** 查询自定义供应商该 runtime 是否已有可注入的 API key(不暴露明文)。 */export function hasCustomProviderKey(providerId: string, agent: AgentKind): boolean {if (isProviderRouteMutationInProgress(providerId)) return false;- return Boolean(customProviderKeyReader(providerId, agent));+ return Boolean(customProviderKeyReader(storedCustomProviderId(providerId), agent));}export interface ProviderOAuthTokenReadOptions {@@ -620,10 +623,13 @@ async function readProviderRouteCredentials(routing: RoutingDescriptor,agent: AgentKind,): Promise<{ apiKey: string | null; oauthToken: string | null }> {- const apiKey = provider.source === 'user' ? customProviderKeyReader(provider.id, agent) : null;+ const credentialProviderId =+ provider.source === 'user' ? storedCustomProviderId(provider.id) : provider.id;+ const apiKey =+ provider.source === 'user' ? customProviderKeyReader(credentialProviderId, agent) : null;let oauthToken: string | null = null;if (routing.authStrategy === 'oauth-token') {- oauthToken = oauthTokenReader(provider.id);+ oauthToken = oauthTokenReader(credentialProviderId);} else if (routing.authStrategy === 'provider-oauth-header') {try {oauthToken = await providerOAuthTokenReader(provider.id, agent);@@ -682,7 +688,10 @@ export function resolveSessionRouteDecision(if (pendingDecision) return pendingDecision;if (!routingServesWireModel(routing, wireModel)) return null;// 自定义供应商:resolve 时按 provider_key_<id>_<agent> 读出该 runtime 的 API key 注入鉴权头(不在 catalog)。- const apiKey = provider?.source === 'user' ? customProviderKeyReader(providerId, agent) : null;+ const credentialProviderId =+ provider?.source === 'user' ? storedCustomProviderId(providerId) : providerId;+ const apiKey =+ provider?.source === 'user' ? customProviderKeyReader(credentialProviderId, agent) : null;const withRequestPath = (decision: RoutingDecision | null): RoutingDecision | null =>decision && wireModel && routing.requestPath? { ...decision, pathOverride: routing.requestPath }@@ -691,7 +700,13 @@ export function resolveSessionRouteDecision(// (临期刷新在后台单飞,不阻塞路由热路径,规则 10)。if (routing.authStrategy === 'oauth-token') {return withRequestPath(- buildRouteDecision(routing, gatewayKey, agent, apiKey, oauthTokenReader(providerId)),+ buildRouteDecision(+ routing,+ gatewayKey,+ agent,+ apiKey,+ oauthTokenReader(credentialProviderId),+ ),);}if (routing.authStrategy !== 'provider-oauth-header') {diff --git a/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.tsindex d15e3783b2..1ef160d80f 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts@@ -1392,6 +1392,58 @@ describe('provider:custom:* CRUD handlers', () => {expect(deps.refreshCatalog).not.toHaveBeenCalled();});+ it('reserves xai for new providers while preserving edits to an existing legacy row', async () => {+ mountDb();+ const harness = new IpcHarness();+ const deps = makeDeps({+ stageClearProviderDisableOverrides: vi.fn(() => () => true),+ });+ registerProviderHandlers(harness, deps);+ const legacyXai: CustomProviderConfig = {+ id: 'xai',+ name: 'Legacy custom xAI',+ auth: { method: 'apiKey' },+ runtimes: {+ pi: {+ baseUrl: 'https://private-xai.example/v1',+ models: [{ id: 'private-grok', name: 'Private Grok' }],+ },+ },+ };++ await expect(harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_CREATE, legacyXai)).rejects.toThrow(+ /INVALID_PARAMS/,+ );++ raw!+ .prepare(+ `INSERT INTO custom_providers+ (id, name, runtimes, auth, sort_order, created_at, updated_at)+ VALUES (?, ?, ?, ?, 0, 1, 1)`,+ )+ .run(+ legacyXai.id,+ legacyXai.name,+ JSON.stringify(legacyXai.runtimes),+ JSON.stringify(legacyXai.auth),+ );++ await expect(+ harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_UPDATE, {+ ...legacyXai,+ name: 'Legacy custom xAI edited',+ }),+ ).resolves.toEqual({ ok: true });+ expect((await listCustomProviders())[0]?.name).toBe('Legacy custom xAI edited');++ await expect(+ harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_DELETE, 'xai'),+ ).resolves.toEqual({ ok: true });+ expect(deps.stageClearProviderDisableOverrides).toHaveBeenCalledWith('custom:xai');+ expect(deps.stageClearProviderModelPriceOverrides).toHaveBeenCalledWith('custom:xai');+ expect(await listCustomProviders()).toEqual([]);+ });+it('rejects duplicate id with ALREADY_EXISTS', async () => {mountDb();const harness = new IpcHarness();diff --git a/apps/desktop/src/main/maker-ipc/providerHandlers.ts b/apps/desktop/src/main/maker-ipc/providerHandlers.tsindex f6135c0312..9c2b102b09 100644--- a/apps/desktop/src/main/maker-ipc/providerHandlers.ts+++ b/apps/desktop/src/main/maker-ipc/providerHandlers.ts@@ -17,6 +17,7 @@import {isLoopbackProviderUrl,isProviderRequestPath,+ runtimeCustomProviderId,type AgentKind,type CustomProviderConfig,type ProviderModelDiscoveryFailure,@@ -1314,7 +1315,7 @@ export function registerProviderHandlers(registry.handle(MAKER_INVOKE.PROVIDER_CUSTOM_UPDATE, async (event, input: unknown, keyInput?: unknown) => {assertTrustedProviderMutationSender(event);- const v = validateCustomProviderConfig(input);+ const v = validateCustomProviderConfig(input, { allowLegacyXai: true });if (!v.ok) throwIpcError(v.code, v.message);const keys = parseRuntimeKeys(keyInput);if (!keys) throwIpcError('INVALID_PARAMS', 'invalid provider runtime keys');@@ -1401,6 +1402,7 @@ export function registerProviderHandlers(if (typeof providerId !== 'string' || providerId.length === 0) {throwIpcError('INVALID_PARAMS', 'providerId required');}+ const runtimeProviderId = runtimeCustomProviderId(providerId);const ownerAtIngress = captureProviderOwnerSession();return withProviderConfigMutation(providerId, async () => {// 同类 delete 也会在 per-provider 队列后写 owner-scoped 凭证。@@ -1439,9 +1441,9 @@ export function registerProviderHandlers(// 由恢复函数把停用状态原样写回;清理自身抛错时事务未产生破坏,删除中止,// 不再出现「配置删了、override 残留」让同 id 重建复活旧停用状态。restoreDisableOverrides =- deps.stageClearProviderDisableOverrides?.(providerId) ?? null;+ deps.stageClearProviderDisableOverrides?.(runtimeProviderId) ?? null;restorePriceOverrides =- deps.stageClearProviderModelPriceOverrides?.(providerId) ?? null;+ deps.stageClearProviderModelPriceOverrides?.(runtimeProviderId) ?? null;assertProviderMutationOwner(ownerAtIngress);restoreOAuthCredentials = deps.removeOAuthCredentials(providerId);if (!restoreOAuthCredentials) {diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex a94c41c1cd..176e7b930f 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -28,6 +28,7 @@ import type {SessionSendResult,UserMessage,} from '@cindy/maker-core';+import { storedCustomProviderId } from '@cindy/model-providers';import { createId } from '@paralleldrive/cuid2';import { redactSensitiveText } from '@cindy/maker-shared/error-redaction';import { permissionModeOrAsk } from '@cindy/maker-shared/permission-mode';@@ -702,6 +703,7 @@ import {getAnthropicModelDiscoveryFailure,refreshAnthropicModelsFromHttp,} from '../maker-host/model-discovery/anthropic.js';+import { refreshXaiModelsFromHttp } from '../maker-host/model-discovery/xai.js';import { refreshBuiltinProviderModels } from '../maker-host/provider-model-refresh.js';import {configureProviderModelAutoRefresh,@@ -5672,6 +5674,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)refreshAnthropic: refreshAnthropicModelsFromHttp,refreshOpenAi: () =>maker.refreshAgentLocalModels('codex', { credentialMode: 'oauth-bearer' }),+ refreshXai: refreshXaiModelsFromHttp,refreshXaiMedia: refreshXaiMediaModels,}),});@@ -5744,17 +5747,23 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)const provider = getActiveCatalog().providers.find((p) => p.id === providerId);const oauth = provider?.auth.oauth;if (!provider || !oauth) throw new Error(`provider '${providerId}' has no oauth descriptor`);+ const storageProviderId =+ provider.source === 'user' ? storedCustomProviderId(providerId) : providerId;let rollbackCredentials: (() => boolean) | undefined;- const result = await runGenericOAuthLogin({ id: provider.id, name: provider.name }, oauth, {- onProgress: (progress) =>- broadcastToAllWindows(MAKER_PUSH.PROVIDER_OAUTH_PROGRESS, {- providerId,- ...progress,- }),- onCredentialPersisted: (rollback) => {- rollbackCredentials = rollback;+ const result = await runGenericOAuthLogin(+ { id: storageProviderId, name: provider.name },+ oauth,+ {+ onProgress: (progress) =>+ broadcastToAllWindows(MAKER_PUSH.PROVIDER_OAUTH_PROGRESS, {+ providerId,+ ...progress,+ }),+ onCredentialPersisted: (rollback) => {+ rollbackCredentials = rollback;+ },},- });+ );if (result.ok && isCurrent()) {// 授权成功后按 agent 自动发现模型(与内置订阅体验统一,用户不必手填模型):// 发现端点 = 描述符显式声明 ?? 由该 runtime 的 baseUrl 推导(…/v1/models)。@@ -5775,17 +5784,24 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// 去重键含 agent:发现请求头按 wire 分派(cc 带 anthropic-version),同 URL 不同 wire 不能共用响应。const key = `${agent}\n${url}`;if (!fetched.has(key))- fetched.set(key, await discoverGenericOAuthModels(providerId, oauth, url, agent));+ fetched.set(+ key,+ await discoverGenericOAuthModels(storageProviderId, oauth, url, agent),+ );if (!isCurrent()) break;const models = fetched.get(key);if (!models || models.length === 0) continue;if (provider.source === 'user') {- const cfg = await getCustomProvider(providerId);+ const cfg = await getCustomProvider(storageProviderId);if (!isCurrent()) break;if (cfg) {const nextCfg = mergeDiscoveredModelsIntoConfig(cfg, agent, models);if (nextCfg) {- const applied = await updateCustomProviderIfUnchanged(providerId, cfg, nextCfg);+ const applied = await updateCustomProviderIfUnchanged(+ storageProviderId,+ cfg,+ nextCfg,+ );if (!isCurrent()) break;if (applied) customChanged = true;}@@ -5828,12 +5844,13 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)storeCustomProviderKey,removeCustomProviderKey,oauthLogout: async (providerId) => {- if (!logoutGenericOAuth(providerId)) {+ if (!logoutGenericOAuth(storedCustomProviderId(providerId))) {throw new Error('failed to remove generic OAuth credentials');}},- oauthCancel: (providerId) => cancelGenericOAuthLogin(providerId),- removeOAuthCredentials: (providerId) => removeGenericOAuthCredentialsReversibly(providerId),+ oauthCancel: (providerId) => cancelGenericOAuthLogin(storedCustomProviderId(providerId)),+ removeOAuthCredentials: (providerId) =>+ removeGenericOAuthCredentialsReversibly(storedCustomProviderId(providerId)),});// 自定义 MCP 服务器 CRUD —— CRUD 成功后刷新三个 agent 的 mcpProviders 数组diff --git a/apps/desktop/src/main/secrets/__tests__/providerSecretStore.test.ts b/apps/desktop/src/main/secrets/__tests__/providerSecretStore.test.tsindex 0fc861fd07..5cc9fdb551 100644--- a/apps/desktop/src/main/secrets/__tests__/providerSecretStore.test.ts+++ b/apps/desktop/src/main/secrets/__tests__/providerSecretStore.test.ts@@ -51,7 +51,9 @@ import {deriveGhostSecretTail,GHOST_SECRET_TAIL_MIN_VALUE_CHARS,isRendererAccessibleSafeStorageKey,+ PI_PROXY_DERIVATION_KEY_STORAGE_KEY,PROVIDER_SECRET_IDS,+ REMOTE_MCP_BRIDGE_TOKEN_STORAGE_KEY,} from '../../../shared/providerSecrets';/** 内存版 SecretStorageIo:按"存储键名"读写一个 Map,模拟 safeStorage 文件层。 */@@ -105,6 +107,11 @@ describe('providerSecrets registry', () => {expect(isRendererAccessibleSafeStorageKey('PROVIDER_KEY_OPENAI_IMAGES')).toBe(false);});+ it('keeps daemon-wide remote secrets behind the main-only boundary', () => {+ expect(isRendererAccessibleSafeStorageKey(REMOTE_MCP_BRIDGE_TOKEN_STORAGE_KEY)).toBe(false);+ expect(isRendererAccessibleSafeStorageKey(PI_PROXY_DERIVATION_KEY_STORAGE_KEY)).toBe(false);+ });+it('keeps custom-provider header blobs behind the main-only boundary', () => {const key = customProviderHeaderStorageKey('my_or', 'pi');expect(key).toBe('provider_headers_my_or_pi');@@ -315,9 +322,13 @@ describe('providerSecretStore account boundary (clearAll + reconcileOwner)', ()const store = createProviderSecretStore(io);store.set('xd', 'sk-x');store.set('mivo', 'mivo_m');+ io.store.set(REMOTE_MCP_BRIDGE_TOKEN_STORAGE_KEY, 'remote-token');+ io.store.set(PI_PROXY_DERIVATION_KEY_STORAGE_KEY, 'pi-key');store.clearAll();expect(store.get('xd')).toBeNull();expect(store.get('mivo')).toBeNull();+ expect(io.store.has(REMOTE_MCP_BRIDGE_TOKEN_STORAGE_KEY)).toBe(false);+ expect(io.store.has(PI_PROXY_DERIVATION_KEY_STORAGE_KEY)).toBe(false);});it('换账号清理连带动态键名密钥:provider_oauth_* blob 与 provider_key_* 自定义 key', () => {diff --git a/apps/desktop/src/main/secrets/providerSecretStore.ts b/apps/desktop/src/main/secrets/providerSecretStore.tsindex eec8387aee..d6b6f74327 100644--- a/apps/desktop/src/main/secrets/providerSecretStore.ts+++ b/apps/desktop/src/main/secrets/providerSecretStore.ts@@ -2,6 +2,8 @@ import { app, safeStorage } from 'electron';import fs from 'node:fs';import path from 'node:path';+import { storedCustomProviderId } from '@cindy/model-providers';+import { createLogger } from '../logger.js';import {providerSecretStorageKey,@@ -17,6 +19,7 @@ import {GHOST_SECRET_PREFIX,GHOST_SECRET_HINT_PREFIX,PROVIDER_SECRET_IDS,+ PI_PROXY_DERIVATION_KEY_STORAGE_KEY,REMOTE_MCP_BRIDGE_TOKEN_STORAGE_KEY,type ProviderSecretId,} from '../../shared/providerSecrets.js';@@ -275,6 +278,7 @@ export function createProviderSecretStore(// SSH 远端 daemon 直连 MCP bridge 的 persistent token 同清:同机换账号后,// 旧账号远端 host 上仍在跑的 daemon env 里的 token 必须失效,防串号。io.remove(REMOTE_MCP_BRIDGE_TOKEN_STORAGE_KEY);+ io.remove(PI_PROXY_DERIVATION_KEY_STORAGE_KEY);// 动态键名密钥同清(按前缀扫 io.list()):自定义 MCP bearer token(mcp_token_<id>)、// 自定义供应商 per-runtime key(provider_key_*)、通用 OAuth 凭证 blob(provider_oauth_*)、// 意识 network 槽凭证(ghost_secret_*)。这些不在 PROVIDER_SECRET_IDS 静态集合里,@@ -388,8 +392,9 @@ export function getProviderSecretStore(): ProviderSecretStore {* 与 renderer 经通用 safe-storage IPC 写入的 .enc 文件字节级互通。*/export function readCustomProviderKey(providerId: string, agent: string): string | null {+ const storageProviderId = storedCustomProviderId(providerId);try {- return electronSecretIo.read(customProviderSecretStorageKey(providerId, agent));+ return electronSecretIo.read(customProviderSecretStorageKey(storageProviderId, agent));} catch (err) {log.warn({ providerId, agent, err: err instanceof Error ? err.message : String(err) },@@ -416,8 +421,9 @@ export function readCustomProviderHeaders(providerId: string,agent: string,): Record<string, string> | null {+ const storageProviderId = storedCustomProviderId(providerId);try {- const raw = electronSecretIo.read(customProviderHeaderStorageKey(providerId, agent));+ const raw = electronSecretIo.read(customProviderHeaderStorageKey(storageProviderId, agent));return raw === null ? null : parseCustomProviderHeaders(raw);} catch (err) {log.warn(@@ -566,6 +572,32 @@ export function writeRemoteMcpBridgeToken(value: string): boolean {}}+/** Read the host-only HMAC key used to derive remote Pi proxy session tokens. */+export function readPiProxyDerivationKey(): string | null {+ try {+ return electronSecretIo.read(PI_PROXY_DERIVATION_KEY_STORAGE_KEY);+ } catch (err) {+ log.warn(+ { err: err instanceof Error ? err.message : String(err) },+ 'read pi proxy derivation key failed',+ );+ return null;+ }+}++/** Persist the host-only remote Pi proxy derivation key on first use. */+export function writePiProxyDerivationKey(value: string): boolean {+ try {+ return electronSecretIo.write(PI_PROXY_DERIVATION_KEY_STORAGE_KEY, value);+ } catch (err) {+ log.warn(+ { err: err instanceof Error ? err.message : String(err) },+ 'write pi proxy derivation key failed',+ );+ return false;+ }+}+/** 删除某自定义供应商 runtime 的 API key;不存在视为成功。 */export function removeCustomProviderKey(providerId: string,diff --git a/apps/desktop/src/main/utility-model/__tests__/oneshotProviderUsability.test.ts b/apps/desktop/src/main/utility-model/__tests__/oneshotProviderUsability.test.tsindex 66d4a8d033..f215539524 100644--- a/apps/desktop/src/main/utility-model/__tests__/oneshotProviderUsability.test.ts+++ b/apps/desktop/src/main/utility-model/__tests__/oneshotProviderUsability.test.ts@@ -117,6 +117,19 @@ describe('hasOneshotProviderCredential · 自定义供应商', () => {expect(hasOneshotProviderCredential(p, 'codex')).toBe(true);});+ it('legacy custom xai 的 OAuth 凭证仍按存储 id 读取', () => {+ const oauth = { issuer: 'https://issuer.example.com' } as never;+ const p = custom(+ 'custom:xai',+ { codex: { upstream: 'https://up.example.com', authStrategy: 'oauth-token' } },+ { method: 'oauth', oauth },+ );+ vi.mocked(readCachedGenericOAuthAccessToken).mockReturnValue('cached' as never);++ expect(hasOneshotProviderCredential(p, 'codex')).toBe(true);+ expect(readCachedGenericOAuthAccessToken).toHaveBeenCalledWith('xai', oauth);+ });+it('不支持的鉴权策略 / 缺 routing → 不可用', () => {const bespoke = custom('c4', { codex: { upstream: 'https://up.example.com', authStrategy: 'bespoke' as never } });expect(hasOneshotProviderCredential(bespoke, 'codex')).toBe(false);diff --git a/apps/desktop/src/main/utility-model/oneShotCandidates.ts b/apps/desktop/src/main/utility-model/oneShotCandidates.tsindex 08b09e59df..0b99284c73 100644--- a/apps/desktop/src/main/utility-model/oneShotCandidates.ts+++ b/apps/desktop/src/main/utility-model/oneShotCandidates.ts@@ -1,7 +1,7 @@import { randomUUID } from 'node:crypto';import { type AgentKind, type Maker } from '@cindy/maker-core';-import { appendProviderRequestPath } from '@cindy/model-providers';+import { appendProviderRequestPath, storedCustomProviderId } from '@cindy/model-providers';import { createLogger } from '../logger.js';import { readClaudeApiKey } from '../maker-host/auth-adapters.js';@@ -470,7 +470,7 @@ async function requestExplicitProviderText(const isOAuth = authStrategy === 'oauth-token';const noAuth = authStrategy === 'none';const credential = isOAuth- ? readCachedGenericOAuthAccessToken(provider.id, provider.auth.oauth)+ ? readCachedGenericOAuthAccessToken(storedCustomProviderId(provider.id), provider.auth.oauth): noAuth? null: readCustomProviderKey(provider.id, agentKind);diff --git a/apps/desktop/src/main/utility-model/oneshotProviderUsability.ts b/apps/desktop/src/main/utility-model/oneshotProviderUsability.tsindex ff7c3464de..cf28d411c2 100644--- a/apps/desktop/src/main/utility-model/oneshotProviderUsability.ts+++ b/apps/desktop/src/main/utility-model/oneshotProviderUsability.ts@@ -6,7 +6,7 @@* 选项是清单的失职。这里全部走同步缓存态(cindy-prefs 读 handler 是 sendSync,* 不能 async);它是展示层过滤,不是安全边界——执行侧仍逐候选现查现验。*/-import type { AgentKind, Provider } from '@cindy/model-providers';+import { storedCustomProviderId, type AgentKind, type Provider } from '@cindy/model-providers';import { readClaudeApiKey } from '../maker-host/auth-adapters.js';import { getClaudeAiOAuthForSpawn } from '../maker-host/claude-oauth-refresh.js';@@ -39,7 +39,10 @@ export function hasOneshotProviderCredential(provider: Provider, agentKind: Agenif (!routing) return false;if (routing.authStrategy === 'none') return true;if (routing.authStrategy === 'oauth-token') {- return readCachedGenericOAuthAccessToken(provider.id, provider.auth?.oauth) != null;+ return readCachedGenericOAuthAccessToken(+ storedCustomProviderId(provider.id),+ provider.auth?.oauth,+ ) != null;}if (routing.authStrategy === 'api-key-header') {if (readCustomProviderKey(provider.id, agentKind)) return true;diff --git a/apps/desktop/src/renderer/__tests__/addProviderWizardPresetEntry.test.tsx b/apps/desktop/src/renderer/__tests__/addProviderWizardPresetEntry.test.tsxindex 5e5fa06f76..86ce595b14 100644--- a/apps/desktop/src/renderer/__tests__/addProviderWizardPresetEntry.test.tsx+++ b/apps/desktop/src/renderer/__tests__/addProviderWizardPresetEntry.test.tsx@@ -141,6 +141,7 @@ const piReasoningPreset = {name: 'Reasoning Model',reasoning: true,reasoningEfforts: ['low', 'high'] as const,+ reasoningDefaultEffort: 'high' as const,},],},@@ -380,6 +381,7 @@ describe('AddProviderWizard — preset 直达', () => {id: 'reasoning-model',reasoning: true,reasoningEfforts: ['low', 'high'],+ reasoningDefaultEffort: 'high',}),]);});diff --git a/apps/desktop/src/renderer/__tests__/customProviderDialogPresetLocale.test.tsx b/apps/desktop/src/renderer/__tests__/customProviderDialogPresetLocale.test.tsxindex be221f2cfc..3922b930f7 100644--- a/apps/desktop/src/renderer/__tests__/customProviderDialogPresetLocale.test.tsx+++ b/apps/desktop/src/renderer/__tests__/customProviderDialogPresetLocale.test.tsx@@ -25,6 +25,15 @@ vi.mock('@/lib/customProviderId', () => ({vi.mock('@/lib/customProviders', () => ({createCustomProvider: vi.fn(async () => undefined),+ piCatalogProviderIdAfterRouteEdit: (+ _agent: string,+ previous: { baseUrl: string; wireProtocol: string; piCatalogProviderId?: string },+ next: { baseUrl: string; wireProtocol: string; piCatalogProviderId?: string },+ ) =>+ next.piCatalogProviderId === previous.piCatalogProviderId+ && (next.baseUrl !== previous.baseUrl || next.wireProtocol !== previous.wireProtocol)+ ? undefined+ : next.piCatalogProviderId,readCustomProviderKey: vi.fn(),replaceCustomProviderModelId: vi.fn(),setCustomProviderModelReasoning: vi.fn(),diff --git a/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx b/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsxindex 00cc866b76..ded7b4f9dd 100644--- a/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx+++ b/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx@@ -792,6 +792,9 @@ export function AddProviderWizard({? {reasoning: true,reasoningEfforts: [...presetModel.reasoningEfforts],+ ...(presetModel.reasoningDefaultEffort+ ? { reasoningDefaultEffort: presetModel.reasoningDefaultEffort }+ : {}),}: {}),};@@ -804,6 +807,7 @@ export function AddProviderWizard({models: agentModels,...(rt.headers ? { headers: rt.headers } : {}),...(rt.modelsUrl ? { modelsUrl: rt.modelsUrl } : {}),+ ...(rt.piCatalogProviderId ? { piCatalogProviderId: rt.piCatalogProviderId } : {}),};if (preset.authMethod !== 'none') {const k = apiKey.trim();diff --git a/apps/desktop/src/renderer/components/settings/CustomProviderDialog.tsx b/apps/desktop/src/renderer/components/settings/CustomProviderDialog.tsxindex 53d09b62c7..bf3f37242d 100644--- a/apps/desktop/src/renderer/components/settings/CustomProviderDialog.tsx+++ b/apps/desktop/src/renderer/components/settings/CustomProviderDialog.tsx@@ -40,6 +40,7 @@ import {import { extractIpcError } from '@/utils/ipcError';import {createCustomProvider,+ piCatalogProviderIdAfterRouteEdit,readCustomProviderKey,replaceCustomProviderModelId,setCustomProviderModelReasoning,@@ -172,6 +173,8 @@ interface RuntimeFields extends RuntimeFillDraft {headers: HeaderRow[];/** 隐藏字段:列模型端点(预设 / 已存配置快照进来),「获取模型列表」用;不在表单展示。 */modelsUrl: string;+ /** 隐藏字段:从 Pi 官方目录生成该 runtime;编辑保存必须无损保留。 */+ piCatalogProviderId?: string;}/** 每个 runtime Tab 的「测试连接」状态(idle → testing → ok/fail)。 */@@ -192,6 +195,7 @@ function emptyRuntime(agent: DialogAgentKind): RuntimeFields {models: [{ id: '', name: '' }],headers: [{ name: '', value: '' }],modelsUrl: '',+ piCatalogProviderId: undefined,};}@@ -216,6 +220,7 @@ function initRuntimes(initial?: CustomProviderConfig): Record<DialogAgentKind, R? Object.entries(rc.headers).map(([n, v]) => ({ name: n, value: v })): [{ name: '', value: '' }],modelsUrl: rc.modelsUrl ?? '',+ piCatalogProviderId: rc.piCatalogProviderId,headersState: rc.headersState,};}@@ -504,9 +509,13 @@ export function CustomProviderDialog({const setRtSynced = useCallback((fn: (prev: Record<DialogAgentKind, RuntimeFields>) => Record<DialogAgentKind, RuntimeFields>) => {setRt((prev) => {- const next = fn(prev);- rtRef.current = next;- return next;+ const updated = fn(prev);+ // Do not consume the catalog marker while the user is still editing.+ // A temporary route/model change can be reverted before Save; marker+ // ownership is decided once below from the persisted baseline and the+ // final serialized values.+ rtRef.current = updated;+ return updated;});},[],@@ -628,6 +637,7 @@ export function CustomProviderDialog({? Object.entries(rc.headers).map(([n, v]) => ({ name: n, value: v })): [{ name: '', value: '' }],modelsUrl: rc.modelsUrl ?? '',+ piCatalogProviderId: rc.piCatalogProviderId,};}return next;@@ -1112,7 +1122,13 @@ export function CustomProviderDialog({...(m.defaultEnabled === false ? { defaultEnabled: false } : {}),...(m.supportsImageInput === true ? { supportsImageInput: true } : {}),...(m.reasoning === true && m.reasoningEfforts?.length- ? { reasoning: true, reasoningEfforts: [...m.reasoningEfforts] }+ ? {+ reasoning: true,+ reasoningEfforts: [...m.reasoningEfforts],+ ...(m.reasoningDefaultEffort+ ? { reasoningDefaultEffort: m.reasoningDefaultEffort }+ : {}),+ }: {}),})).filter((m) => m.id.length > 0);@@ -1136,7 +1152,13 @@ export function CustomProviderDialog({...(cur?.defaultEnabled === false ? { defaultEnabled: false } : {}),...(cur?.supportsImageInput === true ? { supportsImageInput: true } : {}),...(cur?.reasoning === true && cur.reasoningEfforts?.length- ? { reasoning: true, reasoningEfforts: [...cur.reasoningEfforts] }+ ? {+ reasoning: true,+ reasoningEfforts: [...cur.reasoningEfforts],+ ...(cur.reasoningDefaultEffort+ ? { reasoningDefaultEffort: cur.reasoningDefaultEffort }+ : {}),+ }: {}),};}),@@ -1196,6 +1218,9 @@ export function CustomProviderDialog({const supportsImageInput = latest ? latest.supportsImageInput : m.supportsImageInput;const reasoning = latest ? latest.reasoning : m.reasoning;const reasoningEfforts = latest ? latest.reasoningEfforts : m.reasoningEfforts;+ const reasoningDefaultEffort = latest+ ? latest.reasoningDefaultEffort+ : m.reasoningDefaultEffort;return {id: m.id,name: latest?.name.trim() ? latest.name.trim() : m.name,@@ -1203,7 +1228,13 @@ export function CustomProviderDialog({...(defaultEnabled === false ? { defaultEnabled: false } : {}),...(supportsImageInput === true ? { supportsImageInput: true } : {}),...(reasoning === true && reasoningEfforts?.length- ? { reasoning: true, reasoningEfforts: [...reasoningEfforts] }+ ? {+ reasoning: true,+ reasoningEfforts: [...reasoningEfforts],+ ...(reasoningDefaultEffort+ ? { reasoningDefaultEffort }+ : {}),+ }: {}),};});@@ -1217,7 +1248,13 @@ export function CustomProviderDialog({...(m.defaultEnabled === false ? { defaultEnabled: false } : {}),...(m.supportsImageInput === true ? { supportsImageInput: true } : {}),...(m.reasoning === true && m.reasoningEfforts?.length- ? { reasoning: true, reasoningEfforts: [...m.reasoningEfforts] }+ ? {+ reasoning: true,+ reasoningEfforts: [...m.reasoningEfforts],+ ...(m.reasoningDefaultEffort+ ? { reasoningDefaultEffort: m.reasoningDefaultEffort }+ : {}),+ }: {}),});}@@ -1345,7 +1382,13 @@ export function CustomProviderDialog({...(m.defaultEnabled === false ? { defaultEnabled: false } : {}),...(m.supportsImageInput === true ? { supportsImageInput: true } : {}),...(m.reasoning === true && m.reasoningEfforts?.length- ? { reasoning: true, reasoningEfforts: [...m.reasoningEfforts] }+ ? {+ reasoning: true,+ reasoningEfforts: [...m.reasoningEfforts],+ ...(m.reasoningDefaultEffort+ ? { reasoningDefaultEffort: m.reasoningDefaultEffort }+ : {}),+ }: {}),})).filter((m) => m.id && m.name);@@ -1375,7 +1418,22 @@ export function CustomProviderDialog({models,...(Object.keys(savedHeaders).length > 0 ? { headers: savedHeaders } : {}),...(rf.modelsUrl.trim() ? { modelsUrl: rf.modelsUrl.trim() } : {}),+ ...(a === 'pi' && rf.piCatalogProviderId+ ? { piCatalogProviderId: rf.piCatalogProviderId }+ : {}),};+ if (a === 'pi' && initial?.runtimes.pi?.piCatalogProviderId) {+ const savedPiCatalogProviderId = piCatalogProviderIdAfterRouteEdit(+ a,+ initial.runtimes.pi,+ runtimes.pi!,+ );+ if (savedPiCatalogProviderId) {+ runtimes.pi!.piCatalogProviderId = savedPiCatalogProviderId;+ } else {+ delete runtimes.pi!.piCatalogProviderId;+ }+ }// OAuth 形态不收集 per-runtime API key(鉴权走 Runner 的 Bearer)。if (authMode === 'apiKey' &&diff --git a/apps/desktop/src/renderer/lib/__tests__/customProviderRuntimeFill.test.ts b/apps/desktop/src/renderer/lib/__tests__/customProviderRuntimeFill.test.tsindex 9dee09506f..b959d0c997 100644--- a/apps/desktop/src/renderer/lib/__tests__/customProviderRuntimeFill.test.ts+++ b/apps/desktop/src/renderer/lib/__tests__/customProviderRuntimeFill.test.ts@@ -576,6 +576,7 @@ describe('custom provider runtime fill', () => {supportsImageInput: true,reasoning: true,reasoningEfforts: ['low', 'high'],+ reasoningDefaultEffort: 'high',},],});@@ -592,6 +593,7 @@ describe('custom provider runtime fill', () => {supportsImageInput: true,reasoning: true,reasoningEfforts: ['low', 'high'],+ reasoningDefaultEffort: 'high',},]);});diff --git a/apps/desktop/src/renderer/lib/__tests__/customProviders.test.ts b/apps/desktop/src/renderer/lib/__tests__/customProviders.test.tsindex 101707c8c6..91c8cc6a62 100644--- a/apps/desktop/src/renderer/lib/__tests__/customProviders.test.ts+++ b/apps/desktop/src/renderer/lib/__tests__/customProviders.test.ts@@ -1,10 +1,15 @@import { afterEach, describe, expect, it, vi } from 'vitest';+import { customProviderSecretStorageKey } from '@/../shared/providerSecrets';+import {appendDiscoveredCustomProviderModels,createCustomProvider,customProviderModelConfigFromCatalogModel,+ deleteCustomProvider,+ piCatalogProviderIdAfterRouteEdit,providerViewToCustomProviderConfig,+ readCustomProviderKey,replaceCustomProviderModelId,setCustomProviderModelReasoning,setCustomProviderModelReasoningEffort,@@ -20,6 +25,170 @@ afterEach(() => {vi.unstubAllGlobals();});+describe('piCatalogProviderIdAfterRouteEdit', () => {+ const official = {+ baseUrl: 'https://api.example.com/anthropic',+ wireProtocol: 'anthropic-messages' as const,+ piCatalogProviderId: 'example',+ };++ it('keeps a newly applied marker and an unchanged official route', () => {+ expect(+ piCatalogProviderIdAfterRouteEdit(+ 'pi',+ { ...official, piCatalogProviderId: undefined },+ official,+ ),+ ).toBe('example');+ expect(piCatalogProviderIdAfterRouteEdit('pi', official, official)).toBe('example');+ expect(+ piCatalogProviderIdAfterRouteEdit('pi', official, {+ ...official,+ baseUrl: `${official.baseUrl}/`,+ }),+ ).toBe('example');+ });++ it('clears the marker after either endpoint or protocol is edited', () => {+ expect(+ piCatalogProviderIdAfterRouteEdit('pi', official, {+ ...official,+ baseUrl: 'https://proxy.example/v1',+ }),+ ).toBeUndefined();+ expect(+ piCatalogProviderIdAfterRouteEdit('pi', official, {+ ...official,+ wireProtocol: 'openai-chat',+ }),+ ).toBeUndefined();+ });++ it('keeps the marker when a temporary route edit is reverted before the final save', () => {+ const temporaryEdit = {+ ...official,+ baseUrl: 'https://proxy.example/v1',+ };+ expect(piCatalogProviderIdAfterRouteEdit('pi', official, temporaryEdit)).toBeUndefined();+ expect(+ piCatalogProviderIdAfterRouteEdit('pi', official, {+ ...temporaryEdit,+ baseUrl: official.baseUrl,+ }),+ ).toBe('example');+ expect(+ piCatalogProviderIdAfterRouteEdit('pi', official, {+ ...temporaryEdit,+ wireProtocol: official.wireProtocol,+ }),+ ).toBeUndefined();+ });++ it('treats an omitted Pi protocol as the effective openai-chat default', () => {+ const openAiChat = {+ ...official,+ wireProtocol: 'openai-chat' as const,+ };+ expect(piCatalogProviderIdAfterRouteEdit('pi', openAiChat, {+ ...openAiChat,+ wireProtocol: undefined,+ })).toBe('example');+ expect(piCatalogProviderIdAfterRouteEdit('pi', {+ ...openAiChat,+ wireProtocol: undefined,+ }, openAiChat)).toBe('example');+ expect(piCatalogProviderIdAfterRouteEdit('pi', openAiChat, {+ ...openAiChat,+ wireProtocol: 'anthropic-messages',+ })).toBeUndefined();+ });++ it('clears the marker after any model metadata is edited', () => {+ const withModels: {+ baseUrl: string;+ wireProtocol: 'anthropic-messages';+ piCatalogProviderId: string;+ models: ProviderRuntimeModelConfig[];+ } = {+ ...official,+ models: [{+ id: 'model-a',+ name: 'Model A',+ contextWindow: 128_000,+ supportsImageInput: true,+ reasoning: true,+ reasoningEfforts: ['low', 'high'],+ reasoningDefaultEffort: 'high',+ }],+ };+ expect(piCatalogProviderIdAfterRouteEdit('pi', withModels, withModels)).toBe('example');+ const editedModels: ProviderRuntimeModelConfig[] = [+ { ...withModels.models[0], name: 'Renamed' },+ { ...withModels.models[0], contextWindow: 64_000 },+ { ...withModels.models[0], supportsImageInput: false },+ { ...withModels.models[0], reasoningEfforts: ['low'] },+ ];+ for (const model of editedModels) {+ expect(piCatalogProviderIdAfterRouteEdit('pi', withModels, {+ ...withModels,+ models: [model],+ })).toBeUndefined();+ }+ expect(piCatalogProviderIdAfterRouteEdit('pi', withModels, {+ ...withModels,+ models: [+ ...withModels.models,+ { id: 'models-url-only', name: 'Models URL Only', defaultEnabled: false },+ ],+ })).toBe('example');+ expect(piCatalogProviderIdAfterRouteEdit('pi', withModels, {+ ...withModels,+ models: [{ ...withModels.models[0], defaultEnabled: false }],+ })).toBe('example');+ expect(piCatalogProviderIdAfterRouteEdit('pi', withModels, {+ ...withModels,+ models: [],+ })).toBeUndefined();+ expect(piCatalogProviderIdAfterRouteEdit('pi', withModels, {+ ...withModels,+ models: [{+ id: 'model-b',+ name: 'My Model B',+ contextWindow: 64_000,+ supportsImageInput: false,+ reasoning: true,+ reasoningEfforts: ['low'],+ reasoningDefaultEffort: 'low',+ }],+ })).toBeUndefined();+ expect(piCatalogProviderIdAfterRouteEdit('pi', withModels, {+ ...withModels,+ models: [+ { id: 'new-model', name: 'New model' },+ withModels.models[0],+ ],+ })).toBe('example');+ const twoModels = {+ ...withModels,+ models: [+ withModels.models[0],+ { id: 'model-b', name: 'Model B', contextWindow: 64_000 },+ ],+ };+ expect(piCatalogProviderIdAfterRouteEdit('pi', twoModels, {+ ...twoModels,+ models: [...twoModels.models].reverse(),+ })).toBe('example');+ expect(piCatalogProviderIdAfterRouteEdit('pi', withModels, {+ ...withModels,+ models: [+ { ...withModels.models[0], name: 'Edited first duplicate' },+ withModels.models[0],+ ],+ })).toBeUndefined();+ });+});+describe('replaceCustomProviderModelId', () => {it('drops hidden metadata when the model id changes', () => {expect(replaceCustomProviderModelId({@@ -29,6 +198,7 @@ describe('replaceCustomProviderModelId', () => {supportsImageInput: true,reasoning: true,reasoningEfforts: ['low', 'high'],+ reasoningDefaultEffort: 'high',}, 'another-model')).toEqual({id: 'another-model',name: 'MiniMax M3',@@ -160,12 +330,14 @@ describe('customProviderModelConfigFromCatalogModel', () => {name: 'Reasoner',contextWindow: 200_000,efforts: ['low', 'high', 'xhigh'] as CatalogModel['efforts'],+ defaultEffort: 'xhigh' as const,};expect(customProviderModelConfigFromCatalogModel(catalogModel, 'pi')).toEqual({id: 'reasoner',name: 'Reasoner',reasoning: true,reasoningEfforts: ['low', 'high', 'xhigh'],+ reasoningDefaultEffort: 'xhigh',});expect(customProviderModelConfigFromCatalogModel(catalogModel, 'codex')).toEqual({id: 'reasoner',@@ -174,7 +346,68 @@ describe('customProviderModelConfigFromCatalogModel', () => {});});+describe('providerViewToCustomProviderConfig Pi catalog metadata', () => {+ it('preserves the hidden Pi official catalog provider id', () => {+ const provider = {+ id: 'deepseek',+ name: 'DeepSeek',+ source: 'user',+ agents: ['pi'],+ auth: { method: 'apiKey' },+ routing: {+ pi: {+ upstream: 'https://api.deepseek.com',+ authStrategy: 'api-key-header',+ piCatalogProviderId: 'deepseek',+ },+ },+ models: {+ pi: [{+ id: 'deepseek-v4-pro',+ name: 'DeepSeek V4 Pro',+ contextWindow: 1_000_000,+ efforts: ['high', 'max'],+ defaultEffort: 'high',+ }],+ },+ } as ProviderView;+ expect(providerViewToCustomProviderConfig(provider).runtimes.pi?.piCatalogProviderId)+ .toBe('deepseek');+ });+});+describe('providerViewToCustomProviderConfig', () => {+ it('restores the stored id for a legacy custom xai runtime projection', () => {+ const provider = {+ id: 'custom:xai',+ name: 'Legacy custom xAI',+ source: 'user',+ agents: ['codex'],+ auth: { method: 'apiKey' },+ access: { kind: 'api' },+ routing: {+ codex: {+ upstream: 'https://private-xai.example/v1',+ authStrategy: 'api-key-header',+ },+ },+ models: {+ codex: [+ {+ id: 'private-grok',+ name: 'Private Grok',+ contextWindow: 200_000,+ efforts: [],+ defaultEffort: null,+ },+ ],+ },+ connected: true,+ } satisfies ProviderView;++ expect(providerViewToCustomProviderConfig(provider).id).toBe('xai');+ });+it('preserves no-auth and exact request-path fields through the edit round trip', () => {const provider = {id: 'local-chat',@@ -255,6 +488,7 @@ describe('providerViewToCustomProviderConfig', () => {name: 'Reasoner',reasoning: true,reasoningEfforts: ['low', 'high', 'xhigh'],+ reasoningDefaultEffort: 'high',},]);});@@ -330,6 +564,39 @@ describe('appendDiscoveredCustomProviderModels', () => {});describe('custom provider credential lifecycle', () => {+ it('maps the legacy runtime id back to its stored config and credential keys', async () => {+ const read = vi.fn(async () => 'legacy-key');+ const update = vi.fn(async () => ({ ok: true }));+ const remove = vi.fn(async () => ({ ok: true }));+ vi.stubGlobal('window', {+ electronAPI: {+ safeStorageRead: read,+ maker: {+ updateCustomProvider: update,+ deleteCustomProvider: remove,+ },+ },+ });+ const config = {+ id: 'custom:xai',+ name: 'Legacy custom xAI',+ runtimes: {+ codex: {+ baseUrl: 'https://private-xai.example/v1',+ models: [{ id: 'private-grok', name: 'Private Grok' }],+ },+ },+ };++ await expect(readCustomProviderKey('custom:xai', 'codex')).resolves.toBe('legacy-key');+ await updateCustomProvider(config, { codex: 'replacement-key' });+ await deleteCustomProvider('custom:xai');++ expect(read).toHaveBeenCalledWith(customProviderSecretStorageKey('xai', 'codex'));+ expect(update).toHaveBeenCalledWith({ ...config, id: 'xai' }, { codex: 'replacement-key' });+ expect(remove).toHaveBeenCalledWith('xai');+ });+it('submits create config and keys through one main-process mutation', async () => {const create = vi.fn(async () => ({ ok: true }));vi.stubGlobal('window', {diff --git a/apps/desktop/src/renderer/lib/__tests__/piRuntimeInitialization.test.ts b/apps/desktop/src/renderer/lib/__tests__/piRuntimeInitialization.test.tsindex 2409ce3df5..c1da8965b8 100644--- a/apps/desktop/src/renderer/lib/__tests__/piRuntimeInitialization.test.ts+++ b/apps/desktop/src/renderer/lib/__tests__/piRuntimeInitialization.test.ts@@ -17,6 +17,7 @@ describe('derivePiRuntimeFromClaudeRuntime', () => {supportsImageInput: true,reasoning: true,reasoningEfforts: ['high'],+ reasoningDefaultEffort: 'high',},],});diff --git a/apps/desktop/src/renderer/lib/customProviderRuntimeFill.ts b/apps/desktop/src/renderer/lib/customProviderRuntimeFill.tsindex 512af5d91a..eeae2ea167 100644--- a/apps/desktop/src/renderer/lib/customProviderRuntimeFill.ts+++ b/apps/desktop/src/renderer/lib/customProviderRuntimeFill.ts@@ -163,7 +163,13 @@ function modelsForTarget(...portable,...(existing?.supportsImageInput === true ? { supportsImageInput: true } : {}),...(existing?.reasoning === true && existing.reasoningEfforts?.length- ? { reasoning: true, reasoningEfforts: [...existing.reasoningEfforts] }+ ? {+ reasoning: true,+ reasoningEfforts: [...existing.reasoningEfforts],+ ...(existing.reasoningDefaultEffort+ ? { reasoningDefaultEffort: existing.reasoningDefaultEffort }+ : {}),+ }: {}),};});diff --git a/apps/desktop/src/renderer/lib/customProviders.ts b/apps/desktop/src/renderer/lib/customProviders.tsindex 8a46226886..a8ce8c85d6 100644--- a/apps/desktop/src/renderer/lib/customProviders.ts+++ b/apps/desktop/src/renderer/lib/customProviders.ts@@ -11,7 +11,13 @@import { customProviderSecretStorageKey } from '@/../shared/providerSecrets';-import { DEFAULT_CUSTOM_CONTEXT_WINDOW, PI_REASONING_EFFORTS } from '@cindy/model-providers';+import {+ DEFAULT_CUSTOM_CONTEXT_WINDOW,+ effectivePiWireProtocol,+ PI_REASONING_EFFORTS,+ preservesPiCatalogModels,+ storedCustomProviderId,+} from '@cindy/model-providers';import type {AgentKind,CatalogModel,@@ -19,8 +25,33 @@ import type {PiReasoningEffort,ProviderView,ProviderRuntimeModelConfig,+ ProviderWireProtocol,} from '@cindy/model-providers';+interface PiCatalogRouteDraft {+ baseUrl: string;+ wireProtocol?: ProviderWireProtocol;+ piCatalogProviderId?: string;+ models?: readonly ProviderRuntimeModelConfig[];+}++/** The catalog marker is valid while the route and every existing model's capability fields stay unchanged. */+export function piCatalogProviderIdAfterRouteEdit(+ agent: AgentKind,+ previous: PiCatalogRouteDraft,+ next: PiCatalogRouteDraft,+): string | undefined {+ const marker = next.piCatalogProviderId;+ if (agent !== 'pi' || !marker || marker !== previous.piCatalogProviderId) return marker;+ const normalizeBaseUrl = (value: string) => value.trim().replace(/\/+$/, '');+ return normalizeBaseUrl(previous.baseUrl) === normalizeBaseUrl(next.baseUrl)+ && effectivePiWireProtocol(previous.wireProtocol)+ === effectivePiWireProtocol(next.wireProtocol)+ && preservesPiCatalogModels(previous.models, next.models)+ ? marker+ : undefined;+}+/** 开启 Pi reasoning 时的保守常用档位;xhigh/max 仍需用户明确勾选。 */export const DEFAULT_PI_CUSTOM_REASONING_EFFORTS: readonly PiReasoningEffort[] = ['minimal',@@ -66,6 +97,7 @@ export function setCustomProviderModelReasoning(const rest = { ...model };delete rest.reasoning;delete rest.reasoningEfforts;+ delete rest.reasoningDefaultEffort;return rest;}return {@@ -91,10 +123,14 @@ export function setCustomProviderModelReasoningEffort(const selected = new Set(current);if (enabled) selected.add(effort);else selected.delete(effort);- return {+ const next = {...model,reasoningEfforts: PI_REASONING_EFFORTS.filter((candidate) => selected.has(candidate)),};+ if (!enabled && model.reasoningDefaultEffort === effort) {+ delete next.reasoningDefaultEffort;+ }+ return next;});}@@ -114,7 +150,7 @@ export function customProviderModelConfigFromCatalogModel(| 'defaultEnabled'| 'supportsImageInput'> &- Partial<Pick<CatalogModel, 'efforts'>>,+ Partial<Pick<CatalogModel, 'efforts' | 'defaultEffort'>>,agent?: AgentKind,): ProviderRuntimeModelConfig {const reasoningEfforts =@@ -132,6 +168,11 @@ export function customProviderModelConfigFromCatalogModel(...(model.defaultEnabled === false ? { defaultEnabled: false } : {}),...(model.supportsImageInput === true ? { supportsImageInput: true } : {}),...(reasoningEfforts.length > 0 ? { reasoning: true, reasoningEfforts } : {}),+ ...(agent === 'pi'+ && model.defaultEffort+ && reasoningEfforts.includes(model.defaultEffort as PiReasoningEffort)+ ? { reasoningDefaultEffort: model.defaultEffort as PiReasoningEffort }+ : {}),};}@@ -151,10 +192,11 @@ export function providerViewToCustomProviderConfig(p: ProviderView): CustomProvi: {}),...(routing?.headerOverrideState ? { headersState: routing.headerOverrideState } : {}),...(routing?.modelsUrl ? { modelsUrl: routing.modelsUrl } : {}),+ ...(routing?.piCatalogProviderId ? { piCatalogProviderId: routing.piCatalogProviderId } : {}),};}return {- id: p.id,+ id: storedCustomProviderId(p.id),name: p.name,...(p.auth.method === 'oauth' && p.auth.oauth? { auth: { method: 'oauth' as const, oauth: p.auth.oauth } }@@ -201,7 +243,7 @@ export async function readCustomProviderKey(agent: AgentKind,): Promise<string | null> {const value = await window.electronAPI.safeStorageRead(- customProviderSecretStorageKey(providerId, agent),+ customProviderSecretStorageKey(storedCustomProviderId(providerId), agent),);return value && value.length > 0 ? value : null;}@@ -223,10 +265,13 @@ export async function updateCustomProvider(config: CustomProviderConfig,keys: RuntimeKeys,): Promise<void> {- await window.electronAPI.maker.updateCustomProvider(config, keys);+ await window.electronAPI.maker.updateCustomProvider(+ { ...config, id: storedCustomProviderId(config.id) },+ keys,+ );}/** 删除:main 在同一 provider mutation queue 内清配置与所有凭证。 */export async function deleteCustomProvider(providerId: string): Promise<void> {- await window.electronAPI.maker.deleteCustomProvider(providerId);+ await window.electronAPI.maker.deleteCustomProvider(storedCustomProviderId(providerId));}diff --git a/apps/desktop/src/shared/piRuntimeInitialization.ts b/apps/desktop/src/shared/piRuntimeInitialization.tsindex 0d04635313..df3bdd30be 100644--- a/apps/desktop/src/shared/piRuntimeInitialization.ts+++ b/apps/desktop/src/shared/piRuntimeInitialization.ts@@ -16,7 +16,13 @@ export function savedCustomProviderModelShape(? { supportsImageInput: true }: {}),...(includePiCapabilities && model.reasoning === true && model.reasoningEfforts?.length- ? { reasoning: true, reasoningEfforts: [...model.reasoningEfforts] }+ ? {+ reasoning: true,+ reasoningEfforts: [...model.reasoningEfforts],+ ...(model.reasoningDefaultEffort+ ? { reasoningDefaultEffort: model.reasoningDefaultEffort }+ : {}),+ }: {}),};}diff --git a/apps/desktop/src/shared/providerSecrets.ts b/apps/desktop/src/shared/providerSecrets.tsindex 3dfb5edfa1..37d596f646 100644--- a/apps/desktop/src/shared/providerSecrets.ts+++ b/apps/desktop/src/shared/providerSecrets.ts@@ -74,11 +74,18 @@ export function providerSecretStorageKey(id: ProviderSecretId): string {*/export const REMOTE_MCP_BRIDGE_TOKEN_STORAGE_KEY = 'remote_mcp_bridge_token';+/**+ * Host-only HMAC key for remote Pi proxy session tokens. Unlike the derived+ * per-session token, this value never enters a child/remote process env.+ */+export const PI_PROXY_DERIVATION_KEY_STORAGE_KEY = 'pi_proxy_derivation_key';+const MAIN_ONLY_PROVIDER_SECRET_STORAGE_KEYS = new Set<string>([STORAGE_KEYS['voice-asr'].toLowerCase(),STORAGE_KEYS['gemini'].toLowerCase(),STORAGE_KEYS['openai-images'].toLowerCase(),REMOTE_MCP_BRIDGE_TOKEN_STORAGE_KEY.toLowerCase(),+ PI_PROXY_DERIVATION_KEY_STORAGE_KEY.toLowerCase(),]);/** Custom-provider runtime header blobs are main-only credential material. */diff --git a/package.json b/package.jsonindex 9b6943c624..d6616df849 100644--- a/package.json+++ b/package.json@@ -85,6 +85,7 @@"update:codex": "node tools/codex/update.mjs","update:ripgrep": "node tools/ripgrep/update.mjs","update:pi": "node tools/pi/update.mjs",+ "sync:pi-model-catalog": "node tools/pi/sync-model-catalog.mjs","update:vendors": "node tools/claude/update.mjs && node tools/codex/update.mjs && node tools/ripgrep/update.mjs && node tools/pi/update.mjs","install:claude": "node scripts/ensure-agent-binaries.mjs --kinds=claude","install:codex": "node scripts/ensure-agent-binaries.mjs --kinds=codex",diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.tsindex 5ad841a4db..68d801c071 100644--- a/packages/maker-core/src/agents/base-agent.ts+++ b/packages/maker-core/src/agents/base-agent.ts@@ -180,18 +180,39 @@ export type PiNativeApi =| 'openai-completions'| 'google-generative-ai';-export type PiNativeThinkingLevel = Exclude<Effort, 'ultra'>;+export type PiNativeThinkingLevel = 'off' | Exclude<Effort, 'ultra'>;++export interface PiNativeModelCost {+ input: number;+ output: number;+ cacheRead: number;+ cacheWrite: number;+ tiers?: Array<{+ inputTokensAbove: number;+ input: number;+ output: number;+ cacheRead: number;+ cacheWrite: number;+ }>;+}/** BYOM:写进 pi models.json 的一个模型(原生 provider 块内)。 */export interface PiNativeModelSpec {id: string;name?: string;+ /** Per-model request headers from the authoritative Pi catalog. */+ headers?: Record<string, string>;+ /** Per-model API from Pi's official catalog; providers may mix protocols. */+ api?: PiNativeApi;reasoning?: boolean;/** Pi models.json 的 provider-specific thinking level 映射;null 明确禁用该档。 */thinkingLevelMap?: Partial<Record<PiNativeThinkingLevel, string | null>>;contextWindow?: number;maxTokens?: number;input?: Array<'text' | 'image'>;+ cost?: PiNativeModelCost;+ compat?: Record<string, unknown>;+ samplingParams?: Record<string, unknown>;}/**@@ -232,6 +253,17 @@ export interface PiNativeProviderSpec {apiKeyEnvVar?: string;headers?: Record<string, string>;models: PiNativeModelSpec[];+ /** Translate Cindy's persisted/public model id to the Pi-native model id for this provider. */+ modelIdAliases?: Record<string, string>;+ /**+ * This provider is backed by a loopback service owned by the Desktop host. Remote Pi may use+ * it only after the host establishes the exact SSH reverse-forward described here. The marker+ * is host control-plane data and is never serialized into models.json.+ */+ hostProxyForward?: {+ localUrl: string;+ remotePort: number;+ };}/** host 解析出的 pi 原生 provider + 需注入子进程的 env(api keys)。 */@@ -442,6 +474,13 @@ export interface AgentDeps {*/registerPiProxySession?: (sessionId: string, token: string) => (() => void) | void;+ /**+ * Pi-only: host-owned derivation for restart-stable remote proxy tokens.+ * Desktop persists the secret key; maker-core receives only the per-session+ * result. Missing hooks preserve the legacy process-stable fallback.+ */+ derivePiProxySessionToken?: (sessionId: string) => string;+/*** BYOM:host 解析出当前会话可用的 pi **原生 provider**(用户自定义/本地模型)+ 需注入的* env(api keys)。PiAgent 把这些写进 models.json 的独立 provider 块(直连用户端点,不过@@ -450,7 +489,14 @@ export interface AgentDeps {* 缺省 / 返回空 → 只有网关 provider `cindy`(现状,行为不变)。keyless provider 的 key 可省。*/resolvePiNativeProviders?: (- ctx: { workingDir: string; remoteHostId?: string | null },+ ctx: {+ workingDir: string;+ remoteHostId?: string | null;+ providerId?: string | null;+ model: string;+ /** Present only when restoring an existing Pi session; permits private compatibility ids. */+ resumeSessionId?: string;+ },) => Promise<PiNativeProvidersResult | null>;/**@@ -679,6 +725,11 @@ export interface AgentDeps {logger: AgentDeps['logger'];/** maker sessionId(daemon 模式用作远端 daemon 的 session key)。 */sessionId?: string | null;+ /** Host-owned loopback providers that must be reverse-forwarded before remote Pi starts. */+ hostProxyForwards?: ReadonlyArray<{+ localUrl: string;+ remotePort: number;+ }>;},) => import('./pi/transport.js').PiTransport | Promise<import('./pi/transport.js').PiTransport>;diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.tsindex 495d892550..d9c89aec34 100644--- a/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.ts@@ -203,6 +203,301 @@ describe('Pi provider-aware model routing', () => {await nativeHandle.close();});+ it('keeps xAI and custom providers in one snapshot and switches both directions', async () => {+ const agent = new PiAgent({+ auth: {+ getState: async () => ({ authenticated: true, identity: 'SuperGrok', authSource: 'oauth' as const }),+ triggerLogin: async () => ({ authenticated: true }),+ logout: async () => {},+ getAuthEnv: async () => ({ CINDY_PI_API_KEY: 'gateway-key' }),+ },+ runtimeConfig: { endpoint: 'http://127.0.0.1:9' },+ binaryPath: path.join(agentHome, 'pi'),+ logger: noopLogger,+ capabilityAdditions: {+ availableModels: [+ {+ id: 'xai/grok-4.6',+ displayName: 'Grok 4.6',+ contextWindow: 500_000,+ efforts: ['minimal', 'low', 'medium', 'high'],+ defaultEffort: 'medium',+ },+ {+ id: 'local-model',+ displayName: 'Local Model',+ contextWindow: 128_000,+ efforts: [],+ defaultEffort: null,+ },+ ],+ },+ resolvePiAgentHome: () => agentHome,+ resolvePiNativeProviders: async () => ({+ providers: [+ {+ id: 'xai',+ name: 'xAI',+ baseUrl: 'http://127.0.0.1:9',+ api: 'anthropic-messages',+ apiKeyEnvVar: 'CINDY_PI_XAI_PROXY_API_KEY',+ headers: {+ 'x-cindy-pi-session-id': '$CINDY_PI_SESSION_ID',+ 'x-cindy-pi-session-token': '$CINDY_PI_SESSION_TOKEN',+ },+ modelIdAliases: {+ 'grok-4.6': 'xai/grok-4.6',+ 'xai/grok-4.6': 'xai/grok-4.6',+ },+ models: [{+ id: 'xai/grok-4.6',+ api: 'anthropic-messages',+ contextWindow: 500_000,+ maxTokens: 500_000,+ input: ['text', 'image'],+ reasoning: true,+ compat: {+ supportsStore: false,+ supportsDeveloperRole: false,+ supportsReasoningEffort: false,+ },+ }],+ },+ {+ id: 'native-a',+ name: 'Native A',+ baseUrl: 'http://a.test',+ api: 'openai-completions',+ models: [{ id: 'local-model' }],+ },+ ],+ env: { CINDY_PI_XAI_PROXY_API_KEY: 'xai-proxy-placeholder' },+ }),+ });++ const handle = await agent.startSession({+ sessionId: 'grok-46-native',+ workingDir: cwd,+ model: 'xai/grok-4.6',+ providerId: 'xai',+ effort: 'medium',+ });+ expect(captured.args.slice(captured.args.indexOf('--provider'), captured.args.indexOf('--provider') + 2))+ .toEqual(['--provider', 'xai']);+ expect(captured.args.slice(captured.args.indexOf('--model'), captured.args.indexOf('--model') + 2))+ .toEqual(['--model', 'xai/grok-4.6']);+ expect(captured.env.CINDY_PI_API_KEY).toBe('gateway-key');+ expect(captured.env.CINDY_PI_XAI_PROXY_API_KEY).toBe('xai-proxy-placeholder');++ const models = JSON.parse(+ readFileSync(path.join(captured.env.PI_CODING_AGENT_DIR as string, 'models.json'), 'utf8'),+ ) as { providers: Record<string, { apiKey: string; models: Array<Record<string, unknown>> }> };+ expect(models.providers.cindy?.apiKey).toBe('$CINDY_PI_API_KEY');+ expect(models.providers.xai?.apiKey).toBe('$CINDY_PI_XAI_PROXY_API_KEY');+ expect(models.providers.xai?.models.find((model) => model.id === 'xai/grok-4.6')).toMatchObject({+ api: 'anthropic-messages',+ contextWindow: 500_000,+ maxTokens: 500_000,+ input: ['text', 'image'],+ compat: {+ supportsStore: false,+ supportsDeveloperRole: false,+ supportsReasoningEffort: false,+ },+ });+ expect(JSON.parse(readFileSync(runtimeFileOf('subagent', 'grok-46-native'), 'utf8'))).toEqual({+ model: 'xai/grok-4.6',+ provider: 'xai',+ });+ await handle.setModel!('local-model', { providerId: 'native-a' });+ await handle.setModel!('xai/grok-4.6', { providerId: 'xai' });+ expect(captured.requests).toContainEqual({+ type: 'set_model',+ provider: 'native-a',+ modelId: 'local-model',+ });+ expect(captured.requests).toContainEqual({+ type: 'set_model',+ provider: 'xai',+ modelId: 'xai/grok-4.6',+ });+ await handle.close();+ });++ it('applies each native provider alias during provider-less compatibility routing', async () => {+ const provider = (id: string, aliases?: Record<string, string>) => ({+ id,+ name: id,+ baseUrl: `http://${id}.test`,+ api: 'anthropic-messages' as const,+ ...(aliases ? { modelIdAliases: aliases } : {}),+ models: [{ id: id === 'xai' ? 'xai/grok-4.6' : 'other-model' }],+ });+ const agent = new PiAgent({+ auth: {+ getState: async (options) => ({+ authenticated: true,+ identity: options?.providerId === 'xai' ? 'SuperGrok' : 'test',+ authSource: 'oauth' as const,+ }),+ triggerLogin: async () => ({ authenticated: true }),+ logout: async () => {},+ getAuthEnv: async () => ({}),+ },+ runtimeConfig: { endpoint: 'http://127.0.0.1:9' },+ binaryPath: path.join(agentHome, 'pi'),+ logger: noopLogger,+ capabilityAdditions: {+ availableModels: [{+ id: 'grok-4.6',+ displayName: 'Grok 4.6',+ contextWindow: 500_000,+ efforts: [],+ defaultEffort: null,+ }],+ },+ resolvePiAgentHome: () => agentHome,+ resolvePiNativeProviders: async () => ({+ providers: [+ provider('other'),+ provider('xai', {+ 'grok-4.6': 'xai/grok-4.6',+ 'xai/grok-4.6': 'xai/grok-4.6',+ }),+ ],+ env: {},+ }),+ });++ const bare = await agent.startSession({+ sessionId: 'providerless-grok-bare',+ workingDir: cwd,+ model: 'grok-4.6',+ });+ expect(captured.args.slice(captured.args.indexOf('--provider'), captured.args.indexOf('--provider') + 2))+ .toEqual(['--provider', 'xai']);+ expect(captured.args.slice(captured.args.indexOf('--model'), captured.args.indexOf('--model') + 2))+ .toEqual(['--model', 'xai/grok-4.6']);+ await bare.close();++ const namespaced = await agent.startSession({+ sessionId: 'providerless-grok-namespaced',+ workingDir: cwd,+ model: 'xai/grok-4.6',+ });+ expect(captured.args.slice(captured.args.indexOf('--provider'), captured.args.indexOf('--provider') + 2))+ .toEqual(['--provider', 'xai']);+ await namespaced.close();+ });++ it('fails closed when provider-less aliases are ambiguous', async () => {+ const agent = new PiAgent(byomDeps(async () => ({+ providers: [+ {+ id: 'native-a',+ name: 'Native A',+ baseUrl: 'http://a.test',+ api: 'openai-completions',+ modelIdAliases: { legacy: 'native-a-model' },+ models: [{ id: 'native-a-model' }],+ },+ {+ id: 'native-b',+ name: 'Native B',+ baseUrl: 'http://b.test',+ api: 'openai-completions',+ modelIdAliases: { legacy: 'native-b-model' },+ models: [{ id: 'native-b-model' }],+ },+ ],+ env: {},+ })));+ await expect(agent.startSession({+ sessionId: 'providerless-alias-conflict',+ workingDir: cwd,+ model: 'legacy',+ })).rejects.toThrow(/matches multiple native providers.*refusing to guess an endpoint/);+ expect(captured.args).toEqual([]);+ });++ it('fails closed when an explicit xAI selection cannot build the Pi native provider', async () => {+ const deps: AgentDeps = {+ auth: {+ getState: async () => ({ authenticated: true, identity: 'SuperGrok', authSource: 'oauth' as const }),+ triggerLogin: async () => ({ authenticated: true }),+ logout: async () => {},+ getAuthEnv: async () => ({}),+ },+ runtimeConfig: { endpoint: 'http://127.0.0.1:9' },+ binaryPath: path.join(agentHome, 'pi'),+ logger: noopLogger,+ capabilityAdditions: {+ availableModels: [{+ id: 'grok-4.6',+ displayName: 'Grok 4.6',+ contextWindow: 500_000,+ efforts: ['minimal', 'low', 'medium', 'high'],+ defaultEffort: 'medium',+ }],+ },+ resolvePiAgentHome: () => agentHome,+ resolvePiNativeProviders: async () => {+ throw new Error('xAI token unavailable');+ },+ };+ await expect(new PiAgent(deps).startSession({+ sessionId: 'grok-46-native-failed',+ workingDir: cwd,+ model: 'grok-4.6',+ providerId: 'xai',+ })).rejects.toThrow(/BYOM provider 'xai' cannot serve model 'grok-4.6'.*refusing to fall back/);+ expect(captured.args).toEqual([]);+ });++ it('passes resume identity so a historical xAI model can stay private to the restored session', async () => {+ const resolver = vi.fn(async (ctx) => ({+ providers: [{+ id: 'xai',+ name: 'xAI',+ baseUrl: 'http://127.0.0.1:9',+ api: 'anthropic-messages' as const,+ modelIdAliases: { 'grok-retired': 'xai/grok-retired' },+ models: [{ id: 'xai/grok-retired', api: 'anthropic-messages' as const }],+ }],+ env: {},+ }));+ const agent = new PiAgent({+ auth: {+ getState: async () => ({ authenticated: true, identity: 'SuperGrok', authSource: 'oauth' as const }),+ triggerLogin: async () => ({ authenticated: true }),+ logout: async () => {},+ getAuthEnv: async () => ({ CINDY_PI_API_KEY: 'provider-auth-placeholder' }),+ },+ runtimeConfig: { endpoint: 'http://127.0.0.1:9' },+ binaryPath: path.join(agentHome, 'pi'),+ logger: noopLogger,+ capabilityAdditions: { availableModels: [] },+ resolvePiAgentHome: () => agentHome,+ resolvePiNativeProviders: resolver,+ });++ const handle = await agent.startSession({+ sessionId: 'historical-xai-resume',+ resumeSessionId: 'pi-sdk-session-old',+ workingDir: cwd,+ model: 'grok-retired',+ providerId: 'xai',+ });+ expect(resolver).toHaveBeenCalledWith(expect.objectContaining({+ providerId: 'xai',+ model: 'grok-retired',+ resumeSessionId: 'pi-sdk-session-old',+ }));+ expect(captured.args.slice(captured.args.indexOf('--model'), captured.args.indexOf('--model') + 2))+ .toEqual(['--model', 'xai/grok-retired']);+ await handle.close();+ });+it('keeps built-in gateway reasoning when a same-id non-reasoning BYOM empties the flat effort intersection', async () => {const resolver = vi.fn((_providerId: string | null | undefined, modelId: string) => {if (modelId !== 'shared-model') return null;@@ -1262,6 +1557,321 @@ describe('Pi provider-aware model routing', () => {expect(captured.args).toEqual([]);});+ it('allows an explicitly forwarded remote xAI provider and keeps proxy auth in the remote env', async () => {+ const remoteStub: import('../transport.js').PiTransport = {+ writeLine: async () => {},+ onLine: () => () => {},+ onStderr: () => () => {},+ onClose: () => () => {},+ close: async () => {},+ pid: 4321,+ isClosed: () => false,+ remoteBinaryPath: '/remote/pi',+ killRemoteSession: async () => {},+ ensureHostProxyForward: async () => {},+ };+ let transportOptions:+ Parameters<NonNullable<AgentDeps['getRemotePiTransport']>>[1] | undefined;+ let registeredToken: string | undefined;+ let disposed = 0;+ const base = byomDeps(+ async () => ({+ providers: [+ {+ id: 'xai',+ name: 'xAI',+ baseUrl: 'http://127.0.0.1:47989',+ api: 'anthropic-messages',+ apiKeyEnvVar: 'CINDY_PI_XAI_PROXY_API_KEY',+ headers: {+ 'x-cindy-pi-session-id': '$CINDY_PI_SESSION_ID',+ 'x-cindy-pi-session-token': '$CINDY_PI_SESSION_TOKEN',+ },+ models: [{ id: 'xai/grok-4.6' }],+ modelIdAliases: {+ 'grok-4.6': 'xai/grok-4.6',+ 'xai/grok-4.6': 'xai/grok-4.6',+ },+ hostProxyForward: {+ localUrl: 'http://127.0.0.1:18765',+ remotePort: 47989,+ },+ },+ ],+ env: { CINDY_PI_XAI_PROXY_API_KEY: 'xai-proxy-placeholder' },+ }),+ [+ {+ id: 'gateway-model',+ displayName: 'Gateway model',+ contextWindow: 200_000,+ efforts: [],+ defaultEffort: null,+ },+ {+ id: 'grok-4.6',+ displayName: 'Grok 4.6',+ contextWindow: 500_000,+ efforts: [],+ defaultEffort: null,+ },+ ],+ );+ const stableTokens = new Map([+ ['remote-xai-forward', 'a'.repeat(43)],+ ['remote-xai-other', 'b'.repeat(43)],+ ]);+ const derivePiProxySessionToken = vi.fn((sessionId: string) => stableTokens.get(sessionId)!);+ const agentDeps: AgentDeps = {+ ...base,+ auth: {+ ...base.auth,+ getState: async () => ({+ authenticated: true,+ identity: 'SuperGrok',+ authSource: 'oauth',+ }),+ getAuthEnv: async () => ({ CINDY_PI_API_KEY: 'gateway-key' }),+ },+ runtimeConfig: {+ ...base.runtimeConfig,+ remoteEndpoint: 'https://gateway.example.test',+ },+ registerPiProxySession: (_sessionId, token) => {+ registeredToken = token;+ return () => {+ disposed += 1;+ };+ },+ derivePiProxySessionToken,+ resolveRemotePiBinaryPath: async () => '/remote/pi',+ getRemotePiFileOps: () => ({+ mkdirp: async () => {},+ writeFile: async () => {},+ stat: async () => ({ isFile: true }),+ rm: async () => {},+ listDir: async () => [],+ }),+ getRemotePiTransport: async (_hostId, opts) => {+ transportOptions = opts;+ return remoteStub;+ },+ };+ const agent = new PiAgent(agentDeps);+ const handle = await agent.startSession({+ sessionId: 'remote-xai-forward',+ workingDir: cwd,+ model: 'grok-4.6',+ providerId: 'xai',+ remoteHostId: 'remote-host',+ });+ expect(transportOptions?.hostProxyForwards).toEqual([+ { localUrl: 'http://127.0.0.1:18765', remotePort: 47989 },+ ]);+ expect(registeredToken).toMatch(/^[A-Za-z0-9_-]{40,}$/);+ expect(transportOptions?.env.CINDY_PI_API_KEY).toBe('gateway-key');+ expect(transportOptions?.env.CINDY_PI_XAI_PROXY_API_KEY).toBe('xai-proxy-placeholder');+ expect(JSON.parse(transportOptions?.env.CINDY_PI_SECRET_ENV_NAMES ?? '[]')).toEqual(+ expect.arrayContaining(['CINDY_PI_API_KEY', 'CINDY_PI_XAI_PROXY_API_KEY']),+ );+ expect(transportOptions?.env.CINDY_PI_SESSION_TOKEN).toBe(registeredToken);+ const firstToken = registeredToken;+ const firstSpawnEnv = { ...transportOptions?.env };++ captured.requests.length = 0;+ await handle.setModel!('gateway-model', { providerId: 'xd' });+ await handle.setModel!('grok-4.6', { providerId: 'xai' });+ expect(captured.requests).toContainEqual({+ type: 'set_model',+ provider: 'cindy',+ modelId: 'gateway-model',+ });+ expect(captured.requests).toContainEqual({+ type: 'set_model',+ provider: 'xai',+ modelId: 'xai/grok-4.6',+ });+ await handle.close();+ expect(disposed).toBe(1);++ // Reconstruct the agent to model a Desktop restart. The host-owned+ // derivation survives while maker-core process-local state does not.+ const reattached = await new PiAgent(agentDeps).startSession({+ sessionId: 'remote-xai-forward',+ workingDir: cwd,+ model: 'grok-4.6',+ providerId: 'xai',+ remoteHostId: 'remote-host',+ });+ expect(registeredToken).toBe(firstToken);+ expect(transportOptions?.env).toEqual(firstSpawnEnv);+ expect(transportOptions?.env.CINDY_PI_SESSION_TOKEN).toBe(firstToken);+ await reattached.close();+ expect(disposed).toBe(2);++ const otherSession = await new PiAgent(agentDeps).startSession({+ sessionId: 'remote-xai-other',+ workingDir: cwd,+ model: 'grok-4.6',+ providerId: 'xai',+ remoteHostId: 'remote-host',+ });+ expect(registeredToken).not.toBe(firstToken);+ expect(transportOptions?.env.CINDY_PI_SESSION_TOKEN).toBe(registeredToken);+ expect(derivePiProxySessionToken).toHaveBeenCalledWith('remote-xai-forward');+ expect(derivePiProxySessionToken).toHaveBeenCalledWith('remote-xai-other');+ await otherSession.close();+ expect(disposed).toBe(3);++ const legacyDeps: AgentDeps = {+ ...agentDeps,+ derivePiProxySessionToken: undefined,+ };+ const legacy = await new PiAgent(legacyDeps).startSession({+ sessionId: 'remote-xai-legacy',+ workingDir: cwd,+ model: 'grok-4.6',+ providerId: 'xai',+ remoteHostId: 'remote-host',+ });+ const legacyToken = registeredToken;+ await legacy.close();+ const legacyReattached = await new PiAgent(legacyDeps).startSession({+ sessionId: 'remote-xai-legacy',+ workingDir: cwd,+ model: 'grok-4.6',+ providerId: 'xai',+ remoteHostId: 'remote-host',+ });+ expect(registeredToken).toBe(legacyToken);+ await legacyReattached.close();+ expect(disposed).toBe(5);+ });++ it('defers the remote xAI forward until a running gateway session actually switches to xAI', async () => {+ const forwardEvents: string[] = [];+ let rejectForward = true;+ let remoteWrites = 0;+ const remoteStub: import('../transport.js').PiTransport = {+ writeLine: async () => {},+ onLine: () => () => {},+ onStderr: () => () => {},+ onClose: () => () => {},+ close: async () => {},+ pid: 4321,+ isClosed: () => false,+ remoteBinaryPath: '/remote/pi',+ killRemoteSession: async () => {},+ ensureHostProxyForward: async (spec) => {+ forwardEvents.push(`forward:${spec.localUrl}:${spec.remotePort}`);+ if (rejectForward) throw new Error('remote port already in use');+ },+ };+ let transportOptions:+ Parameters<NonNullable<AgentDeps['getRemotePiTransport']>>[1] | undefined;+ const base = byomDeps(+ async () => ({+ providers: [+ {+ id: 'xai',+ name: 'xAI',+ baseUrl: 'http://127.0.0.1:47989',+ api: 'anthropic-messages',+ apiKeyEnvVar: 'CINDY_PI_XAI_PROXY_API_KEY',+ models: [{ id: 'xai/grok-4.6' }],+ modelIdAliases: {+ 'grok-4.6': 'xai/grok-4.6',+ 'xai/grok-4.6': 'xai/grok-4.6',+ },+ hostProxyForward: {+ localUrl: 'http://127.0.0.1:18765',+ remotePort: 47989,+ },+ },+ ],+ env: { CINDY_PI_XAI_PROXY_API_KEY: 'xai-proxy-placeholder' },+ }),+ [+ {+ id: 'gateway-model',+ displayName: 'Gateway model',+ contextWindow: 200_000,+ efforts: [],+ defaultEffort: null,+ },+ {+ id: 'grok-4.6',+ displayName: 'Grok 4.6',+ contextWindow: 500_000,+ efforts: [],+ defaultEffort: null,+ },+ ],+ );+ captured.requestHandler = async (command) => {+ if (command.type === 'set_model') forwardEvents.push('set_model');+ return command.type === 'get_state'+ ? { success: true, data: { sessionFile: '/mock/s.jsonl', model: { contextWindow: 200_000 } } }+ : { success: true, data: {} };+ };+ const agent = new PiAgent({+ ...base,+ auth: {+ ...base.auth,+ getAuthEnv: async () => ({ CINDY_PI_API_KEY: 'gateway-key' }),+ },+ runtimeConfig: {+ ...base.runtimeConfig,+ remoteEndpoint: 'https://gateway.example.test',+ },+ resolveRemotePiBinaryPath: async () => '/remote/pi',+ getRemotePiFileOps: () => ({+ mkdirp: async () => {},+ writeFile: async () => {+ remoteWrites += 1;+ },+ stat: async () => ({ isFile: true }),+ rm: async () => {},+ listDir: async () => [],+ }),+ getRemotePiTransport: async (_hostId, opts) => {+ transportOptions = opts;+ return remoteStub;+ },+ });+ const handle = await agent.startSession({+ sessionId: 'remote-gateway-then-xai',+ workingDir: cwd,+ model: 'gateway-model',+ providerId: 'xd',+ remoteHostId: 'remote-host',+ });++ expect(transportOptions?.hostProxyForwards).toEqual([]);+ expect(forwardEvents).toEqual([]);++ captured.requests.length = 0;+ remoteWrites = 0;+ await expect(handle.setModel!('grok-4.6', { providerId: 'xai' })).rejects.toThrow(+ /remote port already in use/,+ );+ expect(remoteWrites).toBe(0);+ expect(captured.requests).not.toContainEqual({+ type: 'set_model',+ provider: 'xai',+ modelId: 'xai/grok-4.6',+ });++ rejectForward = false;+ forwardEvents.length = 0;+ await handle.setModel!('grok-4.6', { providerId: 'xai' });+ expect(forwardEvents).toEqual([+ 'forward:http://127.0.0.1:18765:47989',+ 'set_model',+ ]);+ await handle.close();+ });+it('hashes the remote permission snapshot into spawn env so a later Full-access attach restarts', async () => {const remoteStub: import('../transport.js').PiTransport = {writeLine: async () => {},diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.tsindex 7bb3554ec1..5c7a93ff8a 100644--- a/packages/maker-core/src/agents/pi/index.ts+++ b/packages/maker-core/src/agents/pi/index.ts@@ -24,7 +24,7 @@import os from 'node:os';import path from 'node:path';import { promises as fs } from 'node:fs';-import { createHash, randomBytes } from 'node:crypto';+import { createHash, createHmac, randomBytes } from 'node:crypto';/*** 轮 40-w4-t5 CRITICAL:远端 agentHome 是 POSIX 路径($HOME/... 或展开后的@@ -140,10 +140,10 @@ import {import type { PiRuntimeCapabilityManifest } from '../../types/pi-runtime-capabilities.js';const PI_PROVIDER_ID = 'cindy';-// 既非 Cindy 网关(cindy/xd)也非订阅直连(openai/anthropic/xai)的 providerId = 显式 BYOM+// 既非 Cindy 网关(cindy/xd)也非经 compat proxy 的订阅直连(openai/anthropic)的 providerId = 显式 BYOM// 路由,必须在本会话解析出的 nativeProviders 里;缺席时不得静默回落网关(见 startSession /-// setModel 的 fail-closed)。-const NON_BYOM_PROVIDER_IDS = new Set([PI_PROVIDER_ID, 'xd', 'openai', 'anthropic', 'xai']);+// setModel 的 fail-closed)。xAI 已改走 Pi 原生 provider,同样必须解析成功。+const NON_BYOM_PROVIDER_IDS = new Set([PI_PROVIDER_ID, 'xd', 'openai', 'anthropic']);const PI_API_KEY_ENV = 'CINDY_PI_API_KEY';const PI_SESSION_ID_ENV = 'CINDY_PI_SESSION_ID';const PI_SESSION_TOKEN_ENV = 'CINDY_PI_SESSION_TOKEN';@@ -156,6 +156,13 @@ const PI_MODELS_JSON_HASH_ENV = 'CINDY_PI_MODELS_JSON_HASH';const PI_PERMISSION_HASH_ENV = 'CINDY_PI_PERMISSION_HASH';/** 远端附件内联上限:超过则 fail-before-dispatch, 不静默截断。 */const REMOTE_PI_ATTACHMENT_MAX_BYTES = 256 * 1024;+/**+ * Compatibility fallback for hosts that do not provide persistent derivation.+ * Desktop injects its owner-scoped safeStorage-backed deriver so restart and+ * reattach keep the same token; other hosts retain the previous process-stable+ * behavior without making the token derivable from the public session id alone.+ */+const PI_PROXY_SESSION_TOKEN_KEY = randomBytes(32);/*** baseUrl 是否指向本机 loopback(远端会话不可达)。与 host 侧 isLoopbackUrl 同口径:@@ -236,6 +243,20 @@ function stableSessionPathSegment(sid: string | undefined): string {return createHash('sha256').update(sid).digest('hex').slice(0, 12);}+function stableRemoteProxySessionToken(+ sid: string | undefined,+ hostDeriver?: (sessionId: string) => string,+): string {+ if (!sid) return randomBytes(32).toString('base64url');+ const token = hostDeriver+ ? hostDeriver(sid)+ : createHmac('sha256', PI_PROXY_SESSION_TOKEN_KEY).update(sid).digest('base64url');+ if (!/^[A-Za-z0-9_-]{40,256}$/.test(token)) {+ throw new Error('pi: host returned an invalid proxy session token');+ }+ return token;+}+function slugifyForMemory(input: string, maxLen: number): string {const s = input.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');return (s || 'anon').slice(0, maxLen);@@ -600,7 +621,16 @@ export class PiAgent extends BaseAgent {* plan-mode 扩展路径 / subagent spawn env —— 本地场景即 this.deps.binaryPath。*/private async createTransport(- opts: { args: string[]; cwd: string; env: Record<string, string | undefined>; sessionId?: string | null },+ opts: {+ args: string[];+ cwd: string;+ env: Record<string, string | undefined>;+ sessionId?: string | null;+ hostProxyForwards?: ReadonlyArray<{+ localUrl: string;+ remotePort: number;+ }>;+ },onProcessSpawned?: (pid: number) => void | (() => void),remoteHostId?: string | null,remoteBinaryPath?: string,@@ -615,6 +645,7 @@ export class PiAgent extends BaseAgent {env: opts.env,logger: this.deps.logger,sessionId: opts.sessionId ?? null,+ hostProxyForwards: opts.hostProxyForwards,});return { transport, remoteBinaryPath: transport.remoteBinaryPath ?? remoteBinaryPath };}@@ -759,11 +790,16 @@ export class PiAgent extends BaseAgent {models: np.models.map((m) => ({id: m.id,name: m.name ?? m.id,+ ...(m.headers && Object.keys(m.headers).length > 0 ? { headers: m.headers } : {}),+ ...(m.api ? { api: m.api } : {}),reasoning: m.reasoning ?? false,...(m.thinkingLevelMap ? { thinkingLevelMap: { ...m.thinkingLevelMap } } : {}),input: m.input ?? ['text'],contextWindow: m.contextWindow && m.contextWindow > 0 ? m.contextWindow : 128_000,maxTokens: m.maxTokens && m.maxTokens > 0 ? m.maxTokens : 16_000,+ ...(m.cost ? { cost: m.cost } : {}),+ ...(m.compat ? { compat: m.compat } : {}),+ ...(m.samplingParams ? { samplingParams: m.samplingParams } : {}),})),};}@@ -825,6 +861,9 @@ export class PiAgent extends BaseAgent {const resolved = await this.deps.resolvePiNativeProviders({workingDir: opts.workingDir,remoteHostId: opts.remoteHostId,+ providerId: opts.providerId,+ model: opts.model,+ resumeSessionId: opts.resumeSessionId,});nativeProviders = resolved?.providers ?? [];nativeEnv = resolved?.env ?? {};@@ -840,6 +879,8 @@ export class PiAgent extends BaseAgent {.filter((provider) => provider.id !== PI_PROVIDER_ID).map((provider) => [provider.id, provider] as const),);+ const resolveNativeModelId = (providerId: string, model: string): string =>+ nativeProviderById.get(providerId)?.modelIdAliases?.[model] ?? model;// providerId 是模型来源的主键;同名模型可同时存在于 Cindy 网关和多个 BYOM provider。// 三态语义(与 session-provider-store 对齐):// - 显式 BYOM id → 该 native provider(经上面的 model-combo fail-closed 校验);@@ -853,15 +894,28 @@ export class PiAgent extends BaseAgent {): string => {if (providerId) {const native = nativeProviderById.get(providerId);- return native?.models.some((candidate) => candidate.id === model)+ const nativeModel = resolveNativeModelId(providerId, model);+ return native?.models.some((candidate) => candidate.id === nativeModel)? native.id: PI_PROVIDER_ID;}if (providerId === null) return PI_PROVIDER_ID;- return nativeProviders.find(- (provider) => provider.id !== PI_PROVIDER_ID- && provider.models.some((candidate) => candidate.id === model),- )?.id ?? PI_PROVIDER_ID;+ // 旧会话/旧客户端没有 providerId 时,只能按启动快照做兼容回退。每个 provider+ // 必须先应用自己的 alias:例如 xAI 的裸 `grok-4.6` 实际对应+ // `xai/grok-4.6`。若多个 native provider 都能解释同一个 id,则来源并不唯一,+ // 直接拒绝恢复,不能靠数组顺序猜一个端点,更不能把提示词改发到默认网关。+ const matches = nativeProviders.filter((provider) => {+ if (provider.id === PI_PROVIDER_ID) return false;+ const candidateModel = provider.modelIdAliases?.[model] ?? model;+ return provider.models.some((candidate) => candidate.id === candidateModel);+ });+ if (matches.length > 1) {+ throw new Error(+ `pi: provider-less model '${model}' matches multiple native providers `+ + `(${matches.map((provider) => provider.id).join(', ')}); refusing to guess an endpoint.`,+ );+ }+ return matches[0]?.id ?? PI_PROVIDER_ID;};// 显式 BYOM 路由必须 fail closed:当调用方钉了一个既非 Cindy 网关(cindy/xd)也非// 订阅直连(openai/anthropic/xai)的自定义/本地 provider 时,该来源必须在本次解析出的@@ -884,7 +938,8 @@ export class PiAgent extends BaseAgent {if (!providerId || NON_BYOM_PROVIDER_IDS.has(providerId)) return false;if (resolveFailed) return true;const native = nativeProviderById.get(providerId);- return !native || !native.models.some((candidate) => candidate.id === model);+ const nativeModel = resolveNativeModelId(providerId, model);+ return !native || !native.models.some((candidate) => candidate.id === nativeModel);};if (explicitByomUnresolvable(opts.providerId, opts.model, nativeResolveFailed)) {throw new Error(@@ -896,6 +951,7 @@ export class PiAgent extends BaseAgent {);}const initialProvider = resolveProviderForModel(opts.model, opts.providerId);+ const initialPiModel = resolveNativeModelId(initialProvider, opts.model);// 轮 42 P2(codex-connector):远端 Pi 会话 + baseUrl 指向本机 loopback 的 BYOM// provider 必须拒绝 —— 远端 pi 进程在 SSH 主机上连 localhost 连的是**远端// 自己**, 用户本机的 Ollama 等服务不可达, 首回合必然失败/错配(甚至连到远端@@ -910,7 +966,7 @@ export class PiAgent extends BaseAgent {}for (const candidateId of candidateIds) {const loopbackNative = nativeProviderById.get(candidateId);- if (loopbackNative && isLoopbackOnlyBaseUrl(loopbackNative.baseUrl)) {+ if (loopbackNative && isLoopbackOnlyBaseUrl(loopbackNative.baseUrl) && !loopbackNative.hostProxyForward) {throw new Error(`[REMOTE_LOCAL_ONLY_PROVIDER] pi: BYOM provider '${candidateId}' baseUrl ${loopbackNative.baseUrl} is loopback-only — ` +'a remote Pi session runs on the SSH host and cannot reach a service on this machine; ' +@@ -986,7 +1042,9 @@ export class PiAgent extends BaseAgent {): readonly Effort[] | undefined => {if (providerId !== PI_PROVIDER_ID) {return startupEffortsOfNativeModel(- nativeProviderById.get(providerId)?.models.find((model) => model.id === modelId),+ nativeProviderById.get(providerId)?.models.find(+ (model) => model.id === resolveNativeModelId(providerId, modelId),+ ),);}const gatewayModel = modelId === opts.model && selectedRuntimeModel@@ -1030,7 +1088,10 @@ export class PiAgent extends BaseAgent {// pi 会把占位 key 当网关 key 打真实 upstream → 每个远端 turn 都失败。// 远端只支持 gateway-key(与 writeModelsJson 的远端分支一致)。fail-fast// 拒绝比「看似启动、首回合 401」可诊断。- if (opts.remoteHostId && credentialMode === 'oauth-bearer') {+ const remoteOAuthViaHostProxy = Boolean(+ opts.remoteHostId && nativeProviderById.get(initialProvider)?.hostProxyForward,+ );+ if (opts.remoteHostId && credentialMode === 'oauth-bearer' && !remoteOAuthViaHostProxy) {// 轮 42 P2(codex-connector):NotSupportedError 自己拼 message, 不带// bracketed code —— sessionCreateHandler 只认 [REMOTE_*] 前缀。message// 前加 [REMOTE_NATIVE_OAUTH_UNAVAILABLE] 让 renderer 走 5 语言可行动@@ -1406,7 +1467,7 @@ export class PiAgent extends BaseAgent {// 但文件缺失让扩展 fail-closed(不派发);后续每次 setModel 都会重试写// (writeSubagentRuntimeFile 由 subagentRuntimeWriteChain 串行), 文件恢复// 可写即自动恢复。- if (subagentRoutingEnabled && !(await writeSubagentRuntimeFile({ model: opts.model, provider: initialProvider }))) {+ if (subagentRoutingEnabled && !(await writeSubagentRuntimeFile({ model: initialPiModel, provider: initialProvider }))) {this.deps.logger.warn('pi subagent initial runtime snapshot write failed — routing stays enabled, will retry on next model set', {sessionId: opts.sessionId,});@@ -1594,7 +1655,7 @@ export class PiAgent extends BaseAgent {'--no-extensions','--session-dir', sessionDir,'--provider', initialProvider,- '--model', opts.model,+ '--model', initialPiModel,...(reviewMode ? ['--tools', 'read,grep,find,ls'] : []),...(appendSystemPrompt.length > 0 ? ['--append-system-prompt', appendSystemPrompt] : []),'--extension', bridgeExtensionPath,@@ -1708,6 +1769,7 @@ export class PiAgent extends BaseAgent {// preparePiExtraSpawnConfig 注册、但 handle 尚未交出,close() 不会跑 → 单独// 兜底注销 ctx 再抛(构造失败没有 proc 可关)。catch 必抛,故其后 proc 恒已赋值。let proc: PiRpcProcess;+ let sessionTransport: PiTransport | undefined;let runtimeCapabilityManifest: PiRuntimeCapabilityManifest | undefined;let runtimeCapabilityGeneration = 0;const runtimeCapabilityListeners = new Set<(@@ -1731,10 +1793,16 @@ export class PiAgent extends BaseAgent {notifyRuntimeCapabilityListener(listener, manifest);}};- // 远端会话直连网关(remoteEndpoint),不走本地 loopback compat proxy —— session- // token 只对本地代理鉴权有意义,远端注入纯属冗余凭证面(R5 安全审计 C-3):- // 不生成、不注册、不进 env-file。- const proxySessionToken = remote ? undefined : randomBytes(32).toString('base64url');+ // 普通远端会话直连网关(remoteEndpoint),不生成本地 proxy token。只有显式声明+ // hostProxyForward 的 provider(当前为 xAI)仍通过 Desktop compat proxy:+ // SSH 只解决可达性,session token 继续提供逐会话鉴权,不能把 loopback 端口+ // 当作信任边界。+ const remoteUsesHostProxy = remote && nativeProviders.some((provider) => provider.hostProxyForward);+ const proxySessionToken = remoteUsesHostProxy+ ? stableRemoteProxySessionToken(opts.sessionId, this.deps.derivePiProxySessionToken)+ : !remote+ ? randomBytes(32).toString('base64url')+ : undefined;let disposeProxySession: (() => void) | undefined;// 幂等:onExit(进程异常退出)与 close()(用户结束)可能都调用它;首次注销后置位,// 后续调用直接返回,避免二次注销(codex review:crash 时须由 onExit 立即释放)。@@ -1856,8 +1924,15 @@ export class PiAgent extends BaseAgent {spawnEnv[PI_PERMISSION_HASH_ENV] = permissionSnapshotHash;}mergeLoopbackNoProxy(spawnEnv);+ const initialHostProxyForward = nativeProviderById.get(initialProvider)?.hostProxyForward;const { transport } = await this.createTransport(- { args, cwd: opts.workingDir, env: spawnEnv, sessionId: opts.sessionId },+ {+ args,+ cwd: opts.workingDir,+ env: spawnEnv,+ sessionId: opts.sessionId,+ hostProxyForwards: initialHostProxyForward ? [initialHostProxyForward] : [],+ },(pid) =>this.deps.registerLocalAgentProcess?.({pid,@@ -1867,6 +1942,7 @@ export class PiAgent extends BaseAgent {opts.remoteHostId,effectivePiBinaryPath,);+ sessionTransport = transport;proc = new PiRpcProcess({transport,logger: this.deps.logger,@@ -2245,7 +2321,9 @@ export class PiAgent extends BaseAgent {? gatewayImageInputByModel.get(mutableModel) === true: nativeProviderById.get(mutablePiProviderId)- ?.models.find((candidate) => candidate.id === mutableModel)+ ?.models.find(+ (candidate) => candidate.id === resolveNativeModelId(mutablePiProviderId, mutableModel),+ )?.input?.includes('image') === true;if (supportsImageInput) return;throw new PiImageInputUnsupportedError();@@ -2307,6 +2385,21 @@ export class PiAgent extends BaseAgent {if (setOpts?.effort) {assertStartupEffortAllowed(nextEffortSnapshot, setOpts.effort);}+ // 远端启动快照保留会话内可切换的全部 native provider,但 SSH reverse-forward+ // 只为当前实际路由建立。否则用户仅仅登录过 xAI,就会在启动任意 Cindy/BYOM+ // 远程会话时抢占固定端口 47989;端口冲突会阻断一个完全不使用 xAI 的任务。+ // 切到 host-backed provider 前先按需建隧道,且必须排在子代理路由快照与+ // set_model RPC 之前:建隧道失败时父子路由都保持原值。+ const hostProxyForward = nativeProviderById.get(provider)?.hostProxyForward;+ if (remote && hostProxyForward) {+ if (!sessionTransport?.ensureHostProxyForward) {+ throw new Error(+ `[REMOTE_HOST_PROXY_FORWARD_UNAVAILABLE] pi: provider '${provider}' requires a Desktop host proxy forward, ` ++ 'but this remote transport cannot establish one; restart the session after reconnecting the remote host.',+ );+ }+ await sessionTransport.ensureHostProxyForward(hostProxyForward);+ }// 子代理路由快照必须**先落盘、再切 pi 侧模型**,顺序不能反(review)。//// 上一版是先 set_model 成功、再写快照,写失败就置 `subagentRoutingEnabled = false`。@@ -2327,8 +2420,12 @@ export class PiAgent extends BaseAgent {// 所以这一步落的是**带 pending 标记的**新路由:内容已经就位(证明可写、内容可回滚),但// 扩展见到 `pending: true` 就拒绝派发。等待窗口里一个子进程都起不来,既不会用未确认的新// 路由、也不会用与父不一致的旧路由;确认后再清掉标记放行。- const previousSnapshot = { model: mutableModel, provider: mutablePiProviderId };- if (!(await writeSubagentRuntimeFile({ model, provider, pending: true }))) {+ const previousSnapshot = {+ model: resolveNativeModelId(mutablePiProviderId, mutableModel),+ provider: mutablePiProviderId,+ };+ const nativeModel = resolveNativeModelId(provider, model);+ if (!(await writeSubagentRuntimeFile({ model: nativeModel, provider, pending: true }))) {throw new Error('pi: 无法持久化子代理路由快照,已取消本次模型切换(避免父会话切到新 provider 而子代理仍按旧路由派发)。'+ '请检查运行目录是否可写后重试。',@@ -2336,7 +2433,11 @@ export class PiAgent extends BaseAgent {}let resp;try {- resp = await proc.request({ type: 'set_model', provider, modelId: model });+ resp = await proc.request({+ type: 'set_model',+ provider,+ modelId: nativeModel,+ });} catch (err) {// RPC **reject / 超时 / 写 stdin 失败 / 进程已退出**:与 `success:false` 有本质区别 ——// 那种情况我们**知道**没生效,可以回滚;这里我们**不知道** pi 侧到底切没切。@@ -2405,7 +2506,7 @@ export class PiAgent extends BaseAgent {// pi 已确认 → 清掉 pending 标记放行派发。写失败时**不**抛错:模型切换本身确实成功了,// 谎报失败会让上层与 UI 状态和 pi 真实状态背离。代价是这个会话的子代理一直被 pending// 挡住(可见的降级、拒绝时有明确文案),而它是安全方向 —— 绝不会把委派发到错误 endpoint。- if (!(await writeSubagentRuntimeFile({ model, provider }))) {+ if (!(await writeSubagentRuntimeFile({ model: nativeModel, provider }))) {deps.logger.error('pi: model switch confirmed but the subagent routing snapshot stayed pending; '+ 'subagent delegation stays disabled for this session (fail-closed)',diff --git a/packages/maker-core/src/agents/pi/transport.ts b/packages/maker-core/src/agents/pi/transport.tsindex 91b5a5117c..354d058145 100644--- a/packages/maker-core/src/agents/pi/transport.ts+++ b/packages/maker-core/src/agents/pi/transport.ts@@ -78,6 +78,16 @@ export interface PiTransport {* 进程(对齐 CC/Codex daemon 生命周期)。普通(非 daemon)transport 不设。*/killRemoteSession?: () => Promise<void>;++ /**+ * (可选)远端会话按需建立 Desktop host loopback provider 的 SSH reverse-forward。+ * 启动时只为当前 provider 建隧道;会话内 setModel 切到其它 host-backed provider+ * 时先调用本钩子,成功后才允许更新路由快照或发送 set_model RPC。+ */+ ensureHostProxyForward?: (spec: {+ localUrl: string;+ remotePort: number;+ }) => Promise<void>;}export interface PiStdioTransportOptions {diff --git a/packages/model-providers/catalog/pi-model-catalog.json b/packages/model-providers/catalog/pi-model-catalog.jsonnew file mode 100644index 0000000000..735194814b--- /dev/null+++ b/packages/model-providers/catalog/pi-model-catalog.json@@ -0,0 +1,1929 @@+{+ "generatedAt": "2026-08-13T02:13:00.000Z",+ "providers": {+ "deepseek": [+ {+ "id": "deepseek-v4-flash",+ "name": "DeepSeek V4 Flash",+ "api": "openai-completions",+ "baseUrl": "https://api.deepseek.com",+ "provider": "deepseek",+ "reasoning": true,+ "input": [+ "text"+ ],+ "cost": {+ "input": 0.14,+ "output": 0.28,+ "cacheRead": 0.0028,+ "cacheWrite": 0+ },+ "contextWindow": 1000000,+ "maxTokens": 384000,+ "compat": {+ "supportsStore": false,+ "supportsDeveloperRole": false,+ "maxTokensField": "max_tokens",+ "requiresReasoningContentOnAssistantMessages": true,+ "thinkingFormat": "deepseek"+ },+ "thinkingLevelMap": {+ "minimal": null,+ "low": "low",+ "medium": null,+ "high": "high",+ "max": "max"+ }+ },+ {+ "id": "deepseek-v4-pro",+ "name": "DeepSeek V4 Pro",+ "api": "openai-completions",+ "baseUrl": "https://api.deepseek.com",+ "provider": "deepseek",+ "reasoning": true,+ "input": [+ "text"+ ],+ "cost": {+ "input": 0.435,+ "output": 0.87,+ "cacheRead": 0.003625,+ "cacheWrite": 0+ },+ "contextWindow": 1000000,+ "maxTokens": 384000,+ "compat": {+ "supportsStore": false,+ "supportsDeveloperRole": false,+ "maxTokensField": "max_tokens",+ "requiresReasoningContentOnAssistantMessages": true,+ "thinkingFormat": "deepseek"+ },+ "thinkingLevelMap": {+ "minimal": null,+ "low": null,+ "medium": null,+ "high": "high",+ "max": "max"+ }+ }+ ],+ "kimi-coding": [+ {+ "id": "k3",+ "name": "Kimi K3",+ "api": "anthropic-messages",+ "provider": "kimi-coding",+ "baseUrl": "https://api.kimi.com/coding",+ "headers": {+ "User-Agent": "KimiCLI/1.5"+ },+ "compat": {+ "allowEmptySignature": true,+ "forceAdaptiveThinking": true+ },+ "reasoning": true,+ "input": [+ "text",+ "image"+ ],+ "cost": {+ "input": 3,+ "output": 15,+ "cacheRead": 0.3,+ "cacheWrite": 0+ },+ "contextWindow": 1048576,+ "maxTokens": 131072,+ "thinkingLevelMap": {+ "off": null,+ "minimal": null,+ "low": "low",+ "medium": null,+ "high": "high",+ "xhigh": null,+ "max": "max"+ }+ },+ {+ "id": "k3-256k",+ "name": "Kimi K3-256K",+ "api": "anthropic-messages",+ "provider": "kimi-coding",+ "baseUrl": "https://api.kimi.com/coding",+ "headers": {+ "User-Agent": "KimiCLI/1.5"+ },+ "compat": {+ "forceAdaptiveThinking": true+ },+ "reasoning": true,+ "input": [+ "text",+ "image"+ ],+ "cost": {+ "input": 0,+ "output": 0,+ "cacheRead": 0,+ "cacheWrite": 0+ },+ "contextWindow": 262144,+ "maxTokens": 131072,+ "thinkingLevelMap": {+ "off": null,+ "minimal": null,+ "low": "low",+ "medium": null,+ "high": "high",+ "xhigh": null,+ "max": "max"+ }+ },+ {+ "id": "kimi-for-coding",+ "name": "Kimi K2.7 Code",+ "api": "anthropic-messages",+ "provider": "kimi-coding",+ "baseUrl": "https://api.kimi.com/coding",+ "headers": {+ "User-Agent": "KimiCLI/1.5"+ },+ "compat": {+ "allowEmptySignature": true,+ "forceAdaptiveThinking": true+ },+ "reasoning": true,+ "input": [+ "text",+ "image"+ ],+ "cost": {+ "input": 0.95,+ "output": 4,+ "cacheRead": 0.19,+ "cacheWrite": 0+ },+ "contextWindow": 262144,+ "maxTokens": 32768+ },+ {+ "id": "kimi-for-coding-highspeed",+ "name": "Kimi For Coding HighSpeed",+ "api": "anthropic-messages",+ "provider": "kimi-coding",+ "baseUrl": "https://api.kimi.com/coding",+ "headers": {+ "User-Agent": "KimiCLI/1.5"+ },+ "compat": {+ "forceAdaptiveThinking": true+ },+ "reasoning": true,+ "input": [+ "text",+ "image"+ ],+ "cost": {+ "input": 1.9,+ "output": 8,+ "cacheRead": 0.38,+ "cacheWrite": 0+ },+ "contextWindow": 262144,+ "maxTokens": 32768+ }+ ],+ "minimax": [+ {+ "id": "MiniMax-M2.7",+ "name": "MiniMax-M2.7",+ "api": "anthropic-messages",+ "provider": "minimax",+ "baseUrl": "https://api.minimax.io/anthropic",+ "reasoning": true,+ "input": [+ "text"+ ],+ "cost": {+ "input": 0.3,+ "output": 1.2,+ "cacheRead": 0.06,+ "cacheWrite": 0.375+ },+ "contextWindow": 204800,+ "maxTokens": 131072+ },+ {+ "id": "MiniMax-M2.7-highspeed",+ "name": "MiniMax-M2.7-highspeed",+ "api": "anthropic-messages",+ "provider": "minimax",+ "baseUrl": "https://api.minimax.io/anthropic",+ "reasoning": true,+ "input": [+ "text"+ ],+ "cost": {+ "input": 0.6,+ "output": 2.4,+ "cacheRead": 0.06,+ "cacheWrite": 0.375+ },+ "contextWindow": 204800,+ "maxTokens": 131072+ },+ {+ "id": "MiniMax-M3",+ "name": "MiniMax-M3",+ "api": "anthropic-messages",+ "provider": "minimax",+ "baseUrl": "https://api.minimax.io/anthropic",+ "reasoning": true,+ "input": [+ "text",+ "image"+ ],+ "cost": {+ "input": 0.3,+ "output": 1.2,+ "cacheRead": 0.06,+ "cacheWrite": 0+ },+ "contextWindow": 1000000,+ "maxTokens": 128000+ }+ ],+ "minimax-cn": [+ {+ "id": "MiniMax-M2.7",+ "name": "MiniMax-M2.7",+ "api": "anthropic-messages",+ "provider": "minimax-cn",+ "baseUrl": "https://api.minimaxi.com/anthropic",+ "reasoning": true,+ "input": [+ "text"+ ],+ "cost": {+ "input": 0.3,+ "output": 1.2,+ "cacheRead": 0.06,+ "cacheWrite": 0.375+ },+ "contextWindow": 204800,+ "maxTokens": 131072+ },+ {+ "id": "MiniMax-M2.7-highspeed",+ "name": "MiniMax-M2.7-highspeed",+ "api": "anthropic-messages",+ "provider": "minimax-cn",+ "baseUrl": "https://api.minimaxi.com/anthropic",+ "reasoning": true,+ "input": [+ "text"+ ],+ "cost": {+ "input": 0.6,+ "output": 2.4,+ "cacheRead": 0.06,+ "cacheWrite": 0.375+ },+ "contextWindow": 204800,+ "maxTokens": 131072+ },+ {+ "id": "MiniMax-M3",+ "name": "MiniMax-M3",+ "api": "anthropic-messages",+ "provider": "minimax-cn",+ "baseUrl": "https://api.minimaxi.com/anthropic",+ "reasoning": true,+ "input": [+ "text",+ "image"+ ],+ "cost": {+ "input": 0.3,+ "output": 1.2,+ "cacheRead": 0.06,+ "cacheWrite": 0+ },+ "contextWindow": 1000000,+ "maxTokens": 128000+ }+ ],+ "moonshotai": [+ {+ "id": "kimi-k2-0711-preview",+ "name": "Kimi K2 0711",+ "api": "openai-completions",+ "provider": "moonshotai",+ "baseUrl": "https://api.moonshot.ai/v1",+ "reasoning": false,+ "input": [+ "text"+ ],+ "cost": {+ "input": 0.6,+ "output": 2.5,+ "cacheRead": 0.15,+ "cacheWrite": 0+ },+ "contextWindow": 131072,+ "maxTokens": 16384,+ "compat": {+ "supportsStore": false,+ "supportsDeveloperRole": false,+ "supportsReasoningEffort": false,+ "maxTokensField": "max_tokens",+ "supportsStrictMode": false,+ "thinkingFormat": "deepseek"+ }+ },+ {+ "id": "kimi-k2-0905-preview",+ "name": "Kimi K2 0905",+ "api": "openai-completions",+ "provider": "moonshotai",+ "baseUrl": "https://api.moonshot.ai/v1",+ "reasoning": false,+ "input": [+ "text"+ ],+ "cost": {+ "input": 0.6,+ "output": 2.5,+ "cacheRead": 0.15,+ "cacheWrite": 0+ },+ "contextWindow": 262144,+ "maxTokens": 262144,+ "compat": {+ "supportsStore": false,+ "supportsDeveloperRole": false,+ "supportsReasoningEffort": false,+ "maxTokensField": "max_tokens",+ "supportsStrictMode": false,+ "thinkingFormat": "deepseek"+ }+ },+ {+ "id": "kimi-k2-thinking",+ "name": "Kimi K2 Thinking",+ "api": "openai-completions",+ "provider": "moonshotai",+ "baseUrl": "https://api.moonshot.ai/v1",+ "reasoning": true,+ "input": [+ "text"+ ],+ "cost": {+ "input": 0.6,+ "output": 2.5,+ "cacheRead": 0.15,+ "cacheWrite": 0+ },+ "contextWindow": 262144,+ "maxTokens": 262144,+ "compat": {+ "supportsStore": false,+ "supportsDeveloperRole": false,+ "supportsReasoningEffort": false,+ "maxTokensField": "max_tokens",+ "supportsStrictMode": false,+ "thinkingFormat": "deepseek"+ }+ },+ {+ "id": "kimi-k2-thinking-turbo",+ "name": "Kimi K2 Thinking Turbo",+ "api": "openai-completions",+ "provider": "moonshotai",+ "baseUrl": "https://api.moonshot.ai/v1",+ "reasoning": true,+ "input": [+ "text"+ ],+ "cost": {+ "input": 1.15,+ "output": 8,+ "cacheRead": 0.15,+ "cacheWrite": 0+ },+ "contextWindow": 262144,+ "maxTokens": 262144,+ "compat": {+ "supportsStore": false,+ "supportsDeveloperRole": false,+ "supportsReasoningEffort": false,+ "maxTokensField": "max_tokens",+ "supportsStrictMode": false,+ "thinkingFormat": "deepseek"+ }+ },+ {+ "id": "kimi-k2-turbo-preview",+ "name": "Kimi K2 Turbo",+ "api": "openai-completions",+ "provider": "moonshotai",+ "baseUrl": "https://api.moonshot.ai/v1",+ "reasoning": false,+ "input": [+ "text"+ ],+ "cost": {+ "input": 2.4,+ "output": 10,+ "cacheRead": 0.6,+ "cacheWrite": 0+ },+ "contextWindow": 262144,+ "maxTokens": 262144,+ "compat": {+ "supportsStore": false,+ "supportsDeveloperRole": false,+ "supportsReasoningEffort": false,+ "maxTokensField": "max_tokens",+ "supportsStrictMode": false,+ "thinkingFormat": "deepseek"+ }+ },+ {+ "id": "kimi-k2.5",+ "name": "Kimi K2.5",+ "api": "openai-completions",+ "provider": "moonshotai",+ "baseUrl": "https://api.moonshot.ai/v1",+ "reasoning": true,+ "input": [+ "text",+ "image"+ ],+ "cost": {+ "input": 0.6,+ "output": 3,+ "cacheRead": 0.1,+ "cacheWrite": 0+ },+ "contextWindow": 262144,+ "maxTokens": 262144,+ "compat": {+ "supportsStore": false,+ "supportsDeveloperRole": false,+ "supportsReasoningEffort": false,+ "maxTokensField": "max_tokens",+ "supportsStrictMode": false,+ "thinkingFormat": "deepseek"+ }+ },+ {+ "id": "kimi-k2.6",+ "name": "Kimi K2.6",+ "api": "openai-completions",+ "provider": "moonshotai",+ "baseUrl": "https://api.moonshot.ai/v1",+ "reasoning": true,+ "input": [+ "text",+ "image"+ ],+ "cost": {+ "input": 0.95,+ "output": 4,+ "cacheRead": 0.16,+ "cacheWrite": 0+ },+ "contextWindow": 262144,+ "maxTokens": 262144,+ "compat": {+ "supportsStore": false,+ "supportsDeveloperRole": false,+ "supportsReasoningEffort": false,+ "maxTokensField": "max_tokens",+ "supportsStrictMode": false,+ "thinkingFormat": "deepseek"+ }+ },+ {+ "id": "kimi-k2.7-code",+ "name": "Kimi K2.7 Code",+ "api": "openai-completions",+ "provider": "moonshotai",+ "baseUrl": "https://api.moonshot.ai/v1",+ "reasoning": true,+ "input": [+ "text",+ "image"+ ],+ "cost": {+ "input": 0.95,+ "output": 4,+ "cacheRead": 0.19,+ "cacheWrite": 0+ },+ "contextWindow": 262144,+ "maxTokens": 262144,+ "compat": {+ "supportsStore": false,+ "supportsDeveloperRole": false,+ "supportsReasoningEffort": false,+ "maxTokensField": "max_tokens",+ "supportsStrictMode": false,+ "thinkingFormat": "deepseek"+ },+ "thinkingLevelMap": {+ "off": null+ }+ },+ {+ "id": "kimi-k2.7-code-highspeed",+ "name": "Kimi K2.7 Code HighSpeed",+ "api": "openai-completions",+ "provider": "moonshotai",+ "baseUrl": "https://api.moonshot.ai/v1",+ "reasoning": true,+ "input": [+ "text",+ "image"+ ],+ "cost": {+ "input": 1.9,+ "output": 8,+ "cacheRead": 0.38,+ "cacheWrite": 0+ },+ "contextWindow": 262144,+ "maxTokens": 262144,+ "compat": {+ "supportsStore": false,+ "supportsDeveloperRole": false,+ "supportsReasoningEffort": false,+ "maxTokensField": "max_tokens",+ "supportsStrictMode": false,+ "thinkingFormat": "deepseek"+ },+ "thinkingLevelMap": {+ "off": null+ }+ },+ {+ "id": "kimi-k3",+ "name": "Kimi K3",+ "api": "openai-completions",+ "provider": "moonshotai",+ "baseUrl": "https://api.moonshot.ai/v1",+ "reasoning": true,+ "input": [+ "text",+ "image"+ ],+ "cost": {+ "input": 3,+ "output": 15,+ "cacheRead": 0.3,+ "cacheWrite": 0+ },+ "contextWindow": 1048576,+ "maxTokens": 131072,+ "compat": {+ "supportsStore": false,+ "supportsDeveloperRole": false,+ "supportsReasoningEffort": true,+ "maxTokensField": "max_tokens",+ "supportsStrictMode": false,+ "thinkingFormat": "openai",+ "requiresReasoningContentOnAssistantMessages": true,+ "deferredToolsMode": "kimi"+ },+ "thinkingLevelMap": {+ "off": null,+ "minimal": null,+ "low": "low",+ "medium": null,+ "high": "high",+ "xhigh": null,+ "max": "max"+ }+ }+ ],+ "moonshotai-cn": [+ {+ "id": "kimi-k2-0711-preview",+ "name": "Kimi K2 0711",+ "api": "openai-completions",+ "provider": "moonshotai-cn",+ "baseUrl": "https://api.moonshot.cn/v1",+ "reasoning": false,+ "input": [+ "text"+ ],+ "cost": {+ "input": 0.6,+ "output": 2.5,+ "cacheRead": 0.15,+ "cacheWrite": 0+ },+ "contextWindow": 131072,+ "maxTokens": 16384,+ "compat": {+ "supportsStore": false,+ "supportsDeveloperRole": false,+ "supportsReasoningEffort": false,+ "maxTokensField": "max_tokens",+ "supportsStrictMode": false,+ "thinkingFormat": "deepseek"+ }+ },+ {+ "id": "kimi-k2-0905-preview",+ "name": "Kimi K2 0905",+ "api": "openai-completions",+ "provider": "moonshotai-cn",+ "baseUrl": "https://api.moonshot.cn/v1",+ "reasoning": false,+ "input": [+ "text"+ ],+ "cost": {+ "input": 0.6,+ "output": 2.5,+ "cacheRead": 0.15,+ "cacheWrite": 0+ },+ "contextWindow": 262144,+ "maxTokens": 262144,+ "compat": {+ "supportsStore": false,+ "supportsDeveloperRole": false,+ "supportsReasoningEffort": false,+ "maxTokensField": "max_tokens",+ "supportsStrictMode": false,+ "thinkingFormat": "deepseek"+ }+ },+ {+ "id": "kimi-k2-thinking",+ "name": "Kimi K2 Thinking",+ "api": "openai-completions",+ "provider": "moonshotai-cn",+ "baseUrl": "https://api.moonshot.cn/v1",+ "reasoning": true,+ "input": [+ "text"+ ],+ "cost": {+ "input": 0.6,+ "output": 2.5,+ "cacheRead": 0.15,+ "cacheWrite": 0+ },+ "contextWindow": 262144,+ "maxTokens": 262144,+ "compat": {+ "supportsStore": false,+ "supportsDeveloperRole": false,+ "supportsReasoningEffort": false,+ "maxTokensField": "max_tokens",+ "supportsStrictMode": false,+ "thinkingFormat": "deepseek"+ }+ },+ {+ "id": "kimi-k2-thinking-turbo",+ "name": "Kimi K2 Thinking Turbo",+ "api": "openai-completions",+ "provider": "moonshotai-cn",+ "baseUrl": "https://api.moonshot.cn/v1",+ "reasoning": true,+ "input": [+ "text"+ ],+ "cost": {+ "input": 1.15,+ "output": 8,+ "cacheRead": 0.15,+ "cacheWrite": 0+ },+ "contextWindow": 262144,+ "maxTokens": 262144,+ "compat": {+ "supportsStore": false,+ "supportsDeveloperRole": false,+ "supportsReasoningEffort": false,+ "maxTokensField": "max_tokens",+ "supportsStrictMode": false,+ "thinkingFormat": "deepseek"+ }+ },+ {+ "id": "kimi-k2-turbo-preview",+ "name": "Kimi K2 Turbo",+ "api": "openai-completions",+ "provider": "moonshotai-cn",+ "baseUrl": "https://api.moonshot.cn/v1",+ "reasoning": false,+ "input": [+ "text"+ ],+ "cost": {+ "input": 2.4,+ "output": 10,+ "cacheRead": 0.6,+ "cacheWrite": 0+ },+ "contextWindow": 262144,+ "maxTokens": 262144,+ "compat": {+ "supportsStore": false,+ "supportsDeveloperRole": false,+ "supportsReasoningEffort": false,+ "maxTokensField": "max_tokens",+ "supportsStrictMode": false,+ "thinkingFormat": "deepseek"+ }+ },+ {+ "id": "kimi-k2.5",+ "name": "Kimi K2.5",+ "api": "openai-completions",+ "provider": "moonshotai-cn",+ "baseUrl": "https://api.moonshot.cn/v1",+ "reasoning": true,+ "input": [+ "text",+ "image"+ ],+ "cost": {+ "input": 0.6,+ "output": 3,+ "cacheRead": 0.1,+ "cacheWrite": 0+ },+ "contextWindow": 262144,+ "maxTokens": 262144,+ "compat": {+ "supportsStore": false,+ "supportsDeveloperRole": false,+ "supportsReasoningEffort": false,+ "maxTokensField": "max_tokens",+ "supportsStrictMode": false,+ "thinkingFormat": "deepseek"+ }+ },+ {+ "id": "kimi-k2.6",+ "name": "Kimi K2.6",+ "api": "openai-completions",+ "provider": "moonshotai-cn",+ "baseUrl": "https://api.moonshot.cn/v1",+ "reasoning": true,+ "input": [+ "text",+ "image"+ ],+ "cost": {+ "input": 0.95,+ "output": 4,+ "cacheRead": 0.16,+ "cacheWrite": 0+ },+ "contextWindow": 262144,+ "maxTokens": 262144,+ "compat": {+ "supportsStore": false,+ "supportsDeveloperRole": false,+ "supportsReasoningEffort": false,+ "maxTokensField": "max_tokens",+ "supportsStrictMode": false,+ "thinkingFormat": "deepseek"+ }+ },+ {+ "id": "kimi-k2.7-code",+ "name": "Kimi K2.7 Code",+ "api": "openai-completions",+ "provider": "moonshotai-cn",+ "baseUrl": "https://api.moonshot.cn/v1",+ "reasoning": true,+ "input": [+ "text",+ "image"+ ],+ "cost": {+ "input": 0.95,+ "output": 4,+ "cacheRead": 0.19,+ "cacheWrite": 0+ },+ "contextWindow": 262144,+ "maxTokens": 262144,+ "compat": {+ "supportsStore": false,+ "supportsDeveloperRole": false,+ "supportsReasoningEffort": false,+ "maxTokensField": "max_tokens",+ "supportsStrictMode": false,+ "thinkingFormat": "deepseek"+ },+ "thinkingLevelMap": {+ "off": null+ }+ },+ {+ "id": "kimi-k2.7-code-highspeed",+ "name": "Kimi K2.7 Code HighSpeed",+ "api": "openai-completions",+ "provider": "moonshotai-cn",+ "baseUrl": "https://api.moonshot.cn/v1",+ "reasoning": true,+ "input": [+ "text",+ "image"+ ],+ "cost": {+ "input": 1.9,+ "output": 8,+ "cacheRead": 0.38,+ "cacheWrite": 0+ },+ "contextWindow": 262144,+ "maxTokens": 262144,+ "compat": {+ "supportsStore": false,+ "supportsDeveloperRole": false,+ "supportsReasoningEffort": false,+ "maxTokensField": "max_tokens",+ "supportsStrictMode": false,+ "thinkingFormat": "deepseek"+ },+ "thinkingLevelMap": {+ "off": null+ }+ },+ {+ "id": "kimi-k3",+ "name": "Kimi K3",+ "api": "openai-completions",+ "provider": "moonshotai-cn",+ "baseUrl": "https://api.moonshot.cn/v1",+ "reasoning": true,+ "input": [+ "text",+ "image"+ ],+ "cost": {+ "input": 3,+ "output": 15,+ "cacheRead": 0.3,+ "cacheWrite": 0+ },+ "contextWindow": 1048576,+ "maxTokens": 131072,+ "compat": {+ "supportsStore": false,+ "supportsDeveloperRole": false,+ "supportsReasoningEffort": true,+ "maxTokensField": "max_tokens",+ "supportsStrictMode": false,+ "thinkingFormat": "openai",+ "requiresReasoningContentOnAssistantMessages": true,+ "deferredToolsMode": "kimi"+ },+ "thinkingLevelMap": {+ "off": null,+ "minimal": null,+ "low": "low",+ "medium": null,+ "high": "high",+ "xhigh": null,+ "max": "max"+ }+ }+ ],+ "qwen-token-plan-cn": [+ {+ "id": "MiniMax-M2.5",+ "name": "MiniMax-M2.5",+ "api": "openai-completions",+ "provider": "qwen-token-plan-cn",+ "baseUrl": "https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",+ "compat": {+ "thinkingFormat": "qwen",+ "supportsDeveloperRole": false,+ "supportsStore": false,+ "supportsReasoningEffort": false+ },+ "reasoning": true,+ "input": [+ "text"+ ],+ "cost": {+ "input": 0,+ "output": 0,+ "cacheRead": 0,+ "cacheWrite": 0+ },+ "contextWindow": 196608,+ "maxTokens": 32768+ },+ {+ "id": "deepseek-v3.2",+ "name": "DeepSeek V3.2",+ "api": "openai-completions",+ "provider": "qwen-token-plan-cn",+ "baseUrl": "https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",+ "compat": {+ "thinkingFormat": "qwen",+ "supportsDeveloperRole": false,+ "supportsStore": false,+ "supportsReasoningEffort": false+ },+ "reasoning": true,+ "input": [+ "text"+ ],+ "cost": {+ "input": 0,+ "output": 0,+ "cacheRead": 0,+ "cacheWrite": 0+ },+ "contextWindow": 131072,+ "maxTokens": 65536+ },+ {+ "id": "deepseek-v4-flash",+ "name": "DeepSeek V4 Flash",+ "api": "openai-completions",+ "provider": "qwen-token-plan-cn",+ "baseUrl": "https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",+ "compat": {+ "thinkingFormat": "qwen",+ "supportsDeveloperRole": false,+ "supportsStore": false,+ "supportsReasoningEffort": true+ },+ "thinkingLevelMap": {+ "minimal": null,+ "low": null,+ "medium": null,+ "high": "high",+ "xhigh": null,+ "max": "max"+ },+ "reasoning": true,+ "input": [+ "text"+ ],+ "cost": {+ "input": 0,+ "output": 0,+ "cacheRead": 0,+ "cacheWrite": 0+ },+ "contextWindow": 1000000,+ "maxTokens": 384000+ },+ {+ "id": "deepseek-v4-flash-0731",+ "name": "DeepSeek V4 Flash 0731",+ "api": "openai-completions",+ "provider": "qwen-token-plan-cn",+ "baseUrl": "https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",+ "compat": {+ "thinkingFormat": "qwen",+ "supportsDeveloperRole": false,+ "supportsStore": false,+ "supportsReasoningEffort": true+ },+ "thinkingLevelMap": {+ "minimal": null,+ "low": null,+ "medium": null,+ "high": "high",+ "xhigh": null,+ "max": "max"+ },+ "reasoning": true,+ "input": [+ "text"+ ],+ "cost": {+ "input": 0,+ "output": 0,+ "cacheRead": 0,+ "cacheWrite": 0+ },+ "contextWindow": 1000000,+ "maxTokens": 384000+ },+ {+ "id": "deepseek-v4-pro",+ "name": "DeepSeek V4 Pro",+ "api": "openai-completions",+ "provider": "qwen-token-plan-cn",+ "baseUrl": "https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",+ "compat": {+ "thinkingFormat": "qwen",+ "supportsDeveloperRole": false,+ "supportsStore": false,+ "supportsReasoningEffort": true+ },+ "thinkingLevelMap": {+ "minimal": null,+ "low": null,+ "medium": null,+ "high": "high",+ "xhigh": null,+ "max": "max"+ },+ "reasoning": true,+ "input": [+ "text"+ ],+ "cost": {+ "input": 0,+ "output": 0,+ "cacheRead": 0,+ "cacheWrite": 0+ },+ "contextWindow": 1000000,+ "maxTokens": 384000+ },+ {+ "id": "glm-5",+ "name": "GLM-5",+ "api": "openai-completions",+ "provider": "qwen-token-plan-cn",+ "baseUrl": "https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",+ "compat": {+ "thinkingFormat": "qwen",+ "supportsDeveloperRole": false,+ "supportsStore": false,+ "supportsReasoningEffort": true+ },+ "thinkingLevelMap": {+ "minimal": null,+ "low": null,+ "medium": null,+ "high": "high",+ "xhigh": null,+ "max": "max"+ },+ "reasoning": true,+ "input": [+ "text"+ ],+ "cost": {+ "input": 0,+ "output": 0,+ "cacheRead": 0,+ "cacheWrite": 0+ },+ "contextWindow": 202752,+ "maxTokens": 16384+ },+ {+ "id": "glm-5.1",+ "name": "GLM-5.1",+ "api": "openai-completions",+ "provider": "qwen-token-plan-cn",+ "baseUrl": "https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",+ "compat": {+ "thinkingFormat": "qwen",+ "supportsDeveloperRole": false,+ "supportsStore": false,+ "supportsReasoningEffort": true+ },+ "thinkingLevelMap": {+ "minimal": null,+ "low": null,+ "medium": null,+ "high": "high",+ "xhigh": null,+ "max": "max"+ },+ "reasoning": true,+ "input": [+ "text"+ ],+ "cost": {+ "input": 0,+ "output": 0,+ "cacheRead": 0,+ "cacheWrite": 0+ },+ "contextWindow": 202752,+ "maxTokens": 128000+ },+ {+ "id": "glm-5.2",+ "name": "GLM-5.2",+ "api": "openai-completions",+ "provider": "qwen-token-plan-cn",+ "baseUrl": "https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",+ "compat": {+ "thinkingFormat": "qwen",+ "supportsDeveloperRole": false,+ "supportsStore": false,+ "supportsReasoningEffort": true+ },+ "thinkingLevelMap": {+ "minimal": null,+ "low": null,+ "medium": null,+ "high": "high",+ "xhigh": null,+ "max": "max"+ },+ "reasoning": true,+ "input": [+ "text"+ ],+ "cost": {+ "input": 0,+ "output": 0,+ "cacheRead": 0,+ "cacheWrite": 0+ },+ "contextWindow": 1000000,+ "maxTokens": 131072+ },+ {+ "id": "kimi-k2.5",+ "name": "Kimi K2.5",+ "api": "openai-completions",+ "provider": "qwen-token-plan-cn",+ "baseUrl": "https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",+ "compat": {+ "thinkingFormat": "qwen",+ "supportsDeveloperRole": false,+ "supportsStore": false,+ "supportsReasoningEffort": false+ },+ "reasoning": true,+ "input": [+ "text",+ "image"+ ],+ "cost": {+ "input": 0,+ "output": 0,+ "cacheRead": 0,+ "cacheWrite": 0+ },+ "contextWindow": 262144,+ "maxTokens": 98304+ },+ {+ "id": "kimi-k2.6",+ "name": "Kimi K2.6",+ "api": "openai-completions",+ "provider": "qwen-token-plan-cn",+ "baseUrl": "https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",+ "compat": {+ "thinkingFormat": "qwen",+ "supportsDeveloperRole": false,+ "supportsStore": false,+ "supportsReasoningEffort": false+ },+ "reasoning": true,+ "input": [+ "text",+ "image"+ ],+ "cost": {+ "input": 0,+ "output": 0,+ "cacheRead": 0,+ "cacheWrite": 0+ },+ "contextWindow": 262144,+ "maxTokens": 262144+ },+ {+ "id": "kimi-k2.7-code",+ "name": "Kimi K2.7 Code",+ "api": "openai-completions",+ "provider": "qwen-token-plan-cn",+ "baseUrl": "https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",+ "compat": {+ "thinkingFormat": "qwen",+ "supportsDeveloperRole": false,+ "supportsStore": false,+ "supportsReasoningEffort": false+ },+ "reasoning": true,+ "input": [+ "text",+ "image"+ ],+ "cost": {+ "input": 0,+ "output": 0,+ "cacheRead": 0,+ "cacheWrite": 0+ },+ "contextWindow": 262144,+ "maxTokens": 262144+ },+ {+ "id": "qwen3.6-flash",+ "name": "Qwen3.6 Flash",+ "api": "openai-completions",+ "provider": "qwen-token-plan-cn",+ "baseUrl": "https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",+ "compat": {+ "thinkingFormat": "qwen",+ "supportsDeveloperRole": false,+ "supportsStore": false,+ "supportsReasoningEffort": false+ },+ "reasoning": true,+ "input": [+ "text",+ "image"+ ],+ "cost": {+ "input": 0,+ "output": 0,+ "cacheRead": 0,+ "cacheWrite": 0+ },+ "contextWindow": 1000000,+ "maxTokens": 65536+ },+ {+ "id": "qwen3.6-plus",+ "name": "Qwen3.6 Plus",+ "api": "openai-completions",+ "provider": "qwen-token-plan-cn",+ "baseUrl": "https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",+ "compat": {+ "thinkingFormat": "qwen",+ "supportsDeveloperRole": false,+ "supportsStore": false,+ "supportsReasoningEffort": false+ },+ "reasoning": true,+ "input": [+ "text",+ "image"+ ],+ "cost": {+ "input": 0,+ "output": 0,+ "cacheRead": 0,+ "cacheWrite": 0+ },+ "contextWindow": 1000000,+ "maxTokens": 65536+ },+ {+ "id": "qwen3.7-max",+ "name": "Qwen3.7 Max",+ "api": "openai-completions",+ "provider": "qwen-token-plan-cn",+ "baseUrl": "https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",+ "compat": {+ "thinkingFormat": "qwen",+ "supportsDeveloperRole": false,+ "supportsStore": false,+ "supportsReasoningEffort": false+ },+ "reasoning": true,+ "input": [+ "text"+ ],+ "cost": {+ "input": 0,+ "output": 0,+ "cacheRead": 0,+ "cacheWrite": 0+ },+ "contextWindow": 1000000,+ "maxTokens": 131072+ },+ {+ "id": "qwen3.7-plus",+ "name": "Qwen3.7 Plus",+ "api": "openai-completions",+ "provider": "qwen-token-plan-cn",+ "baseUrl": "https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",+ "compat": {+ "thinkingFormat": "qwen",+ "supportsDeveloperRole": false,+ "supportsStore": false,+ "supportsReasoningEffort": false+ },+ "reasoning": true,+ "input": [+ "text",+ "image"+ ],+ "cost": {+ "input": 0,+ "output": 0,+ "cacheRead": 0,+ "cacheWrite": 0+ },+ "contextWindow": 1000000,+ "maxTokens": 65536+ },+ {+ "id": "qwen3.8-max",+ "name": "Qwen3.8 Max",+ "api": "openai-completions",+ "provider": "qwen-token-plan-cn",+ "baseUrl": "https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",+ "compat": {+ "thinkingFormat": "qwen",+ "supportsDeveloperRole": false,+ "supportsStore": false,+ "supportsReasoningEffort": true+ },+ "thinkingLevelMap": {+ "minimal": null,+ "low": "low",+ "medium": "medium",+ "high": null,+ "xhigh": "xhigh",+ "max": null+ },+ "reasoning": true,+ "input": [+ "text",+ "image"+ ],+ "cost": {+ "input": 0,+ "output": 0,+ "cacheRead": 0,+ "cacheWrite": 0+ },+ "contextWindow": 1000000,+ "maxTokens": 131072+ }+ ],+ "xai": [+ {+ "id": "grok-4.3",+ "name": "Grok 4.3",+ "api": "openai-completions",+ "provider": "xai",+ "baseUrl": "https://api.x.ai/v1",+ "reasoning": true,+ "input": [+ "text",+ "image"+ ],+ "cost": {+ "input": 1.25,+ "output": 2.5,+ "cacheRead": 0.2,+ "cacheWrite": 0+ },+ "contextWindow": 1000000,+ "maxTokens": 30000,+ "compat": {+ "supportsStore": false,+ "supportsDeveloperRole": false,+ "supportsReasoningEffort": false+ }+ },+ {+ "id": "grok-4.5",+ "name": "Grok 4.5",+ "api": "openai-responses",+ "provider": "xai",+ "baseUrl": "https://api.x.ai/v1",+ "compat": {+ "supportsLongCacheRetention": false+ },+ "reasoning": true,+ "input": [+ "text",+ "image"+ ],+ "cost": {+ "input": 2,+ "output": 6,+ "cacheRead": 0.3,+ "cacheWrite": 0+ },+ "contextWindow": 500000,+ "maxTokens": 500000,+ "thinkingLevelMap": {+ "off": null,+ "minimal": null,+ "low": "low",+ "medium": "medium",+ "high": "high",+ "xhigh": null,+ "max": null+ }+ },+ {+ "id": "grok-4.6",+ "name": "Grok 4.6",+ "api": "openai-completions",+ "provider": "xai",+ "baseUrl": "https://api.x.ai/v1",+ "reasoning": true,+ "input": [+ "text",+ "image"+ ],+ "cost": {+ "input": 2,+ "output": 6,+ "cacheRead": 0.5,+ "cacheWrite": 0+ },+ "contextWindow": 500000,+ "maxTokens": 500000,+ "compat": {+ "supportsStore": false,+ "supportsDeveloperRole": false,+ "supportsReasoningEffort": false+ }+ },+ {+ "id": "grok-build-0.1",+ "name": "Grok Build 0.1",+ "api": "openai-completions",+ "provider": "xai",+ "baseUrl": "https://api.x.ai/v1",+ "reasoning": true,+ "input": [+ "text",+ "image"+ ],+ "cost": {+ "input": 1,+ "output": 2,+ "cacheRead": 0.2,+ "cacheWrite": 0+ },+ "contextWindow": 256000,+ "maxTokens": 256000,+ "compat": {+ "supportsStore": false,+ "supportsDeveloperRole": false,+ "supportsReasoningEffort": false+ }+ }+ ],+ "xiaomi": [+ {+ "id": "mimo-v2-flash",+ "name": "MiMo-V2-Flash",+ "api": "openai-completions",+ "provider": "xiaomi",+ "baseUrl": "https://api.xiaomimimo.com/v1",+ "compat": {+ "requiresReasoningContentOnAssistantMessages": true,+ "thinkingFormat": "deepseek"+ },+ "reasoning": true,+ "input": [+ "text"+ ],+ "cost": {+ "input": 0.14,+ "output": 0.28,+ "cacheRead": 0.0028,+ "cacheWrite": 0+ },+ "contextWindow": 262144,+ "maxTokens": 65536+ },+ {+ "id": "mimo-v2-omni",+ "name": "MiMo-V2-Omni",+ "api": "openai-completions",+ "provider": "xiaomi",+ "baseUrl": "https://api.xiaomimimo.com/v1",+ "compat": {+ "requiresReasoningContentOnAssistantMessages": true,+ "thinkingFormat": "deepseek"+ },+ "reasoning": true,+ "input": [+ "text",+ "image"+ ],+ "cost": {+ "input": 0.14,+ "output": 0.28,+ "cacheRead": 0.0028,+ "cacheWrite": 0+ },+ "contextWindow": 262144,+ "maxTokens": 131072+ },+ {+ "id": "mimo-v2-pro",+ "name": "MiMo-V2-Pro",+ "api": "openai-completions",+ "provider": "xiaomi",+ "baseUrl": "https://api.xiaomimimo.com/v1",+ "compat": {+ "requiresReasoningContentOnAssistantMessages": true,+ "thinkingFormat": "deepseek"+ },+ "reasoning": true,+ "input": [+ "text"+ ],+ "cost": {+ "input": 0.435,+ "output": 0.87,+ "cacheRead": 0.0036,+ "cacheWrite": 0+ },+ "contextWindow": 1048576,+ "maxTokens": 131072+ },+ {+ "id": "mimo-v2.5",+ "name": "MiMo-V2.5",+ "api": "openai-completions",+ "provider": "xiaomi",+ "baseUrl": "https://api.xiaomimimo.com/v1",+ "compat": {+ "requiresReasoningContentOnAssistantMessages": true,+ "thinkingFormat": "deepseek"+ },+ "reasoning": true,+ "input": [+ "text",+ "image"+ ],+ "cost": {+ "input": 0.14,+ "output": 0.28,+ "cacheRead": 0.0028,+ "cacheWrite": 0+ },+ "contextWindow": 1048576,+ "maxTokens": 131072+ },+ {+ "id": "mimo-v2.5-pro",+ "name": "MiMo-V2.5-Pro",+ "api": "openai-completions",+ "provider": "xiaomi",+ "baseUrl": "https://api.xiaomimimo.com/v1",+ "compat": {+ "requiresReasoningContentOnAssistantMessages": true,+ "thinkingFormat": "deepseek"+ },+ "reasoning": true,+ "input": [+ "text"+ ],+ "cost": {+ "input": 0.435,+ "output": 0.87,+ "cacheRead": 0.0036,+ "cacheWrite": 0+ },+ "contextWindow": 1048576,+ "maxTokens": 131072+ },+ {+ "id": "mimo-v2.5-pro-ultraspeed",+ "name": "MiMo-V2.5-Pro-UltraSpeed",+ "api": "openai-completions",+ "provider": "xiaomi",+ "baseUrl": "https://api.xiaomimimo.com/v1",+ "compat": {+ "requiresReasoningContentOnAssistantMessages": true,+ "thinkingFormat": "deepseek"+ },+ "reasoning": true,+ "input": [+ "text"+ ],+ "cost": {+ "input": 1.305,+ "output": 2.61,+ "cacheRead": 0.0108,+ "cacheWrite": 0+ },+ "contextWindow": 1048576,+ "maxTokens": 131072+ }+ ],+ "xiaomi-token-plan-cn": [+ {+ "id": "mimo-v2-pro",+ "name": "MiMo-V2-Pro",+ "api": "openai-completions",+ "provider": "xiaomi-token-plan-cn",+ "baseUrl": "https://token-plan-cn.xiaomimimo.com/v1",+ "compat": {+ "requiresReasoningContentOnAssistantMessages": true,+ "thinkingFormat": "deepseek"+ },+ "reasoning": true,+ "input": [+ "text"+ ],+ "cost": {+ "input": 0,+ "output": 0,+ "cacheRead": 0,+ "cacheWrite": 0+ },+ "contextWindow": 1048576,+ "maxTokens": 131072+ },+ {+ "id": "mimo-v2.5",+ "name": "MiMo-V2.5",+ "api": "openai-completions",+ "provider": "xiaomi-token-plan-cn",+ "baseUrl": "https://token-plan-cn.xiaomimimo.com/v1",+ "compat": {+ "requiresReasoningContentOnAssistantMessages": true,+ "thinkingFormat": "deepseek"+ },+ "reasoning": true,+ "input": [+ "text",+ "image"+ ],+ "cost": {+ "input": 0,+ "output": 0,+ "cacheRead": 0,+ "cacheWrite": 0+ },+ "contextWindow": 1048576,+ "maxTokens": 131072+ },+ {+ "id": "mimo-v2.5-pro",+ "name": "MiMo-V2.5-Pro",+ "api": "openai-completions",+ "provider": "xiaomi-token-plan-cn",+ "baseUrl": "https://token-plan-cn.xiaomimimo.com/v1",+ "compat": {+ "requiresReasoningContentOnAssistantMessages": true,+ "thinkingFormat": "deepseek"+ },+ "reasoning": true,+ "input": [+ "text"+ ],+ "cost": {+ "input": 0,+ "output": 0,+ "cacheRead": 0,+ "cacheWrite": 0+ },+ "contextWindow": 1048576,+ "maxTokens": 131072+ }+ ],+ "zai": [+ {+ "id": "glm-4.7",+ "name": "GLM-4.7",+ "api": "openai-completions",+ "provider": "zai",+ "baseUrl": "https://api.z.ai/api/coding/paas/v4",+ "reasoning": true,+ "input": [+ "text"+ ],+ "cost": {+ "input": 0,+ "output": 0,+ "cacheRead": 0,+ "cacheWrite": 0+ },+ "compat": {+ "supportsStore": false,+ "supportsDeveloperRole": false,+ "supportsReasoningEffort": false,+ "maxTokensField": "max_tokens",+ "thinkingFormat": "zai",+ "zaiToolStream": true+ },+ "contextWindow": 204800,+ "maxTokens": 131072+ },+ {+ "id": "glm-5-turbo",+ "name": "GLM-5-Turbo",+ "api": "openai-completions",+ "provider": "zai",+ "baseUrl": "https://api.z.ai/api/coding/paas/v4",+ "reasoning": true,+ "input": [+ "text"+ ],+ "cost": {+ "input": 0,+ "output": 0,+ "cacheRead": 0,+ "cacheWrite": 0+ },+ "compat": {+ "supportsStore": false,+ "supportsDeveloperRole": false,+ "supportsReasoningEffort": false,+ "maxTokensField": "max_tokens",+ "thinkingFormat": "zai",+ "zaiToolStream": true+ },+ "contextWindow": 200000,+ "maxTokens": 131072+ },+ {+ "id": "glm-5.2",+ "name": "GLM-5.2",+ "api": "openai-completions",+ "provider": "zai",+ "baseUrl": "https://api.z.ai/api/coding/paas/v4",+ "reasoning": true,+ "thinkingLevelMap": {+ "minimal": null,+ "low": "high",+ "medium": "high",+ "high": "high",+ "max": "max"+ },+ "input": [+ "text"+ ],+ "cost": {+ "input": 0,+ "output": 0,+ "cacheRead": 0,+ "cacheWrite": 0+ },+ "compat": {+ "supportsStore": false,+ "supportsDeveloperRole": false,+ "supportsReasoningEffort": true,+ "maxTokensField": "max_tokens",+ "thinkingFormat": "zai",+ "zaiToolStream": true+ },+ "contextWindow": 1000000,+ "maxTokens": 131072+ },+ {+ "id": "glm-5.2-highspeed",+ "name": "GLM-5.2 Highspeed",+ "api": "openai-completions",+ "provider": "zai",+ "baseUrl": "https://api.z.ai/api/coding/paas/v4",+ "reasoning": true,+ "input": [+ "text"+ ],+ "cost": {+ "input": 0,+ "output": 0,+ "cacheRead": 0,+ "cacheWrite": 0+ },+ "compat": {+ "supportsStore": false,+ "supportsDeveloperRole": false,+ "supportsReasoningEffort": false,+ "maxTokensField": "max_tokens",+ "thinkingFormat": "zai",+ "zaiToolStream": true+ },+ "contextWindow": 1000000,+ "maxTokens": 131072+ }+ ],+ "zai-coding-cn": [+ {+ "id": "glm-4.7",+ "name": "GLM-4.7",+ "api": "openai-completions",+ "provider": "zai-coding-cn",+ "baseUrl": "https://open.bigmodel.cn/api/coding/paas/v4",+ "reasoning": true,+ "input": [+ "text"+ ],+ "cost": {+ "input": 0,+ "output": 0,+ "cacheRead": 0,+ "cacheWrite": 0+ },+ "compat": {+ "supportsStore": false,+ "supportsDeveloperRole": false,+ "supportsReasoningEffort": false,+ "maxTokensField": "max_tokens",+ "thinkingFormat": "zai",+ "zaiToolStream": true+ },+ "contextWindow": 204800,+ "maxTokens": 131072+ },+ {+ "id": "glm-5-turbo",+ "name": "GLM-5-Turbo",+ "api": "openai-completions",+ "provider": "zai-coding-cn",+ "baseUrl": "https://open.bigmodel.cn/api/coding/paas/v4",+ "reasoning": true,+ "input": [+ "text"+ ],+ "cost": {+ "input": 0,+ "output": 0,+ "cacheRead": 0,+ "cacheWrite": 0+ },+ "compat": {+ "supportsStore": false,+ "supportsDeveloperRole": false,+ "supportsReasoningEffort": false,+ "maxTokensField": "max_tokens",+ "thinkingFormat": "zai",+ "zaiToolStream": true+ },+ "contextWindow": 200000,+ "maxTokens": 131072+ },+ {+ "id": "glm-5.2",+ "name": "GLM-5.2",+ "api": "openai-completions",+ "provider": "zai-coding-cn",+ "baseUrl": "https://open.bigmodel.cn/api/coding/paas/v4",+ "reasoning": true,+ "thinkingLevelMap": {+ "minimal": null,+ "low": "high",+ "medium": "high",+ "high": "high",+ "max": "max"+ },+ "input": [+ "text"+ ],+ "cost": {+ "input": 0,+ "output": 0,+ "cacheRead": 0,+ "cacheWrite": 0+ },+ "compat": {+ "supportsStore": false,+ "supportsDeveloperRole": false,+ "supportsReasoningEffort": true,+ "maxTokensField": "max_tokens",+ "thinkingFormat": "zai",+ "zaiToolStream": true+ },+ "contextWindow": 1000000,+ "maxTokens": 131072+ },+ {+ "id": "glm-5.2-highspeed",+ "name": "GLM-5.2 Highspeed",+ "api": "openai-completions",+ "provider": "zai-coding-cn",+ "baseUrl": "https://open.bigmodel.cn/api/coding/paas/v4",+ "reasoning": true,+ "input": [+ "text"+ ],+ "cost": {+ "input": 0,+ "output": 0,+ "cacheRead": 0,+ "cacheWrite": 0+ },+ "compat": {+ "supportsStore": false,+ "supportsDeveloperRole": false,+ "supportsReasoningEffort": false,+ "maxTokensField": "max_tokens",+ "thinkingFormat": "zai",+ "zaiToolStream": true+ },+ "contextWindow": 1000000,+ "maxTokens": 131072+ }+ ]+ }+}diff --git a/packages/model-providers/catalog/providers.json b/packages/model-providers/catalog/providers.jsonindex bcb7a3b1c1..15c22be255 100644--- a/packages/model-providers/catalog/providers.json+++ b/packages/model-providers/catalog/providers.json@@ -1,11 +1,15 @@{- "version": "2",+ "version": "3","providers": [{"id": "xai","name": "xAI","source": "builtin",- "agents": ["claude-code", "codex"],+ "agents": [+ "claude-code",+ "codex",+ "pi"+ ],"auth": {"method": "oauth"},@@ -33,7 +37,9 @@"claude-code": {"upstream": "https://api.x.ai/v1","authStrategy": "oauth-passthrough",- "modelPrefixes": ["xai/"]+ "modelPrefixes": [+ "xai/"+ ]},"codex": {"upstream": "https://api.x.ai/v1",@@ -41,8 +47,25 @@"modelIdRewrite": {"stripPrefix": "xai/"},- "headerDelete": ["chatgpt-account-id", "openai-beta", "originator", "session_id"],- "modelPrefixes": ["xai/"]+ "headerDelete": [+ "chatgpt-account-id",+ "openai-beta",+ "originator",+ "session_id"+ ],+ "modelPrefixes": [+ "xai/"+ ]+ },+ "pi": {+ "upstream": "https://api.x.ai/v1",+ "authStrategy": "provider-oauth-header",+ "headerDelete": [+ "chatgpt-account-id",+ "openai-beta",+ "originator",+ "session_id"+ ]}},"models": {@@ -54,7 +77,11 @@"sortOrder": 49,"description": "xAI Grok 4.5 新旗舰,编码/agent 任务最强,500k 上下文(SuperGrok 订阅直连)","contextWindow": 500000,- "efforts": ["low", "medium", "high"],+ "efforts": [+ "low",+ "medium",+ "high"+ ],"defaultEffort": "high","status": "active"},@@ -65,7 +92,11 @@"sortOrder": 51,"description": "xAI Grok 4.3 通用旗舰,1M 上下文(SuperGrok 订阅直连)","contextWindow": 1000000,- "efforts": ["low", "medium", "high"],+ "efforts": [+ "low",+ "medium",+ "high"+ ],"defaultEffort": "high","status": "active"},@@ -124,7 +155,12 @@"sortOrder": 98,"description": "旧版兼容 alias;新会话请使用明确的 Grok 4.20 model ID","contextWindow": 1000000,- "efforts": ["low", "medium", "high", "xhigh"],+ "efforts": [+ "low",+ "medium",+ "high",+ "xhigh"+ ],"defaultEffort": "high","status": "deprecated","defaultEnabled": false@@ -150,7 +186,11 @@"sortOrder": 49,"description": "xAI Grok 4.5 新旗舰,编码/agent 任务最强,500k 上下文(SuperGrok 订阅直连)","contextWindow": 500000,- "efforts": ["low", "medium", "high"],+ "efforts": [+ "low",+ "medium",+ "high"+ ],"defaultEffort": "high","status": "active"},@@ -161,7 +201,11 @@"sortOrder": 51,"description": "xAI Grok 4.3 通用旗舰,1M 上下文(SuperGrok 订阅直连)","contextWindow": 1000000,- "efforts": ["low", "medium", "high"],+ "efforts": [+ "low",+ "medium",+ "high"+ ],"defaultEffort": "high","status": "active"},@@ -220,7 +264,11 @@"sortOrder": 98,"description": "旧版兼容 alias;新会话请使用明确的 Grok 4.20 model ID","contextWindow": 1000000,- "efforts": ["low", "medium", "high"],+ "efforts": [+ "low",+ "medium",+ "high"+ ],"defaultEffort": "high","status": "deprecated","defaultEnabled": false@@ -237,6 +285,84 @@"status": "deprecated","defaultEnabled": false}+ ],+ "pi": [+ {+ "id": "grok-4.3",+ "name": "Grok 4.3",+ "group": "grok",+ "sortOrder": 49,+ "contextWindow": 1000000,+ "maxOutput": 30000,+ "efforts": [],+ "defaultEffort": null,+ "status": "active",+ "supportsImageInput": true,+ "cost": {+ "input": 1.25,+ "output": 2.5,+ "cacheRead": 0.2,+ "cacheWrite": 0+ }+ },+ {+ "id": "grok-4.5",+ "name": "Grok 4.5",+ "group": "grok",+ "sortOrder": 50,+ "contextWindow": 500000,+ "maxOutput": 500000,+ "efforts": [+ "low",+ "medium",+ "high"+ ],+ "defaultEffort": "medium",+ "status": "active",+ "supportsImageInput": true,+ "cost": {+ "input": 2,+ "output": 6,+ "cacheRead": 0.3,+ "cacheWrite": 0+ }+ },+ {+ "id": "grok-4.6",+ "name": "Grok 4.6",+ "group": "grok",+ "sortOrder": 51,+ "contextWindow": 500000,+ "maxOutput": 500000,+ "efforts": [],+ "defaultEffort": null,+ "status": "active",+ "supportsImageInput": true,+ "cost": {+ "input": 2,+ "output": 6,+ "cacheRead": 0.5,+ "cacheWrite": 0+ }+ },+ {+ "id": "grok-build-0.1",+ "name": "Grok Build 0.1",+ "group": "grok",+ "sortOrder": 52,+ "contextWindow": 256000,+ "maxOutput": 256000,+ "efforts": [],+ "defaultEffort": null,+ "status": "active",+ "supportsImageInput": true,+ "cost": {+ "input": 1,+ "output": 2,+ "cacheRead": 0.2,+ "cacheWrite": 0+ }+ }]}}@@ -318,6 +444,37 @@}],"modelsUrl": "https://api.deepseek.com/models"+ },+ "pi": {+ "baseUrl": "https://api.deepseek.com",+ "wireProtocol": "openai-chat",+ "modelsUrl": "https://api.deepseek.com/models",+ "piCatalogProviderId": "deepseek",+ "models": [+ {+ "id": "deepseek-v4-flash",+ "name": "DeepSeek V4 Flash",+ "contextWindow": 1000000,+ "reasoning": true,+ "reasoningEfforts": [+ "low",+ "high",+ "max"+ ],+ "reasoningDefaultEffort": "high"+ },+ {+ "id": "deepseek-v4-pro",+ "name": "DeepSeek V4 Pro",+ "contextWindow": 1000000,+ "reasoning": true,+ "reasoningEfforts": [+ "high",+ "max"+ ],+ "reasoningDefaultEffort": "high"+ }+ ]}}},@@ -440,6 +597,76 @@}],"modelsUrl": "https://api.moonshot.cn/v1/models"+ },+ "pi": {+ "baseUrl": "https://api.moonshot.cn/v1",+ "wireProtocol": "openai-chat",+ "modelsUrl": "https://api.moonshot.cn/v1/models",+ "piCatalogProviderId": "moonshotai-cn",+ "models": [+ {+ "id": "kimi-k2-0711-preview",+ "name": "Kimi K2 0711",+ "contextWindow": 131072+ },+ {+ "id": "kimi-k2-0905-preview",+ "name": "Kimi K2 0905",+ "contextWindow": 262144+ },+ {+ "id": "kimi-k2-thinking",+ "name": "Kimi K2 Thinking",+ "contextWindow": 262144+ },+ {+ "id": "kimi-k2-thinking-turbo",+ "name": "Kimi K2 Thinking Turbo",+ "contextWindow": 262144+ },+ {+ "id": "kimi-k2-turbo-preview",+ "name": "Kimi K2 Turbo",+ "contextWindow": 262144+ },+ {+ "id": "kimi-k2.5",+ "name": "Kimi K2.5",+ "contextWindow": 262144,+ "supportsImageInput": true+ },+ {+ "id": "kimi-k2.6",+ "name": "Kimi K2.6",+ "contextWindow": 262144,+ "supportsImageInput": true+ },+ {+ "id": "kimi-k2.7-code",+ "name": "Kimi K2.7 Code",+ "contextWindow": 262144,+ "supportsImageInput": true+ },+ {+ "id": "kimi-k2.7-code-highspeed",+ "name": "Kimi K2.7 Code HighSpeed",+ "contextWindow": 262144,+ "supportsImageInput": true+ },+ {+ "id": "kimi-k3",+ "name": "Kimi K3",+ "contextWindow": 1048576,+ "supportsImageInput": true,+ "reasoning": true,+ "reasoningEfforts": [+ "low",+ "high",+ "max"+ ],+ "reasoningDefaultEffort": "max"+ }+ ]}}},@@ -488,6 +715,76 @@}],"modelsUrl": "https://api.moonshot.ai/v1/models"+ },+ "pi": {+ "baseUrl": "https://api.moonshot.ai/v1",+ "wireProtocol": "openai-chat",+ "modelsUrl": "https://api.moonshot.ai/v1/models",+ "piCatalogProviderId": "moonshotai",+ "models": [+ {+ "id": "kimi-k2-0711-preview",+ "name": "Kimi K2 0711",+ "contextWindow": 131072+ },+ {+ "id": "kimi-k2-0905-preview",+ "name": "Kimi K2 0905",+ "contextWindow": 262144+ },+ {+ "id": "kimi-k2-thinking",+ "name": "Kimi K2 Thinking",+ "contextWindow": 262144+ },+ {+ "id": "kimi-k2-thinking-turbo",+ "name": "Kimi K2 Thinking Turbo",+ "contextWindow": 262144+ },+ {+ "id": "kimi-k2-turbo-preview",+ "name": "Kimi K2 Turbo",+ "contextWindow": 262144+ },+ {+ "id": "kimi-k2.5",+ "name": "Kimi K2.5",+ "contextWindow": 262144,+ "supportsImageInput": true+ },+ {+ "id": "kimi-k2.6",+ "name": "Kimi K2.6",+ "contextWindow": 262144,+ "supportsImageInput": true+ },+ {+ "id": "kimi-k2.7-code",+ "name": "Kimi K2.7 Code",+ "contextWindow": 262144,+ "supportsImageInput": true+ },+ {+ "id": "kimi-k2.7-code-highspeed",+ "name": "Kimi K2.7 Code HighSpeed",+ "contextWindow": 262144,+ "supportsImageInput": true+ },+ {+ "id": "kimi-k3",+ "name": "Kimi K3",+ "contextWindow": 1048576,+ "supportsImageInput": true,+ "reasoning": true,+ "reasoningEfforts": [+ "low",+ "high",+ "max"+ ],+ "reasoningDefaultEffort": "max"+ }+ ]}}},@@ -538,6 +835,51 @@"contextWindow": 262144}]+ },+ "pi": {+ "baseUrl": "https://api.kimi.com/coding",+ "wireProtocol": "anthropic-messages",+ "piCatalogProviderId": "kimi-coding",+ "models": [+ {+ "id": "k3",+ "name": "Kimi K3",+ "contextWindow": 1048576,+ "supportsImageInput": true,+ "reasoning": true,+ "reasoningEfforts": [+ "low",+ "high",+ "max"+ ],+ "reasoningDefaultEffort": "high"+ },+ {+ "id": "k3-256k",+ "name": "Kimi K3-256K",+ "contextWindow": 262144,+ "supportsImageInput": true,+ "reasoning": true,+ "reasoningEfforts": [+ "low",+ "high",+ "max"+ ],+ "reasoningDefaultEffort": "high"+ },+ {+ "id": "kimi-for-coding",+ "name": "Kimi K2.7 Code",+ "contextWindow": 262144,+ "supportsImageInput": true+ },+ {+ "id": "kimi-for-coding-highspeed",+ "name": "Kimi For Coding HighSpeed",+ "contextWindow": 262144,+ "supportsImageInput": true+ }+ ]}}},@@ -576,6 +918,29 @@"name": "MiniMax M2.5"}]+ },+ "pi": {+ "baseUrl": "https://api.minimaxi.com/anthropic",+ "wireProtocol": "anthropic-messages",+ "piCatalogProviderId": "minimax-cn",+ "models": [+ {+ "id": "MiniMax-M2.7",+ "name": "MiniMax-M2.7",+ "contextWindow": 204800+ },+ {+ "id": "MiniMax-M2.7-highspeed",+ "name": "MiniMax-M2.7-highspeed",+ "contextWindow": 204800+ },+ {+ "id": "MiniMax-M3",+ "name": "MiniMax-M3",+ "contextWindow": 1000000,+ "supportsImageInput": true+ }+ ]}}},@@ -612,6 +977,29 @@"name": "MiniMax M2.5"}]+ },+ "pi": {+ "baseUrl": "https://api.minimax.io/anthropic",+ "wireProtocol": "anthropic-messages",+ "piCatalogProviderId": "minimax",+ "models": [+ {+ "id": "MiniMax-M2.7",+ "name": "MiniMax-M2.7",+ "contextWindow": 204800+ },+ {+ "id": "MiniMax-M2.7-highspeed",+ "name": "MiniMax-M2.7-highspeed",+ "contextWindow": 204800+ },+ {+ "id": "MiniMax-M3",+ "name": "MiniMax-M3",+ "contextWindow": 1000000,+ "supportsImageInput": true+ }+ ]}}},@@ -741,6 +1129,144 @@"contextWindow": 1048576}]+ },+ "pi": {+ "baseUrl": "https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",+ "wireProtocol": "openai-chat",+ "modelsUrl": "https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/models",+ "piCatalogProviderId": "qwen-token-plan-cn",+ "models": [+ {+ "id": "MiniMax-M2.5",+ "name": "MiniMax-M2.5",+ "contextWindow": 196608+ },+ {+ "id": "deepseek-v3.2",+ "name": "DeepSeek V3.2",+ "contextWindow": 131072+ },+ {+ "id": "deepseek-v4-flash",+ "name": "DeepSeek V4 Flash",+ "contextWindow": 1000000,+ "reasoning": true,+ "reasoningEfforts": [+ "high",+ "max"+ ],+ "reasoningDefaultEffort": "high"+ },+ {+ "id": "deepseek-v4-flash-0731",+ "name": "DeepSeek V4 Flash 0731",+ "contextWindow": 1000000,+ "reasoning": true,+ "reasoningEfforts": [+ "high",+ "max"+ ],+ "reasoningDefaultEffort": "high"+ },+ {+ "id": "deepseek-v4-pro",+ "name": "DeepSeek V4 Pro",+ "contextWindow": 1000000,+ "reasoning": true,+ "reasoningEfforts": [+ "high",+ "max"+ ],+ "reasoningDefaultEffort": "high"+ },+ {+ "id": "glm-5",+ "name": "GLM-5",+ "contextWindow": 202752,+ "reasoning": true,+ "reasoningEfforts": [+ "high",+ "max"+ ],+ "reasoningDefaultEffort": "high"+ },+ {+ "id": "glm-5.1",+ "name": "GLM-5.1",+ "contextWindow": 202752,+ "reasoning": true,+ "reasoningEfforts": [+ "high",+ "max"+ ],+ "reasoningDefaultEffort": "high"+ },+ {+ "id": "glm-5.2",+ "name": "GLM-5.2",+ "contextWindow": 1000000,+ "reasoning": true,+ "reasoningEfforts": [+ "high",+ "max"+ ],+ "reasoningDefaultEffort": "high"+ },+ {+ "id": "kimi-k2.5",+ "name": "Kimi K2.5",+ "contextWindow": 262144,+ "supportsImageInput": true+ },+ {+ "id": "kimi-k2.6",+ "name": "Kimi K2.6",+ "contextWindow": 262144,+ "supportsImageInput": true+ },+ {+ "id": "kimi-k2.7-code",+ "name": "Kimi K2.7 Code",+ "contextWindow": 262144,+ "supportsImageInput": true+ },+ {+ "id": "qwen3.6-flash",+ "name": "Qwen3.6 Flash",+ "contextWindow": 1000000,+ "supportsImageInput": true+ },+ {+ "id": "qwen3.6-plus",+ "name": "Qwen3.6 Plus",+ "contextWindow": 1000000,+ "supportsImageInput": true+ },+ {+ "id": "qwen3.7-max",+ "name": "Qwen3.7 Max",+ "contextWindow": 1000000+ },+ {+ "id": "qwen3.7-plus",+ "name": "Qwen3.7 Plus",+ "contextWindow": 1000000,+ "supportsImageInput": true+ },+ {+ "id": "qwen3.8-max",+ "name": "Qwen3.8 Max",+ "contextWindow": 1000000,+ "supportsImageInput": true,+ "reasoning": true,+ "reasoningEfforts": [+ "low",+ "medium",+ "xhigh"+ ],+ "reasoningDefaultEffort": "medium"+ }+ ]}}},@@ -914,6 +1440,144 @@"contextWindow": 196608}]+ },+ "pi": {+ "baseUrl": "https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",+ "wireProtocol": "openai-chat",+ "modelsUrl": "https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/models",+ "piCatalogProviderId": "qwen-token-plan-cn",+ "models": [+ {+ "id": "MiniMax-M2.5",+ "name": "MiniMax-M2.5",+ "contextWindow": 196608+ },+ {+ "id": "deepseek-v3.2",+ "name": "DeepSeek V3.2",+ "contextWindow": 131072+ },+ {+ "id": "deepseek-v4-flash",+ "name": "DeepSeek V4 Flash",+ "contextWindow": 1000000,+ "reasoning": true,+ "reasoningEfforts": [+ "high",+ "max"+ ],+ "reasoningDefaultEffort": "high"+ },+ {+ "id": "deepseek-v4-flash-0731",+ "name": "DeepSeek V4 Flash 0731",+ "contextWindow": 1000000,+ "reasoning": true,+ "reasoningEfforts": [+ "high",+ "max"+ ],+ "reasoningDefaultEffort": "high"+ },+ {+ "id": "deepseek-v4-pro",+ "name": "DeepSeek V4 Pro",+ "contextWindow": 1000000,+ "reasoning": true,+ "reasoningEfforts": [+ "high",+ "max"+ ],+ "reasoningDefaultEffort": "high"+ },+ {+ "id": "glm-5",+ "name": "GLM-5",+ "contextWindow": 202752,+ "reasoning": true,+ "reasoningEfforts": [+ "high",+ "max"+ ],+ "reasoningDefaultEffort": "high"+ },+ {+ "id": "glm-5.1",+ "name": "GLM-5.1",+ "contextWindow": 202752,+ "reasoning": true,+ "reasoningEfforts": [+ "high",+ "max"+ ],+ "reasoningDefaultEffort": "high"+ },+ {+ "id": "glm-5.2",+ "name": "GLM-5.2",+ "contextWindow": 1000000,+ "reasoning": true,+ "reasoningEfforts": [+ "high",+ "max"+ ],+ "reasoningDefaultEffort": "high"+ },+ {+ "id": "kimi-k2.5",+ "name": "Kimi K2.5",+ "contextWindow": 262144,+ "supportsImageInput": true+ },+ {+ "id": "kimi-k2.6",+ "name": "Kimi K2.6",+ "contextWindow": 262144,+ "supportsImageInput": true+ },+ {+ "id": "kimi-k2.7-code",+ "name": "Kimi K2.7 Code",+ "contextWindow": 262144,+ "supportsImageInput": true+ },+ {+ "id": "qwen3.6-flash",+ "name": "Qwen3.6 Flash",+ "contextWindow": 1000000,+ "supportsImageInput": true+ },+ {+ "id": "qwen3.6-plus",+ "name": "Qwen3.6 Plus",+ "contextWindow": 1000000,+ "supportsImageInput": true+ },+ {+ "id": "qwen3.7-max",+ "name": "Qwen3.7 Max",+ "contextWindow": 1000000+ },+ {+ "id": "qwen3.7-plus",+ "name": "Qwen3.7 Plus",+ "contextWindow": 1000000,+ "supportsImageInput": true+ },+ {+ "id": "qwen3.8-max",+ "name": "Qwen3.8 Max",+ "contextWindow": 1000000,+ "supportsImageInput": true,+ "reasoning": true,+ "reasoningEfforts": [+ "low",+ "medium",+ "xhigh"+ ],+ "reasoningDefaultEffort": "medium"+ }+ ]}}},@@ -1028,6 +1692,41 @@"name": "GLM-5.1"}]+ },+ "pi": {+ "baseUrl": "https://open.bigmodel.cn/api/coding/paas/v4",+ "wireProtocol": "openai-chat",+ "piCatalogProviderId": "zai-coding-cn",+ "models": [+ {+ "id": "glm-4.7",+ "name": "GLM-4.7",+ "contextWindow": 204800+ },+ {+ "id": "glm-5-turbo",+ "name": "GLM-5-Turbo",+ "contextWindow": 200000+ },+ {+ "id": "glm-5.2",+ "name": "GLM-5.2",+ "contextWindow": 1000000,+ "reasoning": true,+ "reasoningEfforts": [+ "low",+ "medium",+ "high",+ "max"+ ],+ "reasoningDefaultEffort": "medium"+ },+ {+ "id": "glm-5.2-highspeed",+ "name": "GLM-5.2 Highspeed",+ "contextWindow": 1000000+ }+ ]}}},@@ -1068,6 +1767,41 @@"name": "GLM-5.1"}]+ },+ "pi": {+ "baseUrl": "https://api.z.ai/api/coding/paas/v4",+ "wireProtocol": "openai-chat",+ "piCatalogProviderId": "zai",+ "models": [+ {+ "id": "glm-4.7",+ "name": "GLM-4.7",+ "contextWindow": 204800+ },+ {+ "id": "glm-5-turbo",+ "name": "GLM-5-Turbo",+ "contextWindow": 200000+ },+ {+ "id": "glm-5.2",+ "name": "GLM-5.2",+ "contextWindow": 1000000,+ "reasoning": true,+ "reasoningEfforts": [+ "low",+ "medium",+ "high",+ "max"+ ],+ "reasoningDefaultEffort": "medium"+ },+ {+ "id": "glm-5.2-highspeed",+ "name": "GLM-5.2 Highspeed",+ "contextWindow": 1000000+ }+ ]}}},@@ -1108,6 +1842,45 @@"contextWindow": 1000000}]+ },+ "pi": {+ "baseUrl": "https://api.xiaomimimo.com/v1",+ "wireProtocol": "openai-chat",+ "piCatalogProviderId": "xiaomi",+ "models": [+ {+ "id": "mimo-v2-flash",+ "name": "MiMo-V2-Flash",+ "contextWindow": 262144+ },+ {+ "id": "mimo-v2-omni",+ "name": "MiMo-V2-Omni",+ "contextWindow": 262144,+ "supportsImageInput": true+ },+ {+ "id": "mimo-v2-pro",+ "name": "MiMo-V2-Pro",+ "contextWindow": 1048576+ },+ {+ "id": "mimo-v2.5",+ "name": "MiMo-V2.5",+ "contextWindow": 1048576,+ "supportsImageInput": true+ },+ {+ "id": "mimo-v2.5-pro",+ "name": "MiMo-V2.5-Pro",+ "contextWindow": 1048576+ },+ {+ "id": "mimo-v2.5-pro-ultraspeed",+ "name": "MiMo-V2.5-Pro-UltraSpeed",+ "contextWindow": 1048576+ }+ ]}}},@@ -1148,6 +1921,29 @@"contextWindow": 1000000}]+ },+ "pi": {+ "baseUrl": "https://token-plan-cn.xiaomimimo.com/v1",+ "wireProtocol": "openai-chat",+ "piCatalogProviderId": "xiaomi-token-plan-cn",+ "models": [+ {+ "id": "mimo-v2-pro",+ "name": "MiMo-V2-Pro",+ "contextWindow": 1048576+ },+ {+ "id": "mimo-v2.5",+ "name": "MiMo-V2.5",+ "contextWindow": 1048576,+ "supportsImageInput": true+ },+ {+ "id": "mimo-v2.5-pro",+ "name": "MiMo-V2.5-Pro",+ "contextWindow": 1048576+ }+ ]}}},diff --git a/packages/model-providers/package.json b/packages/model-providers/package.jsonindex 36b56f4312..e564e0a381 100644--- a/packages/model-providers/package.json+++ b/packages/model-providers/package.json@@ -9,6 +9,7 @@"exports": {".": "./src/index.ts","./catalog": "./catalog/providers.json",+ "./pi-model-catalog": "./catalog/pi-model-catalog.json","./sections": "./src/sections.ts","./branding": "./src/providerBranding.ts","./registry": "./src/registry.ts",diff --git a/packages/model-providers/src/__tests__/catalog.test.ts b/packages/model-providers/src/__tests__/catalog.test.tsindex 14a4222b17..b9f7568495 100644--- a/packages/model-providers/src/__tests__/catalog.test.ts+++ b/packages/model-providers/src/__tests__/catalog.test.ts@@ -4,7 +4,7 @@* **清单来源唯一化**——* - anthropic / openai / xd 是动态清单供应商:bundled 目录只有身份卡,models 恒为空,* 清单运行时由 host 注入(SDK 发现 / codex 注册表 / 网关下发);- * - xai 是唯一的静态清单供应商(官方无列模型通道),清单活在 catalog/providers.json;+ * - xai 的静态段是离线 fallback/元数据层;登录后的成员由账号发现决定;* - presets 是自定义供应商模板,随目录 OSS 热更。** 本测试守:(a) bundled 结构合法且符合上述形态;(b) parseCatalog 校验规则@@ -26,7 +26,7 @@ import type { AgentKind, Catalog, CatalogModel } from '../types.js';/** 动态清单供应商(bundled 零模型,运行时注入)。 */const DYNAMIC_PROVIDER_IDS = ['anthropic', 'openai', 'xd'] as const;-/** xai 静态清单(唯一活在目录文件里的模型清单)。 */+/** xAI 随包 fallback 元数据清单。 */const EXPECTED_XAI_IDS = ['xai/grok-4.5','xai/grok-4.3',@@ -37,6 +37,7 @@ const EXPECTED_XAI_IDS = ['xai/grok-4.20','xai/grok-code-fast',];+const EXPECTED_XAI_PI_IDS = ['grok-4.3', 'grok-4.5', 'grok-4.6', 'grok-build-0.1'];function provider(id: string) {const p = BUNDLED_CATALOG.providers.find((x) => x.id === id);@@ -137,10 +138,18 @@ describe('bundled catalog validity (dynamic-first contract)', () => {}});- it('xai is the only provider with a static model list', () => {+ it('xai ships a static fallback list and Pi official metadata', () => {const xai = provider('xai');expect((xai.models['claude-code'] ?? []).map((m) => m.id)).toEqual(EXPECTED_XAI_IDS);expect((xai.models.codex ?? []).map((m) => m.id)).toEqual(EXPECTED_XAI_IDS);+ expect((xai.models.pi ?? []).map((m) => m.id)).toEqual(EXPECTED_XAI_PI_IDS);+ expect(xai.models.pi?.find((m) => m.id === 'grok-4.6')).toMatchObject({+ contextWindow: 500_000,+ maxOutput: 500_000,+ supportsImageInput: true,+ efforts: [],+ defaultEffort: null,+ });});it('xai ships both Grok Imagine subscription image models', () => {@@ -225,11 +234,7 @@ describe('bundled catalog validity (dynamic-first contract)', () => {).toBe(1_000_000);});- it('Kimi Code(编程计划)预设的每个模型都带 contextWindow(k3 缺失曾回落 200K)', () => {- // k3 此前没带 contextWindow → buildUserProvider 回落 200K 保守默认:选择器- // 显示 200K 且压缩阈值过早触发(用户反馈「动不动就压缩」)。取 262144 与同- // 套餐 kimi-for-coding 口径一致(K3 开放平台规格 1M,但编程计划端点是否限窗- // 无公开文档,保守取值;实测放开后可上调)。+ it('Kimi Code(编程计划)按各 harness 的权威目录保留 contextWindow', () => {const presets = BUNDLED_CATALOG.presets ?? [];const kimiCode = presets.find((p) => p.id === 'moonshot-kimi-code');expect(kimiCode).toBeDefined();@@ -240,7 +245,9 @@ describe('bundled catalog validity (dynamic-first contract)', () => {`${agent}/${m.id} 缺 contextWindow`,).toBe(true);}- expect(rt!.models.find((m) => m.id === 'k3')?.contextWindow, `${agent}/k3`).toBe(262_144);+ expect(rt!.models.find((m) => m.id === 'k3')?.contextWindow, `${agent}/k3`).toBe(+ agent === 'pi' ? 1_048_576 : 262_144,+ );}});@@ -497,7 +504,7 @@ describe('fast-mode per-provider resolution (model-level SSoT)', () => {});});-describe('vendor grouping metadata (xai 静态清单)', () => {+describe('vendor grouping metadata (xai fallback metadata)', () => {it('every static model carries group=grok + numeric sortOrder', () => {const xai = provider('xai');for (const agent of xai.agents) {diff --git a/packages/model-providers/src/__tests__/pi-catalog-marker.test.ts b/packages/model-providers/src/__tests__/pi-catalog-marker.test.tsnew file mode 100644index 0000000000..d15d83bd49--- /dev/null+++ b/packages/model-providers/src/__tests__/pi-catalog-marker.test.ts@@ -0,0 +1,15 @@+import { describe, expect, it } from 'vitest';++import { effectivePiWireProtocol } from '../pi-catalog-marker.js';++describe('effectivePiWireProtocol', () => {+ it('normalizes an omitted Pi protocol to openai-chat', () => {+ expect(effectivePiWireProtocol(undefined)).toBe('openai-chat');+ expect(effectivePiWireProtocol('openai-chat')).toBe('openai-chat');+ });++ it('preserves explicit non-default protocols', () => {+ expect(effectivePiWireProtocol('anthropic-messages')).toBe('anthropic-messages');+ expect(effectivePiWireProtocol('openai-responses')).toBe('openai-responses');+ });+});diff --git a/packages/model-providers/src/__tests__/presets.test.ts b/packages/model-providers/src/__tests__/presets.test.tsindex 9c3fe6e1a5..fa32bda4eb 100644--- a/packages/model-providers/src/__tests__/presets.test.ts+++ b/packages/model-providers/src/__tests__/presets.test.ts@@ -11,7 +11,7 @@ import { describe, it, expect } from 'vitest';import { BUNDLED_CATALOG, parseCatalog, presetDisplayName, sanitizePresets, sortPresetsForRegion } from '../catalog.js';import { mergeWithBundled } from '../source.js';-import type { Catalog } from '../types.js';+import type { AgentKind, Catalog } from '../types.js';/** 最小合法目录(单 provider)。 */function minimalCatalog(extra?: Partial<Catalog>): Catalog {@@ -45,6 +45,30 @@ const VALID_PRESET = {};describe('sanitizePresets', () => {+ it('accepts Pi official catalog provider ids only on Pi runtimes', () => {+ const valid = {+ ...VALID_PRESET,+ id: 'pi-catalog',+ runtimes: {+ pi: {+ baseUrl: 'https://api.deepseek.com',+ piCatalogProviderId: 'deepseek',+ models: [{ id: 'deepseek-v4-pro', name: 'DeepSeek V4 Pro' }],+ },+ },+ };+ expect(sanitizePresets([valid])).toEqual([valid]);+ expect(sanitizePresets([{+ ...valid,+ id: 'wrong-runtime',+ runtimes: { codex: valid.runtimes.pi },+ }])).toEqual([]);+ expect(sanitizePresets([{+ ...valid,+ id: 'bad-id',+ runtimes: { pi: { ...valid.runtimes.pi, piCatalogProviderId: '../xai' } },+ }])).toEqual([]);+ });it('accepts explicit Pi reasoning metadata and rejects ambiguous capability declarations', () => {const piReasoning = {...VALID_PRESET,@@ -59,12 +83,31 @@ describe('sanitizePresets', () => {name: 'Reasoner',reasoning: true,reasoningEfforts: ['low', 'high', 'xhigh'],+ reasoningDefaultEffort: 'high',},],},},};expect(sanitizePresets([piReasoning])).toEqual([piReasoning]);+ expect(+ sanitizePresets([{+ ...piReasoning,+ id: 'invalid-default-effort',+ runtimes: {+ pi: {+ ...piReasoning.runtimes.pi,+ models: [{+ id: 'reasoner',+ name: 'Reasoner',+ reasoning: true,+ reasoningEfforts: ['low', 'high'],+ reasoningDefaultEffort: 'max',+ }],+ },+ },+ }]),+ ).toEqual([]);expect(sanitizePresets([{@@ -227,6 +270,27 @@ describe('parseCatalog presets 容错', () => {});describe('mergeWithBundled presets 兜底', () => {+ it('远端 xAI 目录缺少 Pi 时不在 bundled 合并层复活静态成员', () => {+ const bundledXai = BUNDLED_CATALOG.providers.find((provider) => provider.id === 'xai')!;+ const remoteXai = {+ ...bundledXai,+ agents: ['claude-code', 'codex'] as AgentKind[],+ routing: {+ 'claude-code': bundledXai.routing['claude-code']!,+ codex: bundledXai.routing.codex!,+ },+ models: {+ 'claude-code': bundledXai.models['claude-code']!,+ codex: bundledXai.models.codex!,+ },+ };+ const merged = mergeWithBundled(minimalCatalog({ providers: [remoteXai] }));+ const xai = merged.providers.find((provider) => provider.id === 'xai');+ expect(xai?.agents).not.toContain('pi');+ expect(xai?.routing.pi).toBeUndefined();+ expect(xai?.models.pi).toBeUndefined();+ });+it('远端 presets 与 bundled 按 id 合并:远端同 id 优先,bundled 缺项不丢', () => {const merged = mergeWithBundled(minimalCatalog({ presets: [VALID_PRESET] }));expect(merged.presets?.find((preset) => preset.id === 'openrouter')).toEqual(VALID_PRESET);@@ -296,6 +360,45 @@ describe('mergeWithBundled presets 兜底', () => {).toBe(512_000);});+ it.each(['deepseek', 'moonshot-kimi-cn', 'moonshot-kimi-global'])(+ '旧远端 %s 缺少 Pi runtime 时从 bundled 回填已核实的 Pi 元数据',+ (id) => {+ const bundled = BUNDLED_CATALOG.presets?.find((preset) => preset.id === id);+ expect(bundled?.runtimes.pi).toBeDefined();+ const { pi: _missing, ...remoteRuntimes } = bundled!.runtimes;+ const remote = { ...bundled!, name: `Remote ${id}`, runtimes: remoteRuntimes };+ const merged = mergeWithBundled(minimalCatalog({ version: '2', presets: [remote] }));+ const resolved = merged.presets?.find((preset) => preset.id === id);+ expect(resolved?.name).toBe(`Remote ${id}`);+ expect(resolved?.runtimes.pi).toEqual(bundled?.runtimes.pi);+ },+ );++ it('远端已有 Pi runtime 时完整优先,不与 bundled 模型级混合', () => {+ const bundled = BUNDLED_CATALOG.presets?.find((preset) => preset.id === 'deepseek');+ const remotePi = {+ baseUrl: 'https://remote.example/v1',+ models: [{ id: 'remote-model', name: 'Remote Model' }],+ };+ const merged = mergeWithBundled(minimalCatalog({+ presets: [{ ...bundled!, runtimes: { ...bundled!.runtimes, pi: remotePi } }],+ }));+ expect(merged.presets?.find((preset) => preset.id === 'deepseek')?.runtimes.pi).toEqual(remotePi);+ });++ it('当前或未知目录版本缺少 Pi runtime 时保持缺失,不静默复活 bundled runtime', () => {+ const bundled = BUNDLED_CATALOG.presets?.find((preset) => preset.id === 'deepseek');+ const { pi: _missing, ...remoteRuntimes } = bundled!.runtimes;+ for (const version of ['3', '4', 'test']) {+ const merged = mergeWithBundled(minimalCatalog({+ version,+ presets: [{ ...bundled!, runtimes: remoteRuntimes }],+ }));+ expect(merged.presets?.find((preset) => preset.id === 'deepseek')?.runtimes.pi)+ .toBeUndefined();+ }+ });+it('旧远端同 id preset 缺少 nameZhTW 时从 bundled 回填,显式远端值仍优先', () => {const bundled = BUNDLED_CATALOG.presets?.find((preset) => preset.id === 'zhipu-glm-cn');expect(bundled?.nameZhTW).toBe('智譜 GLM(中國大陸)');@@ -599,6 +702,56 @@ describe('官方渠道预设契约', () => {});});+ it('DeepSeek 的 Pi runtime 来自官方目录并保留逐模型推理档位', () => {+ const pi = preset('deepseek')?.runtimes.pi;+ expect(pi?.piCatalogProviderId).toBe('deepseek');+ expect(pi?.models.find((model) => model.id === 'deepseek-v4-flash')).toMatchObject({+ contextWindow: 1_000_000,+ reasoning: true,+ reasoningEfforts: ['low', 'high', 'max'],+ reasoningDefaultEffort: 'high',+ });+ expect(pi?.models.find((model) => model.id === 'deepseek-v4-pro')).toMatchObject({+ contextWindow: 1_000_000,+ reasoning: true,+ reasoningEfforts: ['high', 'max'],+ reasoningDefaultEffort: 'high',+ });+ });++ it.each([+ ['moonshot-kimi-cn', 'https://api.moonshot.cn/v1'],+ ['moonshot-kimi-global', 'https://api.moonshot.ai/v1'],+ ])('%s 为 Pi 同步完整 Kimi 官方目录与逐模型能力', (id, baseUrl) => {+ const pi = preset(id)?.runtimes.pi;+ expect(pi?.baseUrl).toBe(baseUrl);+ expect(pi?.piCatalogProviderId).toBe(id === 'moonshot-kimi-cn' ? 'moonshotai-cn' : 'moonshotai');+ expect(pi?.models.length).toBeGreaterThan(3);+ expect(pi?.models.find((model) => model.id === 'kimi-k3')).toMatchObject({+ contextWindow: 1_048_576,+ supportsImageInput: true,+ reasoning: true,+ reasoningEfforts: ['low', 'high', 'max'],+ reasoningDefaultEffort: 'max',+ });+ expect(pi?.models.find((model) => model.id === 'kimi-k2.7-code')).toMatchObject({+ contextWindow: 262_144,+ supportsImageInput: true,+ });+ expect(pi?.models.find((model) => model.id === 'kimi-k2.7-code'))+ .not.toHaveProperty('reasoningEfforts');+ });++ it.each([+ ['moonshot-kimi-code', 'kimi-coding'],+ ['minimax-cn', 'minimax-cn'],+ ['minimax-global', 'minimax'],+ ])('%s 的 Pi 预设投影官方 Anthropic Messages 协议', (id, providerId) => {+ const pi = preset(id)?.runtimes.pi;+ expect(pi?.piCatalogProviderId).toBe(providerId);+ expect(pi?.wireProtocol).toBe('anthropic-messages');+ });+it.each([['zhipu-coding-plan-cn', 'https://open.bigmodel.cn/api/coding/paas/v4'],['zai-coding-plan-global', 'https://api.z.ai/api/coding/paas/v4'],diff --git a/packages/model-providers/src/__tests__/source-registry.test.ts b/packages/model-providers/src/__tests__/source-registry.test.tsindex b27495e5cb..ec71a8b034 100644--- a/packages/model-providers/src/__tests__/source-registry.test.ts+++ b/packages/model-providers/src/__tests__/source-registry.test.ts@@ -109,7 +109,7 @@ describe('mergeWithBundled', () => {expect(merged.providers.find((p) => p.id === 'anthropic')!.models['claude-code']!.length).toBe(1);});- it('keeps a newer bundled modelRegistry when the primary full snapshot is stale', () => {+ it('keeps a newer bundled Registry without replacing the independent xAI fallback provider', () => {const bundledRegistry = BUNDLED_CATALOG.modelRegistry;const bundledXai = BUNDLED_CATALOG.providers.find((provider) => provider.id === 'xai');if (!bundledRegistry) throw new Error('missing bundled modelRegistry');@@ -129,7 +129,7 @@ describe('mergeWithBundled', () => {expect(merged.modelRegistry).toBe(bundledRegistry);expect(merged.modelRegistry?.models.length).toBeGreaterThan(staleRegistry.models.length);- expect(merged.providers.find((provider) => provider.id === 'xai')).toBe(bundledXai);+ expect(merged.providers.find((provider) => provider.id === 'xai')?.name).toBe('STALE-XAI');});it('uses a newer primary modelRegistry as one complete snapshot, including retirements', () => {@@ -153,7 +153,13 @@ describe('mergeWithBundled', () => {expect(merged.modelRegistry).toBe(newerRegistry);expect(merged.modelRegistry?.models).toHaveLength(1);expect(merged.modelRegistry?.models[0]?.status).toBe('retired');- expect(merged.providers.find((provider) => provider.id === 'xai')).toBe(newerXai);+ const mergedXai = merged.providers.find((provider) => provider.id === 'xai');+ expect(mergedXai).toMatchObject({+ ...newerXai,+ agents: expect.arrayContaining(['claude-code', 'codex', 'pi']),+ routing: expect.objectContaining({ pi: bundledXai.routing.pi }),+ models: expect.objectContaining({ pi: bundledXai.models.pi }),+ });});it('orders result by bundled provider order (v2 远端只带 xai 时不得窜位)', () => {@@ -416,6 +422,45 @@ describe('loadCatalog', () => {expect(bundled).toEqual({ source: 'bundled', catalog: BUNDLED_CATALOG });});+ it('only backfills Pi metadata for proven legacy snapshots across local, remote, and cache', async () => {+ const bundledPreset = BUNDLED_CATALOG.presets?.find((preset) => preset.id === 'deepseek');+ if (!bundledPreset) throw new Error('missing bundled DeepSeek preset');+ const { pi: _missing, ...legacyRuntimes } = bundledPreset.runtimes;+ const legacy = JSON.stringify({+ version: '2',+ providers: MINIMAL.providers,+ presets: [{ ...bundledPreset, runtimes: legacyRuntimes }],+ });+ const current = JSON.stringify({+ version: BUNDLED_CATALOG.version,+ providers: MINIMAL.providers,+ presets: [{ ...bundledPreset, runtimes: legacyRuntimes }],+ });+ const local = await loadCatalogWithSource(+ { localPath: '/repo/providers.json' },+ { readFile: vi.fn(async () => legacy) },+ );+ const remote = await loadCatalogWithSource(+ { url: 'https://catalog.example.test/providers.json' },+ { fetchText: vi.fn(async () => legacy) },+ );+ const cache = await loadCatalogWithSource(+ { url: 'https://catalog.example.test/providers.json', remoteBudgetMs: 0 },+ { readCache: vi.fn(async () => legacy) },+ );+ for (const loaded of [local, remote, cache]) {+ expect(loaded.catalog.presets?.find((preset) => preset.id === 'deepseek')?.runtimes.pi)+ .toEqual(bundledPreset.runtimes.pi);+ }++ const currentLoaded = await loadCatalogWithSource(+ { url: 'https://catalog.example.test/providers.json' },+ { fetchText: vi.fn(async () => current) },+ );+ expect(currentLoaded.catalog.presets?.find((preset) => preset.id === 'deepseek')?.runtimes.pi)+ .toBeUndefined();+ });+it('persists a valid remote snapshot and uses its source-scoped LKG after failure', async () => {const url = 'https://catalog.example.test/providers.json';const writeCache = vi.fn(async (_scope: string, _text: string) => undefined);diff --git a/packages/model-providers/src/__tests__/user-provider.test.ts b/packages/model-providers/src/__tests__/user-provider.test.tsindex 86f8972a12..dbfa749f95 100644--- a/packages/model-providers/src/__tests__/user-provider.test.ts+++ b/packages/model-providers/src/__tests__/user-provider.test.ts@@ -10,8 +10,14 @@import { describe, it, expect } from 'vitest';-import { buildUserProvider, DEFAULT_CUSTOM_CONTEXT_WINDOW } from '../user-provider.js';+import {+ buildUserProvider,+ DEFAULT_CUSTOM_CONTEXT_WINDOW,+ LEGACY_XAI_CUSTOM_PROVIDER_RUNTIME_ID,+ storedCustomProviderId,+} from '../user-provider.js';import type { CustomProviderConfig } from '../types.js';+import { BUNDLED_CATALOG } from '../catalog.js';const codexOnly: CustomProviderConfig = {id: 'openrouter',@@ -28,6 +34,17 @@ const codexOnly: CustomProviderConfig = {};describe('buildUserProvider (per-runtime)', () => {+ it('projects a legacy custom xai row under a collision-free runtime id', () => {+ const provider = buildUserProvider({+ ...codexOnly,+ id: 'xai',+ name: 'My xAI-compatible endpoint',+ });+ expect(provider.id).toBe(LEGACY_XAI_CUSTOM_PROVIDER_RUNTIME_ID);+ expect(provider.routing.codex?.upstream).toBe('https://openrouter.ai/api/v1');+ expect(storedCustomProviderId(provider.id)).toBe('xai');+ });+it('maps a single-runtime config to a standard user Provider', () => {const p = buildUserProvider(codexOnly);expect(p.id).toBe('openrouter');@@ -106,6 +123,127 @@ describe('buildUserProvider (per-runtime)', () => {});});+ it('inherits Registry efforts only for a unique route of the target agent', () => {+ const provider = buildUserProvider(+ {+ id: 'relay',+ name: 'Relay',+ runtimes: {+ codex: {+ baseUrl: 'https://relay.example/v1',+ models: [+ { id: 'gpt-5.6-sol', name: 'GPT-5.6-Sol' },+ { id: 'chatgpt/gpt-5.6-sol', name: 'GPT-5.6-Sol ChatGPT' },+ { id: 'unregistered-model', name: 'Unregistered' },+ ],+ },+ 'claude-code': {+ baseUrl: 'https://relay.example/anthropic',+ models: [{ id: 'gpt-5.6-sol', name: 'GPT-5.6-Sol' }],+ },+ },+ },+ { modelRegistry: BUNDLED_CATALOG.modelRegistry },+ );++ expect(provider.routing).toMatchObject({+ codex: { upstream: 'https://relay.example/v1' },+ 'claude-code': { upstream: 'https://relay.example/anthropic' },+ });+ expect(provider.models.codex).toEqual([+ expect.objectContaining({+ id: 'gpt-5.6-sol',+ efforts: ['low', 'medium', 'high', 'xhigh', 'max', 'ultra'],+ defaultEffort: 'high',+ }),+ expect.objectContaining({+ id: 'chatgpt/gpt-5.6-sol',+ efforts: ['low', 'medium', 'high', 'xhigh', 'max', 'ultra'],+ defaultEffort: 'high',+ }),+ expect.objectContaining({+ id: 'unregistered-model',+ efforts: ['low', 'medium', 'high', 'xhigh'],+ defaultEffort: 'high',+ }),+ ]);+ expect(provider.models['claude-code']?.[0]).toMatchObject({+ id: 'gpt-5.6-sol',+ efforts: ['low', 'medium', 'high', 'xhigh', 'max'],+ defaultEffort: 'high',+ });+ });++ it('falls back safely for ambiguous matches, missing target routes and invalid defaults', () => {+ const registry = structuredClone(BUNDLED_CATALOG.modelRegistry);+ if (!registry) throw new Error('missing bundled model registry');+ const baseEntry = registry.models.find((entry) => entry.id === 'openai/gpt-5.6-sol');+ if (!baseEntry) throw new Error('missing gpt-5.6-sol registry entry');+ baseEntry.perAgent = {+ ...baseEntry.perAgent,+ codex: { efforts: ['minimal', 'max'], defaultEffort: 'high' },+ };+ registry.models.push({+ ...structuredClone(baseEntry),+ id: 'alternate/gpt-5.6-sol',+ });++ const ambiguous = buildUserProvider(+ {+ id: 'ambiguous',+ name: 'Ambiguous',+ runtimes: {+ codex: {+ baseUrl: 'https://relay.example/v1',+ models: [{ id: 'gpt-5.6-sol', name: 'GPT-5.6-Sol' }],+ },+ },+ },+ { modelRegistry: registry },+ );+ expect(ambiguous.models.codex?.[0]).toMatchObject({+ efforts: ['low', 'medium', 'high', 'xhigh'],+ defaultEffort: 'high',+ });++ registry.models.pop();+ const invalidDefault = buildUserProvider(+ {+ id: 'unique',+ name: 'Unique',+ runtimes: {+ codex: {+ baseUrl: 'https://relay.example/v1',+ models: [{ id: 'gpt-5.6-sol', name: 'GPT-5.6-Sol' }],+ },+ },+ },+ { modelRegistry: registry },+ );+ expect(invalidDefault.models.codex?.[0]).toMatchObject({+ efforts: ['minimal', 'max'],+ defaultEffort: 'max',+ });++ const noTargetRoute = buildUserProvider(+ {+ id: 'wrong-agent',+ name: 'Wrong agent',+ runtimes: {+ codex: {+ baseUrl: 'https://relay.example/v1',+ models: [{ id: 'google/gemini-3.5-flash', name: 'Gemini 3.5 Flash' }],+ },+ },+ },+ { modelRegistry: BUNDLED_CATALOG.modelRegistry },+ );+ expect(noTargetRoute.models.codex?.[0]).toMatchObject({+ efforts: ['low', 'medium', 'high', 'xhigh'],+ defaultEffort: 'high',+ });+ });+it('respects an explicit hidden default for discovered models', () => {const p = buildUserProvider({...codexOnly,@@ -293,6 +431,23 @@ describe('buildUserProvider (per-runtime)', () => {expect((p.models.pi ?? [])[0]?.supportsImageInput).toBe(true);});+ it('never infers Pi efforts from a same-named Registry model', () => {+ const p = buildUserProvider(+ {+ id: 'pi-relay',+ name: 'Pi Relay',+ runtimes: {+ pi: {+ baseUrl: 'https://relay.example/v1',+ models: [{ id: 'gpt-5.6-sol', name: 'GPT-5.6-Sol' }],+ },+ },+ },+ { modelRegistry: BUNDLED_CATALOG.modelRegistry },+ );+ expect(p.models.pi?.[0]).toMatchObject({ efforts: [], defaultEffort: null });+ });+it('exports only the explicitly supported effort levels for a Pi reasoning model', () => {const p = buildUserProvider({id: 'reasoning-pi',@@ -319,6 +474,29 @@ describe('buildUserProvider (per-runtime)', () => {});});+ it.each([+ ['kimi', 'max'],+ ['deepseek', 'high'],+ ] as const)('uses the explicit %s Pi default reasoning effort', (id, expected) => {+ const p = buildUserProvider({+ id,+ name: id,+ runtimes: {+ pi: {+ baseUrl: `https://${id}.example/v1`,+ models: [{+ id: `${id}-model`, name: `${id} model`, reasoning: true,+ reasoningEfforts: ['low', 'high', 'max'], reasoningDefaultEffort: expected,+ }],+ },+ },+ });+ expect(p.models.pi?.[0]).toMatchObject({+ efforts: ['low', 'high', 'max'],+ defaultEffort: expected,+ });+ });+it('orders pi after claude-code and codex (AGENT_ORDER)', () => {const p = buildUserProvider({id: 'multi',diff --git a/packages/model-providers/src/catalog.ts b/packages/model-providers/src/catalog.tsindex 70447c2469..66ba21b7d8 100644--- a/packages/model-providers/src/catalog.ts+++ b/packages/model-providers/src/catalog.ts@@ -2,9 +2,11 @@* 目录运行时校验(parseCatalog)+ presets 清洗排序。** 2026-07-19 起 bundled 目录由 `builtin.ts` 组装:内置供应商身份卡是 TS 常量,- * `catalog/providers.json`(v2)只承载 xai 静态清单 + presets 模板——它仍是+ * `catalog/providers.json`(v2)承载 xAI 的离线 fallback 元数据 + presets 模板——它仍是* ① OSS `cfg/providers.json` 的发布物 ② dev 直读的仓库文件。anthropic/openai/xd* 的模型清单运行时动态注入(见 apps/desktop maker-host active-catalog),不再进目录文件。+ * xAI 登录后同样由账号 `/v1/models` 决定成员;此处静态段只在尚无成功账号快照时救急,+ * 并为已发现成员补上下文、价格、能力与路由。* 所有跨端模型元数据统一进入严格版本化的 `modelRegistry`;目录顶层不接受旁路元数据块。*/@@ -46,18 +48,31 @@ function hasValidPresetReasoningCapability(agent: AgentKind,model: Record<string, unknown>,): boolean {- const hasCapability = model.reasoning !== undefined || model.reasoningEfforts !== undefined;+ const hasCapability =+ model.reasoning !== undefined+ || model.reasoningEfforts !== undefined+ || model.reasoningDefaultEffort !== undefined;if (!hasCapability) return true;if (agent !== 'pi' || typeof model.reasoning !== 'boolean') return false;- if (model.reasoning !== true) return model.reasoningEfforts === undefined;+ if (model.reasoning !== true) {+ return model.reasoningEfforts === undefined && model.reasoningDefaultEffort === undefined;+ }if (!Array.isArray(model.reasoningEfforts) || model.reasoningEfforts.length === 0) return false;const efforts = model.reasoningEfforts;- return (+ const effortsValid = (efforts.every((effort) =>typeof effort === 'string' && (PI_REASONING_EFFORTS as readonly string[]).includes(effort),) && new Set(efforts).size === efforts.length);+ if (!effortsValid) return false;+ return (+ model.reasoningDefaultEffort === undefined+ || (+ typeof model.reasoningDefaultEffort === 'string'+ && efforts.includes(model.reasoningDefaultEffort)+ )+ );}function assert(cond: unknown, msg: string): asserts cond {@@ -429,6 +444,10 @@ function isValidPreset(v: unknown): v is ProviderPreset {if (Object.values(r.headers as Record<string, unknown>).some((x) => typeof x !== 'string')) return false;}if (r.baseUrlEditable !== undefined && typeof r.baseUrlEditable !== 'boolean') return false;+ if (+ r.piCatalogProviderId !== undefined+ && (agent !== 'pi' || typeof r.piCatalogProviderId !== 'string' || !/^[a-z0-9-]+$/.test(r.piCatalogProviderId))+ ) return false;// modelsUrl / requestPath 不在此淘汰整条——非法值由 sanitizePresets 剥字段。}return true;diff --git a/packages/model-providers/src/index.ts b/packages/model-providers/src/index.tsindex 2a0b2bf10c..4ee7d573bd 100644--- a/packages/model-providers/src/index.ts+++ b/packages/model-providers/src/index.ts@@ -35,11 +35,19 @@ export type {export { PI_REASONING_EFFORTS } from './types.js';+export { effectivePiWireProtocol, preservesPiCatalogModels } from './pi-catalog-marker.js';+export { resolveCodexCompatibilityWireProtocol } from './codexCompatibility.js';export { BUNDLED_CATALOG, BUILTIN_PROVIDERS, parseCatalog, presetDisplayName, sanitizePresets, sortPresetsForRegion } from './catalog.js';-export { buildUserProvider, DEFAULT_CUSTOM_CONTEXT_WINDOW } from './user-provider.js';+export {+ buildUserProvider,+ DEFAULT_CUSTOM_CONTEXT_WINDOW,+ LEGACY_XAI_CUSTOM_PROVIDER_RUNTIME_ID,+ runtimeCustomProviderId,+ storedCustomProviderId,+} from './user-provider.js';export {appendProviderRequestPath,isLoopbackProviderUrl,diff --git a/packages/model-providers/src/pi-catalog-marker.ts b/packages/model-providers/src/pi-catalog-marker.tsnew file mode 100644index 0000000000..ac17661a5d--- /dev/null+++ b/packages/model-providers/src/pi-catalog-marker.ts@@ -0,0 +1,43 @@+import type { ProviderRuntimeModelConfig, ProviderWireProtocol } from './types.js';++/** Pi treats an omitted wire protocol as its effective OpenAI Chat default. */+export function effectivePiWireProtocol(+ value: ProviderWireProtocol | undefined,+): ProviderWireProtocol {+ return value ?? 'openai-chat';+}++function projectedPiCatalogFields(model: ProviderRuntimeModelConfig): object {+ return {+ name: model.name,+ contextWindow: model.contextWindow,+ supportsImageInput: model.supportsImageInput,+ reasoning: model.reasoning,+ reasoningEfforts: model.reasoningEfforts,+ reasoningDefaultEffort: model.reasoningDefaultEffort,+ };+}++/**+ * Whether an edited model list still represents the same catalog-backed models.+ *+ * New models and presentation-only edits may coexist with the catalog snapshot, but every+ * previously saved model must still exist with the same catalog-projected fields. First-wins+ * duplicate handling mirrors custom-provider persistence normalization, so a duplicate row cannot+ * hide a replacement or metadata override from the main-process check.+ */+export function preservesPiCatalogModels(+ previous: readonly ProviderRuntimeModelConfig[] | undefined,+ next: readonly ProviderRuntimeModelConfig[] | undefined,+): boolean {+ const nextById = new Map<string, ProviderRuntimeModelConfig>();+ for (const model of next ?? []) {+ if (!nextById.has(model.id)) nextById.set(model.id, model);+ }+ return (previous ?? []).every((model) => {+ const candidate = nextById.get(model.id);+ return candidate !== undefined+ && JSON.stringify(projectedPiCatalogFields(model))+ === JSON.stringify(projectedPiCatalogFields(candidate));+ });+}diff --git a/packages/model-providers/src/source.ts b/packages/model-providers/src/source.tsindex a7c276668a..cb74f97630 100644--- a/packages/model-providers/src/source.ts+++ b/packages/model-providers/src/source.ts@@ -28,6 +28,9 @@ export const CATALOG_CFG_PATH = '/cfg/providers.json';/** 整条远端 Catalog fallback 链共享的默认启动等待预算。 */export const DEFAULT_REMOTE_CATALOG_BUDGET_MS = 15_000;+/** Only numeric catalog snapshots older than v3 predate the Pi preset metadata contract. */+const PI_RUNTIME_METADATA_CATALOG_VERSION = 3;+export interface CatalogSourceConfig {/** 完整覆盖源 URL(env XDT_MODELS_URL);缺省使用公共 catalog API。 */url?: string;@@ -127,6 +130,15 @@ function remoteErrorForLog(error: unknown, remoteUrl: string, logUrl: string): sreturn String(error).split(remoteUrl).join(logUrl);}+function numericCatalogVersion(version: string): number | null {+ return /^\d+$/.test(version) ? Number(version) : null;+}++function allowsLegacyPiRuntimeBackfill(primary: Catalog): boolean {+ const version = numericCatalogVersion(primary.version);+ return version !== null && version < PI_RUNTIME_METADATA_CATALOG_VERSION;+}+/** 只给仍保持 bundled 鉴权与上游路由形状的旧条目迁移 access,不能仅凭 provider id 猜计费。 */function legacyAccessFor(primary: Provider, bundled: Provider): Provider['access'] {if (primary.auth.method !== bundled.auth.method) return undefined;@@ -159,16 +171,17 @@ function allowsBundledImageInheritance(}/**- * 同 id preset 仍以远端为主;bundled 只给远端仍保留的同 runtime / 同 model- * 回填缺失的 contextWindow。这样旧远端不会把已核实的长上下文元数据降级,同时远端- * 仍可通过移除 runtime / model 停止新建,或用显式窗口覆盖 bundled。+ * 同 id preset 仍以远端为主;bundled 给远端仍保留的同 runtime / 同 model 回填缺失的+ * contextWindow,并为旧 schema 中完全缺席的 Pi runtime 回填已核实能力。这样旧远端不会+ * 把长上下文或 Pi 能力降级;已有 Pi runtime 与显式窗口仍完整由远端优先。*/-function backfillPresetContextWindows(+function backfillPresetMetadata(primary: ProviderPreset,bundled: ProviderPreset,+ allowLegacyPiBackfill: boolean,): ProviderPreset {let changed = primary.nameZhTW === undefined && bundled.nameZhTW !== undefined;- const runtimes: ProviderPreset['runtimes'] = {};+ const runtimes: ProviderPreset['runtimes'] = { ...primary.runtimes };for (const [agent, runtime] of Object.entries(primary.runtimes) as [AgentKind,NonNullable<ProviderPreset['runtimes'][AgentKind]>,@@ -189,6 +202,17 @@ function backfillPresetContextWindows(});runtimes[agent] = runtimeChanged ? { ...runtime, models } : runtime;}+ // Pi runtime 是 2026-08 后新增的预设能力槽。旧远端目录没有表达“显式禁用 Pi”的+ // 字段,缺席只代表旧 schema;对随包已核实的官方预设回填整段,避免远端 LKG 把+ // DeepSeek/Kimi 的推理档位与视觉能力遮掉。远端一旦自行提供 Pi,仍完整优先。+ if (+ allowLegacyPiBackfill+ && primary.runtimes.pi === undefined+ && bundled.runtimes.pi !== undefined+ ) {+ runtimes.pi = bundled.runtimes.pi;+ changed = true;+ }return changed? {...primary,@@ -290,11 +314,12 @@ export function mergeWithBundled(primary: Catalog): Catalog {// 远端独有项按远端原序追加。避免旧远端的非空 presets 整段遮掉新版客户端内置条目。const primaryPresets = primary.presets ?? [];const bundledPresets = BUNDLED_CATALOG.presets ?? [];+ const allowLegacyPiBackfill = allowsLegacyPiRuntimeBackfill(primary);const primaryPresetsById = new Map(primaryPresets.map((preset) => [preset.id, preset]));const bundledPresetIds = new Set(bundledPresets.map((preset) => preset.id));const presets = bundledPresets.map((bundled) => {const remote = primaryPresetsById.get(bundled.id);- return remote ? backfillPresetContextWindows(remote, bundled) : bundled;+ return remote ? backfillPresetMetadata(remote, bundled, allowLegacyPiBackfill) : bundled;});for (const preset of primaryPresets) {if (!bundledPresetIds.has(preset.id)) presets.push(preset);@@ -303,17 +328,9 @@ export function mergeWithBundled(primary: Catalog): Catalog {// 保留新版客户端随包快照,避免复现 presets 曾出现的“旧远端遮掉新本地能力”;// 远端较新时整份生效,继续支持 status=retired、route 删除和价格纠错。const selectedRegistry = selectNewerModelRegistry(primary, BUNDLED_CATALOG);- // xAI is the only provider whose model list is a static part of this Catalog snapshot. When- // bundled wins the registry revision guard, keep its xAI provider with that same snapshot- // instead of combining a new registry with an older remote/LKG list.- const providers = selectedRegistry.fromFallback && primary.modelRegistry !== undefined- ? merged.map((provider) =>- provider.id === 'xai' ? (bundledById.get('xai') ?? provider) : provider,- )- : merged;return {version: primary.version,- providers,+ providers: merged,...(presets && presets.length > 0 ? { presets } : {}),...(selectedRegistry.modelRegistry ? { modelRegistry: selectedRegistry.modelRegistry } : {}),};diff --git a/packages/model-providers/src/types.ts b/packages/model-providers/src/types.tsindex 2b8851e5b2..1272ee8221 100644--- a/packages/model-providers/src/types.ts+++ b/packages/model-providers/src/types.ts@@ -184,6 +184,8 @@ export interface RoutingDescriptor {* (providerViewToConfig 从 routing 重建配置)不丢这个持久化字段。*/modelsUrl?: string;+ /** Pi 官方模型目录的 provider id;仅供 Pi 原生 provider 复用上游核实的模型协议/能力。 */+ piCatalogProviderId?: string;/*** 该路由能服务的 wire model id 命名空间前缀白名单(每项形如 `xai/`,必须以 `/` 结尾)。*@@ -487,6 +489,8 @@ export interface ProviderRuntimeModelConfig {* provider 类型猜测,避免把 UI 可选档位导出给实际不支持 reasoning 的 BYOM 端点。*/reasoningEfforts?: PiReasoningEffort[];+ /** Pi 自定义模型的厂商推荐默认推理强度;必须包含在 reasoningEfforts 中。 */+ reasoningDefaultEffort?: PiReasoningEffort;}/**@@ -515,6 +519,8 @@ export interface ProviderPresetRuntime {* 防用户无意改坏已核验端点。*/baseUrlEditable?: boolean;+ /** 对应 `pi.dev/api/models/providers/<id>`;创建连接时快照,旧连接不自动补。 */+ piCatalogProviderId?: string;}/**@@ -604,6 +610,8 @@ export interface CustomProviderRuntimeConfig {* 从预设创建时随 `ProviderPresetRuntime.modelsUrl` 快照进来并持久化,编辑态仍可再拉。*/modelsUrl?: string;+ /** Pi 官方模型目录 provider id;缺省保持历史手填/BYOM 行为。 */+ piCatalogProviderId?: string;}/**diff --git a/packages/model-providers/src/user-provider.ts b/packages/model-providers/src/user-provider.tsindex 8b8c44ca42..093b6429b8 100644--- a/packages/model-providers/src/user-provider.ts+++ b/packages/model-providers/src/user-provider.ts@@ -21,11 +21,26 @@ import type {ProviderWireProtocol,RoutingDescriptor,} from './types.js';+import type { ModelRegistry } from './modelAccessBean.js';import { isLoopbackProviderUrl } from './provider-url.js';/** 自定义模型缺省上下文窗口(用户不填元数据时的保守默认,仅用于展示)。 */export const DEFAULT_CUSTOM_CONTEXT_WINDOW = 200_000;+/**+ * Older releases allowed a user provider to occupy `xai`, which is now the built-in SuperGrok+ * source. Preserve the stored id, but project that legacy row under a collision-free runtime id.+ */+export const LEGACY_XAI_CUSTOM_PROVIDER_RUNTIME_ID = 'custom:xai';++export function runtimeCustomProviderId(providerId: string): string {+ return providerId === 'xai' ? LEGACY_XAI_CUSTOM_PROVIDER_RUNTIME_ID : providerId;+}++export function storedCustomProviderId(providerId: string): string {+ return providerId === LEGACY_XAI_CUSTOM_PROVIDER_RUNTIME_ID ? 'xai' : providerId;+}+/*** 自定义模型的默认 effort 档位(「参考默认设置」)——与内置当代旗舰模型对齐:* - claude-code:low/medium/high/xhigh/max(同 opus / fable);@@ -41,6 +56,50 @@ const CUSTOM_EFFORTS: Partial<Record<AgentKind, Effort[]>> = {/** 自定义模型默认选中的 effort(与内置旗舰一致)。 */const DEFAULT_CUSTOM_EFFORT: Effort = 'high';+interface RegistryEffortMetadata {+ efforts: Effort[];+ defaultEffort: Effort | null;+}++/**+ * 仅在模型能由当前 agent 的 Registry route 唯一识别时复用 effort 元数据。+ * 自定义 provider 的 id、model id 与路由保持原值;Pi 能力继续只认逐模型显式配置。+ */+function registryEffortMetadata(+ registry: ModelRegistry | null | undefined,+ modelId: string,+ agent: AgentKind,+): RegistryEffortMetadata | undefined {+ if (agent === 'pi' || !registry) return undefined;++ const candidates = new Set([modelId]);+ if (modelId.startsWith('chatgpt/')) {+ candidates.add(modelId.slice('chatgpt/'.length));+ }+ const matches = registry.models.filter((entry) =>+ entry.routes.some(+ (route) =>+ route.agents.includes(agent) &&+ (candidates.has(entry.id) || candidates.has(route.modelId)),+ ),+ );+ const uniqueEntries = [...new Map(matches.map((entry) => [entry.id, entry])).values()];+ if (uniqueEntries.length !== 1) return undefined;++ const entry = uniqueEntries[0]!;+ const perAgent = entry.perAgent?.[agent];+ const efforts = perAgent?.efforts ?? entry.efforts;+ if (!efforts) return undefined;+ const declaredDefault = perAgent?.defaultEffort ?? entry.defaultEffort;+ const defaultEffort =+ declaredDefault && efforts.includes(declaredDefault)+ ? declaredDefault+ : efforts.includes(DEFAULT_CUSTOM_EFFORT)+ ? DEFAULT_CUSTOM_EFFORT+ : (efforts[efforts.length - 1] ?? null);+ return { efforts: [...efforts], defaultEffort };+}+/** 固定 agent 顺序:保证派生出的 provider.agents / routing / models 顺序稳定。 */const AGENT_ORDER: readonly AgentKind[] = ['claude-code', 'codex', 'pi'];@@ -49,6 +108,7 @@ function toCatalogModel(m: ProviderRuntimeModelConfig,providerId: string,agent: AgentKind,+ modelRegistry: ModelRegistry | null | undefined,): CatalogModel {// Pi BYOM 不从 runtime / 协议猜模型能力:只有用户逐模型明确确认后才向 catalog 暴露// effort。这样 catalog/UI 与稍后写入 models.json 的能力保持同一份契约,旧配置安全关闭。@@ -58,9 +118,15 @@ function toCatalogModel(? [...(m.reasoningEfforts ?? [])]: []: (CUSTOM_EFFORTS[agent] ?? []);- const defaultEffort = efforts.includes(DEFAULT_CUSTOM_EFFORT)- ? DEFAULT_CUSTOM_EFFORT- : (efforts[0] ?? null);+ const registryEfforts = registryEffortMetadata(modelRegistry, m.id, agent);+ const effectiveEfforts = registryEfforts?.efforts ?? efforts;+ const defaultEffort =+ registryEfforts?.defaultEffort ??+ (agent === 'pi' && m.reasoningDefaultEffort && effectiveEfforts.includes(m.reasoningDefaultEffort)+ ? m.reasoningDefaultEffort+ : effectiveEfforts.includes(DEFAULT_CUSTOM_EFFORT)+ ? DEFAULT_CUSTOM_EFFORT+ : (effectiveEfforts[0] ?? null));return {id: m.id,name: m.name,@@ -71,7 +137,7 @@ function toCatalogModel(// 显式配置的窗口打标:编辑表单回转配置时必须与「缺省物化成的默认值」可区分,// 哪怕用户显式填的恰好等于当前默认(未来默认升级后显式值要原样保留)。...(m.contextWindow !== undefined ? { contextWindowExplicit: true } : {}),- efforts,+ efforts: effectiveEfforts,defaultEffort,// 选择器右栏按 group 聚合:同一自定义来源的模型聚成一组(渲染层用 provider 名兜底标签)。group: `custom:${providerId}`,@@ -101,6 +167,7 @@ function toRouting(strategy: 'api-key-header' | 'oauth-token' | 'none',modelsUrl?: string,wireProtocol?: 'anthropic-messages' | 'openai-responses' | 'openai-chat',+ piCatalogProviderId?: string,): RoutingDescriptor {const r: RoutingDescriptor = {upstream: baseUrl,@@ -121,6 +188,7 @@ function toRouting(}// 列模型端点回带(编辑表单从 routing 重建配置时不丢;路由器不消费本字段)。if (modelsUrl) r.modelsUrl = modelsUrl;+ if (piCatalogProviderId) r.piCatalogProviderId = piCatalogProviderId;return r;}@@ -129,7 +197,15 @@ function toRouting(* 按 `runtimes` 里**已配置的 runtime** 生成各 agent 的 routing / models(每 runtime 独立 baseUrl /* 模型 / headers);空 runtimes 产出空 Provider(不出现在任何 agent 列表,无害)。*/-export function buildUserProvider(config: CustomProviderConfig): Provider {+export interface BuildUserProviderOptions {+ modelRegistry?: ModelRegistry | null;+}++export function buildUserProvider(+ config: CustomProviderConfig,+ options: BuildUserProviderOptions = {},+): Provider {+ const runtimeProviderId = runtimeCustomProviderId(config.id);// OAuth 形态路由走 Runner Bearer;none 明确走无鉴权且由 host 剥凭证;缺省保持历史 API key。const oauth = config.auth?.method === 'oauth' ? config.auth.oauth : undefined;const isOAuth = oauth !== undefined;@@ -151,11 +227,14 @@ export function buildUserProvider(config: CustomProviderConfig): Provider {strategy,rt.modelsUrl,rt.wireProtocol,+ rt.piCatalogProviderId,+ );+ models[agent] = rt.models.map((m) =>+ toCatalogModel(m, config.id, agent, options.modelRegistry),);- models[agent] = rt.models.map((m) => toCatalogModel(m, config.id, agent));}return {- id: config.id,+ id: runtimeProviderId,name: config.name,source: 'user',agents,diff --git a/tools/pi/sync-model-catalog.mjs b/tools/pi/sync-model-catalog.mjsnew file mode 100644index 0000000000..5a7e0fe46a--- /dev/null+++ b/tools/pi/sync-model-catalog.mjs@@ -0,0 +1,200 @@+#!/usr/bin/env node++import fs from 'node:fs/promises';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');+const CATALOG_PATH = path.join(ROOT, 'packages/model-providers/catalog/providers.json');+const SNAPSHOT_PATH = path.join(ROOT, 'packages/model-providers/catalog/pi-model-catalog.json');+const PI_CATALOG_BASE = 'https://pi.dev/api/models/providers';+const PI_LEVELS = ['minimal', 'low', 'medium', 'high', 'xhigh', 'max'];++// Only exact Pi provider routes belong here. A similar model family or compatible wire protocol+// is not enough evidence: unmatched presets retain their existing generic Pi derivation path.+const PRESET_PROVIDER_MAP = {+ deepseek: { providerId: 'deepseek', sourceAgent: 'codex' },+ 'moonshot-kimi-cn': { providerId: 'moonshotai-cn', sourceAgent: 'codex' },+ 'moonshot-kimi-global': { providerId: 'moonshotai', sourceAgent: 'codex' },+ 'moonshot-kimi-code': { providerId: 'kimi-coding', sourceAgent: 'claude-code' },+ 'minimax-cn': { providerId: 'minimax-cn', sourceAgent: 'claude-code' },+ 'minimax-global': { providerId: 'minimax', sourceAgent: 'claude-code' },+ 'aliyun-bailian-token-plan-cn': { providerId: 'qwen-token-plan-cn', sourceAgent: 'codex' },+ 'aliyun-bailian-token-plan-team-cn': { providerId: 'qwen-token-plan-cn', sourceAgent: 'codex' },+ 'zhipu-coding-plan-cn': { providerId: 'zai-coding-cn', sourceAgent: 'codex' },+ 'zai-coding-plan-global': { providerId: 'zai', sourceAgent: 'codex' },+ 'xiaomi-mimo-api-cn': { providerId: 'xiaomi', sourceAgent: 'codex' },+ 'xiaomi-mimo-token-plan-cn': { providerId: 'xiaomi-token-plan-cn', sourceAgent: 'codex' },+};++const PROVIDER_IDS = [...new Set([+ ...Object.values(PRESET_PROVIDER_MAP).map(({ providerId }) => providerId),+ 'xai',+])].sort();++function catalogEntries(providerId, value) {+ const entries = Array.isArray(value)+ ? value+ : value && typeof value === 'object' && Array.isArray(value.models)+ ? value.models+ : value && typeof value === 'object'+ ? Object.values(value)+ : null;+ if (!entries) throw new Error(`Pi catalog '${providerId}' is not an array or model map`);+ return entries.map((entry) => {+ if (!entry || typeof entry !== 'object' || typeof entry.id !== 'string') {+ throw new Error(`Pi catalog '${providerId}' contains an invalid model`);+ }+ if (entry.provider !== providerId) {+ throw new Error(`Pi catalog '${providerId}' model '${entry.id}' has provider '${entry.provider}'`);+ }+ return entry;+ });+}++function supportedEfforts(model) {+ if (model.reasoning !== true || !model.thinkingLevelMap) return [];+ return PI_LEVELS.filter((level) => {+ const mapped = model.thinkingLevelMap?.[level];+ return mapped !== undefined && mapped !== null;+ });+}++function defaultEffort(efforts) {+ if (efforts.length === 0) return undefined;+ const requested = PI_LEVELS.indexOf('medium');+ for (let i = requested; i < PI_LEVELS.length; i += 1) {+ if (efforts.includes(PI_LEVELS[i])) return PI_LEVELS[i];+ }+ for (let i = requested - 1; i >= 0; i -= 1) {+ if (efforts.includes(PI_LEVELS[i])) return PI_LEVELS[i];+ }+ return efforts[0];+}++function presetModel(model, previous) {+ const efforts = supportedEfforts(model);+ const previousDefault = previous?.reasoningDefaultEffort;+ const effectiveDefault = previousDefault && efforts.includes(previousDefault)+ ? previousDefault+ : defaultEffort(efforts);+ return {+ id: model.id,+ name: model.name ?? model.id,+ ...(Number.isFinite(model.contextWindow) && model.contextWindow > 0+ ? { contextWindow: model.contextWindow }+ : {}),+ ...(Array.isArray(model.input) && model.input.includes('image')+ ? { supportsImageInput: true }+ : {}),+ ...(efforts.length > 0+ ? {+ reasoning: true,+ reasoningEfforts: efforts,+ ...(effectiveDefault ? { reasoningDefaultEffort: effectiveDefault } : {}),+ }+ : {}),+ };+}++function runtimeWireProtocol(providerId, models) {+ const apis = [...new Set(models.map((model) => model.api))];+ if (apis.length !== 1) {+ throw new Error(`Pi catalog '${providerId}' does not have one runtime protocol`);+ }+ switch (apis[0]) {+ case 'anthropic-messages':+ return 'anthropic-messages';+ case 'openai-responses':+ return 'openai-responses';+ case 'openai-completions':+ return 'openai-chat';+ default:+ throw new Error(`Pi catalog '${providerId}' has unsupported api '${apis[0]}'`);+ }+}++function xaiCatalogModel(model, index) {+ const efforts = supportedEfforts(model);+ return {+ // Pi uses provider provenance, so its xAI model ids stay identical to Pi's official catalog.+ // Claude/Codex keep the historical xai/ namespace in their own per-agent lists.+ id: model.id,+ name: model.name ?? model.id,+ group: 'grok',+ sortOrder: 49 + index,+ contextWindow: model.contextWindow,+ ...(Number.isFinite(model.maxTokens) && model.maxTokens > 0 ? { maxOutput: model.maxTokens } : {}),+ efforts,+ defaultEffort: defaultEffort(efforts) ?? null,+ status: 'active',+ ...(Array.isArray(model.input) && model.input.includes('image') ? { supportsImageInput: true } : {}),+ ...(model.cost ? { cost: model.cost } : {}),+ };+}++async function main() {+ const providers = {};+ let newestModified = 0;+ const inputIndex = process.argv.indexOf('--input');+ const inputPath = inputIndex >= 0 ? process.argv[inputIndex + 1] : undefined;+ const generatedAtIndex = process.argv.indexOf('--generated-at');+ const generatedAtArg = generatedAtIndex >= 0 ? process.argv[generatedAtIndex + 1] : undefined;+ if (inputPath) {+ const input = JSON.parse(await fs.readFile(path.resolve(inputPath), 'utf8'));+ for (const providerId of PROVIDER_IDS) {+ if (!(providerId in input)) throw new Error(`Input catalog lacks provider '${providerId}'`);+ providers[providerId] = catalogEntries(providerId, input[providerId]);+ }+ } else {+ for (const providerId of PROVIDER_IDS) {+ const response = await fetch(`${PI_CATALOG_BASE}/${encodeURIComponent(providerId)}`, {+ headers: { accept: 'application/json', 'user-agent': 'cindy-pi-catalog-sync' },+ });+ if (!response.ok) throw new Error(`Pi catalog '${providerId}' returned HTTP ${response.status}`);+ const modified = Date.parse(response.headers.get('last-modified') ?? '');+ if (!Number.isNaN(modified)) newestModified = Math.max(newestModified, modified);+ providers[providerId] = catalogEntries(providerId, await response.json());+ }+ }++ const catalog = JSON.parse(await fs.readFile(CATALOG_PATH, 'utf8'));+ for (const preset of catalog.presets ?? []) {+ const mapping = PRESET_PROVIDER_MAP[preset.id];+ if (!mapping) {+ // Remove only Pi runtimes previously generated by this script. Hand-authored/generic Pi+ // runtimes have no catalog marker and remain untouched.+ if (preset.runtimes?.pi?.piCatalogProviderId) delete preset.runtimes.pi;+ continue;+ }+ const source = preset.runtimes?.[mapping.sourceAgent];+ if (!source) throw new Error(`Preset '${preset.id}' lacks source runtime '${mapping.sourceAgent}'`);+ const previousModels = new Map((preset.runtimes.pi?.models ?? []).map((model) => [model.id, model]));+ preset.runtimes.pi = {+ baseUrl: source.baseUrl,+ wireProtocol: runtimeWireProtocol(mapping.providerId, providers[mapping.providerId]),+ ...(source.modelsUrl ? { modelsUrl: source.modelsUrl } : {}),+ piCatalogProviderId: mapping.providerId,+ models: providers[mapping.providerId].map((model) => presetModel(model, previousModels.get(model.id))),+ };+ }++ const xai = (catalog.providers ?? []).find((provider) => provider.id === 'xai');+ if (!xai) throw new Error('Catalog lacks builtin xai provider');+ if (!xai.agents.includes('pi')) xai.agents.push('pi');+ xai.routing.pi = {+ upstream: 'https://api.x.ai/v1',+ authStrategy: 'provider-oauth-header',+ headerDelete: ['chatgpt-account-id', 'openai-beta', 'originator', 'session_id'],+ };+ xai.models.pi = providers.xai.map(xaiCatalogModel);++ const generatedAt = generatedAtArg+ ? new Date(generatedAtArg).toISOString()+ : new Date(newestModified || Date.now()).toISOString();+ await fs.writeFile(CATALOG_PATH, `${JSON.stringify(catalog, null, 2)}\n`);+ await fs.writeFile(SNAPSHOT_PATH, `${JSON.stringify({ generatedAt, providers }, null, 2)}\n`);+ console.log(`Synced ${PROVIDER_IDS.length} Pi providers at ${generatedAt}`);+}++await main();