Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): complete media invocation integration
liugaowei02260c37c8af
diff --cc apps/desktop/drizzle/0092_fixed_zeigeist.sqlindex 88bb781726,0000000000..808731d65amode 100644,000000..100644--- a/apps/desktop/drizzle/0092_fixed_zeigeist.sql+++ b/apps/desktop/drizzle/0092_fixed_zeigeist.sql@@@ -1,15 -1,0 +1,16 @@@+CREATE TABLE IF NOT EXISTS `media_invocations` (+ `id` text PRIMARY KEY NOT NULL,+ `owner` text NOT NULL,+ `model_id` text NOT NULL,+ `capability` text NOT NULL,+ `guide_revision` text NOT NULL,+ `guide_json` text NOT NULL,+ `state` text NOT NULL,+ `task_id` text,++ `response_json` text,+ `created_at` integer NOT NULL,+ `updated_at` integer NOT NULL+);+--> statement-breakpoint+CREATE INDEX IF NOT EXISTS `media_invocations_owner_created_at_idx` ON `media_invocations` (`owner`,`created_at`);--> statement-breakpoint+CREATE INDEX IF NOT EXISTS `media_invocations_owner_state_idx` ON `media_invocations` (`owner`,`state`);diff --cc apps/desktop/drizzle/meta/0092_snapshot.jsonindex 0000000000,0000000000..bb601c7092new file mode 100644--- /dev/null+++ b/apps/desktop/drizzle/meta/0092_snapshot.json@@@ -1,0 -1,0 +1,4032 @@@++{++ "version": "6",++ "dialect": "sqlite",++ "id": "ba4a24fc-8903-415b-9bf9-fee4bd54f907",++ "prevId": "678c1f41-343b-49e0-92d8-20247184dc60",++ "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",++ "tableTo": "sessions",++ "columnsFrom": ["session_id"],++ "columnsTo": ["id"],++ "onDelete": "cascade",++ "onUpdate": "no action"++ }++ },++ "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",++ "tableTo": "sessions",++ "columnsFrom": ["target_session_id"],++ "columnsTo": ["id"],++ "onDelete": "cascade",++ "onUpdate": "no action"++ }++ },++ "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_invocations": {++ "name": "media_invocations",++ "columns": {++ "id": {++ "name": "id",++ "type": "text",++ "primaryKey": true,++ "notNull": true,++ "autoincrement": false++ },++ "owner": {++ "name": "owner",++ "type": "text",++ "primaryKey": false,++ "notNull": true,++ "autoincrement": false++ },++ "model_id": {++ "name": "model_id",++ "type": "text",++ "primaryKey": false,++ "notNull": true,++ "autoincrement": false++ },++ "capability": {++ "name": "capability",++ "type": "text",++ "primaryKey": false,++ "notNull": true,++ "autoincrement": false++ },++ "guide_revision": {++ "name": "guide_revision",++ "type": "text",++ "primaryKey": false,++ "notNull": true,++ "autoincrement": false++ },++ "guide_json": {++ "name": "guide_json",++ "type": "text",++ "primaryKey": false,++ "notNull": true,++ "autoincrement": false++ },++ "state": {++ "name": "state",++ "type": "text",++ "primaryKey": false,++ "notNull": true,++ "autoincrement": false++ },++ "task_id": {++ "name": "task_id",++ "type": "text",++ "primaryKey": false,++ "notNull": false,++ "autoincrement": false++ },++ "response_json": {++ "name": "response_json",++ "type": "text",++ "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": {++ "media_invocations_owner_created_at_idx": {++ "name": "media_invocations_owner_created_at_idx",++ "columns": ["owner", "created_at"],++ "isUnique": false++ },++ "media_invocations_owner_state_idx": {++ "name": "media_invocations_owner_state_idx",++ "columns": ["owner", "state"],++ "isUnique": false++ }++ },++ "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",++ "tableTo": "media_blobs",++ "columnsFrom": ["hash"],++ "columnsTo": ["hash"],++ "onDelete": "cascade",++ "onUpdate": "no action"++ }++ },++ "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",++ "tableTo": "sessions",++ "columnsFrom": ["session_id"],++ "columnsTo": ["id"],++ "onDelete": "cascade",++ "onUpdate": "no action"++ }++ },++ "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"],++ "isUnique": true,++ "where": "\"orca_teams\".\"status\" = 'active'"++ },++ "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",++ "tableTo": "sessions",++ "columnsFrom": ["lead_session_id"],++ "columnsTo": ["id"],++ "onDelete": "cascade",++ "onUpdate": "no action"++ }++ },++ "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",++ "tableTo": "orca_teams",++ "columnsFrom": ["team_id"],++ "columnsTo": ["id"],++ "onDelete": "cascade",++ "onUpdate": "no action"++ }++ },++ "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"],++ "isUnique": true,++ "where": "\"orca_workers\".\"focused\" = 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",++ "tableTo": "orca_teams",++ "columnsFrom": ["team_id"],++ "columnsTo": ["id"],++ "onDelete": "cascade",++ "onUpdate": "no action"++ },++ "orca_workers_session_id_sessions_id_fk": {++ "name": "orca_workers_session_id_sessions_id_fk",++ "tableFrom": "orca_workers",++ "tableTo": "sessions",++ "columnsFrom": ["session_id"],++ "columnsTo": ["id"],++ "onDelete": "cascade",++ "onUpdate": "no action"++ }++ },++ "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"],++ "isUnique": true,++ "where": "\"right_sidebar_tabs\".\"kind\" = 'subagents'"++ }++ },++ "foreignKeys": {++ "right_sidebar_tabs_session_id_sessions_id_fk": {++ "name": "right_sidebar_tabs_session_id_sessions_id_fk",++ "tableFrom": "right_sidebar_tabs",++ "tableTo": "sessions",++ "columnsFrom": ["session_id"],++ "columnsTo": ["id"],++ "onDelete": "cascade",++ "onUpdate": "no action"++ }++ },++ "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",++ "tableTo": "schedules",++ "columnsFrom": ["schedule_id"],++ "columnsTo": ["id"],++ "onDelete": "cascade",++ "onUpdate": "no action"++ },++ "schedule_runs_session_id_sessions_id_fk": {++ "name": "schedule_runs_session_id_sessions_id_fk",++ "tableFrom": "schedule_runs",++ "tableTo": "sessions",++ "columnsFrom": ["session_id"],++ "columnsTo": ["id"],++ "onDelete": "set null",++ "onUpdate": "no action"++ }++ },++ "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",++ "tableTo": "sessions",++ "columnsFrom": ["target_session_id"],++ "columnsTo": ["id"],++ "onDelete": "set null",++ "onUpdate": "no action"++ },++ "schedules_skip_log_session_id_sessions_id_fk": {++ "name": "schedules_skip_log_session_id_sessions_id_fk",++ "tableFrom": "schedules",++ "tableTo": "sessions",++ "columnsFrom": ["skip_log_session_id"],++ "columnsTo": ["id"],++ "onDelete": "set null",++ "onUpdate": "no action"++ }++ },++ "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",++ "tableTo": "sessions",++ "columnsFrom": ["session_id"],++ "columnsTo": ["id"],++ "onDelete": "cascade",++ "onUpdate": "no action"++ }++ },++ "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",++ "tableTo": "sessions",++ "columnsFrom": ["session_id"],++ "columnsTo": ["id"],++ "onDelete": "cascade",++ "onUpdate": "no action"++ }++ },++ "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",++ "tableTo": "sessions",++ "columnsFrom": ["parent_session_id"],++ "columnsTo": ["id"],++ "onDelete": "set null",++ "onUpdate": "no action"++ }++ },++ "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",++ "tableTo": "skill_usage_sources",++ "columnsFrom": ["raw_file_path"],++ "columnsTo": ["raw_file_path"],++ "onDelete": "cascade",++ "onUpdate": "no action"++ }++ },++ "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",++ "tableTo": "sessions",++ "columnsFrom": ["session_id"],++ "columnsTo": ["id"],++ "onDelete": "cascade",++ "onUpdate": "no action"++ },++ "subagent_run_aliases_run_id_subagent_runs_id_fk": {++ "name": "subagent_run_aliases_run_id_subagent_runs_id_fk",++ "tableFrom": "subagent_run_aliases",++ "tableTo": "subagent_runs",++ "columnsFrom": ["run_id"],++ "columnsTo": ["id"],++ "onDelete": "cascade",++ "onUpdate": "no action"++ }++ },++ "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",++ "tableTo": "sessions",++ "columnsFrom": ["session_id"],++ "columnsTo": ["id"],++ "onDelete": "cascade",++ "onUpdate": "no action"++ }++ },++ "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",++ "tableTo": "wechat_sync_state",++ "columnsFrom": ["binding_epoch"],++ "columnsTo": ["binding_epoch"],++ "onDelete": "cascade",++ "onUpdate": "no action"++ },++ "wechat_file_attachments_task_id_wechat_inbox_id_fk": {++ "name": "wechat_file_attachments_task_id_wechat_inbox_id_fk",++ "tableFrom": "wechat_file_attachments",++ "tableTo": "wechat_inbox",++ "columnsFrom": ["task_id"],++ "columnsTo": ["id"],++ "onDelete": "cascade",++ "onUpdate": "no action"++ },++ "wechat_file_attachments_session_id_sessions_id_fk": {++ "name": "wechat_file_attachments_session_id_sessions_id_fk",++ "tableFrom": "wechat_file_attachments",++ "tableTo": "sessions",++ "columnsFrom": ["session_id"],++ "columnsTo": ["id"],++ "onDelete": "set null",++ "onUpdate": "no action"++ }++ },++ "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"],++ "isUnique": true,++ "where": "\"wechat_inbox\".\"session_id\" IS NOT NULL AND \"wechat_inbox\".\"status\" IN ('dispatching', 'accepted_running', 'waiting_desktop', 'delivery_pending')"++ }++ },++ "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",++ "tableTo": "wechat_sync_state",++ "columnsFrom": ["binding_epoch"],++ "columnsTo": ["binding_epoch"],++ "onDelete": "cascade",++ "onUpdate": "no action"++ },++ "wechat_inbox_session_id_sessions_id_fk": {++ "name": "wechat_inbox_session_id_sessions_id_fk",++ "tableFrom": "wechat_inbox",++ "tableTo": "sessions",++ "columnsFrom": ["session_id"],++ "columnsTo": ["id"],++ "onDelete": "set null",++ "onUpdate": "no action"++ }++ },++ "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",++ "tableTo": "wechat_sync_state",++ "columnsFrom": ["binding_epoch"],++ "columnsTo": ["binding_epoch"],++ "onDelete": "cascade",++ "onUpdate": "no action"++ },++ "wechat_outbox_task_id_wechat_inbox_id_fk": {++ "name": "wechat_outbox_task_id_wechat_inbox_id_fk",++ "tableFrom": "wechat_outbox",++ "tableTo": "wechat_inbox",++ "columnsFrom": ["task_id"],++ "columnsTo": ["id"],++ "onDelete": "cascade",++ "onUpdate": "no action"++ }++ },++ "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"],++ "isUnique": true,++ "where": "\"wechat_sync_state\".\"is_active\" = 1"++ }++ },++ "foreignKeys": {},++ "compositePrimaryKeys": {},++ "uniqueConstraints": {},++ "checkConstraints": {}++ }++ },++ "views": {},++ "enums": {},++ "_meta": {++ "schemas": {},++ "tables": {},++ "columns": {}++ },++ "internal": {++ "indexes": {++ "uniq_orca_worker_creation_reservations_team_label": {++ "columns": {++ "lower(\"label\")": {++ "isExpression": true++ }++ }++ },++ "uniq_orca_workers_team_label": {++ "columns": {++ "lower(\"label\")": {++ "isExpression": true++ }++ }++ }++ }++ }++}diff --cc apps/desktop/drizzle/meta/_journal.jsonindex 0de462e27a,3ee6feefbd..373bb71830--- a/apps/desktop/drizzle/meta/_journal.json+++ b/apps/desktop/drizzle/meta/_journal.json@@@ -635,9 -635,16 +635,23 @@@{"idx": 90,"version": "6",- "when": 1786439640217,- "tag": "0090_fixed_zeigeist",+ "when": 1786726026223,+ "tag": "0090_distinguish_xai_provider_provenance",+ "breakpoints": true+ },+ {+ "idx": 91,+ "version": "6",+ "when": 1786794359638,+ "tag": "0091_amazing_blur",+ "breakpoints": true++ },++ {++ "idx": 92,++ "version": "6",++ "when": 1786696564943,++ "tag": "0092_fixed_zeigeist",+ "breakpoints": true}]--}++}diff --cc apps/desktop/drizzle/scripts/0092_fixed_zeigeist.tsindex 0000000000,0000000000..97cb0138a4new file mode 100644--- /dev/null+++ b/apps/desktop/drizzle/scripts/0092_fixed_zeigeist.ts@@@ -1,0 -1,0 +1,11 @@@++import type Database from 'better-sqlite3';++++function run(db: Database.Database): void {++ const columns = db.prepare(`PRAGMA table_info('media_invocations')`).all() as Array<{++ name: string;++ }>;++ if (columns.some((column) => column.name === 'response_json')) return;++ db.exec('ALTER TABLE `media_invocations` ADD `response_json` text');++}++++module.exports = { run };diff --cc apps/desktop/src/main/cindy-brain/forge.tsindex d33bf4ed41,9aece04ba2..d1a8dee2c5--- a/apps/desktop/src/main/cindy-brain/forge.ts+++ b/apps/desktop/src/main/cindy-brain/forge.ts@@@ -2223,90 -2218,6 +2223,89 @@@ const r = await cindy.send(- 同步返回,没有异步单;每插件在途上限与媒体代办共用;装入确认框会单列一行「可把文字送去算成向量」并写明单次条数上限。+## 4.0.4 媒体模型配置与调用边界++媒体上层能力由插件定义,Cindy Core 只提供两项低级能力:++1. 插件设置页 / panel 按类型读取当前可用模型,用来保存插件自己的模型选择;+2. 当前 Agent 执行插件能力时,使用永久注册的 Cindy Core \`media\` 工具发起调用。++设置页 / panel 没有 preload 桥,直接走同源只读端点。插件必须声明 \`cindy\` 槽,+并在 \`cindy.image\` 或 \`cindy.video\` 中声明至少一个动作:++\`\`\`js+const result = await (await fetch('/media-models?type=image')).json();+// → {+// ok:true,+// type:'image',+// models:[{+// id,+// name,+// modalities:{ input:['text','image'], output:['image'] }+// }],+// defaultModelId:string|null+// }+\`\`\`+- \`type\` 只接受 \`image\` / \`video\`。Host 只按 Gateway \`mode\` 切大类,并把- Gateway \`architecture\` 已归一化后的 \`modalities.input/output\` 原样交给插件;- **Host 不把它翻译成出图、改图、文生视频或图生视频等插件业务动作**。这些动作怎样匹配- 输入/输出模态由插件自行决定,例如 Art 可以要求改图模型同时包含 \`text\`、\`image\`- 输入和 \`image\` 输出。\`modalities\` 缺省表示上游没有声明,插件不得按型号名或 Guide- 猜测支持度。-- Guide 是独立可选信息,不在此接口返回,也不决定模型是否出现在目录中。插件可把用户- 选择的模型 id 存进自己的 \`/kv\`,再通过工具结果或插件说明交给当前 Agent。++\`type\` 只接受 \`image\` / \`video\`。Host 按 Gateway \`mode\` 切大类,并结合插件在++\`cindy.image/video\` 声明的动作、Gateway \`modalities\`、Guide operation 与当前客户端++协议支持度,只返回当前真正可执行的模型。单个模型的 Guide 缺失、损坏或版本过新只隔离++该模型,不拖垮整个目录。++++响应仍只把 Gateway \`architecture\` 已归一化后的 \`modalities.input/output\` 原样交给插件,++不下发 Guide、endpoint、凭证或 Host 内部兼容判定。插件可把用户选择的模型 id 存进自己的++\`/kv\`,再通过工具结果或插件说明交给当前 Agent;付费请求前 Core 会再次校验。++插件与 Agent 不需要新的媒体协议,继续使用现有工具调用链:++1. Agent 用 \`ghost_call\` 调用插件的业务工具;+2. 插件通过普通 \`tool-result\` JSON 返回业务参数、面板里保存的模型选择或其它上下文;+3. 同一个 Agent 读取结果后,自行调用 Cindy Core \`media\` 工具;+4. 如果插件需要最终媒体,在普通接收工具的 \`attachmentArgs\` 声明承载媒体地址的+ 顶层参数;Agent 按该参数调用时,Host 机械提取地址并复用通用 attachments 授权链,+ 再把声明参数中的原地址改写为该插件自己的 \`cindy-ghost://<id>/media/<hash>.<ext>\`+ 地址后派发,避免把本地绝对路径暴露给插件。插件自行保存业务状态与更新 UI;显式+ \`ghost_call.attachments\` 仍保持兼容。++第 2 步的字段完全由插件定义,Host 不识别 \`mediaIntent\`、\`nextTool\` 等保留字段,也不+自动把插件结果转成媒体请求。下面只是普通结果示例,字段名不是平台契约:++\`\`\`js+const prefs = await (await fetch('/kv')).json();+await cindy.send({+ type: 'tool-result',+ callId: msg.callId,+ ok: true,+ result: {+ prompt: msg.args.prompt,+ selectedModel: prefs.imageModelId,+ sceneOptions: { aspectRatio: msg.args.aspectRatio }+ }+});+\`\`\`++媒体生成硬规则:插件沙箱和 panel 不直接提交生成请求,不持有 endpoint、凭证、+轮询或下载逻辑。当前 Agent 自己决定如何把插件的普通结果转换为 \`media\` 调用,并根据+Guide 组装请求;Core 负责鉴权、Guide、安全边界、任务状态与结果入库。插件可以提供+业务参数、参数规范化、模型偏好和可选 UI,但不负责执行底层请求。++插件获取结果不需要专用回调协议:++\`\`\`js+// manifest:声明哪个顶层参数承载媒体地址+// { name:'import_artwork', attachmentArgs:['mediaUrl'], parameters:{ ... } }+// Agent 侧:Core media 成功后按普通工具参数交给插件+ghost_call({+ ghost_id: 'cindy-art',+ tool: 'import_artwork',+ args: { mediaUrl: resultUrl, caption: prompt }+});++// 插件侧:msg.args.attachments 是已授权指纹;插件自行写 /kv 并广播面板+\`\`\`++Host 不理解“画廊”或其它插件业务,也不会因为一次 \`media\` 成功自动唤醒、回调任意插件。+## 4.1 宿主公开上下文(request,无需卡槽)电子脑需要按宿主构建身份或当前语言选择公开配置/界面文案时,走只读 request。当前只暴露diff --cc apps/desktop/src/main/cindy-brain/index.tsindex 482760185d,2c78f13f5b..2a32dbe7f0--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@@ -310,11 -304,14 +310,18 @@@ importremoveGhostSecrets,storeGhostSecret,} from '../secrets/providerSecretStore.js';-import { getActiveCatalog } from '../maker-host/active-catalog.js';+import { getActiveCatalog, getXdGatewayModels } from '../maker-host/active-catalog.js';- import { projectProviderCatalogForBuildRegion } from '../maker-host/provider-access-policy.js';- import { getGrokAccessToken, hasGrokOAuthLogin } from '../maker-host/grok-oauth-login.js';+ import {+ getGrokAccessToken,+ getGrokOAuthCredentialGeneration,+ hasGrokOAuthLogin,+ } from '../maker-host/grok-oauth-login.js';import { invalidateXaiBridgeAuth } from '../maker-host/xai-auth-invalidation-host.js';--import { isModelDisabled, isProviderDisabled } from '@cindy/model-providers';++import {++ isModelDisabled,++ isProviderDisabled,++ type MediaCapability,++} from '@cindy/model-providers';import { readModelDisableOverrides } from '../maker-host/model-disable-store.js';import { readProviderOrder } from '../maker-host/provider-order-store.js';import { outboundFetch } from '../maker-host/outbound-fetch.js';@@@ -365,10 -363,6 +373,11 @@@ import { MAKER_PUSH } from '../maker-ipimport { ghostSetupNavigationForAction } from './ghostSetupNavigation.js';import { assessGhostHostSetupRequirements } from './ghostHostSetupRequirements.js';import { isModelAccessReady } from '../model-access/readiness.js';+import {+ filterEnabledGatewayMediaModels,- listAvailableMediaModels,++ isMediaModelExecutable,++ listExecutableMediaModels,+} from '../model-access/mediaModels.js';// ⚠️ 下面三个依赖必须保持模块顶层静态 import,禁止改回函数内 await import():// 运行时 import() 会被 Rollup 编译成跨 chunk 的 require(尤其 drizzle-orm 会拆独立// chunk),而 bootstrap chunk 因 conf(electron-store 依赖)的模块副作用@@@ -3114,120 -3147,6 +3162,150 @@@ const getCatalogVideoConfig = (): Returconst getCatalogEmbedConfig = (): ReturnType<typeof getCatalogMediaConfig> =>getCatalogMediaConfig('embed');+/**+ * Art 等插件的媒体偏好只认 Gateway `/models` 快照,并叠加客户端现有停用准入。+ * 不合并 providers.json 的 OpenAI/Gemini/自定义来源;第三方媒体模型后续单独接入。+ */+function getGatewayMediaPreferenceConfig(kind: 'image' | 'video'): CindyMediaCatalogConfig {+ const capability = kind === 'image' ? 'image.generate' : 'video.generate';+ const models = filterEnabledGatewayMediaModels(+ getXdGatewayModels(),+ capability,+ readModelDisableOverrides(),- ).map((model) => ({- id: model.id,- label: model.name ?? model.id,- providerId: 'xd',- // Host 不从 modalities 推导插件业务动作;Art 等插件读取 /media-models 后自行判断。- supportsEdit: true,- }));++ )++ .filter((model) => isMediaModelExecutable(model.id, capability))++ .map((model) => ({++ id: model.id,++ label: model.name ?? model.id,++ providerId: 'xd',++ supportsEdit: isMediaModelExecutable(++ model.id,++ kind === 'image' ? 'image.edit' : 'video.image_to_video',++ ),++ }));+ const standard = models[0]?.id;+ return {+ models,+ defaults: standard ? { standard, draft: standard, best: standard } : null,+ };+}++/**+ * 插件配置页的模型目录;这里只读目录,不提供任何生成入口。Host 只按 Gateway mode+ * 切图片/视频大类并透传 modalities,具体动作支持度由插件自行解释。+ */+async function getGhostConfigurableMediaModels(+ ghostId: string,+ type: GhostMediaModelType,+): Promise<GhostMediaModelsResult> {+ const ghost = findAvailableGhost(ghostId);+ if (!ghost || !ghost.enabled) {+ return { ok: false, errorCode: 'NOT_AVAILABLE', message: '插件当前不可用' };+ }+ const declared = ghost.manifest.cindy?.[type] ?? [];+ if (!ghost.manifest.slots?.includes('cindy') || declared.length === 0) {+ return {+ ok: false,+ errorCode: 'PERMISSION_DENIED',+ message: `插件未声明 Cindy ${type} 能力`,+ };+ }+ try {- const models = await listAvailableMediaModels(- type === 'image' ? 'image.generate' : 'video.generate',++ const requiredCapabilities: MediaCapability[] = declared.map((action) =>++ type === 'image'++ ? action === 'generate'++ ? 'image.generate'++ : 'image.edit'++ : action === 'generate'++ ? 'video.generate'++ : 'video.image_to_video',+ );++ const availability = await listExecutableMediaModels(requiredCapabilities);++ const mode = type === 'image' ? 'image_generation' : 'video_generation';++ const models = availability.models.filter((model) => model.mode === mode);++ if (++ models.length === 0 &&++ availability.unavailable.some((model) => model.retryable)++ ) {++ return {++ ok: false,++ errorCode: 'NOT_AVAILABLE',++ message: '媒体调用说明暂时无法读取,请稍后重试',++ };++ }++ if (availability.unavailable.length > 0) {++ log.warn('plugin media catalog skipped unavailable models', {++ ghostId,++ type,++ unavailableModelCount: availability.unavailable.length,++ });++ }+ return {+ ok: true,+ type,+ models: models.map((model) => ({+ id: model.id,+ name: model.name ?? model.id,+ ...(model.modalities+ ? {+ modalities: {+ input: [...model.modalities.input],+ output: [...model.modalities.output],+ },+ }+ : {}),+ })),+ defaultModelId: models[0]?.id ?? null,+ };+ } catch (error) {+ log.warn('read plugin media model catalog failed', {+ ghostId,+ type,+ error: error instanceof Error ? error.message : String(error),+ });+ return { ok: false, errorCode: 'NOT_AVAILABLE', message: '媒体模型目录暂不可用' };+ }+}++/**+ * 读取插件在 Host「Cindy 能力」中的现有媒体选型。+ * 这里只投影当前有效值,不复制或迁移配置;override 失效时与设置 UI 一样回落目录默认。+ */+function getGhostConfiguredMediaModel(+ ghostId: string,+ capability: unknown,+): GhostCindyPreferenceResult {+ if (+ typeof capability !== 'string' ||+ !(GHOST_MEDIA_CAPABILITIES as readonly string[]).includes(capability)+ ) {+ return { ok: false, errorCode: 'INVALID_REQUEST', message: '未知的 Cindy 媒体能力' };+ }+ const mediaCapability = capability as GhostMediaCapability;+ const [type, action] = mediaCapability.split('.') as ['image' | 'video', 'generate' | 'edit'];+ const ghost = findAvailableGhost(ghostId);+ if (!ghost || !ghost.enabled) {+ return { ok: false, errorCode: 'NOT_AVAILABLE', message: '插件当前不可用' };+ }+ const declared = ghost.manifest.cindy?.[type] ?? [];+ if (!ghost.manifest.slots?.includes('cindy') || !declared.includes(action)) {+ return {+ ok: false,+ errorCode: 'PERMISSION_DENIED',+ message: `插件未声明 Cindy ${mediaCapability} 能力`,+ };+ }++ const config = getGatewayMediaPreferenceConfig(type);+ const available = new Set(config.models.map((model) => model.id));+ const override = readGhostCindyOverrides(ghostId)[mediaCapability];+ const modelId = override && available.has(override) ? override : config.defaults?.standard;+ if (!modelId) {+ return { ok: false, errorCode: 'NOT_AVAILABLE', message: '当前没有可用的媒体模型' };+ }+ return { ok: true, capability: mediaCapability, modelId };+}+/*** 派发前重查(PR #744 review 第二十轮):cindySlot 从白名单校验到实际下单之间隔着* 归属查账、参考图准备等长 await,期间该媒体模型 / 供应商可能被用户停用 —— 在diff --cc apps/desktop/src/main/cindy-brain/runtime/electronSandboxAdapter.tsindex 26193bfc3c,32b3591770..d7c1c4cefa--- a/apps/desktop/src/main/cindy-brain/runtime/electronSandboxAdapter.ts+++ b/apps/desktop/src/main/cindy-brain/runtime/electronSandboxAdapter.ts@@@ -301,30 -285,6 +301,30 @@@ function registerGhostProtocol(partitio},});}- // /media-models?type=image|video:插件自己的设置页 / 面板读取可配置模型及- // Gateway modalities。Host 不解释具体业务动作;端点仍不发起生成,也不返回- // 凭证、endpoint 或 Guide。++ // /media-models?type=image|video:插件自己的设置页 / 面板读取当前客户端可执行++ // 模型及 Gateway modalities。兼容判定由 Host provider 完成;端点仍不发起生成,++ // 也不返回凭证、endpoint、Guide 或内部判定细节。+ if (url.pathname === '/media-models') {+ if (request.method !== 'GET') return new Response(null, { status: 405 });+ const keys = [...url.searchParams.keys()];+ const types = url.searchParams.getAll('type');+ if (keys.length !== 1 || keys[0] !== 'type' || types.length !== 1) {+ return new Response(null, { status: 400 });+ }+ const type = types[0];+ if (type !== 'image' && type !== 'video') {+ return new Response(null, { status: 400 });+ }+ if (!ghostMediaModelsProvider) return new Response(null, { status: 503 });+ const result = await ghostMediaModelsProvider(ghostId, type);+ return new Response(JSON.stringify(result), {+ status: result.ok ? 200 : result.errorCode === 'PERMISSION_DENIED' ? 403 : 503,+ headers: {+ 'Content-Type': 'application/json; charset=utf-8',+ 'Cache-Control': 'no-store',+ },+ });+ }// /kv:意识自定义参数存取(FORGE_GUIDE §4.8)。设置页/面板/电子脑// 同源共用;分区专属通道天然只碰自己的账。分派与校验在纯函数层// (ghostKvEndpoint,已单测),这里只做 Response 包装。diff --cc apps/desktop/src/main/cindy-media/__tests__/invocationService.test.tsindex 1397fe6fb9,0000000000..1d9e22357dmode 100644,000000..100644--- a/apps/desktop/src/main/cindy-media/__tests__/invocationService.test.ts+++ b/apps/desktop/src/main/cindy-media/__tests__/invocationService.test.ts@@@ -1,550 -1,0 +1,878 @@@+import { beforeEach, describe, expect, it, vi } from 'vitest';+++interface MockPreparedGuide extends Record<string, unknown> {++ modelId: string;++ capability: string;++ revision: string;++}++++interface MockTransitionInput {++ id: string;++ owner: string;++ from: string;++ to: string;++ taskId?: string;++ responseJson?: string;++}+++const mocks = vi.hoisted(() => ({+ currentUserId: 'media-user-0',+ ownerGeneration: 1,+ models: vi.fn(),++ executableModels: vi.fn(),+ guide: vi.fn(),+ outboundFetch: vi.fn(),+ ingestMedia: vi.fn(),- recover: vi.fn(async (_owner: string) => 0),++ readBlob: vi.fn(),++ db: {++ owner: 'media-user-0',++ drizzle: { owner: 'media-user-0' },++ },++ dbOwnerId: 'media-user-0',++ transitionDbs: [] as unknown[],++ recover: vi.fn<(owner: string, db: unknown) => Promise<number>>(async () => 0),+ prune: vi.fn(async () => undefined),+ rows: new Map<string, Record<string, unknown>>(),+}));++vi.mock('../../authManager.js', () => ({+ getCurrentUserId: () => mocks.currentUserId,+ getActiveAuthRealm: () => 'cn',+ getAuthState: () => ({+ user: mocks.currentUserId ? { id: mocks.currentUserId } : null,++ dataOwnerId: mocks.currentUserId,+ ownerGeneration: mocks.ownerGeneration,+ }),+}));+vi.mock('../../appCapabilities.js', () => ({+ getAppCapabilities: () => ({ canUseCindyGateway: true }),+}));+vi.mock('../../model-access/effectiveEndpoint.js', () => ({+ effectiveXdGatewayBaseUrl: () => 'https://gateway.example.com',+}));+vi.mock('../../secrets/providerSecretStore.js', () => ({+ getProviderSecretStore: () => ({ get: () => 'test-api-key' }),+}));++vi.mock('../../localDb/client/current.js', () => ({++ getDbClient: () => mocks.db,++ getCurrentDbClientUserId: () => mocks.dbOwnerId,++}));+vi.mock('../../maker-host/outbound-fetch.js', () => ({+ outboundFetch: mocks.outboundFetch,+}));+vi.mock('../../model-access/mediaModels.js', () => ({+ listAvailableMediaModels: mocks.models,++ listExecutableMediaModels: mocks.executableModels,+ fetchMediaInvocationGuide: mocks.guide,++ MediaGuideCompatibilityError: class MediaGuideCompatibilityError extends Error {++ constructor(++ readonly code: string,++ message: string,++ readonly detail?: string,++ ) {++ super(message);++ }++ },++ MediaModelCatalogError: class MediaModelCatalogError extends Error {++ constructor(++ message: string,++ readonly detail?: string,++ ) {++ super(message);++ }++ },+}));+vi.mock('../ingest.js', () => ({ ingestMedia: mocks.ingestMedia }));+vi.mock('../blobStore.js', () => ({- readFile: vi.fn(),++ readFile: mocks.readBlob,+ supportedMime: (mime: string) =>+ ['image/png', 'video/mp4', 'audio/mpeg'].includes(mime),+}));+vi.mock('../../imageCacheStore.js', () => ({ resolveSafe: vi.fn() }));+vi.mock('../../logger.js', () => ({+ createLogger: () => ({ warn: vi.fn(), info: vi.fn(), debug: vi.fn(), error: vi.fn() }),+}));+vi.mock('../../serverApiClient.js', () => ({+ ServerApiError: class ServerApiError extends Error {+ constructor(readonly code: string) {+ super(code);+ }+ },+}));+vi.mock('../mediaInvocationStore.js', () => ({+ recoverInterruptedMediaInvocations: mocks.recover,+ pruneMediaInvocations: mocks.prune,+ countMediaInvocations: async () => mocks.rows.size,- createMediaInvocation: async ({ id, owner, guide, createdAt }: any) => {++ createMediaInvocation: async ({++ id,++ owner,++ guide,++ createdAt,++ }: {++ id: string;++ owner: string;++ guide: MockPreparedGuide;++ createdAt: number;++ }) => {+ mocks.rows.set(id, {+ id,+ owner,+ modelId: guide.modelId,+ capability: guide.capability,+ guideRevision: guide.revision,+ guide,+ state: 'prepared',+ createdAt,+ updatedAt: createdAt,+ });+ },+ getMediaInvocation: async (id: string, owner: string) => {+ const row = mocks.rows.get(id);+ return row?.owner === owner ? row : null;+ },- transitionMediaInvocation: async ({ id, owner, from, to, taskId }: any) => {++ transitionMediaInvocation: async (++ { id, owner, from, to, taskId, responseJson }: MockTransitionInput,++ db: unknown,++ ) => {++ mocks.transitionDbs.push(db);+ const row = mocks.rows.get(id);+ if (!row || row.owner !== owner || row.state !== from) return false;+ row.state = to;+ row.updatedAt = Date.now();+ if (taskId) row.taskId = taskId;++ if (responseJson) row.responseJson = responseJson;+ return true;+ },+}));++import { callCindyMedia } from '../invocationService.js';++const PNG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 1]);+const MP4 = Buffer.from([+ 0x00, 0x00, 0x00, 0x10,+ 0x66, 0x74, 0x79, 0x70,+ 0x69, 0x73, 0x6f, 0x6d,+ 0x00, 0x00, 0x00, 0x00,+]);++function operation(response: Record<string, unknown>, path = '/images/generations') {+ return {+ capability: 'image.generate',+ request: {+ method: 'POST',+ path,++ bodyEncoding: 'json',+ bodyModelPath: ['model'],+ timeoutMs: 5_000,+ maxRequestBytes: 1_048_576,+ maxResponseBytes: 1_048_576,+ },+ response,+ instructions: '按协议组装请求',+ exampleBody: { prompt: 'hello' },+ inputSchema: { type: 'object' },+ officialDocs: 'https://docs.example.com/images',+ };+}++function resolvedGuide(op: Record<string, unknown>) {+ return {+ modelId: 'image-model',- wireModelId: 'wire-image-model',+ guide: {+ schemaVersion: 1,+ guideId: 'images-v1',+ revision: '2026-08-13.1',+ connection: { providerId: 'xd' },+ operations: [op],+ },+ };+}++async function prepare(): Promise<string> {+ const result = await callCindyMedia({+ action: 'prepare',+ modelId: 'image-model',+ capability: 'image.generate',+ });+ expect(result).toMatchObject({ ok: true, status: 'prepared', model_id: 'image-model' });+ return result.invocation_id as string;+}++describe('Cindy Core media invocation state and security boundary', () => {+ beforeEach(() => {+ mocks.currentUserId = `media-user-${crypto.randomUUID()}`;+ mocks.ownerGeneration += 1;++ mocks.dbOwnerId = mocks.currentUserId;++ mocks.db = {++ owner: mocks.currentUserId,++ drizzle: { owner: mocks.currentUserId },++ };++ mocks.transitionDbs.length = 0;+ mocks.rows.clear();+ mocks.models.mockReset().mockResolvedValue([+ { id: 'image-model', name: 'Image Model', mode: 'image_generation' },+ ]);++ mocks.executableModels.mockReset().mockResolvedValue({++ models: [{ id: 'image-model', name: 'Image Model', mode: 'image_generation' }],++ unavailable: [],++ candidateCount: 1,++ });+ mocks.guide.mockReset();+ mocks.outboundFetch.mockReset();+ mocks.ingestMedia.mockReset().mockResolvedValue({+ url: `cindy-media://blobs/${'a'.repeat(64)}.png`,+ });++ mocks.readBlob.mockReset();+ mocks.recover.mockClear();+ mocks.prune.mockClear();+ });++ it('按 modelId 取 Guide、覆盖 body.model,并以一次性 invocation 完成同步结果入仓', async () => {+ mocks.guide.mockResolvedValue(+ resolvedGuide(+ operation({+ mode: 'sync',+ media: [{ path: ['data'], encoding: 'base64', kind: 'image' }],+ }),+ ),+ );+ mocks.outboundFetch.mockResolvedValue(+ new Response(JSON.stringify({ data: PNG.toString('base64') }), {+ status: 200,+ headers: { 'content-type': 'application/json' },+ }),+ );++ const invocationId = await prepare();+ const result = await callCindyMedia({+ action: 'request',+ invocationId,+ body: { prompt: 'cat', model: 'agent-must-not-control-this' },+ });++ expect(result).toMatchObject({ ok: true, status: 'complete' });+ const [, init] = mocks.outboundFetch.mock.calls[0];+ expect(mocks.outboundFetch.mock.calls[0][0]).toBe(+ 'https://gateway.example.com/images/generations',+ );- expect(JSON.parse(init.body)).toEqual({ prompt: 'cat', model: 'wire-image-model' });++ expect(JSON.parse(init.body)).toEqual({ prompt: 'cat', model: 'image-model' });+ expect(init.headers.Authorization).toBe('Bearer test-api-key');+ await expect(+ callCindyMedia({ action: 'request', invocationId, body: { prompt: 'again' } }),+ ).resolves.toMatchObject({ ok: false, errorCode: 'INVOCATION_ALREADY_USED' });+ expect(mocks.outboundFetch).toHaveBeenCalledTimes(1);+ });+- it('模型可见但 Guide 缺少目标 operation 时只在 prepare 明确拒绝', async () => {++ it('按 Guide 把受管图片机械组装为 multipart 文件请求', async () => {++ const op = operation(++ {++ mode: 'sync',++ media: [{ path: ['data'], encoding: 'base64', kind: 'image' }],++ },++ '/v1/images/edits',++ );++ const multipartOp = {++ ...op,++ capability: 'image.generate',++ request: {++ ...op.request,++ bodyEncoding: 'multipart',++ multipartFiles: [++ { bodyField: 'image', formField: 'image[]', kind: 'image', maxItems: 16 },++ ],++ },++ };++ mocks.guide.mockResolvedValue(resolvedGuide(multipartOp));++ mocks.readBlob.mockResolvedValue({ buffer: PNG, mimeType: 'image/png' });++ mocks.outboundFetch.mockResolvedValue(++ new Response(JSON.stringify({ data: PNG.toString('base64') }), { status: 200 }),++ );++++ await expect(++ callCindyMedia({++ action: 'request',++ invocationId: await prepare(),++ body: {++ prompt: 'add snow',++ image: `cindy-media://blobs/${'b'.repeat(64)}.png`,++ },++ }),++ ).resolves.toMatchObject({ ok: true, status: 'complete' });++++ const [, init] = mocks.outboundFetch.mock.calls[0];++ expect(init.headers).not.toHaveProperty('Content-Type');++ expect(init.body).toBeInstanceOf(FormData);++ const form = init.body as FormData;++ expect(form.get('model')).toBe('image-model');++ expect(form.get('prompt')).toBe('add snow');++ expect(form.get('image[]')).toBeInstanceOf(Blob);++ });++++ it('同步生成成功后下载暂时失败时复用已保存响应,不会再次付费 POST', async () => {++ mocks.guide.mockResolvedValue(++ resolvedGuide(++ operation({++ mode: 'sync',++ media: [++ {++ path: ['data'],++ encoding: 'url',++ kind: 'image',++ allowedUrlHosts: ['cdn.example.com'],++ },++ ],++ }),++ ),++ );++ mocks.outboundFetch++ .mockResolvedValueOnce(++ new Response(JSON.stringify({ data: 'https://cdn.example.com/generated.png' }), {++ status: 200,++ }),++ )++ .mockRejectedValueOnce(new TypeError('temporary network failure'))++ .mockResolvedValueOnce(++ new Response(PNG, { status: 200, headers: { 'content-type': 'image/png' } }),++ );++++ const invocationId = await prepare();++ await expect(++ callCindyMedia({ action: 'request', invocationId, body: { prompt: 'cat' } }),++ ).resolves.toMatchObject({++ ok: false,++ errorCode: 'MEDIA_DOWNLOAD_FAILED',++ retryable: true,++ retry_action: 'request',++ });++ expect(mocks.rows.get(invocationId)).toMatchObject({++ state: 'pending',++ responseJson: JSON.stringify({ data: 'https://cdn.example.com/generated.png' }),++ });++++ await expect(++ callCindyMedia({ action: 'request', invocationId, body: { prompt: 'ignored-on-retry' } }),++ ).resolves.toMatchObject({ ok: true, status: 'complete' });++ expect(mocks.outboundFetch).toHaveBeenCalledTimes(3);++ expect(mocks.outboundFetch.mock.calls[0][0]).toBe(++ 'https://gateway.example.com/images/generations',++ );++ expect(mocks.outboundFetch.mock.calls[1][0]).toBe('https://cdn.example.com/generated.png');++ expect(mocks.outboundFetch.mock.calls[2][0]).toBe('https://cdn.example.com/generated.png');++ });++++ it('结果下载期间账号切换时不向新账号入库,并允许原账号恢复结果', async () => {++ mocks.guide.mockResolvedValue(++ resolvedGuide(++ operation({++ mode: 'sync',++ media: [++ {++ path: ['data'],++ encoding: 'url',++ kind: 'image',++ allowedUrlHosts: ['cdn.example.com'],++ },++ ],++ }),++ ),++ );++ const originalUserId = mocks.currentUserId;++ const originalDb = mocks.db;++ mocks.outboundFetch++ .mockResolvedValueOnce(++ new Response(JSON.stringify({ data: 'https://cdn.example.com/generated.png' }), {++ status: 200,++ }),++ )++ .mockImplementationOnce(async () => {++ mocks.currentUserId = `other-user-${crypto.randomUUID()}`;++ mocks.ownerGeneration += 1;++ mocks.dbOwnerId = mocks.currentUserId;++ mocks.db = {++ owner: mocks.currentUserId,++ drizzle: { owner: mocks.currentUserId },++ };++ return new Response(PNG, { status: 200, headers: { 'content-type': 'image/png' } });++ })++ .mockResolvedValueOnce(++ new Response(PNG, { status: 200, headers: { 'content-type': 'image/png' } }),++ );++++ const invocationId = await prepare();++ await expect(++ callCindyMedia({ action: 'request', invocationId, body: { prompt: 'cat' } }),++ ).resolves.toMatchObject({ ok: false, errorCode: 'ACCOUNT_CHANGED' });++ expect(mocks.ingestMedia).not.toHaveBeenCalled();++ expect(mocks.rows.get(invocationId)?.state).toBe('pending');++++ mocks.currentUserId = originalUserId;++ mocks.ownerGeneration += 1;++ mocks.dbOwnerId = originalUserId;++ mocks.db = originalDb;++ await expect(++ callCindyMedia({ action: 'request', invocationId, body: { prompt: 'ignored-on-retry' } }),++ ).resolves.toMatchObject({ ok: true, status: 'complete' });++ expect(mocks.ingestMedia).toHaveBeenCalledTimes(1);++ expect(mocks.outboundFetch).toHaveBeenCalledTimes(3);++ expect(mocks.transitionDbs.every((db) => db === originalDb)).toBe(true);++ });++++ it('结果入库期间账号切换时沿用原账号 DB,并在写入闸处停止', async () => {++ mocks.guide.mockResolvedValue(++ resolvedGuide(++ operation({++ mode: 'sync',++ media: [{ path: ['data'], encoding: 'base64', kind: 'image' }],++ }),++ ),++ );++ mocks.outboundFetch.mockResolvedValue(++ new Response(JSON.stringify({ data: PNG.toString('base64') }), { status: 200 }),++ );++ const originalDb = mocks.db;++ mocks.ingestMedia.mockImplementationOnce(async (++ params: { assertStillValid(): void },++ db: unknown,++ ) => {++ expect(db).toBe(originalDb.drizzle);++ mocks.currentUserId = `other-user-${crypto.randomUUID()}`;++ mocks.ownerGeneration += 1;++ mocks.dbOwnerId = mocks.currentUserId;++ mocks.db = {++ owner: mocks.currentUserId,++ drizzle: { owner: mocks.currentUserId },++ };++ params.assertStillValid();++ throw new Error('unreachable');++ });++++ const invocationId = await prepare();++ await expect(++ callCindyMedia({ action: 'request', invocationId, body: { prompt: 'cat' } }),++ ).resolves.toMatchObject({ ok: false, errorCode: 'ACCOUNT_CHANGED' });++ expect(mocks.rows.get(invocationId)?.state).toBe('pending');++ expect(mocks.transitionDbs.every((db) => db === originalDb)).toBe(true);++ });++++ it('Guide 缺少目标 operation 时在 prepare 返回稳定的能力不支持错误', async () => {+ mocks.guide.mockResolvedValue(+ resolvedGuide({+ ...operation({+ mode: 'sync',+ media: [{ path: ['data'], encoding: 'base64', kind: 'image' }],+ }),+ capability: 'image.edit',+ }),+ );++ await expect(+ callCindyMedia({+ action: 'prepare',+ modelId: 'image-model',+ capability: 'image.generate',+ }),- ).resolves.toMatchObject({ ok: false, errorCode: 'GUIDE_NOT_AVAILABLE' });++ ).resolves.toMatchObject({ ok: false, errorCode: 'CAPABILITY_NOT_SUPPORTED' });+ expect(mocks.rows.size).toBe(0);+ });++ it('付费提交网络结果未知后禁止再次 POST', async () => {+ mocks.guide.mockResolvedValue(+ resolvedGuide(+ operation({+ mode: 'sync',+ media: [{ path: ['data'], encoding: 'base64', kind: 'image' }],+ }),+ ),+ );+ mocks.outboundFetch.mockRejectedValue(new TypeError('network unavailable'));++ const invocationId = await prepare();+ await expect(+ callCindyMedia({ action: 'request', invocationId, body: { prompt: 'cat' } }),+ ).resolves.toMatchObject({ ok: false, errorCode: 'SUBMISSION_OUTCOME_UNKNOWN' });+ await expect(+ callCindyMedia({ action: 'request', invocationId, body: { prompt: 'cat' } }),+ ).resolves.toMatchObject({ ok: false, errorCode: 'INVOCATION_ALREADY_USED' });+ expect(mocks.rows.get(invocationId)?.state).toBe('unknown');+ expect(mocks.outboundFetch).toHaveBeenCalledTimes(1);+ });++ it('付费提交准备参数期间账号切换时不发出上游请求', async () => {+ mocks.guide.mockResolvedValue(+ resolvedGuide(+ operation({+ mode: 'sync',+ media: [{ path: ['data'], encoding: 'base64', kind: 'image' }],+ }),+ ),+ );+ const invocationId = await prepare();+ mocks.models.mockImplementationOnce(async () => {+ mocks.currentUserId = `other-user-${crypto.randomUUID()}`;+ mocks.ownerGeneration += 1;++ mocks.dbOwnerId = mocks.currentUserId;++ mocks.db = {++ owner: mocks.currentUserId,++ drizzle: { owner: mocks.currentUserId },++ };+ return [{ id: 'image-model', name: 'Image Model', mode: 'image_generation' }];+ });++ await expect(+ callCindyMedia({ action: 'request', invocationId, body: { prompt: 'cat' } }),+ ).resolves.toMatchObject({ ok: false, errorCode: 'ACCOUNT_CHANGED' });+ expect(mocks.outboundFetch).not.toHaveBeenCalled();+ expect(mocks.rows.get(invocationId)?.state).toBe('prepared');+ });++ it('进程中断遗留的 submitting 在恢复时转为 unknown,不会补发 POST', async () => {+ const op = operation({+ mode: 'sync',+ media: [{ path: ['data'], encoding: 'base64', kind: 'image' }],+ });+ const resolved = resolvedGuide(op);+ const invocationId = crypto.randomUUID();+ const now = Date.now();+ mocks.rows.set(invocationId, {+ id: invocationId,+ owner: `cn:${mocks.currentUserId}`,+ modelId: resolved.modelId,+ capability: op.capability,+ guideRevision: resolved.guide.revision,+ guide: {+ modelId: resolved.modelId,- wireModelId: resolved.wireModelId,+ schemaVersion: resolved.guide.schemaVersion,+ guideId: resolved.guide.guideId,+ revision: resolved.guide.revision,+ connection: resolved.guide.connection,+ ...op,+ },+ state: 'submitting',+ createdAt: now,+ updatedAt: now,+ });+ mocks.recover.mockImplementationOnce(async (owner: string) => {+ let recovered = 0;+ for (const row of mocks.rows.values()) {+ if (row.owner === owner && row.state === 'submitting') {+ row.state = 'unknown';+ recovered += 1;+ }+ }+ return recovered;+ });++ await expect(+ callCindyMedia({ action: 'request', invocationId, body: { prompt: 'cat' } }),+ ).resolves.toMatchObject({ ok: false, errorCode: 'INVOCATION_ALREADY_USED' });- expect(mocks.recover).toHaveBeenCalledWith(`cn:${mocks.currentUserId}`);++ expect(mocks.recover).toHaveBeenCalledWith(`cn:${mocks.currentUserId}`, mocks.db);+ expect(mocks.outboundFetch).not.toHaveBeenCalled();+ });++ it('不接受 Guide/Content-Type 冒充的图片字节', async () => {+ mocks.guide.mockResolvedValue(+ resolvedGuide(+ operation({+ mode: 'sync',+ media: [{ path: ['data'], encoding: 'base64', kind: 'image', mediaType: 'image/png' }],+ }),+ ),+ );+ mocks.outboundFetch.mockResolvedValue(+ new Response(JSON.stringify({ data: Buffer.from('not-an-image').toString('base64') }), {+ status: 200,+ }),+ );++ const result = await callCindyMedia({+ action: 'request',+ invocationId: await prepare(),+ body: { prompt: 'cat' },+ });+ expect(result).toMatchObject({ ok: false, errorCode: 'MEDIA_RESULT_INVALID' });+ expect(mocks.ingestMedia).not.toHaveBeenCalled();+ });++ it('响应超过 Guide 上限时拒绝入仓', async () => {+ mocks.guide.mockResolvedValue(+ resolvedGuide(+ operation({+ mode: 'sync',+ media: [{ path: ['data'], encoding: 'base64', kind: 'image' }],+ }),+ ),+ );+ mocks.outboundFetch.mockResolvedValue(+ new Response('{}', {+ status: 200,+ headers: { 'content-length': String(1_048_577) },+ }),+ );++ await expect(+ callCindyMedia({+ action: 'request',+ invocationId: await prepare(),+ body: { prompt: 'cat' },+ }),+ ).resolves.toMatchObject({ ok: false, errorCode: 'RESPONSE_TOO_LARGE' });+ expect(mocks.ingestMedia).not.toHaveBeenCalled();+ });++ it('上游错误文本进入 Agent 前脱敏 URL、凭据和长值', async () => {+ mocks.guide.mockResolvedValue(+ resolvedGuide(+ operation({+ mode: 'sync',+ media: [{ path: ['data'], encoding: 'base64', kind: 'image' }],+ }),+ ),+ );+ const opaque = 'A'.repeat(120);+ mocks.outboundFetch.mockResolvedValue(+ new Response(+ JSON.stringify({+ message: `bad https://cdn.example.com/x?signature=secret Bearer token-1234567890123456 ${opaque}`,+ }),+ { status: 400 },+ ),+ );++ const result = await callCindyMedia({+ action: 'request',+ invocationId: await prepare(),+ body: { prompt: 'cat' },+ });+ expect(result).toMatchObject({ ok: false, errorCode: 'UPSTREAM_REJECTED' });+ expect(result.message).not.toContain('signature=secret');+ expect(result.message).not.toContain('token-1234567890123456');+ expect(result.message).not.toContain(opaque);+ });++ it('拒绝非可信媒体域名,可信下载不携带网关凭据且禁止重定向', async () => {+ const urlOperation = operation({+ mode: 'sync',+ media: [{+ path: ['data'],+ encoding: 'url',+ kind: 'image',+ allowedUrlHosts: ['cdn.example.com'],+ }],+ });+ mocks.guide.mockResolvedValue(resolvedGuide(urlOperation));+ mocks.outboundFetch.mockResolvedValueOnce(+ new Response(JSON.stringify({ data: 'https://127.0.0.1/private.png' }), { status: 200 }),+ );++ await expect(+ callCindyMedia({+ action: 'request',+ invocationId: await prepare(),+ body: { prompt: 'cat' },+ }),+ ).resolves.toMatchObject({ ok: false, errorCode: 'MEDIA_RESULT_INVALID' });+ expect(mocks.outboundFetch).toHaveBeenCalledTimes(1);++ mocks.outboundFetch.mockReset()+ .mockResolvedValueOnce(+ new Response(+ JSON.stringify({ data: 'https://cdn.example.com/generated.png?signature=opaque' }),+ { status: 200 },+ ),+ )+ .mockResolvedValueOnce(+ new Response(PNG, { status: 200, headers: { 'content-type': 'image/png' } }),+ );+ await expect(+ callCindyMedia({+ action: 'request',+ invocationId: await prepare(),+ body: { prompt: 'cat' },+ }),+ ).resolves.toMatchObject({ ok: true, status: 'complete' });+ const [, downloadInit] = mocks.outboundFetch.mock.calls[1];+ expect(downloadInit.redirect).toBe('error');+ expect(downloadInit.headers).toBeUndefined();+ });++ it('即使持久快照异常包含反斜杠路径,也在发网前拒绝跨 Gateway origin', async () => {+ mocks.guide.mockResolvedValue(+ resolvedGuide(+ operation(+ { mode: 'sync', media: [{ path: ['data'], encoding: 'base64', kind: 'image' }] },+ '/\\evil.example.com/steal',+ ),+ ),+ );+ const result = await callCindyMedia({+ action: 'request',+ invocationId: await prepare(),+ body: { prompt: 'cat' },+ });+ expect(result).toMatchObject({ ok: false, errorCode: 'GUIDE_INVALID' });+ expect(mocks.outboundFetch).not.toHaveBeenCalled();+ });++ it('异步提交持久化 task id,poll 可跨调用恢复并下载视频', async () => {+ const asyncOperation = {+ ...operation({+ mode: 'async',+ taskIdPath: ['task_id'],+ poll: {+ method: 'GET',+ path: '/video/tasks/{taskId}',+ statusPath: ['status'],+ successValues: ['succeeded'],+ failureValues: ['failed'],+ recommendedIntervalMs: 10,+ timeoutMs: 5_000,+ maxResponseBytes: 1_048_576,+ media: [{ path: ['video'], encoding: 'base64', kind: 'video' }],+ },+ }, '/video/tasks'),+ capability: 'video.generate',+ };+ mocks.models.mockResolvedValue([+ { id: 'image-model', name: 'Video Model', mode: 'video_generation' },+ ]);+ mocks.guide.mockResolvedValue(resolvedGuide(asyncOperation));+ mocks.outboundFetch+ .mockResolvedValueOnce(new Response(JSON.stringify({ task_id: 'task-1' }), { status: 200 }))+ .mockResolvedValueOnce(+ new Response(+ JSON.stringify({ status: 'succeeded', video: MP4.toString('base64') }),+ { status: 200 },+ ),+ );+ mocks.ingestMedia.mockResolvedValue({+ url: `cindy-media://blobs/${'b'.repeat(64)}.mp4`,+ });++ const prepared = await callCindyMedia({+ action: 'prepare',+ modelId: 'image-model',+ capability: 'video.generate',+ });+ const invocationId = prepared.invocation_id as string;+ await expect(+ callCindyMedia({ action: 'request', invocationId, body: { content: [] } }),+ ).resolves.toMatchObject({ ok: true, status: 'pending' });+ await expect(callCindyMedia({ action: 'poll', invocationId })).resolves.toMatchObject({+ ok: true,+ status: 'complete',+ xdt_video_urls: [`cindy-media://blobs/${'b'.repeat(64)}.mp4`],+ });+ expect(mocks.outboundFetch.mock.calls[1][0]).toBe(+ 'https://gateway.example.com/video/tasks/task-1',+ );+ });++ it('异步任务成功但媒体结果确定无效时终止 invocation,不诱导重复 poll', async () => {+ const asyncOperation = {+ ...operation({+ mode: 'async',+ taskIdPath: ['task_id'],+ poll: {+ method: 'GET',+ path: '/video/tasks/{taskId}',+ statusPath: ['status'],+ successValues: ['succeeded'],+ failureValues: ['failed'],+ recommendedIntervalMs: 10,+ timeoutMs: 5_000,+ maxResponseBytes: 1_048_576,+ media: [{ path: ['video'], encoding: 'base64', kind: 'video' }],+ },+ }, '/video/tasks'),+ capability: 'video.generate',+ };+ mocks.models.mockResolvedValue([+ { id: 'image-model', name: 'Video Model', mode: 'video_generation' },+ ]);+ mocks.guide.mockResolvedValue(resolvedGuide(asyncOperation));+ mocks.outboundFetch+ .mockResolvedValueOnce(new Response(JSON.stringify({ task_id: 'task-2' }), { status: 200 }))+ .mockResolvedValueOnce(+ new Response(JSON.stringify({ status: 'succeeded' }), { status: 200 }),+ );++ const prepared = await callCindyMedia({+ action: 'prepare',+ modelId: 'image-model',+ capability: 'video.generate',+ });+ const invocationId = prepared.invocation_id as string;+ await callCindyMedia({ action: 'request', invocationId, body: { content: [] } });++ await expect(callCindyMedia({ action: 'poll', invocationId })).resolves.toMatchObject({+ ok: false,+ errorCode: 'MEDIA_RESULT_MISSING',+ retryable: false,+ });+ expect(mocks.rows.get(invocationId)?.state).toBe('failed');+ await expect(callCindyMedia({ action: 'poll', invocationId })).resolves.toMatchObject({+ ok: false,+ errorCode: 'INVOCATION_NOT_PENDING',+ });+ });++++ it('异步任务成功后的永久下载拒绝会终止 invocation', async () => {++ const asyncOperation = {++ ...operation(++ {++ mode: 'async',++ taskIdPath: ['task_id'],++ poll: {++ method: 'GET',++ path: '/video/tasks/{taskId}',++ statusPath: ['status'],++ successValues: ['succeeded'],++ failureValues: ['failed'],++ recommendedIntervalMs: 10,++ timeoutMs: 5_000,++ maxResponseBytes: 1_048_576,++ media: [++ {++ path: ['video'],++ encoding: 'url',++ kind: 'video',++ allowedUrlHosts: ['cdn.example.com'],++ },++ ],++ },++ },++ '/video/tasks',++ ),++ capability: 'video.generate',++ };++ mocks.models.mockResolvedValue([++ { id: 'image-model', name: 'Video Model', mode: 'video_generation' },++ ]);++ mocks.guide.mockResolvedValue(resolvedGuide(asyncOperation));++ mocks.outboundFetch++ .mockResolvedValueOnce(new Response(JSON.stringify({ task_id: 'task-3' }), { status: 200 }))++ .mockResolvedValueOnce(++ new Response(++ JSON.stringify({ status: 'succeeded', video: 'https://cdn.example.com/expired.mp4' }),++ { status: 200 },++ ),++ )++ .mockResolvedValueOnce(new Response(null, { status: 403 }));++++ const prepared = await callCindyMedia({++ action: 'prepare',++ modelId: 'image-model',++ capability: 'video.generate',++ });++ const invocationId = prepared.invocation_id as string;++ await callCindyMedia({ action: 'request', invocationId, body: { content: [] } });++++ await expect(callCindyMedia({ action: 'poll', invocationId })).resolves.toMatchObject({++ ok: false,++ errorCode: 'MEDIA_DOWNLOAD_REJECTED',++ retryable: false,++ });++ expect(mocks.rows.get(invocationId)?.state).toBe('failed');++ expect(mocks.outboundFetch).toHaveBeenCalledTimes(3);++ });+});diff --cc apps/desktop/src/main/cindy-media/invocationService.tsindex 0658527e05,0000000000..5b1a5c7758mode 100644,000000..100644--- a/apps/desktop/src/main/cindy-media/invocationService.ts+++ b/apps/desktop/src/main/cindy-media/invocationService.ts@@@ -1,875 -1,0 +1,1246 @@@+import fs from 'node:fs/promises';+import { randomUUID } from 'node:crypto';+import type { MediaCapability } from '@cindy/model-providers';+import type { CindyMediaToolRequest } from 'cindy-tools';+import type {+ MediaAsyncPollGuide,++ MediaMultipartFileGuide,+ PreparedMediaInvocationGuide,+ MediaResultExtractor,+ MediaResultKind,+ ResolvedMediaInvocationGuide,+} from '../../shared/mediaInvocation.js';+import { getAppCapabilities } from '../appCapabilities.js';+import * as authManager from '../authManager.js';+import * as imageCacheStore from '../imageCacheStore.js';+import { createLogger } from '../logger.js';+import { ServerApiError } from '../serverApiClient.js';++import { getCurrentDbClientUserId, getDbClient } from '../localDb/client/current.js';++import type { DbClient } from '../localDb/client/DbClient.js';+import { effectiveXdGatewayBaseUrl } from '../model-access/effectiveEndpoint.js';+import { outboundFetch } from '../maker-host/outbound-fetch.js';+import {+ fetchMediaInvocationGuide,+ listAvailableMediaModels,++ listExecutableMediaModels,++ MediaGuideCompatibilityError,++ MediaModelCatalogError,+} from '../model-access/mediaModels.js';+import { getProviderSecretStore } from '../secrets/providerSecretStore.js';+import * as blobStore from './blobStore.js';+import { ingestMedia } from './ingest.js';+import { sniffMediaMime } from './sniffMediaMime.js';+import {+ countMediaInvocations,+ createMediaInvocation,+ getMediaInvocation,+ pruneMediaInvocations,+ recoverInterruptedMediaInvocations,+ transitionMediaInvocation,+ type StoredMediaInvocation,+} from './mediaInvocationStore.js';++const log = createLogger('cindyMediaInvocation');+const INVOCATION_TTL_MS = 6 * 60 * 60 * 1_000;+const PREPARED_INVOCATION_TTL_MS = 5 * 60 * 1_000;+const MAX_INVOCATIONS = 128;- const MAX_LOCAL_MEDIA_INPUT_BYTES = 20 * 1024 * 1024;++const MAX_LOCAL_MEDIA_INPUT_BYTES = 50 * 1024 * 1024;+const MAX_IMAGE_RESULT_BYTES = 32 * 1024 * 1024;+const MAX_AUDIO_RESULT_BYTES = 128 * 1024 * 1024;+const MAX_VIDEO_RESULT_BYTES = 256 * 1024 * 1024;+const MAX_MEDIA_RESULTS = 16;- const MAX_LOCAL_MEDIA_INPUTS = 16;- const MAX_LOCAL_MEDIA_INPUT_TOTAL_BYTES = 64 * 1024 * 1024;++const MAX_LOCAL_MEDIA_INPUTS = 32;++const MAX_LOCAL_MEDIA_INPUT_TOTAL_BYTES = 128 * 1024 * 1024;+const FORBIDDEN_PATH_SEGMENTS = new Set(['__proto__', 'prototype', 'constructor']);+const TERMINAL_MEDIA_RESULT_ERRORS = new Set([++ 'MEDIA_DOWNLOAD_REJECTED',+ 'MEDIA_RESULT_INVALID',+ 'MEDIA_RESULT_MISSING',+ 'MEDIA_RESULT_TOO_LARGE',+ 'RESPONSE_TOO_LARGE',+]);++interface MediaConnection {+ baseUrl: string;+ apiKey: string;+}++class MediaInvocationError extends Error {+ constructor(+ readonly code: string,+ message: string,+ readonly outcomeUnknown = false,+ ) {+ super(message);+ this.name = 'MediaInvocationError';+ }+}+- const recoveredOwners = new Set<string>();++const recoveredDatabases = new WeakSet<DbClient>();++interface MediaAuthScope {+ owner: string;++ dbOwnerId: string;+ generation: number;+}++function currentAuthScope(): MediaAuthScope {+ const state = authManager.getAuthState();+ const userId = state.user?.id ?? null;- if (!userId) {++ const dbOwnerId = state.dataOwnerId;++ if (!userId || !dbOwnerId) {+ throw new MediaInvocationError('CONNECTION_UNAVAILABLE', '当前没有可用的 Cindy 登录态');+ }+ return {+ owner: `${authManager.getActiveAuthRealm()}:${userId}`,++ dbOwnerId,+ generation: state.ownerGeneration,+ };+}++function assertAuthScope(scope: MediaAuthScope, expectedOwner = scope.owner): void {+ const current = currentAuthScope();- if (current.owner !== expectedOwner || current.generation !== scope.generation) {++ if (++ current.owner !== expectedOwner ||++ current.dbOwnerId !== scope.dbOwnerId ||++ current.generation !== scope.generation++ ) {+ throw new MediaInvocationError(+ 'ACCOUNT_CHANGED',+ '媒体调用期间 Cindy 账号发生变化,请在当前账号下重新准备',+ );+ }+}+- async function ensureOwnerRecovered(owner: string): Promise<void> {- if (recoveredOwners.has(owner)) return;- recoveredOwners.add(owner);++function captureMediaDb(scope: MediaAuthScope): DbClient {++ assertAuthScope(scope);++ const dbOwnerId = getCurrentDbClientUserId();++ if (dbOwnerId !== scope.dbOwnerId) {++ throw new MediaInvocationError(++ dbOwnerId ? 'ACCOUNT_CHANGED' : 'CONNECTION_UNAVAILABLE',++ dbOwnerId ? '媒体调用期间 Cindy 账号发生变化' : '当前账号的本地数据尚未就绪',++ );++ }++ const db = getDbClient();++ assertAuthScope(scope);++ return db;++}++++async function ensureOwnerRecovered(scope: MediaAuthScope, db: DbClient): Promise<void> {++ if (recoveredDatabases.has(db)) return;++ recoveredDatabases.add(db);+ try {- await recoverInterruptedMediaInvocations(owner);++ await recoverInterruptedMediaInvocations(scope.owner, db);++ assertAuthScope(scope);+ } catch (error) {- recoveredOwners.delete(owner);++ recoveredDatabases.delete(db);+ throw error;+ }+}+- async function pruneInvocations(owner: string): Promise<void> {++async function pruneInvocations(owner: string, db: DbClient): Promise<void> {+ const now = Date.now();- await pruneMediaInvocations({- owner,- preparedBefore: now - PREPARED_INVOCATION_TTL_MS,- terminalBefore: now - INVOCATION_TTL_MS,- });++ await pruneMediaInvocations(++ {++ owner,++ preparedBefore: now - PREPARED_INVOCATION_TTL_MS,++ terminalBefore: now - INVOCATION_TTL_MS,++ },++ db,++ );++}++++function failure(++ code: string,++ message: string,++ retryable = false,++ details: Record<string, unknown> = {},++): Record<string, unknown> {++ return { ok: false, errorCode: code, message, retryable, ...details };+}+- function failure(code: string, message: string, retryable = false): Record<string, unknown> {- return { ok: false, errorCode: code, message, retryable };++const GUIDE_FALLBACK_ACTIONS = [++ 'choose_another_model',++ 'use_another_tool',++ 'use_legacy_adapter_if_available',++] as const;++++function submissionOutcomeUnknown(message: string): Record<string, unknown> {++ return failure('SUBMISSION_OUTCOME_UNKNOWN', message, false, {++ outcomeKnown: false,++ allowedActions: [++ 'wait_or_check_existing_task',++ 'ask_user_before_new_submission',++ 'use_another_tool',++ ],++ });+}++function resolveConnection(providerId: string): MediaConnection {+ if (providerId !== 'xd') {+ throw new MediaInvocationError(+ 'CONNECTION_NOT_SUPPORTED',+ `当前 Cindy 版本没有注册媒体连接 ${JSON.stringify(providerId)}`,+ );+ }+ if (!getAppCapabilities().canUseCindyGateway) {+ throw new MediaInvocationError('CONNECTION_UNAVAILABLE', '当前账号不能使用 Cindy AI 网关');+ }+ const baseUrl = effectiveXdGatewayBaseUrl().trim();+ const apiKey = getProviderSecretStore().get('xd')?.trim() ?? '';+ if (!baseUrl || !apiKey) {+ throw new MediaInvocationError('CONNECTION_UNAVAILABLE', 'Cindy AI 连接尚未就绪,请先完成登录');+ }+ let parsed: URL;+ try {+ parsed = new URL(baseUrl);+ } catch {+ throw new MediaInvocationError('CONNECTION_INVALID', 'Cindy AI endpoint 不合法');+ }+ if (+ (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') ||+ parsed.username ||+ parsed.password+ ) {+ throw new MediaInvocationError('CONNECTION_INVALID', 'Cindy AI endpoint 不合法');+ }+ return { baseUrl, apiKey };+}++function requestUrl(baseUrl: string, relativePath: string): string {+ const base = new URL(baseUrl);+ if (+ !relativePath.startsWith('/') ||+ relativePath.startsWith('//') ||+ relativePath.includes('://')+ ) {+ throw new MediaInvocationError('GUIDE_INVALID', '调用说明包含不安全的请求路径');+ }+ const resolved = new URL(relativePath, base.origin);+ if (resolved.origin !== base.origin) {+ throw new MediaInvocationError('GUIDE_INVALID', '调用说明的请求路径越出 Gateway origin');+ }+ return resolved.toString();+}++async function readBoundedResponse(response: Response, maxBytes: number): Promise<Buffer> {+ const declared = response.headers.get('content-length');+ if (declared !== null && Number(declared) > maxBytes) {+ throw new MediaInvocationError('RESPONSE_TOO_LARGE', `上游响应超过 ${maxBytes} 字节限制`);+ }+ if (!response.body) return Buffer.alloc(0);+ const reader = response.body.getReader();+ const chunks: Uint8Array[] = [];+ let size = 0;+ try {+ for (;;) {+ const { done, value } = await reader.read();+ if (done) break;+ size += value.byteLength;+ if (size > maxBytes) {+ await reader.cancel();+ throw new MediaInvocationError('RESPONSE_TOO_LARGE', `上游响应超过 ${maxBytes} 字节限制`);+ }+ chunks.push(value);+ }+ } finally {+ reader.releaseLock();+ }+ return Buffer.concat(+ chunks.map((chunk) => Buffer.from(chunk)),+ size,+ );+}++function providerErrorMessage(buffer: Buffer): string {+ const text = buffer.toString('utf8').slice(0, 2_000);+ try {+ const value = JSON.parse(text) as {+ error?: { message?: unknown };+ message?: unknown;+ msg?: unknown;+ };+ const message = value.error?.message ?? value.message ?? value.msg;+ if (typeof message !== 'string' || !message.trim()) return '上游拒绝请求';+ return message+ .replace(/data:[^,\s]{1,128};base64,[A-Za-z0-9+/=\s]+/gi, '[已脱敏 data URL]')+ .replace(/\bhttps?:\/\/[^\s"'<>]+/gi, '[已脱敏 URL]')+ .replace(/\bBearer\s+[A-Za-z0-9._~+/-]{16,}\b/gi, 'Bearer [已脱敏]')+ .replace(/\b[A-Za-z0-9+/_-]{80,}={0,2}\b/g, '[已脱敏长值]')+ .slice(0, 500);+ } catch {+ return '上游拒绝请求';+ }+}+- async function dispatchJson(input: {++function multipartRequestBody(++ body: Record<string, unknown>,++ fileGuides: readonly MediaMultipartFileGuide[],++): FormData {++ const form = new FormData();++ const filesByBodyField = new Map(fileGuides.map((guide) => [guide.bodyField, guide]));++ for (const [field, value] of Object.entries(body)) {++ const fileGuide = filesByBodyField.get(field);++ if (!fileGuide) {++ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {++ form.append(field, String(value));++ continue;++ }++ if (value === undefined || value === null) continue;++ throw new MediaInvocationError(++ 'REQUEST_INVALID',++ `multipart 字段 ${field} 必须是字符串、数字或布尔值`,++ );++ }++++ const values = Array.isArray(value) ? value : [value];++ if (values.length === 0 || values.length > fileGuide.maxItems) {++ throw new MediaInvocationError(++ 'MEDIA_INPUT_INVALID',++ `媒体字段 ${field} 必须包含 1–${fileGuide.maxItems} 个文件`,++ );++ }++ for (const [index, item] of values.entries()) {++ if (typeof item !== 'string') {++ throw new MediaInvocationError('MEDIA_INPUT_INVALID', `媒体字段 ${field} 必须是媒体地址`);++ }++ const match = /^data:([^;,]+);base64,([A-Za-z0-9+/=\r\n]+)$/i.exec(item);++ if (!match) {++ throw new MediaInvocationError(++ 'MEDIA_INPUT_INVALID',++ `multipart 媒体字段 ${field} 必须使用 Cindy 受管媒体`,++ );++ }++ const mimeType = match[1].toLowerCase();++ const buffer = Buffer.from(match[2].replace(/[\r\n]/g, ''), 'base64');++ if (++ buffer.byteLength === 0 ||++ !mimeType.startsWith(`${fileGuide.kind}/`) ||++ !blobStore.supportedMime(mimeType) ||++ sniffMediaMime(buffer, mimeType) !== mimeType++ ) {++ throw new MediaInvocationError(++ 'MEDIA_INPUT_INVALID',++ `媒体字段 ${field} 不是 Cindy 支持的 ${fileGuide.kind} 文件`,++ );++ }++ const extension =++ ({++ 'image/jpeg': 'jpg',++ 'video/quicktime': 'mov',++ 'audio/mpeg': 'mp3',++ 'audio/mp4': 'm4a',++ } as Record<string, string>)[mimeType] ?? mimeType.split('/')[1];++ form.append(++ fileGuide.formField,++ new Blob([buffer], { type: mimeType }),++ `${field}-${index + 1}.${extension}`,++ );++ }++ }++ return form;++}++++async function dispatchRequest(input: {+ connection: MediaConnection;+ method: 'GET' | 'POST';+ path: string;+ headers?: Record<string, string>;+ body?: Record<string, unknown>;++ bodyEncoding?: 'json' | 'multipart';++ multipartFiles?: readonly MediaMultipartFileGuide[];+ timeoutMs: number;+ maxResponseBytes: number;+ operation: 'submit' | 'poll';+}): Promise<unknown> {+ const controller = new AbortController();+ const timeout = setTimeout(() => controller.abort(), input.timeoutMs);+ timeout.unref?.();+ try {++ const requestBody = input.body++ ? input.bodyEncoding === 'multipart'++ ? multipartRequestBody(input.body, input.multipartFiles ?? [])++ : JSON.stringify(input.body)++ : undefined;+ const response = await outboundFetch(requestUrl(input.connection.baseUrl, input.path), {+ method: input.method,+ headers: {+ Accept: 'application/json',- ...(input.body ? { 'Content-Type': 'application/json' } : {}),++ ...(input.body && input.bodyEncoding !== 'multipart'++ ? { 'Content-Type': 'application/json' }++ : {}),+ ...(input.headers ?? {}),+ Authorization: `Bearer ${input.connection.apiKey}`,+ },- ...(input.body ? { body: JSON.stringify(input.body) } : {}),++ ...(requestBody ? { body: requestBody } : {}),+ redirect: 'error',+ signal: controller.signal,+ });+ const buffer = await readBoundedResponse(response, input.maxResponseBytes);+ if (!response.ok) {+ const message = providerErrorMessage(buffer);+ if (response.status >= 500) {+ if (input.operation === 'poll') {+ throw new MediaInvocationError(+ 'POLL_UNAVAILABLE',+ `上游状态查询返回 HTTP ${response.status},可稍后重试`,+ );+ }+ throw new MediaInvocationError(+ 'SUBMISSION_OUTCOME_UNKNOWN',+ `上游返回 HTTP ${response.status},无法确认任务是否已经创建;不要自动重提`,+ true,+ );+ }+ throw new MediaInvocationError(+ 'UPSTREAM_REJECTED',+ `上游返回 HTTP ${response.status}: ${message}`,+ );+ }+ try {+ return JSON.parse(buffer.toString('utf8')) as unknown;+ } catch {+ throw new MediaInvocationError('UPSTREAM_RESPONSE_INVALID', '上游成功响应不是合法 JSON');+ }+ } catch (error) {+ if (error instanceof MediaInvocationError) throw error;+ const aborted = error instanceof Error && error.name === 'AbortError';+ if (input.operation === 'poll') {+ throw new MediaInvocationError(+ 'POLL_UNAVAILABLE',+ aborted ? '上游状态查询超时,可稍后重试' : '上游状态查询网络失败,可稍后重试',+ );+ }+ throw new MediaInvocationError(+ 'SUBMISSION_OUTCOME_UNKNOWN',+ aborted+ ? '上游请求超时,无法确认任务是否已经创建;不要自动重提'+ : '上游网络请求失败,无法确认任务是否已经创建;不要自动重提',+ true,+ );+ } finally {+ clearTimeout(timeout);+ }+}++function setObjectPath(+ target: Record<string, unknown>,+ path: readonly string[],+ value: unknown,+): void {+ let cursor: Record<string, unknown> = target;+ for (const [index, segment] of path.entries()) {+ if (!segment || segment === '*' || FORBIDDEN_PATH_SEGMENTS.has(segment)) {+ throw new MediaInvocationError('GUIDE_INVALID', '调用说明包含不安全的注入路径');+ }+ if (index === path.length - 1) {+ cursor[segment] = value;+ return;+ }+ const next = cursor[segment];+ if (!next || typeof next !== 'object' || Array.isArray(next)) {+ const created: Record<string, unknown> = {};+ cursor[segment] = created;+ cursor = created;+ } else {+ cursor = next as Record<string, unknown>;+ }+ }+}++function valuesAtPath(value: unknown, path: readonly string[]): unknown[] {+ let values = [value];+ for (const segment of path) {+ const next: unknown[] = [];+ for (const candidate of values) {+ if (segment === '*') {+ if (Array.isArray(candidate)) next.push(...candidate);+ else if (candidate && typeof candidate === 'object') {+ next.push(...Object.values(candidate as Record<string, unknown>));+ }+ } else if (candidate && typeof candidate === 'object') {+ const child = (candidate as Record<string, unknown>)[segment];+ if (child !== undefined) next.push(child);+ }+ }+ values = next;+ }+ return values;+}++async function localMediaDataUrl(+ ref: string,+ state: { localInputs: number; localBytes: number },+): Promise<string | null> {+ let buffer: Buffer;+ let mimeType: string;+ if (ref.startsWith('cindy-media://')) {+ const loaded = await blobStore.readFile(ref);+ buffer = loaded.buffer;+ mimeType = loaded.mimeType;+ } else if (ref.startsWith('xdt-image://')) {+ const resolved = imageCacheStore.resolveSafe(ref);+ buffer = await fs.readFile(resolved.absPath);+ mimeType = resolved.mimeType;+ } else {+ return null;+ }+ state.localInputs += 1;+ state.localBytes += buffer.byteLength;+ if (+ state.localInputs > MAX_LOCAL_MEDIA_INPUTS ||+ state.localBytes > MAX_LOCAL_MEDIA_INPUT_TOTAL_BYTES+ ) {- throw new MediaInvocationError('MEDIA_INPUT_INVALID', '本地参考图数量或总大小超过限制');++ throw new MediaInvocationError('MEDIA_INPUT_INVALID', '本地参考媒体数量或总大小超过限制');+ }- if (buffer.byteLength > MAX_LOCAL_MEDIA_INPUT_BYTES || !mimeType.startsWith('image/')) {++ const supportedKind = ['image/', 'video/', 'audio/'].some((prefix) => mimeType.startsWith(prefix));++ if (++ buffer.byteLength > MAX_LOCAL_MEDIA_INPUT_BYTES ||++ !supportedKind ||++ !blobStore.supportedMime(mimeType)++ ) {+ throw new MediaInvocationError(+ 'MEDIA_INPUT_INVALID',- `本地参考图必须是 ${MAX_LOCAL_MEDIA_INPUT_BYTES} 字节以内的图片`,++ `本地参考媒体必须是 ${MAX_LOCAL_MEDIA_INPUT_BYTES} 字节以内的受支持文件`,+ );+ }+ return `data:${mimeType};base64,${buffer.toString('base64')}`;+}++async function expandLocalMediaRefs(+ value: unknown,+ state: { nodes: number; localInputs: number; localBytes: number },+ depth = 0,+): Promise<unknown> {+ state.nodes += 1;+ if (depth > 24 || state.nodes > 10_000) {+ throw new MediaInvocationError('REQUEST_INVALID', '请求 body 嵌套过深或字段过多');+ }+ if (typeof value === 'string') return (await localMediaDataUrl(value, state)) ?? value;+ if (Array.isArray(value)) {+ const output: unknown[] = [];+ for (const item of value) output.push(await expandLocalMediaRefs(item, state, depth + 1));+ return output;+ }+ if (value && typeof value === 'object') {+ const output: Record<string, unknown> = {};+ for (const [key, child] of Object.entries(value as Record<string, unknown>)) {+ if (FORBIDDEN_PATH_SEGMENTS.has(key)) {+ throw new MediaInvocationError('REQUEST_INVALID', `请求 body 包含非法字段 ${key}`);+ }+ output[key] = await expandLocalMediaRefs(child, state, depth + 1);+ }+ return output;+ }+ return value;+}++async function prepareRequestBody(+ body: Record<string, unknown>,+ guide: PreparedMediaInvocationGuide,+): Promise<Record<string, unknown>> {+ const expanded = await expandLocalMediaRefs(body, { nodes: 0, localInputs: 0, localBytes: 0 });+ if (!expanded || typeof expanded !== 'object' || Array.isArray(expanded)) {+ throw new MediaInvocationError('REQUEST_INVALID', '请求 body 必须是 JSON 对象');+ }+ const output = expanded as Record<string, unknown>;- setObjectPath(output, guide.request.bodyModelPath, guide.wireModelId);++ setObjectPath(output, guide.request.bodyModelPath, guide.modelId);+ const bytes = Buffer.byteLength(JSON.stringify(output), 'utf8');+ if (bytes > guide.request.maxRequestBytes) {+ throw new MediaInvocationError(+ 'REQUEST_TOO_LARGE',+ `请求 body 超过 ${guide.request.maxRequestBytes} 字节限制`,+ );+ }+ return output;+}++function maxResultBytes(kind: MediaResultKind): number {+ if (kind === 'image') return MAX_IMAGE_RESULT_BYTES;+ if (kind === 'audio') return MAX_AUDIO_RESULT_BYTES;+ return MAX_VIDEO_RESULT_BYTES;+}++function assertResultMime(kind: MediaResultKind, mimeType: string): void {+ if (!mimeType.startsWith(`${kind}/`) || !blobStore.supportedMime(mimeType)) {+ throw new MediaInvocationError(+ 'MEDIA_RESULT_INVALID',+ `上游返回的字节不是 Cindy 支持的 ${kind} 媒体`,+ );+ }+}++function allowedDownloadUrl(raw: string, extractor: MediaResultExtractor): URL {+ let parsed: URL;+ try {+ parsed = new URL(raw);+ } catch {+ throw new MediaInvocationError('MEDIA_RESULT_INVALID', '上游媒体 URL 不合法');+ }+ if (parsed.protocol !== 'https:' || parsed.username || parsed.password) {+ throw new MediaInvocationError('MEDIA_RESULT_INVALID', '上游媒体 URL 必须是 HTTPS');+ }+ const hostname = parsed.hostname.toLowerCase();+ if (parsed.port) {+ throw new MediaInvocationError('MEDIA_RESULT_INVALID', '上游媒体 URL 不允许自定义端口');+ }+ const allowed = (extractor.allowedUrlHosts ?? []).some((suffix) => {+ const normalized = suffix.toLowerCase();+ return hostname === normalized || hostname.endsWith(`.${normalized}`);+ });+ if (!allowed) {+ throw new MediaInvocationError('MEDIA_RESULT_INVALID', '上游媒体 URL 不在调用说明的可信域名内');+ }+ return parsed;+}++async function mediaBytes(+ raw: string,+ extractor: MediaResultExtractor,+): Promise<{ buffer: Buffer; mimeType: string }> {+ let buffer: Buffer;+ let headerMime: string | null = null;+ if (extractor.encoding === 'url') {+ const url = allowedDownloadUrl(raw, extractor);+ const controller = new AbortController();+ const timeout = setTimeout(() => controller.abort(), 120_000);+ timeout.unref?.();+ try {+ const response = await outboundFetch(url.toString(), {+ method: 'GET',+ redirect: 'error',+ signal: controller.signal,+ });+ if (!response.ok) {++ const permanentClientError =++ response.status >= 400 &&++ response.status < 500 &&++ ![408, 425, 429].includes(response.status);+ throw new MediaInvocationError(- 'MEDIA_DOWNLOAD_FAILED',++ permanentClientError ? 'MEDIA_DOWNLOAD_REJECTED' : 'MEDIA_DOWNLOAD_FAILED',+ `媒体下载失败 (HTTP ${response.status})`,+ );+ }+ headerMime =+ response.headers.get('content-type')?.split(';', 1)[0].trim().toLowerCase() ?? null;+ buffer = await readBoundedResponse(response, maxResultBytes(extractor.kind));+ } catch (error) {+ if (error instanceof MediaInvocationError) throw error;+ throw new MediaInvocationError('MEDIA_DOWNLOAD_FAILED', '媒体下载超时或网络失败');+ } finally {+ clearTimeout(timeout);+ }+ } else {+ const dataUrl = /^data:([^;,]+);base64,(.+)$/s.exec(raw);+ const encoded = (dataUrl ? dataUrl[2] : raw).replace(/\s/g, '');+ headerMime = dataUrl?.[1]?.toLowerCase() ?? null;+ if (encoded.length > Math.ceil((maxResultBytes(extractor.kind) * 4) / 3) + 16) {+ throw new MediaInvocationError('MEDIA_RESULT_TOO_LARGE', '上游 base64 媒体超过大小限制');+ }+ if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(encoded)) {+ throw new MediaInvocationError('MEDIA_RESULT_INVALID', '上游 base64 媒体编码不合法');+ }+ buffer = Buffer.from(encoded, 'base64');+ }+ if (buffer.byteLength === 0 || buffer.byteLength > maxResultBytes(extractor.kind)) {+ throw new MediaInvocationError('MEDIA_RESULT_INVALID', '上游返回空媒体或媒体超过大小限制');+ }+ // Guide / Content-Type 只能帮助识别容器变体(例如无 ftyp 的 QuickTime),+ // 不能在魔数识别失败时替上游字节“声明”一个可信类型。+ const declaredMime = extractor.mediaType ?? headerMime ?? '';+ const mimeType = sniffMediaMime(buffer, declaredMime);+ if (!mimeType) throw new MediaInvocationError('MEDIA_RESULT_INVALID', '无法从上游字节识别媒体类型');+ assertResultMime(extractor.kind, mimeType);+ return { buffer, mimeType };+}++async function materializeResults(+ payload: unknown,+ extractors: readonly MediaResultExtractor[],++ scope: MediaAuthScope,++ db: DbClient,+): Promise<Record<string, unknown>> {+ const found: Array<{ raw: string; extractor: MediaResultExtractor }> = [];+ const seen = new Set<string>();+ for (const extractor of extractors) {+ for (const value of valuesAtPath(payload, extractor.path)) {+ if (typeof value !== 'string' || value.length === 0 || seen.has(value)) continue;+ seen.add(value);+ found.push({ raw: value, extractor });+ if (found.length > MAX_MEDIA_RESULTS) {+ throw new MediaInvocationError('MEDIA_RESULT_INVALID', '上游返回的媒体结果数量超过限制');+ }+ }+ }+ if (found.length === 0) {+ throw new MediaInvocationError('MEDIA_RESULT_MISSING', '上游成功响应中没有找到媒体结果');+ }+ const images: string[] = [];+ const videos: string[] = [];+ const audio: string[] = [];+ for (const item of found) {- const media = await mediaBytes(item.raw, item.extractor);- const stored = await ingestMedia({ buffer: media.buffer, mimeType: media.mimeType, refs: [] });++ assertAuthScope(scope);++ let media: Awaited<ReturnType<typeof mediaBytes>>;++ try {++ media = await mediaBytes(item.raw, item.extractor);++ } catch (error) {++ // 账号切换与下载失败同时发生时,账号边界优先,避免旧账号结果继续落状态。++ assertAuthScope(scope);++ throw error;++ }++ assertAuthScope(scope);++ const stored = await ingestMedia(++ {++ buffer: media.buffer,++ mimeType: media.mimeType,++ refs: [],++ assertStillValid: () => assertAuthScope(scope),++ },++ db.drizzle,++ );++ assertAuthScope(scope);+ if (item.extractor.kind === 'image') images.push(stored.url);+ else if (item.extractor.kind === 'video') videos.push(stored.url);+ else audio.push(stored.url);+ }+ return {+ ...(images.length > 0 ? { xdt_image_urls: images } : {}),+ ...(videos.length > 0 ? { xdt_video_urls: videos } : {}),+ ...(audio.length > 0+ ? { xdt_audio_tracks: audio.map((url) => ({ xdt_audio_url: url, kind: 'generated' })) }+ : {}),+ };+}+++function persistedResponse(invocation: StoredMediaInvocation): unknown {++ if (!invocation.responseJson) {++ throw new MediaInvocationError('MEDIA_RESULT_MISSING', '已提交调用缺少可恢复的上游响应');++ }++ try {++ return JSON.parse(invocation.responseJson) as unknown;++ } catch {++ throw new MediaInvocationError('MEDIA_RESULT_INVALID', '已提交调用保存的上游响应不合法');++ }++}++++async function materializeSyncInvocation(++ invocation: StoredMediaInvocation,++ response: unknown,++ scope: MediaAuthScope,++ db: DbClient,++): Promise<Record<string, unknown>> {++ const responseGuide = invocation.guide.response;++ if (responseGuide.mode !== 'sync') {++ throw new MediaInvocationError('MEDIA_RESULT_INVALID', '同步媒体调用缺少同步响应说明');++ }++ try {++ const media = await materializeResults(response, responseGuide.media, scope, db);++ assertAuthScope(scope, invocation.owner);++ await transitionMediaInvocation(++ {++ id: invocation.id,++ owner: invocation.owner,++ from: 'pending',++ to: 'complete',++ },++ db,++ );++ assertAuthScope(scope, invocation.owner);++ return { ok: true, status: 'complete', invocation_id: invocation.id, ...media };++ } catch (error) {++ assertAuthScope(scope, invocation.owner);++ if (error instanceof MediaInvocationError) {++ if (TERMINAL_MEDIA_RESULT_ERRORS.has(error.code)) {++ await transitionMediaInvocation(++ {++ id: invocation.id,++ owner: invocation.owner,++ from: 'pending',++ to: 'failed',++ },++ db,++ );++ assertAuthScope(scope, invocation.owner);++ return failure(error.code, error.message);++ }++ if (error.code === 'MEDIA_DOWNLOAD_FAILED') {++ return {++ ...failure(error.code, error.message, true),++ retry_action: 'request',++ };++ }++ throw error;++ }++ log.warn('sync media materialization failed', {++ error: error instanceof Error ? error.message : String(error),++ });++ return {++ ...failure('MEDIA_MATERIALIZATION_FAILED', '媒体结果暂时无法保存', true),++ retry_action: 'request',++ };++ }++}+++async function prepareInvocation(+ modelId: string,+ capability: MediaCapability,+): Promise<Record<string, unknown>> {+ const scope = currentAuthScope();+ const owner = scope.owner;- await ensureOwnerRecovered(owner);++ const db = captureMediaDb(scope);++ await ensureOwnerRecovered(scope, db);+ assertAuthScope(scope);+ const models = await listAvailableMediaModels(capability);+ assertAuthScope(scope);+ const model = models.find((candidate) => candidate.id === modelId);+ if (!model) {+ return failure('MODEL_NOT_AVAILABLE', '该模型当前不可见,或不是请求的媒体类型');+ }+ let resolvedGuide: ResolvedMediaInvocationGuide;+ try {+ resolvedGuide = await fetchMediaInvocationGuide(modelId);+ assertAuthScope(scope);+ } catch (error) {+ if (error instanceof ServerApiError && error.code === 'MEDIA_INVOCATION_GUIDE_NOT_FOUND') {- return failure('GUIDE_NOT_AVAILABLE', '该模型当前没有可用的调用说明');++ return failure('GUIDE_NOT_AVAILABLE', '该模型当前没有可用的调用说明', false, {++ outcomeKnown: true,++ allowedActions: GUIDE_FALLBACK_ACTIONS,++ });++ }++ if (error instanceof MediaGuideCompatibilityError) {++ log.warn('media Guide rejected by current client', {++ modelId,++ code: error.code,++ detail: error.detail,++ });++ return failure(error.code, error.message, false, {++ outcomeKnown: true,++ allowedActions: GUIDE_FALLBACK_ACTIONS,++ });++ }++ if (error instanceof ServerApiError) {++ return failure('GUIDE_SERVICE_UNAVAILABLE', '媒体调用说明暂时无法读取,请稍后重试', true, {++ outcomeKnown: true,++ allowedActions: GUIDE_FALLBACK_ACTIONS,++ });+ }+ throw error;+ }+ const operation = resolvedGuide.guide.operations.find(+ (candidate) => candidate.capability === capability,+ );+ if (!operation) {- return failure('GUIDE_NOT_AVAILABLE', '该模型的调用协议当前不支持请求的媒体能力');++ return failure(++ 'CAPABILITY_NOT_SUPPORTED',++ '该模型的调用协议当前不支持请求的媒体能力',++ false,++ {++ outcomeKnown: true,++ allowedActions: GUIDE_FALLBACK_ACTIONS,++ },++ );+ }+ const { operations: _operations, ...guideProtocol } = resolvedGuide.guide;+ void _operations;+ const preparedGuide: PreparedMediaInvocationGuide = {+ modelId: resolvedGuide.modelId,- wireModelId: resolvedGuide.wireModelId,+ ...guideProtocol,+ ...operation,+ };- await pruneInvocations(owner);++ await pruneInvocations(owner, db);+ assertAuthScope(scope);- if ((await countMediaInvocations(owner)) >= MAX_INVOCATIONS) {++ if ((await countMediaInvocations(owner, db)) >= MAX_INVOCATIONS) {+ return failure('TOO_MANY_INVOCATIONS', '媒体任务数量已达上限,请等待现有任务完成后重试');+ }+ assertAuthScope(scope);+ const id = randomUUID();+ const createdAt = Date.now();- await createMediaInvocation({- id,- owner,- guide: preparedGuide,- createdAt,- });++ await createMediaInvocation(++ {++ id,++ owner,++ guide: preparedGuide,++ createdAt,++ },++ db,++ );+ assertAuthScope(scope);+ return {+ ok: true,+ status: 'prepared',+ invocation_id: id,+ model_id: modelId,+ model_name: model.name,+ capability,+ guide_revision: preparedGuide.revision,+ instructions: preparedGuide.instructions,+ input_schema: preparedGuide.inputSchema,+ example_body: preparedGuide.exampleBody,+ official_docs: preparedGuide.officialDocs,+ guidance: '按 instructions/input_schema 组装 body;不要添加 model、endpoint、headers 或凭证。',+ };+}++async function requireInvocation(id: string): Promise<StoredMediaInvocation> {+ const scope = currentAuthScope();+ const owner = scope.owner;- await ensureOwnerRecovered(owner);++ const db = captureMediaDb(scope);++ await ensureOwnerRecovered(scope, db);+ assertAuthScope(scope);- await pruneInvocations(owner);++ await pruneInvocations(owner, db);+ assertAuthScope(scope);- const invocation = await getMediaInvocation(id, owner);++ const invocation = await getMediaInvocation(id, owner, db);+ assertAuthScope(scope);+ if (!invocation)+ throw new MediaInvocationError('INVOCATION_NOT_FOUND', '调用已过期或不存在,请重新 prepare');+ return invocation;+}++async function submitInvocation(+ invocation: StoredMediaInvocation,+ body: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const scope = currentAuthScope();+ assertAuthScope(scope, invocation.owner);++ const db = captureMediaDb(scope);++ if (++ invocation.state === 'pending' &&++ invocation.guide.response.mode === 'sync' &&++ invocation.responseJson++ ) {++ return materializeSyncInvocation(invocation, persistedResponse(invocation), scope, db);++ }+ if (invocation.state !== 'prepared') {+ return failure(+ 'INVOCATION_ALREADY_USED',+ `该 invocation 当前状态为 ${invocation.state};付费提交不可重复执行`,+ );+ }+ if (Date.now() - invocation.createdAt > PREPARED_INVOCATION_TTL_MS) {- await transitionMediaInvocation({- id: invocation.id,- owner: invocation.owner,- from: 'prepared',- to: 'failed',- });++ await transitionMediaInvocation(++ {++ id: invocation.id,++ owner: invocation.owner,++ from: 'prepared',++ to: 'failed',++ },++ db,++ );++ assertAuthScope(scope, invocation.owner);+ return failure('INVOCATION_EXPIRED', '调用准备已超过 5 分钟,请重新查询模型并 prepare');+ }+ // prepare 与实际付费提交之间可能隔着 Agent 组装参数的时间;提交边界重新读取+ // Gateway 清单和客户端停用状态,避免模型/供应商刚被停用后仍发出新请求。+ const models = await listAvailableMediaModels(invocation.capability);+ assertAuthScope(scope, invocation.owner);+ if (!models.some((model) => model.id === invocation.modelId)) {+ return failure('MODEL_NOT_AVAILABLE', '该模型已下架或被停用,本次生成未发出');+ }+ const requestBody = await prepareRequestBody(body, invocation.guide);+ assertAuthScope(scope, invocation.owner);- const claimed = await transitionMediaInvocation({- id: invocation.id,- owner: invocation.owner,- from: 'prepared',- to: 'submitting',- });++ const claimed = await transitionMediaInvocation(++ {++ id: invocation.id,++ owner: invocation.owner,++ from: 'prepared',++ to: 'submitting',++ },++ db,++ );+ if (!claimed) {- const current = await getMediaInvocation(invocation.id, invocation.owner);++ const current = await getMediaInvocation(invocation.id, invocation.owner, db);++ assertAuthScope(scope, invocation.owner);+ return failure(+ 'INVOCATION_ALREADY_USED',+ `该 invocation 当前状态为 ${current?.state ?? 'unknown'};付费提交不可重复执行`,+ );+ }+ // claim 之后再过一次认证代次闸;通过后到 outboundFetch 发起之间没有异步让出点,+ // 因而不会拿切换后账号的 endpoint / key 提交旧账号的付费请求。+ assertAuthScope(scope, invocation.owner);+ const connection = resolveConnection(invocation.guide.connection.providerId);+ try {- const response = await dispatchJson({++ const response = await dispatchRequest({+ connection,+ method: invocation.guide.request.method,+ path: invocation.guide.request.path,+ headers: invocation.guide.request.headers,+ body: requestBody,++ bodyEncoding: invocation.guide.request.bodyEncoding,++ multipartFiles: invocation.guide.request.multipartFiles,+ timeoutMs: invocation.guide.request.timeoutMs,+ maxResponseBytes: invocation.guide.request.maxResponseBytes,+ operation: 'submit',+ });+ if (invocation.guide.response.mode === 'sync') {- const media = await materializeResults(response, invocation.guide.response.media);- await transitionMediaInvocation({- id: invocation.id,- owner: invocation.owner,- from: 'submitting',- to: 'complete',- });- return { ok: true, status: 'complete', invocation_id: invocation.id, ...media };++ const responseJson = JSON.stringify(response);++ const persisted = await transitionMediaInvocation(++ {++ id: invocation.id,++ owner: invocation.owner,++ from: 'submitting',++ to: 'pending',++ responseJson,++ },++ db,++ );++ if (!persisted) {++ return submissionOutcomeUnknown(++ '上游结果已生成,但本地未能保存结果;不要自动重提',++ );++ }++ assertAuthScope(scope, invocation.owner);++ return materializeSyncInvocation(++ { ...invocation, state: 'pending', responseJson },++ response,++ scope,++ db,++ );+ }+ const taskId = valuesAtPath(response, invocation.guide.response.taskIdPath).find(+ (value): value is string => typeof value === 'string' && value.length > 0,+ );+ if (!taskId) {- await transitionMediaInvocation({- id: invocation.id,- owner: invocation.owner,- from: 'submitting',- to: 'unknown',- });- return failure(- 'SUBMISSION_OUTCOME_UNKNOWN',++ await transitionMediaInvocation(++ {++ id: invocation.id,++ owner: invocation.owner,++ from: 'submitting',++ to: 'unknown',++ },++ db,++ );++ return submissionOutcomeUnknown(+ '上游响应没有任务 id,无法确认任务状态;不要自动重提',+ );+ }- const persisted = await transitionMediaInvocation({- id: invocation.id,- owner: invocation.owner,- from: 'submitting',- to: 'pending',- taskId,- });++ const persisted = await transitionMediaInvocation(++ {++ id: invocation.id,++ owner: invocation.owner,++ from: 'submitting',++ to: 'pending',++ taskId,++ },++ db,++ );+ if (!persisted) {- return failure(- 'SUBMISSION_OUTCOME_UNKNOWN',++ return submissionOutcomeUnknown(+ '上游任务已创建,但本地未能保存任务 id;不要自动重提',+ );+ }++ assertAuthScope(scope, invocation.owner);+ return {+ ok: true,+ status: 'pending',+ invocation_id: invocation.id,+ recommended_poll_after_ms: invocation.guide.response.poll.recommendedIntervalMs,+ };+ } catch (error) {+ const expected = error instanceof MediaInvocationError ? error : null;- await transitionMediaInvocation({- id: invocation.id,- owner: invocation.owner,- from: 'submitting',- to: expected?.outcomeUnknown ? 'unknown' : 'failed',- }).catch(() => false);- if (expected) return failure(expected.code, expected.message, false);++ await transitionMediaInvocation(++ {++ id: invocation.id,++ owner: invocation.owner,++ from: 'submitting',++ to: expected?.outcomeUnknown ? 'unknown' : 'failed',++ },++ db,++ ).catch(() => false);++ if (expected) {++ return expected.outcomeUnknown++ ? submissionOutcomeUnknown(expected.message)++ : failure(expected.code, expected.message, false, { outcomeKnown: true });++ }+ log.warn('media submission failed', {+ error: error instanceof Error ? error.message : String(error),+ });+ return failure('INTERNAL', '媒体任务提交失败');+ }+}++function pollPath(path: string, taskId: string): string {+ return path.replaceAll('{taskId}', encodeURIComponent(taskId));+}++function pollBody(guide: MediaAsyncPollGuide, taskId: string): Record<string, unknown> | undefined {+ if (guide.method !== 'POST') return undefined;+ const body: Record<string, unknown> = {};+ if (guide.bodyTaskIdPath) setObjectPath(body, guide.bodyTaskIdPath, taskId);+ return body;+}++async function pollInvocation(invocation: StoredMediaInvocation): Promise<Record<string, unknown>> {+ const scope = currentAuthScope();+ assertAuthScope(scope, invocation.owner);++ const db = captureMediaDb(scope);+ if (invocation.guide.response.mode !== 'async') {+ return failure('POLL_NOT_SUPPORTED', '同步媒体调用不需要 poll');+ }+ if (invocation.state !== 'pending' || !invocation.taskId) {+ return failure('INVOCATION_NOT_PENDING', `该 invocation 当前状态为 ${invocation.state}`);+ }+ const guide = invocation.guide.response.poll;+ try {- const response = await dispatchJson({++ const response = await dispatchRequest({+ connection: resolveConnection(invocation.guide.connection.providerId),+ method: guide.method,+ path: pollPath(guide.path, invocation.taskId),+ headers: guide.headers,+ body: pollBody(guide, invocation.taskId),+ timeoutMs: guide.timeoutMs,+ maxResponseBytes: guide.maxResponseBytes,+ operation: 'poll',+ });+ assertAuthScope(scope, invocation.owner);+ const rawStatus = valuesAtPath(response, guide.statusPath)[0];+ const status = typeof rawStatus === 'string' ? rawStatus : '';+ if (guide.successValues.includes(status)) {+ let media: Record<string, unknown>;+ try {- media = await materializeResults(response, guide.media);++ media = await materializeResults(response, guide.media, scope, db);+ } catch (error) {- if (- error instanceof MediaInvocationError &&- TERMINAL_MEDIA_RESULT_ERRORS.has(error.code)- ) {- await transitionMediaInvocation({- id: invocation.id,- owner: invocation.owner,- from: 'pending',- to: 'failed',- });++ assertAuthScope(scope, invocation.owner);++ if (error instanceof MediaInvocationError && TERMINAL_MEDIA_RESULT_ERRORS.has(error.code)) {++ await transitionMediaInvocation(++ {++ id: invocation.id,++ owner: invocation.owner,++ from: 'pending',++ to: 'failed',++ },++ db,++ );++ assertAuthScope(scope, invocation.owner);+ return failure(error.code, error.message);+ }+ throw error;+ }- await transitionMediaInvocation({- id: invocation.id,- owner: invocation.owner,- from: 'pending',- to: 'complete',- });++ await transitionMediaInvocation(++ {++ id: invocation.id,++ owner: invocation.owner,++ from: 'pending',++ to: 'complete',++ },++ db,++ );++ assertAuthScope(scope, invocation.owner);+ return { ok: true, status: 'complete', invocation_id: invocation.id, ...media };+ }+ if (guide.failureValues.includes(status)) {- await transitionMediaInvocation({- id: invocation.id,- owner: invocation.owner,- from: 'pending',- to: 'failed',- });++ await transitionMediaInvocation(++ {++ id: invocation.id,++ owner: invocation.owner,++ from: 'pending',++ to: 'failed',++ },++ db,++ );++ assertAuthScope(scope, invocation.owner);+ return failure('UPSTREAM_TASK_FAILED', `上游媒体任务失败,状态: ${status || 'unknown'}`);+ }+ return {+ ok: true,+ status: 'pending',+ invocation_id: invocation.id,+ upstream_status: status || 'unknown',+ recommended_poll_after_ms: guide.recommendedIntervalMs,+ };+ } catch (error) {+ if (error instanceof MediaInvocationError) {+ // Poll is read-only/idempotent: transient failure does not invalidate the submitted task.+ return failure(error.code, error.message, true);+ }+ return failure('POLL_UNAVAILABLE', '媒体任务状态查询失败', true);+ }+}++/** 当前 Agent 永久注册的 `mcp__cindy__media` 工具实现;不暴露给插件运行时。 */+export async function callCindyMedia(+ request: CindyMediaToolRequest,+): Promise<Record<string, unknown>> {+ try {+ if (request.action === 'list_models') {- const models = await listAvailableMediaModels(- request.capability as MediaCapability | undefined,++ const capability = request.capability as MediaCapability | undefined;++ const availability = await listExecutableMediaModels(++ capability ? [capability] : [],+ );++ if (availability.models.length === 0 && capability) {++ if (availability.candidateCount === 0) {++ return failure(++ 'CAPABILITY_NOT_SUPPORTED',++ '当前没有已启用模型声明支持该媒体能力',++ false,++ { outcomeKnown: true, allowedActions: ['use_another_tool'] },++ );++ }++ const upgradeRequired = availability.unavailable.some(++ (item) => item.errorCode === 'CLIENT_UPGRADE_REQUIRED',++ );++ const temporarilyUnavailable = availability.unavailable.some((item) => item.retryable);++ const errorCode = upgradeRequired++ ? 'CLIENT_UPGRADE_REQUIRED'++ : temporarilyUnavailable++ ? 'GUIDE_SERVICE_UNAVAILABLE'++ : 'GUIDE_NOT_AVAILABLE';++ const message = upgradeRequired++ ? '当前 Cindy 版本不支持可用模型的调用协议,请升级客户端或使用其他工具。'++ : temporarilyUnavailable++ ? '媒体调用说明暂时无法读取,请稍后重试或使用其他工具。'++ : '当前没有带可用调用说明的模型支持该媒体能力。';++ return failure(errorCode, message, temporarilyUnavailable, {++ outcomeKnown: true,++ allowedActions: GUIDE_FALLBACK_ACTIONS,++ });++ }+ return {+ ok: true,- models: models.map((model) => ({++ models: availability.models.map((model) => ({+ id: model.id,+ ...(model.name ? { name: model.name } : {}),+ ...(model.mode ? { mode: model.mode } : {}),+ })),++ ...(availability.unavailable.length > 0++ ? {++ unavailable_model_count: availability.unavailable.length,++ guidance: '部分模型当前不可执行;可使用返回的模型,或选择其他已授权工具。',++ }++ : {}),+ };+ }+ if (request.action === 'prepare') {+ return prepareInvocation(request.modelId, request.capability as MediaCapability);+ }+ const invocation = await requireInvocation(request.invocationId);+ return await (request.action === 'request'+ ? submitInvocation(invocation, request.body)+ : pollInvocation(invocation));+ } catch (error) {+ if (error instanceof MediaInvocationError) return failure(error.code, error.message);++ if (error instanceof MediaModelCatalogError) {++ log.warn('media model catalog rejected by current client', { detail: error.detail });++ return failure('MODEL_CATALOG_UNAVAILABLE', error.message, true, {++ outcomeKnown: true,++ allowedActions: ['use_another_tool'],++ });++ }++ if (error instanceof MediaGuideCompatibilityError) {++ return failure(error.code, error.message, false, {++ outcomeKnown: true,++ allowedActions: GUIDE_FALLBACK_ACTIONS,++ });++ }++ if (error instanceof ServerApiError) {++ return failure('MODEL_ACCESS_UNAVAILABLE', '媒体模型服务暂时不可用,请稍后重试', true, {++ outcomeKnown: true,++ allowedActions: ['use_another_tool'],++ });++ }+ log.warn('media tool call failed', {+ error: error instanceof Error ? error.message : String(error),+ });+ return failure('INTERNAL', error instanceof Error ? error.message : '媒体能力调用失败');+ }+}diff --cc apps/desktop/src/main/cindy-media/mediaInvocationStore.tsindex 45f5a577b2,0000000000..a8d76dd1ccmode 100644,000000..100644--- a/apps/desktop/src/main/cindy-media/mediaInvocationStore.ts+++ b/apps/desktop/src/main/cindy-media/mediaInvocationStore.ts@@@ -1,168 -1,0 +1,198 @@@+import type { MediaCapability } from '@cindy/model-providers';+import {+ parsePreparedMediaInvocationGuide,+ type PreparedMediaInvocationGuide,+} from '../../shared/mediaInvocation.js';++import type { DbClient } from '../localDb/client/DbClient.js';+import { getDbClient } from '../localDb/client/current.js';++export type MediaInvocationState =+ 'prepared' | 'submitting' | 'pending' | 'complete' | 'failed' | 'unknown';++export interface StoredMediaInvocation {+ id: string;+ owner: string;+ modelId: string;+ capability: MediaCapability;+ guideRevision: string;+ guide: PreparedMediaInvocationGuide;+ state: MediaInvocationState;+ taskId?: string;++ responseJson?: string;+ createdAt: number;+ updatedAt: number;+}++interface MediaInvocationRow {+ id: string;+ owner: string;+ modelId: string;+ capability: string;+ guideRevision: string;+ guideJson: string;+ state: MediaInvocationState;+ taskId: string | null;++ responseJson: string | null;+ createdAt: number;+ updatedAt: number;+}++function fromRow(row: MediaInvocationRow): StoredMediaInvocation {+ let rawGuide: unknown;+ try {+ rawGuide = JSON.parse(row.guideJson) as unknown;+ } catch {+ throw new Error(`媒体调用 ${row.id} 的 guide 快照不是合法 JSON`);+ }+ const parsed = parsePreparedMediaInvocationGuide(rawGuide);+ if (!parsed.ok) throw new Error(`媒体调用 ${row.id} 的 guide 快照不合法: ${parsed.error}`);+ if (+ parsed.value.modelId !== row.modelId ||+ parsed.value.capability !== row.capability ||+ parsed.value.revision !== row.guideRevision+ ) {+ throw new Error(`媒体调用 ${row.id} 的 guide 快照与索引字段不一致`);+ }+ return {+ id: row.id,+ owner: row.owner,+ modelId: row.modelId,+ capability: parsed.value.capability,+ guideRevision: row.guideRevision,+ guide: parsed.value,+ state: row.state,+ ...(row.taskId ? { taskId: row.taskId } : {}),++ ...(row.responseJson ? { responseJson: row.responseJson } : {}),+ createdAt: row.createdAt,+ updatedAt: row.updatedAt,+ };+}+- export async function recoverInterruptedMediaInvocations(owner: string): Promise<number> {- const result = await getDbClient().exec(++export async function recoverInterruptedMediaInvocations(++ owner: string,++ db: DbClient = getDbClient(),++): Promise<number> {++ const result = await db.exec(+ `UPDATE media_invocations+ SET state = 'unknown', updated_at = ?+ WHERE owner = ? AND state = 'submitting'`,+ [Date.now(), owner],+ );+ return Number(result.changes);+}+- export async function pruneMediaInvocations(input: {- owner: string;- preparedBefore: number;- terminalBefore: number;- }): Promise<void> {- await getDbClient().exec(++export async function pruneMediaInvocations(++ input: {++ owner: string;++ preparedBefore: number;++ terminalBefore: number;++ },++ db: DbClient = getDbClient(),++): Promise<void> {++ await db.exec(+ `DELETE FROM media_invocations+ WHERE owner = ? AND (+ (state = 'prepared' AND created_at < ?)+ OR (state IN ('pending', 'complete', 'failed', 'unknown') AND updated_at < ?)+ )`,+ [input.owner, input.preparedBefore, input.terminalBefore],+ );+}+- export async function countMediaInvocations(owner: string): Promise<number> {- const row = await getDbClient().queryOne<{ count: number }>(++export async function countMediaInvocations(++ owner: string,++ db: DbClient = getDbClient(),++): Promise<number> {++ const row = await db.queryOne<{ count: number }>(+ 'SELECT COUNT(*) AS count FROM media_invocations WHERE owner = ?',+ [owner],+ );+ return Number(row?.count ?? 0);+}+- export async function createMediaInvocation(input: {- id: string;- owner: string;- guide: PreparedMediaInvocationGuide;- createdAt: number;- }): Promise<void> {- await getDbClient().exec(++export async function createMediaInvocation(++ input: {++ id: string;++ owner: string;++ guide: PreparedMediaInvocationGuide;++ createdAt: number;++ },++ db: DbClient = getDbClient(),++): Promise<void> {++ await db.exec(+ `INSERT INTO media_invocations (+ id, owner, model_id, capability, guide_revision, guide_json,+ state, task_id, created_at, updated_at+ ) VALUES (?, ?, ?, ?, ?, ?, 'prepared', NULL, ?, ?)`,+ [+ input.id,+ input.owner,+ input.guide.modelId,+ input.guide.capability,+ input.guide.revision,+ JSON.stringify(input.guide),+ input.createdAt,+ input.createdAt,+ ],+ );+}++export async function getMediaInvocation(+ id: string,+ owner: string,++ db: DbClient = getDbClient(),+): Promise<StoredMediaInvocation | null> {- const row = await getDbClient().queryOne<MediaInvocationRow>(++ const row = await db.queryOne<MediaInvocationRow>(+ `SELECT+ id,+ owner,+ model_id AS modelId,+ capability,+ guide_revision AS guideRevision,+ guide_json AS guideJson,+ state,+ task_id AS taskId,++ response_json AS responseJson,+ created_at AS createdAt,+ updated_at AS updatedAt+ FROM media_invocations+ WHERE id = ? AND owner = ?`,+ [id, owner],+ );+ return row ? fromRow(row) : null;+}+- export async function transitionMediaInvocation(input: {- id: string;- owner: string;- from: MediaInvocationState;- to: MediaInvocationState;- taskId?: string;- }): Promise<boolean> {- const result = input.taskId- ? await getDbClient().exec(- `UPDATE media_invocations++export async function transitionMediaInvocation(++ input: {++ id: string;++ owner: string;++ from: MediaInvocationState;++ to: MediaInvocationState;++ taskId?: string;++ responseJson?: string;++ },++ db: DbClient = getDbClient(),++): Promise<boolean> {++ const result =++ input.taskId !== undefined++ ? await db.exec(++ `UPDATE media_invocations+ SET state = ?, task_id = ?, updated_at = ?+ WHERE id = ? AND owner = ? AND state = ?`,- [input.to, input.taskId, Date.now(), input.id, input.owner, input.from],- )- : await getDbClient().exec(- `UPDATE media_invocations++ [input.to, input.taskId, Date.now(), input.id, input.owner, input.from],++ )++ : input.responseJson !== undefined++ ? await db.exec(++ `UPDATE media_invocations++ SET state = ?, response_json = ?, updated_at = ?++ WHERE id = ? AND owner = ? AND state = ?`,++ [input.to, input.responseJson, Date.now(), input.id, input.owner, input.from],++ )++ : await db.exec(++ `UPDATE media_invocations+ SET state = ?, updated_at = ?+ WHERE id = ? AND owner = ? AND state = ?`,- [input.to, Date.now(), input.id, input.owner, input.from],- );++ [input.to, Date.now(), input.id, input.owner, input.from],++ );+ return Number(result.changes) === 1;+}diff --cc apps/desktop/src/main/localDb/schema.tsindex 366f3c6cfa,adda15792b..8b2319f8a9--- a/apps/desktop/src/main/localDb/schema.ts+++ b/apps/desktop/src/main/localDb/schema.ts@@@ -1556,35 -1558,6 +1558,36 @@@ export const mediaRefs = sqliteTable}),);+/**+ * Cindy Core 媒体模型调用记录。+ *+ * guideJson 固化 prepare 时取得的服务端调用说明,保证后续 request / poll+ * 不会因目录刷新而切换协议;submitting 是付费 POST 的单次消费闸门,进程+ * 中断后恢复为 unknown,禁止自动重提。+ */+export const mediaInvocations = sqliteTable(+ 'media_invocations',+ {+ id: text('id').primaryKey(),+ owner: text('owner').notNull(),+ modelId: text('model_id').notNull(),+ capability: text('capability').notNull(),+ guideRevision: text('guide_revision').notNull(),+ guideJson: text('guide_json').notNull(),+ state: text('state', {+ enum: ['prepared', 'submitting', 'pending', 'complete', 'failed', 'unknown'],+ }).notNull(),+ taskId: text('task_id'),++ responseJson: text('response_json'),+ createdAt: integer('created_at').notNull(),+ updatedAt: integer('updated_at').notNull(),+ },+ (t) => ({+ byOwnerCreatedAt: index('media_invocations_owner_created_at_idx').on(t.owner, t.createdAt),+ byOwnerState: index('media_invocations_owner_state_idx').on(t.owner, t.state),+ }),+);+/*** 意识聊天卡片(卡槽③海报模式)。*diff --cc apps/desktop/src/main/maker-host/__tests__/activeCatalogXdAvailability.test.tsindex 6dd6a205ce,1eed5d0118..3266a53670--- a/apps/desktop/src/main/maker-host/__tests__/activeCatalogXdAvailability.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/activeCatalogXdAvailability.test.ts@@@ -15,6 -15,6 +15,7 @@@ import { BUNDLED_CATALOG, type CatalogMimport {getActiveCatalog,++ getXdGatewayModels,resolveXdPiGatewayWireProtocol,setActiveCatalog,setAnthropicDiscoveredModels,@@@ -187,37 -192,6 +193,37 @@@ describe('XD 网关权威模型清单�expect(xdModels('codex').map((model) => model.id)).toEqual(['codex-native-only']);});- it('媒体 mode 条目不进入聊天目录,并重建设置页专属媒体清单', () => {++ it('媒体 mode 条目不进入聊天目录,并保留在原始 Gateway 快照', () => {+ setActiveCatalog(BUNDLED_CATALOG);+ setXdGatewayModels([+ {+ id: 'image-without-guide',+ mode: 'image_generation',+ agents: [],+ name: 'Image Without Guide',+ },+ {+ id: 'video-model',+ mode: 'video_generation',+ agents: [],+ name: 'Video Model',+ },+ {+ id: 'chat-model',+ mode: 'chat',+ agents: ['codex'],+ },+ ]);+- const xd = getActiveCatalog().providers.find((provider) => provider.id === 'xd');- expect(xd?.imageModels).toEqual([{ id: 'image-without-guide', name: 'Image Without Guide' }]);- expect(xd?.videoModels).toEqual([{ id: 'video-model', name: 'Video Model' }]);- expect(xd?.imageDefaults).toBeUndefined();- expect(xd?.videoDefaults).toBeUndefined();++ expect(getXdGatewayModels().map((model) => model.id)).toEqual([++ 'image-without-guide',++ 'video-model',++ 'chat-model',++ ]);+ expect(xdModels('claude-code')).toEqual([]);+ expect(xdModels('codex').map((model) => model.id)).toEqual(['chat-model']);+ });+it('perAgent 覆盖块按 tab 应用(cc 无 Fast + 1M 窗口;codex 保持基线)', () => {setActiveCatalog(BUNDLED_CATALOG);setXdGatewayModels([diff --cc apps/desktop/src/main/model-access/__tests__/mediaModels.test.tsindex a900ee7ed0,0000000000..623284c125mode 100644,000000..100644--- a/apps/desktop/src/main/model-access/__tests__/mediaModels.test.ts+++ b/apps/desktop/src/main/model-access/__tests__/mediaModels.test.ts@@@ -1,150 -1,0 +1,182 @@@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const serverApiFetchMock = vi.hoisted(() => vi.fn());+const readModelDisableOverridesMock = vi.hoisted(() => vi.fn());++vi.mock('../../serverApiClient.js', () => ({+ serverApiFetch: serverApiFetchMock,++ ServerApiError: class ServerApiError extends Error {++ constructor(++ readonly code: string,++ readonly statusCode: number,++ message: string,++ ) {++ super(message);++ }++ },+}));+vi.mock('../../clientEndpointsService.js', () => ({+ getClientEndpoint: vi.fn(() => 'https://model-access.example.com'),+}));+vi.mock('../../maker-host/model-disable-store.js', () => ({+ readModelDisableOverrides: readModelDisableOverridesMock,+}));+- import { fetchMediaInvocationGuide, listAvailableMediaModels } from '../mediaModels.js';++import {++ fetchMediaInvocationGuide,++ listAvailableMediaModels,++ MediaGuideCompatibilityError,++} from '../mediaModels.js';++const payload = {+ schemaVersion: 4 as const,+ models: [+ {+ id: 'image-without-guide',+ name: 'Image Without Guide',+ mode: 'image_generation',+ currency: 'CNY' as const,+ agents: [],+ modalities: { input: ['text'], output: ['image'] },+ },+ {+ id: 'image-with-guide',+ name: 'Image With Guide',+ mode: 'image_generation',+ currency: 'CNY' as const,+ agents: [],+ modalities: { input: ['text', 'image'], output: ['image'] },+ },+ {+ id: 'video-without-guide',+ name: 'Video Without Guide',+ mode: 'video_generation',+ currency: 'CNY' as const,+ agents: [],+ modalities: { input: ['text', 'image'], output: ['video'] },+ },+ {+ id: 'guide-only-chat',+ name: 'Guide Only Chat',+ mode: 'chat',+ currency: 'CNY' as const,+ contextWindow: 200_000,+ agents: ['codex' as const],+ perAgent: {+ codex: { wireProtocol: 'openai-responses' as const },+ },+ },+ ],+};++describe('listAvailableMediaModels', () => {+ beforeEach(() => {+ serverApiFetchMock.mockReset().mockResolvedValue(payload);+ readModelDisableOverridesMock.mockReset().mockReturnValue({});+ });++ it('不带操作筛选时按 Gateway mode 返回图片/视频模型', async () => {+ await expect(listAvailableMediaModels()).resolves.toMatchObject([+ { id: 'image-without-guide' },+ { id: 'image-with-guide' },+ { id: 'video-without-guide' },+ ]);+ });+- it('带操作筛选时仍只按 Gateway mode 过滤', async () => {++ it('带操作筛选时按 Gateway modalities 判断模型能力', async () => {+ await expect(listAvailableMediaModels('image.generate')).resolves.toMatchObject([+ { id: 'image-without-guide', modalities: { input: ['text'], output: ['image'] } },+ {+ id: 'image-with-guide',+ modalities: { input: ['text', 'image'], output: ['image'] },+ },+ ]);++ await expect(listAvailableMediaModels('image.edit')).resolves.toMatchObject([++ {++ id: 'image-with-guide',++ modalities: { input: ['text', 'image'], output: ['image'] },++ },++ ]);+ });++ it('叠加客户端现有 XD provider/model 停用准入', async () => {+ readModelDisableOverridesMock.mockReturnValueOnce({+ disabledModels: { 'xd:image-without-guide': true },+ });+ await expect(listAvailableMediaModels('image.generate')).resolves.toMatchObject([+ { id: 'image-with-guide' },+ ]);++ readModelDisableOverridesMock.mockReturnValueOnce({ disabledProviders: { xd: true } });+ await expect(listAvailableMediaModels()).resolves.toEqual([]);+ });++ it('拒绝旧版聊天目录,不把版本不匹配静默解释为空媒体列表', async () => {+ serverApiFetchMock.mockResolvedValueOnce({ ...payload, schemaVersion: 3 });+- await expect(listAvailableMediaModels()).rejects.toThrow('媒体模型目录响应版本必须是 4');++ await expect(listAvailableMediaModels()).rejects.toMatchObject({++ name: 'MediaModelCatalogError',++ });+ });++ it('只用 modelId 获取 Cindy Server Guide', async () => {+ serverApiFetchMock.mockResolvedValueOnce({+ modelId: 'image-with-guide',- wireModelId: 'wire-image-model',+ guide: {+ schemaVersion: 1,+ guideId: 'images-v1',+ revision: '2026-08-13.1',+ connection: { providerId: 'xd' },+ operations: [+ {+ capability: 'image.generate',+ request: {+ method: 'POST',+ path: '/images/generations',++ bodyEncoding: 'json',+ bodyModelPath: ['model'],+ timeoutMs: 1_000,+ maxRequestBytes: 1_024,+ maxResponseBytes: 1_024,+ },+ response: {+ mode: 'sync',+ media: [+ {+ path: ['data', '*', 'url'],+ encoding: 'url',+ kind: 'image',+ allowedUrlHosts: ['example.com'],+ },+ ],+ },+ instructions: '按协议组装请求。',+ exampleBody: { prompt: 'hello' },+ inputSchema: { type: 'object' },+ officialDocs: 'https://example.com/images-api',+ },+ ],+ },+ });++ await expect(fetchMediaInvocationGuide('image-with-guide')).resolves.toMatchObject({+ modelId: 'image-with-guide',+ guide: { guideId: 'images-v1', revision: '2026-08-13.1' },+ });+ expect(serverApiFetchMock).toHaveBeenLastCalledWith(+ '/api/model-access/invocation-guide?modelId=image-with-guide',+ expect.any(Object),+ );+ });++++ it('把更高 Guide schemaVersion 分类为客户端需要升级', async () => {++ serverApiFetchMock.mockResolvedValueOnce({++ modelId: 'image-with-guide',++ guide: { schemaVersion: 2 },++ });++++ await expect(fetchMediaInvocationGuide('image-with-guide')).rejects.toMatchObject({++ code: 'CLIENT_UPGRADE_REQUIRED',++ } satisfies Partial<MediaGuideCompatibilityError>);++ });+});diff --cc apps/desktop/src/main/model-access/index.tsindex efdc0d08f6,d988fe235a..ed0d14e7e7--- a/apps/desktop/src/main/model-access/index.ts+++ b/apps/desktop/src/main/model-access/index.ts@@@ -36,6 -36,6 +36,10 @@@ import} from './modelsSyncRefresh.js';import { getGhostSetupChangeBus } from '../cindy-brain/ghostSetupChangeBus.js';import { hasAuthSessionIdentityChanged } from './authSessionIdentity.js';++import {++ listExecutableMediaModels,++ resetExecutableMediaModelCache,++} from './mediaModels.js';export { isModelAccessReady } from './readiness.js';const log = createLogger('modelAccess');@@@ -125,11 -125,9 +129,11 @@@ function broadcastStatus(status: ModelA}// ─── XD 网关模型目录同步(`/models` 是模型、能力与价格的唯一事实源)─────────-// 凭据同步成功后从 model-access-server 拉 GET /models(AIGateway /model-groups-// 的 mode=chat 投影),整体重建 xd 供应商的模型列表(active-catalog-// setXdGatewayModels)。拉取失败保留最后一次完整成功快照;成功空列表同时清空模型和价格。+// 凭据同步成功后从 model-access-server 拉现有 GET /models:聊天模型与+// 媒体模型都来自同一份 AIGateway /model-groups 投影。active-catalog 按 agents- // 重建聊天目录,并按 mode 重建 XD 专属媒体清单供设置页沿用模型停用逻辑;Core- // 媒体工具和插件也只按 mode 投影。调用时只按 modelId 向 Server 懒取 Guide。++// 重建聊天目录;媒体存在性仍按 mode,客户端另行预检 Guide operation 与执行器兼容性,++// 只把当前可执行投影交给插件设置和 Core media。调用时仍按 modelId 再取 Guide 复验。+// 拉取失败保留最后一次完整成功快照;成功空列表同时清空模型和价格。let modelsSyncInflight: Promise<void> | null = null;/** 模型请求的单调尝试号与最近成功号,供手动刷新区分“旧成功 + 本次失败”。 */@@@ -167,6 -165,6 +171,7 @@@ function applyGatewayModels(models: Mod// 一次归一化成 contextWindow / agents / efforts / supportsFastMode / modalities,// 同一含义只下发一个字段。这里直接用下发值,唯一事实源在服务端。// active-catalog 统一收口会原地刷新 Maker capabilities,再广播同一 revision。++ resetExecutableMediaModelCache();setXdGatewayModels(models);}@@@ -204,6 -202,6 +209,27 @@@ async function runModelsSync}log.info(`xd gateway models synced: ${models.length}`);applyGatewayModels(models, authenticatedUserId);++ try {++ const availability = await listExecutableMediaModels([], {++ includeDisabled: true,++ forceRefresh: true,++ });++ if (myGen !== authGeneration) return;++ // executable cache 已按当前客户端 Guide 能力重建;再次提升 catalog revision,++ // 让同步读取插件设置的界面从临时空清单刷新到可执行投影。++ setXdGatewayModels(models);++ if (availability.unavailable.length > 0) {++ log.warn('xd media Guide preflight isolated unavailable models', {++ unavailableModelCount: availability.unavailable.length,++ });++ }++ } catch (error) {++ // 原始模型目录仍然有效;Guide 预检失败只让媒体可执行投影保持为空,++ // 不能撤销聊天目录或拖垮登录后的模型同步。++ log.warn('xd media Guide preflight failed; keeping media execution disabled', {++ error: error instanceof Error ? error.message : String(error),++ });++ }lastModelsSyncSucceededAttempt = myAttempt;}diff --cc apps/desktop/src/main/model-access/mediaModels.tsindex 7f949870ba,0000000000..5485e450eemode 100644,000000..100644--- a/apps/desktop/src/main/model-access/mediaModels.ts+++ b/apps/desktop/src/main/model-access/mediaModels.ts@@@ -1,92 -1,0 +1,446 @@@+import {+ isModelDisabled,+ isProviderDisabled,+ MODEL_ACCESS_CATALOG_SCHEMA_VERSION,+ MODEL_ACCESS_MODELS_PATH,+ parseListModelsResponse,+ type MediaCapability,+ type ModelDisableOverrides,+ type ModelCatalogEntry,+} from '@cindy/model-providers';+import {+ MODEL_ACCESS_INVOCATION_GUIDE_PATH,++ MODEL_ACCESS_INVOCATION_GUIDES_PATH,++ MODEL_ACCESS_INVOCATION_GUIDE_SCHEMA_VERSION,+ parseResolvedMediaInvocationGuide,+ type ResolvedMediaInvocationGuide,+} from '../../shared/mediaInvocation.js';+import { getClientEndpoint } from '../clientEndpointsService.js';+import { readModelDisableOverrides } from '../maker-host/model-disable-store.js';- import { serverApiFetch } from '../serverApiClient.js';++import { serverApiFetch, ServerApiError } from '../serverApiClient.js';++const MEDIA_MODEL_REQUEST_TIMEOUT_MS = 20_000;++const MEDIA_GUIDE_PREFLIGHT_TIMEOUT_MS = 5_000;+const CINDY_AI_PROVIDER_ID = 'xd';+const MEDIA_MODELS_PATH =+ `${MODEL_ACCESS_MODELS_PATH}?schemaVersion=${MODEL_ACCESS_CATALOG_SCHEMA_VERSION}` as const;+++export type MediaGuideCompatibilityErrorCode =++ | 'CLIENT_UPGRADE_REQUIRED'++ | 'GUIDE_INVALID';++++export class MediaGuideCompatibilityError extends Error {++ constructor(++ readonly code: MediaGuideCompatibilityErrorCode,++ message: string,++ readonly detail?: string,++ ) {++ super(message);++ this.name = 'MediaGuideCompatibilityError';++ }++}++++export class MediaModelCatalogError extends Error {++ constructor(++ message: string,++ readonly detail?: string,++ ) {++ super(message);++ this.name = 'MediaModelCatalogError';++ }++}++++export interface UnavailableMediaModel {++ modelId: string;++ errorCode:++ | MediaGuideCompatibilityErrorCode++ | 'GUIDE_NOT_AVAILABLE'++ | 'GUIDE_SERVICE_UNAVAILABLE'++ | 'CAPABILITY_NOT_SUPPORTED';++ message: string;++ retryable: boolean;++}++++export interface ExecutableMediaModelsResult {++ models: ModelCatalogEntry[];++ unavailable: UnavailableMediaModel[];++ candidateCount: number;++}++++interface ExecutableMediaSnapshot {++ models: ModelCatalogEntry[];++ capabilitiesByModel: Map<string, ReadonlySet<MediaCapability>>;++ unavailableByModel: Map<string, UnavailableMediaModel>;++}++++const MEDIA_GUIDE_REFRESH_BACKOFF_INITIAL_MS = 30_000;++const MEDIA_GUIDE_REFRESH_BACKOFF_MAX_MS = 5 * 60_000;++++let executableMediaSnapshot: ExecutableMediaSnapshot | null = null;++let executableMediaRefreshInflight: Promise<ExecutableMediaSnapshot> | null = null;++let executableMediaCacheGeneration = 0;++let executableMediaRefreshFailures = 0;++let executableMediaNextRefreshAt = 0;++let executableMediaLastRefreshError: unknown = null;++++export function resetExecutableMediaModelCache(): void {++ executableMediaCacheGeneration += 1;++ executableMediaSnapshot = null;++ executableMediaRefreshInflight = null;++ executableMediaRefreshFailures = 0;++ executableMediaNextRefreshAt = 0;++ executableMediaLastRefreshError = null;++}++++export function isMediaModelExecutable(++ modelId: string,++ capability: MediaCapability,++): boolean {++ return executableMediaSnapshot?.capabilitiesByModel.get(modelId)?.has(capability) === true;++}++++const MEDIA_CAPABILITY_REQUIREMENTS: Record<++ MediaCapability,++ { input: string[]; inputAny?: string[]; output: string }++> = {++ 'image.generate': { input: ['text'], output: 'image' },++ 'image.edit': { input: ['text', 'image'], output: 'image' },++ 'video.generate': { input: ['text'], output: 'video' },++ 'video.image_to_video': { input: ['text', 'image'], output: 'video' },++};++++export function supportsMediaCapability(++ modalities: { input: string[]; output: string[] } | undefined,++ capability: MediaCapability,++): boolean {++ if (!modalities) return false;++ const requirement = MEDIA_CAPABILITY_REQUIREMENTS[capability];++ const inputs = new Set(modalities.input);++ return (++ modalities.output.includes(requirement.output) &&++ requirement.input.every((input) => inputs.has(input)) &&++ (requirement.inputAny === undefined || requirement.inputAny.some((input) => inputs.has(input)))++ );++}+++/**+ * Gateway mode 决定媒体类型;客户端沿用既有 provider/model 停用准入。+ * `defaultEnabled` 是聊天选择器的默认展示轴,不参与媒体能力准入。+ */- export function filterEnabledGatewayMediaModels<T extends { id: string; mode?: string }>(++export function filterEnabledGatewayMediaModels<++ T extends {++ id: string;++ mode?: string;++ modalities?: { input: string[]; output: string[] };++ },++>(+ models: readonly T[],+ capability: MediaCapability | undefined,+ access: ModelDisableOverrides | undefined,+): T[] {+ if (isProviderDisabled(access, CINDY_AI_PROVIDER_ID)) return [];+ return models.filter((model) => {+ if (isModelDisabled(access, CINDY_AI_PROVIDER_ID, model.id)) return false;- if (capability?.startsWith('image.')) return model.mode === 'image_generation';- if (capability?.startsWith('video.')) return model.mode === 'video_generation';- if (capability !== undefined) return false;++ if (capability?.startsWith('image.') && model.mode !== 'image_generation') return false;++ if (capability?.startsWith('video.') && model.mode !== 'video_generation') return false;++ if (capability !== undefined) return supportsMediaCapability(model.modalities, capability);+ return model.mode === 'image_generation' || model.mode === 'video_generation';+ });+}++/**+ * Cindy Core 的媒体模型发现入口。模型仍来自 Model Access 对 Gateway model-groups+ * 的实时投影;Gateway mode 决定图片/视频模型类型。Guide 独立按 modelId+ * 懒取,不参与模型发现。+ */- export async function listAvailableMediaModels(- capability?: MediaCapability,- ): Promise<ModelCatalogEntry[]> {++async function fetchGatewayMediaModels(): Promise<ModelCatalogEntry[]> {+ const payload = await serverApiFetch<unknown>(MEDIA_MODELS_PATH, {+ baseUrl: () => getClientEndpoint('modelAccessApiBaseUrl'),+ timeoutMs: MEDIA_MODEL_REQUEST_TIMEOUT_MS,+ logLabel: MEDIA_MODELS_PATH,+ });+ if (+ typeof payload !== 'object' ||+ payload === null ||+ !('schemaVersion' in payload) ||+ payload.schemaVersion !== MODEL_ACCESS_CATALOG_SCHEMA_VERSION+ ) {- throw new Error(`媒体模型目录响应版本必须是 ${MODEL_ACCESS_CATALOG_SCHEMA_VERSION}`);++ throw new MediaModelCatalogError(++ '媒体模型目录当前不可用,请稍后重试或使用其他工具。',++ `expected schemaVersion ${MODEL_ACCESS_CATALOG_SCHEMA_VERSION}`,++ );+ }+ const parsed = parseListModelsResponse(payload);- if (!parsed.ok) throw new Error(`媒体模型目录响应不合法: ${parsed.error}`);++ if (!parsed.ok) {++ throw new MediaModelCatalogError(++ '媒体模型目录当前不可用,请稍后重试或使用其他工具。',++ parsed.error,++ );++ }++ return parsed.value.models.filter(++ (model) => model.mode === 'image_generation' || model.mode === 'video_generation',++ );++}++++export async function listAvailableMediaModels(++ capability?: MediaCapability,++): Promise<ModelCatalogEntry[]> {+ return filterEnabledGatewayMediaModels(- parsed.value.models,++ await fetchGatewayMediaModels(),+ capability,+ readModelDisableOverrides(),+ );+}++export async function fetchMediaInvocationGuide(+ modelId: string,++ timeoutMs = MEDIA_MODEL_REQUEST_TIMEOUT_MS,+): Promise<ResolvedMediaInvocationGuide> {+ const query = new URLSearchParams({ modelId });+ const payload = await serverApiFetch<unknown>(+ `${MODEL_ACCESS_INVOCATION_GUIDE_PATH}?${query.toString()}`,+ {+ baseUrl: () => getClientEndpoint('modelAccessApiBaseUrl'),- timeoutMs: MEDIA_MODEL_REQUEST_TIMEOUT_MS,++ timeoutMs,+ logLabel: MODEL_ACCESS_INVOCATION_GUIDE_PATH,+ },+ );++ return parseResolvedGuidePayload(payload, modelId);++}++++function parseResolvedGuidePayload(++ payload: unknown,++ modelId: string,++): ResolvedMediaInvocationGuide {++ const guide =++ payload && typeof payload === 'object' && 'guide' in payload++ ? (payload as { guide?: unknown }).guide++ : undefined;++ const schemaVersion =++ guide && typeof guide === 'object' && 'schemaVersion' in guide++ ? (guide as { schemaVersion?: unknown }).schemaVersion++ : undefined;++ if (++ typeof schemaVersion === 'number' &&++ schemaVersion !== MODEL_ACCESS_INVOCATION_GUIDE_SCHEMA_VERSION++ ) {++ throw new MediaGuideCompatibilityError(++ 'CLIENT_UPGRADE_REQUIRED',++ '当前 Cindy 版本不支持该模型的调用协议,请升级客户端或更换模型。',++ `unsupported Guide schemaVersion: ${schemaVersion}`,++ );++ }+ const parsed = parseResolvedMediaInvocationGuide(payload);- if (!parsed.ok) throw new Error(`媒体模型调用说明不合法: ${parsed.error}`);++ if (!parsed.ok) {++ throw new MediaGuideCompatibilityError(++ 'GUIDE_INVALID',++ '该模型的调用说明当前不可用,请更换模型或稍后重试。',++ parsed.error,++ );++ }+ if (parsed.value.modelId !== modelId) {- throw new Error('媒体模型调用说明与请求的模型不一致');++ throw new MediaGuideCompatibilityError(++ 'GUIDE_INVALID',++ '该模型的调用说明当前不可用,请更换模型或稍后重试。',++ 'resolved Guide modelId does not match request',++ );+ }+ return parsed.value;+}++++async function fetchMediaInvocationGuideBatch(): Promise<{++ byModel: Map<string, unknown>;++ duplicateModelIds: Set<string>;++}> {++ const payload = await serverApiFetch<unknown>(MODEL_ACCESS_INVOCATION_GUIDES_PATH, {++ baseUrl: () => getClientEndpoint('modelAccessApiBaseUrl'),++ timeoutMs: MEDIA_GUIDE_PREFLIGHT_TIMEOUT_MS,++ logLabel: MODEL_ACCESS_INVOCATION_GUIDES_PATH,++ });++ if (++ !payload ||++ typeof payload !== 'object' ||++ !('guides' in payload) ||++ !Array.isArray((payload as { guides?: unknown }).guides) ||++ (payload as { guides: unknown[] }).guides.length > 256++ ) {++ throw new MediaModelCatalogError(++ '媒体调用说明目录当前不可用,请稍后重试或使用其他工具。',++ 'batch Guide response must contain a bounded guides array',++ );++ }++ const byModel = new Map<string, unknown>();++ const duplicateModelIds = new Set<string>();++ for (const value of (payload as { guides: unknown[] }).guides) {++ const modelId =++ value && typeof value === 'object' && 'modelId' in value++ ? (value as { modelId?: unknown }).modelId++ : undefined;++ if (typeof modelId !== 'string' || modelId.length === 0 || modelId.length > 256) continue;++ if (byModel.has(modelId)) {++ byModel.delete(modelId);++ duplicateModelIds.add(modelId);++ continue;++ }++ if (!duplicateModelIds.has(modelId)) byModel.set(modelId, value);++ }++ return { byModel, duplicateModelIds };++}++++function unavailableFromGuideError(modelId: string, error: unknown): UnavailableMediaModel {++ if (error instanceof MediaGuideCompatibilityError) {++ return {++ modelId,++ errorCode: error.code,++ message: error.message,++ retryable: false,++ };++ }++ if (++ error instanceof ServerApiError &&++ error.code === 'MEDIA_INVOCATION_GUIDE_NOT_FOUND'++ ) {++ return {++ modelId,++ errorCode: 'GUIDE_NOT_AVAILABLE',++ message: '该模型当前没有可用的调用说明。',++ retryable: false,++ };++ }++ return {++ modelId,++ errorCode: 'GUIDE_SERVICE_UNAVAILABLE',++ message: '媒体调用说明暂时无法读取,请稍后重试或选择其他工具。',++ retryable: true,++ };++}++++async function buildExecutableMediaSnapshot(): Promise<ExecutableMediaSnapshot> {++ const models = await fetchGatewayMediaModels();++ const batch = await fetchMediaInvocationGuideBatch();++ const capabilitiesByModel = new Map<string, ReadonlySet<MediaCapability>>();++ const unavailableByModel = new Map<string, UnavailableMediaModel>();++++ for (const model of models) {++ if (batch.duplicateModelIds.has(model.id)) {++ unavailableByModel.set(model.id, {++ modelId: model.id,++ errorCode: 'GUIDE_INVALID',++ message: '该模型存在重复调用说明,请更换模型或稍后重试。',++ retryable: false,++ });++ continue;++ }++ const rawGuide = batch.byModel.get(model.id);++ if (rawGuide === undefined) {++ unavailableByModel.set(model.id, {++ modelId: model.id,++ errorCode: 'GUIDE_NOT_AVAILABLE',++ message: '该模型当前没有可用的调用说明。',++ retryable: false,++ });++ continue;++ }++ try {++ const resolvedGuide = parseResolvedGuidePayload(rawGuide, model.id);++ const operations = new Set(++ resolvedGuide.guide.operations++ .filter((operation) => supportsMediaCapability(model.modalities, operation.capability))++ .map((operation) => operation.capability),++ );++ if (operations.size === 0) {++ unavailableByModel.set(model.id, {++ modelId: model.id,++ errorCode: 'CAPABILITY_NOT_SUPPORTED',++ message: '该模型当前没有客户端可执行的媒体能力。',++ retryable: false,++ });++ continue;++ }++ capabilitiesByModel.set(model.id, operations);++ } catch (error) {++ unavailableByModel.set(model.id, unavailableFromGuideError(model.id, error));++ }++ }++++ return { models, capabilitiesByModel, unavailableByModel };++}++++async function getExecutableMediaSnapshot(forceRefresh = false): Promise<ExecutableMediaSnapshot> {++ if (executableMediaSnapshot && !forceRefresh) return executableMediaSnapshot;++ if (executableMediaRefreshInflight) return executableMediaRefreshInflight;++ if (!forceRefresh && Date.now() < executableMediaNextRefreshAt) {++ if (executableMediaSnapshot) return executableMediaSnapshot;++ throw (++ executableMediaLastRefreshError ??++ new MediaModelCatalogError('媒体调用说明目录暂时不可用,请稍后重试。')++ );++ }++++ const generation = executableMediaCacheGeneration;++ const refresh = buildExecutableMediaSnapshot();++ executableMediaRefreshInflight = refresh;++ try {++ const snapshot = await refresh;++ if (generation !== executableMediaCacheGeneration) {++ throw new MediaModelCatalogError('媒体模型目录身份已变化,请重试。');++ }++ executableMediaSnapshot = snapshot;++ executableMediaRefreshFailures = 0;++ executableMediaNextRefreshAt = 0;++ executableMediaLastRefreshError = null;++ return snapshot;++ } catch (error) {++ if (generation === executableMediaCacheGeneration) {++ executableMediaRefreshFailures += 1;++ const multiplier = 2 ** Math.min(executableMediaRefreshFailures - 1, 10);++ executableMediaNextRefreshAt =++ Date.now() +++ Math.min(++ MEDIA_GUIDE_REFRESH_BACKOFF_INITIAL_MS * multiplier,++ MEDIA_GUIDE_REFRESH_BACKOFF_MAX_MS,++ );++ executableMediaLastRefreshError = error;++ }++ if (executableMediaSnapshot) return executableMediaSnapshot;++ throw error;++ } finally {++ if (executableMediaRefreshInflight === refresh) executableMediaRefreshInflight = null;++ }++}++++/**++ * 当前客户端真正可执行的媒体模型投影。一次批量 Guide 成功会重建全部图片/视频能力;++ * 后续调用只读内存,目录或身份变化时由 reset 显式失效。++ */++export async function listExecutableMediaModels(++ capabilities: readonly MediaCapability[] = [],++ options: { includeDisabled?: boolean; forceRefresh?: boolean } = {},++): Promise<ExecutableMediaModelsResult> {++ const snapshot = await getExecutableMediaSnapshot(options.forceRefresh === true);++ const candidates = filterEnabledGatewayMediaModels(++ snapshot.models,++ undefined,++ options.includeDisabled ? undefined : readModelDisableOverrides(),++ ).filter((model) =>++ capabilities.every((capability) => supportsMediaCapability(model.modalities, capability)),++ );++ const models: ModelCatalogEntry[] = [];++ const unavailable: UnavailableMediaModel[] = [];++ for (const model of candidates) {++ const supported = snapshot.capabilitiesByModel.get(model.id);++ if (supported && capabilities.every((capability) => supported.has(capability))) {++ models.push(model);++ continue;++ }++ unavailable.push(++ snapshot.unavailableByModel.get(model.id) ?? {++ modelId: model.id,++ errorCode: 'CAPABILITY_NOT_SUPPORTED',++ message: '该模型的调用协议不包含请求的媒体能力。',++ retryable: false,++ },++ );++ }++ return { models, unavailable, candidateCount: candidates.length };++}diff --cc apps/desktop/src/shared/ghost.tsindex c3bbc227fa,5bd8a41548..afd7606b0b--- a/apps/desktop/src/shared/ghost.ts+++ b/apps/desktop/src/shared/ghost.ts@@@ -6026,51 -6032,6 +6096,51 @@@ export interface GhostAppContextResult};}+/** 插件设置页 / 面板可读取的 Cindy Core 媒体模型类型。 */+export const GHOST_MEDIA_MODEL_TYPES = ['image', 'video'] as const;+export type GhostMediaModelType = (typeof GHOST_MEDIA_MODEL_TYPES)[number];++/** Host「Cindy 能力」区域现有的四项媒体模型配置键。 */+export const GHOST_MEDIA_CAPABILITIES = [+ 'image.generate',+ 'image.edit',+ 'video.generate',+ 'video.edit',+] as const;+export type GhostMediaCapability = (typeof GHOST_MEDIA_CAPABILITIES)[number];++/** 插件读取自身某项 Cindy 媒体能力当前实际选型的只读结果。 */+export type GhostCindyPreferenceResult =+ | { ok: true; capability: GhostMediaCapability; modelId: string }+ | {+ ok: false;+ errorCode: 'INVALID_REQUEST' | 'PERMISSION_DENIED' | 'NOT_AVAILABLE';+ message: string;+ };++/**- * 插件配置界面使用的只读媒体模型目录。模型类型来自 Gateway mode;输入/输出能力- * 原样使用 Model Access 已归一化的 modalities,由插件自行解释,不在 Host 内映射成- * 出图、改图或图生视频等业务动作。Guide 是独立可选信息,不进入这份配置契约。++ * 插件配置界面使用的只读可执行媒体模型目录。Host 根据插件声明、Gateway modalities、++ * Guide operation 与当前客户端协议支持度过滤模型;响应只保留归一化 modalities,++ * 不向插件暴露 Guide 或内部兼容判定。+ */+export type GhostMediaModelsResult =+ | {+ ok: true;+ type: GhostMediaModelType;+ models: Array<{+ id: string;+ name: string;+ /** Gateway architecture 的归一化投影;缺省表示上游未声明,插件不得猜测。 */+ modalities?: { input: string[]; output: string[] };+ }>;+ defaultModelId: string | null;+ }+ | {+ ok: false;+ errorCode: 'PERMISSION_DENIED' | 'NOT_AVAILABLE';+ message: string;+ };+/*** 上行:聊天卡片供片(卡槽③海报模式)。意识为自己的一次 tool-call* 提供聊天流卡片内容:收到 tool-call 后即可发第一版(过程海报),执行中diff --cc apps/desktop/src/shared/mediaInvocation.tsindex 10a2fbe75d,0000000000..9b5657b7f1mode 100644,000000..100644--- a/apps/desktop/src/shared/mediaInvocation.ts+++ b/apps/desktop/src/shared/mediaInvocation.ts@@@ -1,493 -1,0 +1,550 @@@+import {+ MODEL_ACCESS_MEDIA_CAPABILITIES,+ type MediaCapability,+ type ModelAccessParseResult,+} from '@cindy/model-providers';++export const MODEL_ACCESS_INVOCATION_GUIDE_SCHEMA_VERSION = 1 as const;+export const MODEL_ACCESS_INVOCATION_GUIDE_PATH = '/api/model-access/invocation-guide' as const;++export const MODEL_ACCESS_INVOCATION_GUIDES_PATH = '/api/model-access/invocation-guides' as const;++export type MediaResultKind = 'image' | 'video' | 'audio';++export type MediaRequestBodyEncoding = 'json' | 'multipart';++export interface MediaResultExtractor {+ path: string[];+ encoding: 'url' | 'base64';+ kind: MediaResultKind;+ mediaType?: string;+ allowedUrlHosts?: string[];+}++export interface MediaHttpRequestGuide {+ method: 'POST';+ path: string;+ headers?: Record<string, string>;++ /** Defaults to JSON for persisted/older schemaVersion 1 Guides. */++ bodyEncoding?: MediaRequestBodyEncoding;+ bodyModelPath: string[];++ multipartFiles?: MediaMultipartFileGuide[];+ timeoutMs: number;+ maxRequestBytes: number;+ maxResponseBytes: number;+}+++export interface MediaMultipartFileGuide {++ bodyField: string;++ formField: string;++ kind: MediaResultKind;++ maxItems: number;++}+++export interface MediaSyncResponseGuide {+ mode: 'sync';+ media: MediaResultExtractor[];+}++export interface MediaAsyncPollGuide {+ method: 'GET' | 'POST';+ path: string;+ headers?: Record<string, string>;+ bodyTaskIdPath?: string[];+ statusPath: string[];+ successValues: string[];+ failureValues: string[];+ recommendedIntervalMs: number;+ timeoutMs: number;+ maxResponseBytes: number;+ media: MediaResultExtractor[];+}++export interface MediaAsyncResponseGuide {+ mode: 'async';+ taskIdPath: string[];+ poll: MediaAsyncPollGuide;+}++export interface MediaInvocationOperationGuide {+ capability: MediaCapability;+ request: MediaHttpRequestGuide;+ response: MediaSyncResponseGuide | MediaAsyncResponseGuide;+ instructions: string;+ exampleBody: Record<string, unknown>;+ inputSchema: Record<string, unknown>;+ officialDocs: string;+}++export interface MediaInvocationGuide {+ schemaVersion: typeof MODEL_ACCESS_INVOCATION_GUIDE_SCHEMA_VERSION;+ guideId: string;+ revision: string;+ connection: { providerId: string };+ operations: MediaInvocationOperationGuide[];+}++export interface ResolvedMediaInvocationGuide {+ modelId: string;- wireModelId: string;+ guide: MediaInvocationGuide;+}++/** Persisted snapshot after `prepare` selects one operation from the Server Guide. */+export type PreparedMediaInvocationGuide = Omit<MediaInvocationGuide, 'operations'> &- Pick<ResolvedMediaInvocationGuide, 'modelId' | 'wireModelId'> &++ Pick<ResolvedMediaInvocationGuide, 'modelId'> &+ MediaInvocationOperationGuide;++type PlainObject = Record<string, unknown>;++const FORBIDDEN_HEADERS = new Set([+ 'authorization',+ 'cookie',+ 'host',+ 'content-length',++ 'content-type',+ 'proxy-authorization',+ 'proxy-authenticate',+ 'transfer-encoding',+ 'connection',+ 'trailer',+ 'upgrade',+ 'te',+]);+const GUIDE_FIELDS = [+ 'schemaVersion',+ 'guideId',+ 'revision',+ 'connection',+ 'operations',+] as const;- const RESOLVED_GUIDE_FIELDS = ['modelId', 'wireModelId', 'guide'] as const;++const RESOLVED_GUIDE_FIELDS = ['modelId', 'guide'] as const;+const OPERATION_FIELDS = [+ 'capability',+ 'request',+ 'response',+ 'instructions',+ 'exampleBody',+ 'inputSchema',+ 'officialDocs',+] as const;+const PREPARED_GUIDE_FIELDS = [+ 'schemaVersion',+ 'guideId',+ 'modelId',- 'wireModelId',+ 'revision',+ 'connection',+ ...OPERATION_FIELDS,+] as const;++function ok<T>(value: T): ModelAccessParseResult<T> {+ return { ok: true, value };+}++function fail<T>(error: string): ModelAccessParseResult<T> {+ return { ok: false, error };+}++function isPlainObject(value: unknown): value is PlainObject {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+}++function unknownField(value: PlainObject, allowed: readonly string[], path: string): string | null {+ const names = new Set(allowed);+ const field = Object.keys(value).find((candidate) => !names.has(candidate));+ return field ? `${path}.${field} is not allowed` : null;+}++function boundedString(value: unknown, max: number): value is string {+ return typeof value === 'string' && value.length > 0 && value.length <= max;+}++function objectPathError(value: unknown, path: string): string | null {+ if (+ !Array.isArray(value) ||+ value.length === 0 ||+ value.length > 24 ||+ value.some(+ (segment) =>+ !boundedString(segment, 128) ||+ ['__proto__', 'prototype', 'constructor'].includes(segment),+ )+ ) {+ return `${path} must be a non-empty bounded string path`;+ }+ return null;+}++function relativePathError(value: unknown, path: string, allowTaskId: boolean): string | null {+ const containsControlCharacter =+ typeof value === 'string' &&+ [...value].some((character) => {+ const code = character.charCodeAt(0);+ return code <= 0x1f || code === 0x7f;+ });+ if (+ !boundedString(value, 2_048) ||+ !value.startsWith('/') ||+ value.startsWith('//') ||+ value.includes('://') ||+ value.includes('\\') ||+ containsControlCharacter+ ) {+ return `${path} must be a relative HTTP path`;+ }+ if (!allowTaskId && value.includes('{taskId}')) return `${path} cannot contain {taskId}`;+ if (/\{(?!taskId\})/.test(value)) return `${path} contains an unsupported template`;+ return null;+}++function positiveIntegerError(+ value: unknown,+ path: string,+ min: number,+ max: number,+): string | null {+ return !Number.isInteger(value) || (value as number) < min || (value as number) > max+ ? `${path} must be an integer between ${min} and ${max}`+ : null;+}++function headersError(value: unknown, path: string): string | null {+ if (value === undefined) return null;+ if (!isPlainObject(value) || Object.keys(value).length > 16) {+ return `${path} must be an object with at most 16 fields`;+ }+ for (const [name, headerValue] of Object.entries(value)) {+ if (!/^[A-Za-z0-9-]{1,64}$/.test(name) || FORBIDDEN_HEADERS.has(name.toLowerCase())) {+ return `${path}.${name} is not an allowed fixed header`;+ }+ if (typeof headerValue !== 'string' || headerValue.length > 1_024 || /[\r\n]/.test(headerValue)) {+ return `${path}.${name} must be a bounded string`;+ }+ }+ return null;+}++function extractorError(value: unknown, path: string): string | null {+ if (!isPlainObject(value)) return `${path} must be an object`;+ let error = unknownField(+ value,+ ['path', 'encoding', 'kind', 'mediaType', 'allowedUrlHosts'],+ path,+ );+ if (error) return error;+ error = objectPathError(value.path, `${path}.path`);+ if (error) return error;+ if (value.encoding !== 'url' && value.encoding !== 'base64') {+ return `${path}.encoding must be url or base64`;+ }+ if (value.kind !== 'image' && value.kind !== 'video' && value.kind !== 'audio') {+ return `${path}.kind must be image, video or audio`;+ }+ if (value.mediaType !== undefined && !boundedString(value.mediaType, 128)) {+ return `${path}.mediaType must be a bounded string when present`;+ }+ if (value.encoding === 'url') {+ if (+ !Array.isArray(value.allowedUrlHosts) ||+ value.allowedUrlHosts.length === 0 ||+ value.allowedUrlHosts.length > 16 ||+ value.allowedUrlHosts.some(+ (host) =>+ typeof host !== 'string' ||+ !/^[a-z0-9.-]{1,253}$/i.test(host) ||+ !host.includes('.') ||+ /^\d+(?:\.\d+){3}$/.test(host) ||+ host.startsWith('.') ||+ host.endsWith('.') ||+ host.includes('..') ||+ host.toLowerCase().endsWith('.local'),+ )+ ) {+ return `${path}.allowedUrlHosts must contain trusted DNS suffixes`;+ }+ } else if (value.allowedUrlHosts !== undefined) {+ return `${path}.allowedUrlHosts is only valid for URL results`;+ }+ return null;+}++function mediaListError(value: unknown, path: string): string | null {+ if (!Array.isArray(value) || value.length === 0 || value.length > 16) {+ return `${path} must be a non-empty array with at most 16 entries`;+ }+ for (const [index, extractor] of value.entries()) {+ const error = extractorError(extractor, `${path}[${index}]`);+ if (error) return error;+ }+ return null;+}+++function multipartFilesError(value: unknown, path: string): string | null {++ if (!Array.isArray(value) || value.length === 0 || value.length > 16) {++ return `${path} must be a non-empty array with at most 16 entries`;++ }++ const bodyFields = new Set<string>();++ for (const [index, file] of value.entries()) {++ const filePath = `${path}[${index}]`;++ if (!isPlainObject(file)) return `${filePath} must be an object`;++ let error = unknownField(file, ['bodyField', 'formField', 'kind', 'maxItems'], filePath);++ if (error) return error;++ if (!boundedString(file.bodyField, 128) || !/^[A-Za-z0-9_.-]+$/.test(file.bodyField)) {++ return `${filePath}.bodyField must be a safe bounded string`;++ }++ if (++ !boundedString(file.formField, 128) ||++ !/^[A-Za-z0-9_.-]+$/.test(file.formField.replaceAll('[', '').replaceAll(']', ''))++ ) {++ return `${filePath}.formField must be a bounded string`;++ }++ if (file.kind !== 'image' && file.kind !== 'video' && file.kind !== 'audio') {++ return `${filePath}.kind must be image, video or audio`;++ }++ error = positiveIntegerError(file.maxItems, `${filePath}.maxItems`, 1, 16);++ if (error) return error;++ if (bodyFields.has(file.bodyField)) return `${path} must not repeat bodyField`;++ bodyFields.add(file.bodyField);++ }++ return null;++}+++function requestError(value: unknown, path: string): string | null {+ if (!isPlainObject(value)) return `${path} must be an object`;+ let error = unknownField(+ value,+ [+ 'method',+ 'path',+ 'headers',++ 'bodyEncoding',+ 'bodyModelPath',++ 'multipartFiles',+ 'timeoutMs',+ 'maxRequestBytes',+ 'maxResponseBytes',+ ],+ path,+ );+ if (error) return error;+ if (value.method !== 'POST') return `${path}.method must be POST`;+ error = relativePathError(value.path, `${path}.path`, false);+ if (error) return error;+ error = headersError(value.headers, `${path}.headers`);+ if (error) return error;++ if (++ value.bodyEncoding !== undefined &&++ value.bodyEncoding !== 'json' &&++ value.bodyEncoding !== 'multipart'++ ) {++ return `${path}.bodyEncoding must be json or multipart`;++ }+ error = objectPathError(value.bodyModelPath, `${path}.bodyModelPath`);+ if (error) return error;++ if (value.bodyEncoding === 'multipart') {++ if ((value.bodyModelPath as string[]).length !== 1) {++ return `${path}.bodyModelPath must be top-level for multipart requests`;++ }++ error = multipartFilesError(value.multipartFiles, `${path}.multipartFiles`);++ if (error) return error;++ } else if (value.multipartFiles !== undefined) {++ return `${path}.multipartFiles is only valid for multipart requests`;++ }+ for (const [field, max] of [+ ['timeoutMs', 600_000],+ ['maxRequestBytes', 268_435_456],+ ['maxResponseBytes', 268_435_456],+ ] as const) {+ error = positiveIntegerError(value[field], `${path}.${field}`, 1, max);+ if (error) return error;+ }+ return null;+}++function stringSetError(value: unknown, path: string): string | null {+ if (+ !Array.isArray(value) ||+ value.length === 0 ||+ value.length > 32 ||+ value.some((item) => !boundedString(item, 128))+ ) {+ return `${path} must be a non-empty bounded string array`;+ }+ return new Set(value).size === value.length ? null : `${path} must not contain duplicates`;+}++function pollError(value: unknown, path: string): string | null {+ if (!isPlainObject(value)) return `${path} must be an object`;+ let error = unknownField(+ value,+ [+ 'method',+ 'path',+ 'headers',+ 'bodyTaskIdPath',+ 'statusPath',+ 'successValues',+ 'failureValues',+ 'recommendedIntervalMs',+ 'timeoutMs',+ 'maxResponseBytes',+ 'media',+ ],+ path,+ );+ if (error) return error;+ if (value.method !== 'GET' && value.method !== 'POST')+ return `${path}.method must be GET or POST`;+ error = relativePathError(value.path, `${path}.path`, true);+ if (error) return error;+ error = headersError(value.headers, `${path}.headers`);+ if (error) return error;+ if (+ value.method === 'POST' &&+ value.bodyTaskIdPath === undefined &&+ !(value.path as string).includes('{taskId}')+ ) {+ return `${path} POST polling must declare bodyTaskIdPath or {taskId}`;+ }+ if (value.bodyTaskIdPath !== undefined) {+ error = objectPathError(value.bodyTaskIdPath, `${path}.bodyTaskIdPath`);+ if (error) return error;+ }+ error = objectPathError(value.statusPath, `${path}.statusPath`);+ if (error) return error;+ error = stringSetError(value.successValues, `${path}.successValues`);+ if (error) return error;+ error = stringSetError(value.failureValues, `${path}.failureValues`);+ if (error) return error;+ for (const [field, max] of [+ ['recommendedIntervalMs', 300_000],+ ['timeoutMs', 600_000],+ ['maxResponseBytes', 268_435_456],+ ] as const) {+ error = positiveIntegerError(value[field], `${path}.${field}`, 1, max);+ if (error) return error;+ }+ return mediaListError(value.media, `${path}.media`);+}++function responseError(value: unknown, path: string): string | null {+ if (!isPlainObject(value)) return `${path} must be an object`;+ if (value.mode === 'sync') {+ const unknown = unknownField(value, ['mode', 'media'], path);+ return unknown ?? mediaListError(value.media, `${path}.media`);+ }+ if (value.mode === 'async') {+ let error = unknownField(value, ['mode', 'taskIdPath', 'poll'], path);+ if (error) return error;+ error = objectPathError(value.taskIdPath, `${path}.taskIdPath`);+ return error ?? pollError(value.poll, `${path}.poll`);+ }+ return `${path}.mode must be sync or async`;+}++function operationError(value: unknown, path: string, checkFields = true): string | null {+ if (!isPlainObject(value)) return `${path} must be an object`;+ let error = checkFields ? unknownField(value, OPERATION_FIELDS, path) : null;+ if (error) return error;+ if (+ typeof value.capability !== 'string' ||+ !MODEL_ACCESS_MEDIA_CAPABILITIES.includes(value.capability as MediaCapability)+ ) {+ return `${path}.capability must be supported`;+ }+ if (!boundedString(value.instructions, 20_000)) {+ return `${path}.instructions must be a bounded string`;+ }+ error = requestError(value.request, `${path}.request`);+ if (error) return error;+ error = responseError(value.response, `${path}.response`);+ if (error) return error;+ if (!isPlainObject(value.exampleBody)) return `${path}.exampleBody must be an object`;+ if (!isPlainObject(value.inputSchema)) return `${path}.inputSchema must be an object`;+ if (!boundedString(value.officialDocs, 2_048)) return `${path}.officialDocs must be a URL`;+ try {+ const docs = new URL(value.officialDocs);+ if (docs.protocol !== 'https:' || !docs.hostname || docs.username || docs.password) {+ return `${path}.officialDocs must be an HTTPS URL`;+ }+ } catch {+ return `${path}.officialDocs must be an HTTPS URL`;+ }+ return null;+}++function guideBaseError(value: PlainObject, fields: readonly string[]): string | null {+ let error = unknownField(value, fields, 'guide');+ if (error) return error;+ if (value.schemaVersion !== MODEL_ACCESS_INVOCATION_GUIDE_SCHEMA_VERSION) {+ return `guide.schemaVersion must be ${MODEL_ACCESS_INVOCATION_GUIDE_SCHEMA_VERSION}`;+ }+ if (!boundedString(value.guideId, 128) || !/^[a-zA-Z0-9._-]+$/.test(value.guideId)) {+ return 'guide.guideId must be a bounded identifier';+ }+ for (const [field, max] of [['revision', 128]] as const) {+ if (!boundedString(value[field], max)) return `guide.${field} must be a bounded string`;+ }+ if (!isPlainObject(value.connection)) return 'guide.connection must be an object';+ error = unknownField(value.connection, ['providerId'], 'guide.connection');+ if (error) return error;+ if (+ !boundedString(value.connection.providerId, 128) ||+ !/^[a-zA-Z0-9_-]+$/.test(value.connection.providerId)+ ) {+ return 'guide.connection.providerId must be a bounded string';+ }+ return null;+}++function resolvedBindingError(+ value: PlainObject,+ fields: readonly string[],+ path: string,+): string | null {+ const error = unknownField(value, fields, path);+ if (error) return error;- for (const field of ['modelId', 'wireModelId'] as const) {- if (!boundedString(value[field], 256)) return `${path}.${field} must be a bounded string`;- }++ if (!boundedString(value.modelId, 256)) return `${path}.modelId must be a bounded string`;+ return null;+}++export function parseMediaInvocationGuide(+ value: unknown,+): ModelAccessParseResult<MediaInvocationGuide> {+ if (!isPlainObject(value)) return fail('guide must be an object');+ let error = guideBaseError(value, GUIDE_FIELDS);+ if (error) return fail(error);+ if (!Array.isArray(value.operations) || value.operations.length === 0 || value.operations.length > 16) {+ return fail('guide.operations must be a non-empty array with at most 16 entries');+ }+ const capabilities = new Set<MediaCapability>();+ for (const [index, operation] of value.operations.entries()) {+ error = operationError(operation, `guide.operations[${index}]`);+ if (error) return fail(error);+ const capability = (operation as PlainObject).capability as MediaCapability;+ if (capabilities.has(capability)) {+ return fail('guide.operations must not contain duplicate capabilities');+ }+ capabilities.add(capability);+ }+ return ok(value as unknown as MediaInvocationGuide);+}++export function parseResolvedMediaInvocationGuide(+ value: unknown,+): ModelAccessParseResult<ResolvedMediaInvocationGuide> {+ if (!isPlainObject(value)) return fail('resolved guide must be an object');+ const error = resolvedBindingError(value, RESOLVED_GUIDE_FIELDS, 'resolvedGuide');+ if (error) return fail(error);+ const guide = parseMediaInvocationGuide(value.guide);+ if (!guide.ok) return fail(guide.error);+ return ok(value as unknown as ResolvedMediaInvocationGuide);+}++export function parsePreparedMediaInvocationGuide(+ value: unknown,+): ModelAccessParseResult<PreparedMediaInvocationGuide> {+ if (!isPlainObject(value)) return fail('guide must be an object');+ const error =+ guideBaseError(value, PREPARED_GUIDE_FIELDS) ??+ resolvedBindingError(value, PREPARED_GUIDE_FIELDS, 'guide') ??+ operationError(value, 'guide', false);+ return error ? fail(error) : ok(value as unknown as PreparedMediaInvocationGuide);+}diff --cc docs/dev-rules/plugin-security-and-authoring.mdindex 86c34b122e,ec173d2279..5adf826bb4--- a/docs/dev-rules/plugin-security-and-authoring.md+++ b/docs/dev-rules/plugin-security-and-authoring.md@@@ -224,21 -224,6 +224,22 @@@并在票据库内重新解析核对,路径映射已变化时拒绝并要求重新确认。出票后真正读/写时仍须再次核对根与目标真身;保存文件必须排他创建且不跟随最终 symlink,不能让短命票据留下消费期TOCTOU。附件继续使用裁决前已读入的字节,不得在批准后重新跟随原始路径。+- 媒体模型接入分成两层:插件声明并封装业务能力,Cindy Core 提供低级目录和调用能力。- 插件设置页/panel 只能通过同源只读 `/media-models?type=image|video` 配置模型;Host 只按- Gateway `mode` 切图片/视频大类,并把 `architecture` 归一化后的 `modalities.input/output`- 原样交给插件。出图、改图、文生视频、图生视频等业务动作由插件自行解释,Host 不建立- 第二套能力映射;缺少 `modalities` 时插件不得按型号名或 Guide 猜测。响应不得包含 Guide、- endpoint 或凭证。新媒体生成请求只能由当前 Agent 调用永久 Core `media`++ 插件设置页/panel 只能通过同源只读 `/media-models?type=image|video` 配置模型;Host 按++ Gateway `mode` 切图片/视频大类,并结合插件 `cindy.image/video` 声明、Gateway++ `modalities`、Guide operation 与当前客户端协议支持度,只投影当前可执行模型。单模型++ Guide 失败必须局部隔离,不能阻断其余模型或插件面板。响应仍只把归一化后的++ `modalities.input/output` 原样交给插件,不得包含 Guide、endpoint、凭证或内部兼容判定;++ 付费请求前 Core 必须再次校验。新媒体生成请求只能由当前 Agent 调用永久 Core `media`+ 工具发起,插件沙箱和 panel 不得直接提交、轮询或下载。存量 `cindy-request` 媒体代办仅作+ 兼容,不得作为新 Guide 模型的接入路径。插件工具通过现有 `tool-result` 返回普通 JSON,+ Agent 读取后自行决定下一次 `media` 调用;Host 不识别插件专用媒体意图字段,也不自动+ 转发。插件需要结果时,在普通接收工具上用 `attachmentArgs` 声明承载媒体地址的顶层+ 参数名;Agent 后续只需按工具参数调用,Host 从这些参数机械提取地址并复用已有的+ `ghost_call.attachments` 通用授权链完成交接,并在派发前把声明参数中的原地址改写为该+ 插件自己的 `cindy-ghost://<id>/media/<hash>.<ext>` 地址,绝不把本地绝对路径暴露给插件。+ 显式 `ghost_call.attachments` 仍兼容并与声明参数去重;插件自行保存业务状态和更新 UI。+ Host 不自动回调插件,也不得新增画廊等插件业务语义。- 面板供片与注入的主题 token 只用 `ghostPanelTheme.ts` 白名单内的值,不扩大暴露面。- `ios-simulator` 槽只允许读取 Host 当前台前任务的公开模拟器状态,并请求打开既有Host viewer。请求协议不得出现插件自报 `sessionId`,可选 `instanceId` 必须重新匹配diff --cc packages/cindy-tools/src/ghost/mcpServer.tsindex 80555187e5,53cac57893..14d87337ed--- a/packages/cindy-tools/src/ghost/mcpServer.ts+++ b/packages/cindy-tools/src/ghost/mcpServer.ts@@@ -90,18 -89,6 +90,19 @@@ const D_GHOST_CALL ="DIR_INVALID(目录过户失败,查 message)/ INTERNAL。遇到 NOT_FOUND 类错误,已知目标时重查 ghost_info,否则用 ghost_list 看全量。",].join("\n");+const D_MEDIA = [+ "Cindy Core 的低级媒体接口,供当前 Agent 执行插件提供的上层能力;插件负责场景语义和可选 UI,Core 负责模型调用与媒体交付。",+ "常规链路是 Agent 先调用插件工具,读取插件返回的普通 JSON,再自行调用本工具;不存在 mediaIntent 等保留结果格式,Host 也不会自动把插件结果转成本工具调用。",+ "如果插件需要把最终结果同步进自己的面板,Agent 可在本工具成功后再调用插件声明的普通导入工具;这不是生成请求的必经步骤。",- "模型清单来自当前账号的 Model Access model group,并按 Gateway mode 识别;Guide 是可选调用说明,不决定模型是否存在。",++ "模型存在性来自当前账号的 Model Access model group;list_models 只投影同时满足 Gateway modalities、Guide operation 与当前客户端协议支持度的可执行模型。",+ "媒体生成必须由当前 Agent 通过本工具发起;插件面板和插件沙箱代码不得直接提交生成请求。",+ "插件已返回用户配置的 model_id 时可直接用它和目标 capability 走 prepare → request;没有已配置 model_id 时,先用 list_models 查询可用媒体模型。prepare 会由 Server 根据 model_id 返回 Guide,并在 Guide 不存在或不支持该 capability 时明确报错。",- "异步任务的 request 返回 pending 时,再按 recommended_poll_after_ms 调 poll;同步任务会直接返回 xdt_image_urls / xdt_video_urls / xdt_audio_tracks。",++ "异步任务的 request 返回 pending 时,再按 recommended_poll_after_ms 调 poll;同步任务会直接返回 xdt_image_urls / xdt_video_urls。",+ "模型 id、endpoint、Authorization 和 wire model 均由 Host 管理,不要写进 body,不要猜测或覆盖。",++ "Guide 缺失、能力不匹配或当前客户端不支持协议时,结果会带稳定 errorCode、retryable、outcomeKnown 和 allowedActions;可按 allowedActions 换模型、改用其它已授权工具或仍存在的旧链路,不要把 INTERNAL 当成协议能力结论。",+ "prepare 返回的 invocation_id 是一次性付费提交令牌;request 超时或返回 SUBMISSION_OUTCOME_UNKNOWN 时不要自动重提,以免重复扣费。",+].join("\n");+const D_GHOST_FORGE_GUIDE = ["获取《插件(Ghost)编写手册》——为用户制作/修改插件(.cindy 能力包)前必读。","手册随主机版本走,包含:设计对齐提问清单、ghost.json 身份卡全字段、全部卡槽、",