Skip to content

armgit / cindy

Public Imported from GitHub
0

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

feat(wechat): add personal WeChat IM connector (#713)

DavidShenXD798ca06a4cda
diff --git a/apps/desktop/drizzle/0082_daffy_calypso.sql b/apps/desktop/drizzle/0082_daffy_calypso.sql
new file mode 100644
index 0000000000..cfb286eece
--- /dev/null
+++ b/apps/desktop/drizzle/0082_daffy_calypso.sql
@@ -0,0 +1,77 @@
+CREATE TABLE IF NOT EXISTS `wechat_file_attachments` (
+ `id` text PRIMARY KEY NOT NULL,
+ `binding_epoch` text NOT NULL,
+ `task_id` text NOT NULL,
+ `session_id` text,
+ `abs_path` text NOT NULL,
+ `original_name` text NOT NULL,
+ `mime_type` text NOT NULL,
+ `bytes` integer NOT NULL,
+ `status` text DEFAULT 'staged' NOT NULL,
+ `promoted_at` integer,
+ `created_at` integer NOT NULL,
+ FOREIGN KEY (`binding_epoch`) REFERENCES `wechat_sync_state`(`binding_epoch`) ON UPDATE no action ON DELETE cascade,
+ FOREIGN KEY (`task_id`) REFERENCES `wechat_inbox`(`id`) ON UPDATE no action ON DELETE cascade,
+ FOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON UPDATE no action ON DELETE set null
+);
+--> statement-breakpoint
+CREATE INDEX IF NOT EXISTS `idx_wechat_file_attachments_task` ON `wechat_file_attachments` (`binding_epoch`,`task_id`);--> statement-breakpoint
+CREATE TABLE IF NOT EXISTS `wechat_inbox` (
+ `id` text PRIMARY KEY NOT NULL,
+ `binding_epoch` text NOT NULL,
+ `platform_message_id` text NOT NULL,
+ `platform_seq` integer NOT NULL,
+ `peer_id` text NOT NULL,
+ `received_at` integer NOT NULL,
+ `platform_created_at` integer NOT NULL,
+ `expires_at` integer NOT NULL,
+ `status` text DEFAULT 'pending' NOT NULL,
+ `lease_until` integer,
+ `session_id` text,
+ `conversation_epoch` integer DEFAULT 0 NOT NULL,
+ `payload_json` text NOT NULL,
+ `context_nonce` text NOT NULL,
+ `context_ciphertext` text NOT NULL,
+ `context_tag` text NOT NULL,
+ `attempts` integer DEFAULT 0 NOT NULL,
+ `last_error_code` text,
+ FOREIGN KEY (`binding_epoch`) REFERENCES `wechat_sync_state`(`binding_epoch`) ON UPDATE no action ON DELETE cascade,
+ FOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON UPDATE no action ON DELETE set null
+);
+--> statement-breakpoint
+CREATE UNIQUE INDEX IF NOT EXISTS `uniq_wechat_inbox_platform_message` ON `wechat_inbox` (`binding_epoch`,`platform_message_id`);--> statement-breakpoint
+CREATE INDEX IF NOT EXISTS `idx_wechat_inbox_queue` ON `wechat_inbox` (`binding_epoch`,`status`,`received_at`);--> statement-breakpoint
+CREATE INDEX IF NOT EXISTS `idx_wechat_inbox_lease` ON `wechat_inbox` (`binding_epoch`,`lease_until`);--> statement-breakpoint
+CREATE INDEX IF NOT EXISTS `idx_wechat_inbox_conversation` ON `wechat_inbox` (`binding_epoch`,`peer_id`,`conversation_epoch`);--> statement-breakpoint
+CREATE UNIQUE INDEX IF NOT EXISTS `uniq_wechat_inbox_running_session` ON `wechat_inbox` (`binding_epoch`,`session_id`) WHERE "wechat_inbox"."session_id" IS NOT NULL AND "wechat_inbox"."status" IN ('dispatching', 'accepted_running', 'waiting_desktop', 'delivery_pending');--> statement-breakpoint
+CREATE TABLE IF NOT EXISTS `wechat_outbox` (
+ `id` text PRIMARY KEY NOT NULL,
+ `binding_epoch` text NOT NULL,
+ `task_id` text NOT NULL,
+ `client_id` text NOT NULL,
+ `kind` text NOT NULL,
+ `chunk_index` integer NOT NULL,
+ `text` text NOT NULL,
+ `media_json` text DEFAULT '[]' NOT NULL,
+ `status` text DEFAULT 'pending' NOT NULL,
+ `attempts` integer DEFAULT 0 NOT NULL,
+ `next_retry_at` integer NOT NULL,
+ `created_at` integer NOT NULL,
+ `delivered_at` integer,
+ FOREIGN KEY (`binding_epoch`) REFERENCES `wechat_sync_state`(`binding_epoch`) ON UPDATE no action ON DELETE cascade,
+ FOREIGN KEY (`task_id`) REFERENCES `wechat_inbox`(`id`) ON UPDATE no action ON DELETE cascade
+);
+--> statement-breakpoint
+CREATE UNIQUE INDEX IF NOT EXISTS `uniq_wechat_outbox_client_id` ON `wechat_outbox` (`binding_epoch`,`client_id`);--> statement-breakpoint
+CREATE INDEX IF NOT EXISTS `idx_wechat_outbox_delivery` ON `wechat_outbox` (`binding_epoch`,`status`,`next_retry_at`);--> statement-breakpoint
+CREATE INDEX IF NOT EXISTS `idx_wechat_outbox_task` ON `wechat_outbox` (`binding_epoch`,`task_id`,`chunk_index`);--> statement-breakpoint
+CREATE TABLE IF NOT EXISTS `wechat_sync_state` (
+ `binding_epoch` text PRIMARY KEY NOT NULL,
+ `is_active` integer DEFAULT false NOT NULL,
+ `sync_cursor` text DEFAULT '' NOT NULL,
+ `last_poll_at` integer,
+ `last_error_code` text,
+ `updated_at` integer NOT NULL
+);
+--> statement-breakpoint
+CREATE UNIQUE INDEX IF NOT EXISTS `uniq_wechat_sync_active` ON `wechat_sync_state` (`is_active`) WHERE "wechat_sync_state"."is_active" = 1;
diff --git a/apps/desktop/drizzle/meta/0082_snapshot.json b/apps/desktop/drizzle/meta/0082_snapshot.json
new file mode 100644
index 0000000000..32b0404f98
--- /dev/null
+++ b/apps/desktop/drizzle/meta/0082_snapshot.json
@@ -0,0 +1,3708 @@
+{
+ "version": "6",
+ "dialect": "sqlite",
+ "id": "0979ace1-4d1d-4459-9bfa-d9c7eaebcf09",
+ "prevId": "78f061ed-c715-452e-928f-33871745c4d4",
+ "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": false,
+ "autoincrement": false
+ },
+ "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_pk": {
+ "columns": [
+ "day",
+ "agent_kind",
+ "model"
+ ],
+ "name": "daily_model_usage_day_agent_kind_model_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "daily_spend": {
+ "name": "daily_spend",
+ "columns": {
+ "day": {
+ "name": "day",
+ "type": "text",
+ "primaryKey": true,
+ "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": false,
+ "autoincrement": false
+ },
+ "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": {},
+ "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": {}
+ },
+ "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_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
+ }
+ },
+ "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
+ },
+ "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": {}
+ },
+ "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
+ }
+ }
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/apps/desktop/drizzle/meta/_journal.json b/apps/desktop/drizzle/meta/_journal.json
index 4e05bad07b..9291413dfb 100644
--- a/apps/desktop/drizzle/meta/_journal.json
+++ b/apps/desktop/drizzle/meta/_journal.json
@@ -575,6 +575,13 @@
"when": 1785037003169,
"tag": "0081_preserve_gateway_currency",
"breakpoints": true
+ },
+ {
+ "idx": 82,
+ "version": "6",
+ "when": 1785150667133,
+ "tag": "0082_daffy_calypso",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/apps/desktop/forge.config.ts b/apps/desktop/forge.config.ts
index 90df47871b..10b8d8e3ea 100644
--- a/apps/desktop/forge.config.ts
+++ b/apps/desktop/forge.config.ts
@@ -1328,6 +1328,12 @@ const config: ForgeConfig = {
// 不是 Electron preload。
target: 'preload',
},
+ {
+ entry: 'src/main/im/wechat/silkWorker.ts',
+ config: 'vite.silk-worker.config.ts',
+ // SILK/WASM 解码隔离在线程中,避免阻塞 Electron main。
+ target: 'preload',
+ },
{
entry: 'src/main/watcher-host/watcherHostProcess.ts',
config: 'vite.watcher-host.config.ts',
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index 0bac6f4a8c..f28bd77717 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -136,6 +136,7 @@
"jszip": "^3.10.1",
"katex": "^0.16.45",
"@cindy/im": "workspace:*",
+ "@cindy/wechat-ilink": "workspace:*",
"@cindy/mcps": "workspace:*",
"loudness": "^0.4.2",
"lucide-react": "^0.468.0",
@@ -155,6 +156,7 @@
"remark-gfm": "^4.0.1",
"remark-math": "^6.0.0",
"sharp": "^0.35.0",
+ "silk-wasm": "^3.7.1",
"smol-toml": "^1.6.1",
"sortablejs": "^1.15.6",
"tailwind-merge": "^2.6.0",
diff --git a/apps/desktop/resources/THIRD-PARTY-NOTICES.txt b/apps/desktop/resources/THIRD-PARTY-NOTICES.txt
index dea87128fd..a610f8d855 100644
--- a/apps/desktop/resources/THIRD-PARTY-NOTICES.txt
+++ b/apps/desktop/resources/THIRD-PARTY-NOTICES.txt
@@ -3641,7 +3641,7 @@ Apache License
Copyright (c) OpenAI
------------------------------------------------------------------------------
-openclaw fs-safe sources (vendored) vendored
+openclaw fs-safe sources (vendored)
License: MIT
Source: https://github.com/openclaw/openclaw
------------------------------------------------------------------------------
@@ -3729,7 +3729,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-TapDB SDK (vendored) vendored
+TapDB SDK (vendored)
License: Apache-2.0
Source: https://www.taptap.cn/developer
------------------------------------------------------------------------------
@@ -3935,8 +3935,40 @@ Apache License
See the License for the specific language governing permissions and
limitations under the License.
+------------------------------------------------------------------------------
+Tencent openclaw-weixin protocol sources (adapted) 2.4.6
+License: MIT
+Source: https://github.com/Tencent/openclaw-weixin/tree/v2.4.6
+------------------------------------------------------------------------------
+Tencent is pleased to support the open source community by making openclaw-weixin available.
+
+Copyright (C) 2026 Tencent. All rights reserved.
+
+openclaw-weixin is licensed under the MIT.
+
+Terms of the MIT:
+--------------------------------------------------------------------
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
==============================================================================
-SECTION 2: npm packages (800 packages)
+SECTION 2: npm packages (801 packages)
==============================================================================
- @antfu/[email protected] — MIT — https://github.com/antfu/install-pkg
@@ -4657,6 +4689,7 @@ SECTION 2: npm packages (800 packages)
- [email protected] — MIT — https://github.com/ljharb/side-channel-weakmap
- [email protected] — ISC — https://github.com/tapjs/signal-exit
- [email protected] — ISC — https://github.com/tapjs/signal-exit
+- [email protected] — MIT — https://github.com/idranme/silk-wasm
- [email protected] — MIT — https://github.com/feross/simple-concat
- [email protected] — MIT — https://github.com/feross/simple-get
- [email protected] — BSD-3-Clause — https://github.com/squirrelchat/smol-toml
@@ -37826,7 +37859,32 @@ WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
------------------------------------------------------------------------------
-[432] Applies to: npm:[email protected], npm:[email protected]
+[432] Applies to: npm:[email protected]
+------------------------------------------------------------------------------
+MIT License
+
+Copyright (c) 2024 idranme
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+------------------------------------------------------------------------------
+[433] Applies to: npm:[email protected], npm:[email protected]
------------------------------------------------------------------------------
The MIT License (MIT)
@@ -37850,7 +37908,7 @@ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[433] Applies to: npm:[email protected]
+[434] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Copyright (c) Squirrel Chat et al., All rights reserved.
@@ -37878,7 +37936,7 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
------------------------------------------------------------------------------
-[434] Applies to: npm:[email protected]
+[435] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -37903,7 +37961,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[435] Applies to: npm:[email protected]
+[436] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Copyright (c) 2007-2014, Alexandru Marasteanu <hello [at) alexei (dot] ro>
All rights reserved.
@@ -37931,7 +37989,7 @@ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
------------------------------------------------------------------------------
-[436] Applies to: npm:[email protected]
+[437] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -37956,7 +38014,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[437] Applies to: npm:[email protected]
+[438] Applies to: npm:[email protected]
------------------------------------------------------------------------------
The MIT License (MIT)
@@ -37982,7 +38040,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
------------------------------------------------------------------------------
-[438] Applies to: npm:[email protected]
+[439] Applies to: npm:[email protected]
------------------------------------------------------------------------------
The MIT License (MIT)
@@ -38007,7 +38065,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
------------------------------------------------------------------------------
-[439] Applies to: npm:[email protected]
+[440] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Copyright (C) 2018 by Marijn Haverbeke <[email protected]> and others
@@ -38030,7 +38088,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
------------------------------------------------------------------------------
-[440] Applies to: npm:[email protected]
+[441] Applies to: npm:[email protected]
------------------------------------------------------------------------------
The MIT License (MIT)
@@ -38056,7 +38114,7 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[441] Applies to: npm:[email protected]
+[442] Applies to: npm:[email protected]
------------------------------------------------------------------------------
The MIT License (MIT)
@@ -38082,7 +38140,7 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[442] Applies to: npm:[email protected]
+[443] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -38107,7 +38165,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[443] Applies to: npm:[email protected]
+[444] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -38132,7 +38190,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[444] Applies to: npm:[email protected]
+[445] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -38157,7 +38215,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[445] Applies to: npm:[email protected]
+[446] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -38182,7 +38240,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[446] Applies to: npm:[email protected]
+[447] Applies to: npm:[email protected]
------------------------------------------------------------------------------
(The MIT License)
@@ -38207,7 +38265,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
------------------------------------------------------------------------------
-[447] Applies to: npm:[email protected]
+[448] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -38232,7 +38290,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[448] Applies to: npm:[email protected]
+[449] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -38257,7 +38315,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[449] Applies to: npm:[email protected]
+[450] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Copyright (c) Microsoft Corporation.
@@ -38273,7 +38331,7 @@ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
------------------------------------------------------------------------------
-[450] Applies to: npm:[email protected]
+[451] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -38298,7 +38356,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[451] Applies to: npm:[email protected]
+[452] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Apache License
@@ -38357,7 +38415,7 @@ If the Work includes a "NOTICE" text file as part of its distribution, then any
END OF TERMS AND CONDITIONS
------------------------------------------------------------------------------
-[452] Applies to: npm:[email protected]
+[453] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -38370,7 +38428,7 @@ The above copyright notice and this permission notice shall be included in all c
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[453] Applies to: npm:[email protected]
+[454] Applies to: npm:[email protected]
------------------------------------------------------------------------------
TypeBox
@@ -38397,7 +38455,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
------------------------------------------------------------------------------
------------------------------------------------------------------------------
MIT License
@@ -38422,7 +38480,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[455] Applies to: npm:[email protected], npm:[email protected]
+[456] Applies to: npm:[email protected], npm:[email protected]
------------------------------------------------------------------------------
(The MIT License)
@@ -38447,7 +38505,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
------------------------------------------------------------------------------
-[456] Applies to: npm:[email protected]
+[457] Applies to: npm:[email protected]
------------------------------------------------------------------------------
(The MIT license)
@@ -38473,7 +38531,7 @@ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[457] Applies to: npm:[email protected]
+[458] Applies to: npm:[email protected]
------------------------------------------------------------------------------
(The MIT License)
@@ -38497,7 +38555,7 @@ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[458] Applies to: npm:[email protected]
+[459] Applies to: npm:[email protected]
------------------------------------------------------------------------------
(The MIT License)
@@ -38523,7 +38581,7 @@ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[459] Applies to: npm:[email protected]
+[460] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Copyright 2011 Gary Court. All rights reserved.
@@ -38538,7 +38596,7 @@ THIS SOFTWARE IS PROVIDED BY GARY COURT "AS IS" AND ANY EXPRESS OR IMPLIED WARRA
The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of Gary Court.
------------------------------------------------------------------------------
-[460] Applies to: npm:[email protected]
+[461] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Copyright (c) 2012-2014, Bram Stein
All rights reserved.
@@ -38567,7 +38625,7 @@ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
------------------------------------------------------------------------------
-[461] Applies to: npm:[email protected]
+[462] Applies to: npm:[email protected]
------------------------------------------------------------------------------
(The MIT License)
@@ -38595,7 +38653,7 @@ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[462] Applies to: npm:[email protected]
+[463] Applies to: npm:[email protected]
------------------------------------------------------------------------------
The MIT License (MIT)
@@ -38608,7 +38666,7 @@ The above copyright notice and this permission notice shall be included in all c
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[463] Applies to: npm:[email protected]
+[464] Applies to: npm:[email protected]
------------------------------------------------------------------------------
(The MIT License)
@@ -38634,7 +38692,7 @@ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[464] Applies to: npm:[email protected]
+[465] Applies to: npm:[email protected]
------------------------------------------------------------------------------
The MIT License (MIT)
@@ -38660,7 +38718,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[465] Applies to: npm:[email protected]
+[466] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Copyright (c) 2016, Contributors
@@ -38677,7 +38735,7 @@ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
THIS SOFTWARE.
------------------------------------------------------------------------------
-[466] Applies to: npm:[email protected]
+[467] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Apache License
Version 2.0, January 2004
@@ -38882,7 +38940,7 @@ Apache License
limitations under the License.
------------------------------------------------------------------------------
-[467] Applies to: npm:[email protected]
+[468] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Copyright (c) 2011 Einar Otto Stangvik <[email protected]>
Copyright (c) 2013 Arnout Kazemier and contributors
@@ -38906,7 +38964,7 @@ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[468] Applies to: npm:[email protected]
+[469] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Copyright (c) 2015, Contributors
@@ -38923,7 +38981,7 @@ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
THIS SOFTWARE.
------------------------------------------------------------------------------
-[469] Applies to: npm:[email protected]
+[470] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -38948,7 +39006,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
------------------------------------------------------------------------------
-[470] Applies to: npm:[email protected]
+[471] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -38973,7 +39031,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[471] Applies to: npm:[email protected]
+[472] Applies to: npm:[email protected]
------------------------------------------------------------------------------
ISC License
diff --git a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
index 4ea2e51add..5dae01fa23 100644
--- a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
+++ b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
@@ -18,6 +18,21 @@ const hookControlSourcePath = resolve(__dirname, '..', 'hook-control', 'ipc.ts')
const hookControlSource = readFileSync(hookControlSourcePath, 'utf8').replace(/\r\n?/g, '\n');
describe('maker:event hot path ordering', () => {
+ it('rewires a replacement Session instance that retains the same business id', () => {
+ const wireSessionSource = extractWireSessionSource();
+
+ expect(source).toContain('const wiredSessionsById = new Map<string, WiredSessionRegistration>();');
+ expect(wireSessionSource).toContain('if (existing?.session === session)');
+ expect(wireSessionSource).toContain('for (const dispose of existing.disposers) dispose();');
+ expect(wireSessionSource).toContain('existing.session.setInteractionListener(null);');
+ expect(wireSessionSource).toContain(
+ 'registration.disposers.push(session.onEvent((event: AgentEvent) => {',
+ );
+ expect(wireSessionSource).toContain(
+ 'registration.disposers.push(session.onStatusChange((status) => {',
+ );
+ });
+
it('broadcasts EVENT before usage/context/island/idle side effects', () => {
const wireSessionSource = extractWireSessionSource();
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 43d90a9640..092fc2a36d 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -525,13 +525,14 @@ import { registerRemoteCmdIpc } from './commands/remoteCmdIpc.js';
import {
resolvePreferredSystemLocale,
resolveSystemLocale,
- type SupportedLocale,
} from '../shared/locale.js';
import {
IM_DEFAULT_SETTINGS,
isImDefaultAgentKind,
isImDefaultEffort,
+ isImDefaultPermissionMode,
isImDefaultSettingsChannel,
+ isWechatUnsupportedPermissionMode,
type ImDefaultAgentKind,
type ImDefaultAgentSettings,
type ImDefaultSettingsChannel,
@@ -2537,7 +2538,11 @@ const registerIpcHandlers = () => {
MAKER_IPC_INVOKE.IM_DEFAULT_SETTINGS_SET,
async (_e, patch: unknown, rawChannel: unknown) => {
const channel = parseImDefaultSettingsChannel(rawChannel);
- writeImDefaultSettingsPatch(parseImDefaultSettingsPatch(patch), channel);
+ const parsedPatch = parseImDefaultSettingsPatch(patch);
+ if (channel === 'wechat' && isWechatUnsupportedPermissionMode(parsedPatch.permissionMode)) {
+ throwIpcError('INVALID_PARAMS', 'personal WeChat does not support this permission mode');
+ }
+ writeImDefaultSettingsPatch(parsedPatch, channel);
return imDefaultSettingsWire(channel);
},
);
@@ -5936,6 +5941,12 @@ function parseImDefaultSettingsPatch(raw: unknown): ImDefaultSettingsPatch {
}
patch.agentKind = input.agentKind;
}
+ if ('permissionMode' in input) {
+ if (!isImDefaultPermissionMode(input.permissionMode)) {
+ throwIpcError('INVALID_PARAMS', 'im default permissionMode invalid');
+ }
+ patch.permissionMode = input.permissionMode;
+ }
if ('agents' in input) {
if (!input.agents || typeof input.agents !== 'object' || Array.isArray(input.agents)) {
throwIpcError('INVALID_PARAMS', 'im default agents must be object');
diff --git a/apps/desktop/src/main/cindy-media/ledger.ts b/apps/desktop/src/main/cindy-media/ledger.ts
index 23eea8605c..4e9ee91356 100644
--- a/apps/desktop/src/main/cindy-media/ledger.ts
+++ b/apps/desktop/src/main/cindy-media/ledger.ts
@@ -47,6 +47,7 @@ function defaultDb(): LedgerDb {
export type MediaRefKind =
| 'message'
| 'session-attachment'
+ | 'im-inbox'
| 'ghost-gallery'
| 'ghost-grant'
| 'import'
diff --git a/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts b/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts
index d8ecfa1cf4..61b5f291aa 100644
--- a/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts
+++ b/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts
@@ -175,9 +175,19 @@ function makeFakeSession(id: string) {
h.eventCbs.delete(id);
};
},
+ setInteractionListener(listener: (req: unknown) => Promise<unknown>) {
+ h.interactionListeners.set(id, listener);
+ },
send: vi.fn(
- async (_msg: unknown, opts: { onAccepted?: () => Promise<void> }): Promise<unknown> => {
+ async (
+ _msg: unknown,
+ opts: {
+ beforeProviderStart?: () => Promise<void> | void;
+ onAccepted?: () => Promise<void>;
+ },
+ ): Promise<unknown> => {
h.headlessDuringSend.push(isHeadlessGhostSetupTurn(id));
+ await opts.beforeProviderStart?.();
await opts.onAccepted?.();
h.headlessAfterAccepted.push(isHeadlessGhostSetupTurn(id));
// 收口: 模拟 agent 立刻完成本 turn
@@ -659,7 +669,17 @@ describe('进度快照(turn.progress 链路)', () => {
h.eventCbs.delete(id);
};
},
- send: vi.fn(async (_msg: unknown, opts: { onAccepted?: () => Promise<void> }) => {
+ setInteractionListener(listener: (req: unknown) => Promise<unknown>) {
+ h.interactionListeners.set(id, listener);
+ },
+ send: vi.fn(async (
+ _msg: unknown,
+ opts: {
+ beforeProviderStart?: () => Promise<void> | void;
+ onAccepted?: () => Promise<void>;
+ },
+ ) => {
+ await opts.beforeProviderStart?.();
await opts.onAccepted?.();
return {};
}),
@@ -814,14 +834,21 @@ describe('交互卡链路(interaction listener 覆盖)', () => {
setInteractionListener(listener: (req: unknown) => Promise<unknown>) {
h.interactionListeners.set(id, listener);
},
- send: vi.fn(async (_msg: unknown, opts: { onAccepted?: () => Promise<void> }) => {
+ send: vi.fn(async (
+ _msg: unknown,
+ opts: {
+ beforeProviderStart?: () => Promise<void> | void;
+ onAccepted?: () => Promise<void>;
+ },
+ ) => {
+ await opts.beforeProviderStart?.();
await opts.onAccepted?.();
return {};
}),
};
}
- it('ask 请求 -> 发卡回调 -> 按钮决策回流 resolve; 收口后归还桌面 listener', async () => {
+ it('ask 请求 -> 中央 Router 发卡 -> 按钮决策回流 resolve; 收口后释放 route', async () => {
fakeMaker.createSession.mockImplementationOnce(async (opts: { id?: string }) =>
makeInteractiveSession(opts.id ?? 'sess-x'),
);
@@ -842,7 +869,7 @@ describe('交互卡链路(interaction listener 覆盖)', () => {
);
await new Promise((r) => setTimeout(r, 0));
- // hook listener 已覆盖桌面版
+ // Session listener 始终由中央 Router 持有。
const listener = h.interactionListeners.get('sess-new')!;
expect(listener).toBeTypeOf('function');
@@ -865,12 +892,12 @@ describe('交互卡链路(interaction listener 覆盖)', () => {
answers: { '继续重构吗?': '先停' },
});
- // 正常收口: 无未决交互, 不发 cancel, 桌面 listener 归还
+ // 正常收口: 无未决交互, 不发 cancel;无需覆盖/归还 listener。
h.eventCbs.get('sess-new')!({ type: 'done', data: null });
const outcome = await p;
expect(outcome.status).toBe('ok');
expect(cancels).toHaveLength(0);
- expect(h.installDesktopInteractionListener).toHaveBeenCalledTimes(1);
+ expect(h.installDesktopInteractionListener).not.toHaveBeenCalled();
});
it('permission 请求出三按钮卡, 按钮回流 resolve(允许一次)', async () => {
diff --git a/apps/desktop/src/main/hook-control/session-runner.ts b/apps/desktop/src/main/hook-control/session-runner.ts
index 0ed0096c28..cb8d9844c9 100644
--- a/apps/desktop/src/main/hook-control/session-runner.ts
+++ b/apps/desktop/src/main/hook-control/session-runner.ts
@@ -52,10 +52,15 @@ import { getMaker } from '../maker-host/index.js';
import {
wireSessionToIpc,
isSessionInTurn,
- installDesktopInteractionListener,
noteSilentStopUserSend,
onSilentStopSettled,
} from '../maker-ipc/register.js';
+import {
+ beginInteractionRoute,
+ type InteractionHandler,
+ type InteractionRouteLease,
+ type TurnOrigin as RoutedTurnOrigin,
+} from '../maker-ipc/interactionRouter.js';
import { prependHandoffToUserMessage } from '../maker-ipc/agentHandoff.js';
import { agentHandoffPending } from '../maker-ipc/agentHandoffPendingSingleton.js';
import { toDesktopSessionDispatchOutcome } from '../maker-host/send-outcome.js';
@@ -525,13 +530,11 @@ export function createMakerHookSessionRunner(deps: {
// renderer 可见性: 不 wire 则消息不落库、UI 空白(scheduler Phase 6 老坑)
wireSessionToIpc(session);
- // 交互卡链路: 覆盖 wireSessionToIpc 装上的桌面版 interaction listener。
- // hook 是无人值守 turn, 交互必须走来源渠道卡片 + 有界超时 —— 旧行为里
- // 模型调 AskUserQuestion 会把请求发给桌面 renderer 无限死等, 直到
- // 60min 整 turn 硬超时才以 error 收口。turn 结束后归还桌面版 listener
- // (用户在桌面端继续用该会话时交互仍走桌面弹窗)。
+ // hook 是无人值守 turn,交互必须走来源渠道卡片 + 有界超时。Session
+ // listener 由中央 InteractionRouter 持有;这里只准备本 turn 的 handler,
+ // 真正的 route 在 beforeProviderStart 屏障内登记。
const ownInteractionIds = new Set<string>();
- const hookInteractionsInstalled = req.onInteraction !== undefined;
+ let interactionRouteLease: InteractionRouteLease | null = null;
const headlessTurn = {
closed: false,
release: null as (() => void) | null,
@@ -542,10 +545,10 @@ export function createMakerHookSessionRunner(deps: {
if (headlessTurn.closed || headlessTurn.release) return;
headlessTurn.release = beginHeadlessGhostSetupTurn(session.id);
};
- if (req.onInteraction) {
- const sendCard = req.onInteraction;
- const sendCancel = req.onInteractionCancel;
- session.setInteractionListener(async (ireq) => {
+ const handleHookInteraction: InteractionHandler = async (ireq) => {
+ if (req.onInteraction) {
+ const sendCard = req.onInteraction;
+ const sendCancel = req.onInteractionCancel;
// permission 与问答/计划卡同走 compose -> Slack 卡 -> 决策回流:
// 非 bypass 会话(用户在 Slack 显式选了收紧档)的权限请求出三按钮卡,
// 超时/收口安全默认拒绝(compose 的 defaultDecision)
@@ -576,19 +579,35 @@ export function createMakerHookSessionRunner(deps: {
});
ownInteractionIds.delete(ireq.requestId);
return decision;
- });
- }
- /** turn 收口清扫: 未决交互按默认自决 + 归还桌面版 listener。幂等。 */
+ }
+ if (ireq.kind === 'ask_user_question') {
+ return { kind: 'ask_user_question', answers: {} };
+ }
+ if (ireq.kind === 'plan_review') {
+ return {
+ kind: 'plan_review',
+ behavior: 'deny',
+ reason: 'headless_interaction_unavailable',
+ dismissed: true,
+ };
+ }
+ return {
+ kind: 'permission',
+ behavior: 'deny',
+ reason: 'headless_interaction_unavailable',
+ };
+ };
+ /** turn 收口清扫: 未决交互按默认自决 + 释放中央 route。幂等。 */
const finalizeInteractions = (): void => {
headlessTurn.closed = true;
headlessTurn.release?.();
headlessTurn.release = null;
- if (!hookInteractionsInstalled) return;
+ interactionRouteLease?.release('hook_turn_terminal');
+ interactionRouteLease = null;
for (const iid of [...ownInteractionIds]) {
cancelHookInteraction(iid, '任务已结束, 此交互已失效');
}
ownInteractionIds.clear();
- installDesktopInteractionListener(session);
};
// 新建会话广播 -> 侧边栏实时出现(复用/接管的会话本来就在列表里, 不用发)
if (req.isNew) {
@@ -939,6 +958,25 @@ export function createMakerHookSessionRunner(deps: {
const sendResult = await session.send(outgoingMessage, {
origin,
planMode: false,
+ beforeProviderStart: () => {
+ const routeOrigin: RoutedTurnOrigin =
+ req.source?.im === 'slack'
+ ? { kind: 'im', channel: 'slack' }
+ : { kind: 'hook', source: req.source?.im ?? 'unknown' };
+ interactionRouteLease = beginInteractionRoute(session, {
+ route: {
+ sessionId: session.id,
+ turnId: randomUUID(),
+ origin: routeOrigin,
+ interactionSurface: req.onInteraction ? 'channel-card' : 'headless',
+ },
+ handle: handleHookInteraction,
+ onCancel: (requestId) => {
+ ownInteractionIds.delete(requestId);
+ return cancelHookInteraction(requestId, '任务已结束, 此交互已失效');
+ },
+ });
+ },
onAccepted: async () => {
// Admission may wait behind a user-driven Desktop turn. Only this
// accepted hook turn is headless; preparation and queue wait are
@@ -999,7 +1037,7 @@ export function createMakerHookSessionRunner(deps: {
return fail(err instanceof Error ? err.message : String(err));
} finally {
if (hardTimer) clearTimeout(hardTimer);
- // 无论正常收口还是超时/错误, 未决交互都按默认收口并归还桌面 listener
+ // 无论正常收口还是超时/错误,未决交互都按默认收口并释放中央 route
finalizeInteractions();
}
diff --git a/apps/desktop/src/main/im/__tests__/defaultSettingsStore.test.ts b/apps/desktop/src/main/im/__tests__/defaultSettingsStore.test.ts
index 07f38eb5c7..d2b814a222 100644
--- a/apps/desktop/src/main/im/__tests__/defaultSettingsStore.test.ts
+++ b/apps/desktop/src/main/im/__tests__/defaultSettingsStore.test.ts
@@ -87,7 +87,7 @@ describe('im default settings store', () => {
});
const persisted = JSON.parse(fs.readFileSync(settingsFile(), 'utf-8'));
- expect(persisted.schemaVersion).toBe(2);
+ expect(persisted.schemaVersion).toBe(3);
expect(persisted.global).toEqual({
agents: {
codex: {
@@ -124,7 +124,7 @@ describe('im default settings store', () => {
});
const persisted = JSON.parse(fs.readFileSync(settingsFile(), 'utf-8'));
- expect(persisted.schemaVersion).toBe(2);
+ expect(persisted.schemaVersion).toBe(3);
expect(persisted.global).toEqual({
agents: {
'claude-code': {
@@ -173,7 +173,7 @@ describe('im default settings store', () => {
scopeMocks.owner = 'cloud-a';
expect(readImDefaultSettings().agentKind).toBe('codex');
const persisted = JSON.parse(fs.readFileSync(settingsFile(), 'utf-8'));
- expect(persisted.schemaVersion).toBe(2);
+ expect(persisted.schemaVersion).toBe(3);
expect(persisted.global).toEqual({ agentKind: 'codex' });
expect(persisted.agentKind).toBe('codex');
});
@@ -196,8 +196,40 @@ describe('im default settings store', () => {
expect(migrated.channels.feishu).toEqual(migrated.global);
expect(migrated.channels.discord).toEqual(migrated.global);
expect(migrated.channels.slack).toEqual(migrated.global);
+ expect(migrated.channels.wechat).toEqual(migrated.global);
});
+ it('migrates v2 documents to auto permission and seeds an independent WeChat route', () => {
+ const withoutPermission = {
+ agentKind: IM_DEFAULT_SETTINGS.agentKind,
+ agents: IM_DEFAULT_SETTINGS.agents,
+ };
+ const migrated = __testing.normalizeDocument({
+ schemaVersion: 2,
+ global: withoutPermission,
+ channels: {
+ feishu: withoutPermission,
+ discord: withoutPermission,
+ slack: withoutPermission,
+ },
+ });
+
+ expect(migrated.schemaVersion).toBe(3);
+ expect(migrated.global.permissionMode).toBe('auto');
+ expect(migrated.channels.wechat.permissionMode).toBe('auto');
+ expect(migrated.channels.wechat.agentKind).toBe(IM_DEFAULT_SETTINGS.agentKind);
+ });
+
+ it.each(['acceptEdits', 'bypassPermissions'] as const)(
+ 'rejects %s for personal WeChat without changing saved defaults',
+ (permissionMode) => {
+ expect(() =>
+ writeImDefaultSettingsPatch({ permissionMode }, 'wechat'),
+ ).toThrow('WECHAT_PERMISSION_MODE_UNSUPPORTED');
+ expect(readImDefaultSettings('wechat').permissionMode).toBe('auto');
+ },
+ );
+
it('detects legacy files even when v2 defaults are merged in by createOverrideSettingsFile', () => {
// createOverrideSettingsFile calls normalize({ ...defaults(), ...overrides }).
// For a v1 file the overrides are flat route fields; defaults inject
diff --git a/apps/desktop/src/main/im/defaultSessionSettings.ts b/apps/desktop/src/main/im/defaultSessionSettings.ts
index bd70cfcd3d..3780b0e0f4 100644
--- a/apps/desktop/src/main/im/defaultSessionSettings.ts
+++ b/apps/desktop/src/main/im/defaultSessionSettings.ts
@@ -86,7 +86,7 @@ export async function resolveImSessionDefaults(
model: model.modelId,
effort,
providerId,
- permissionMode: config.defaultPermissionMode,
+ permissionMode: raw.permissionMode ?? config.defaultPermissionMode,
fastMode: false,
};
}
diff --git a/apps/desktop/src/main/im/defaultSettingsStore.ts b/apps/desktop/src/main/im/defaultSettingsStore.ts
index 3afdec849e..cb59122da1 100644
--- a/apps/desktop/src/main/im/defaultSettingsStore.ts
+++ b/apps/desktop/src/main/im/defaultSettingsStore.ts
@@ -19,6 +19,8 @@ import {
type ImDefaultSettings,
isImDefaultAgentKind,
isImDefaultEffort,
+ isImDefaultPermissionMode,
+ isWechatUnsupportedPermissionMode,
} from '../../shared/imDefaultSettings.js';
import { desktopMakerLogger } from '../maker-host/logger-adapter.js';
import {
@@ -28,7 +30,7 @@ import {
import { claimLegacyImPath, ownerScopedImUserDataPath } from './ownerScopedStorage.js';
const log = desktopMakerLogger.child('im-default-settings-store');
-const SETTINGS_SCHEMA_VERSION = 2;
+const SETTINGS_SCHEMA_VERSION = 3;
interface ImDefaultSettingsDocument {
schemaVersion: typeof SETTINGS_SCHEMA_VERSION;
@@ -58,6 +60,9 @@ function normalizeSettings(raw: unknown): ImDefaultSettings {
const legacySettings = legacyAgentSettings(r);
return {
agentKind,
+ permissionMode: isImDefaultPermissionMode(r.permissionMode)
+ ? r.permissionMode
+ : IM_DEFAULT_SETTINGS.permissionMode,
agents: {
'claude-code': normalizeAgentSettings(
'claude-code',
@@ -214,6 +219,9 @@ export function writeImDefaultSettingsPatch(
patch: ImDefaultSettingsPatch,
channel?: ImDefaultSettingsChannel,
): OverrideSettingsState<ImDefaultSettings> {
+ if (channel === 'wechat' && isWechatUnsupportedPermissionMode(patch.permissionMode)) {
+ throw new Error('WECHAT_PERMISSION_MODE_UNSUPPORTED');
+ }
const document = store.read();
const current = channel ? document.channels[channel] : document.global;
const next = mergeSettingsPatch(current, patch);
@@ -301,6 +309,9 @@ function settingsOverrides(
): Record<string, unknown> {
const overrides: Record<string, unknown> = {};
if (value.agentKind !== defaults.agentKind) overrides.agentKind = value.agentKind;
+ if (value.permissionMode !== defaults.permissionMode) {
+ overrides.permissionMode = value.permissionMode;
+ }
const agents: Partial<Record<ImDefaultAgentKind, ImDefaultAgentSettings>> = {};
for (const agentKind of ['claude-code', 'codex'] as const) {
if (!agentSettingsEqual(value.agents[agentKind], defaults.agents[agentKind])) {
@@ -314,6 +325,7 @@ function settingsOverrides(
function settingsCustomizedKeys(value: ImDefaultSettings, defaults: ImDefaultSettings): string[] {
const keys: string[] = [];
if (value.agentKind !== defaults.agentKind) keys.push('agentKind');
+ if (value.permissionMode !== defaults.permissionMode) keys.push('permissionMode');
for (const agentKind of ['claude-code', 'codex'] as const) {
if (!agentSettingsEqual(value.agents[agentKind], defaults.agents[agentKind])) {
keys.push(`agents.${agentKind}`);
@@ -329,6 +341,7 @@ function agentSettingsEqual(a: ImDefaultAgentSettings, b: ImDefaultAgentSettings
function cloneSettings(settings: ImDefaultSettings): ImDefaultSettings {
return {
agentKind: settings.agentKind,
+ permissionMode: settings.permissionMode,
agents: {
'claude-code': { ...settings.agents['claude-code'] },
codex: { ...settings.agents.codex },
diff --git a/apps/desktop/src/main/im/discord/adapter.ts b/apps/desktop/src/main/im/discord/adapter.ts
index 9dc5a0fecf..75f33f4fdf 100644
--- a/apps/desktop/src/main/im/discord/adapter.ts
+++ b/apps/desktop/src/main/im/discord/adapter.ts
@@ -28,6 +28,7 @@ export function buildDiscordAdapter(
return {
channel: 'discord',
im: discordIm,
+ output: { kind: 'rich-card', im: discordIm },
config,
ui,
sessions: {
diff --git a/apps/desktop/src/main/im/feishu/adapter.ts b/apps/desktop/src/main/im/feishu/adapter.ts
index db7b7cfb17..65259cc9b1 100644
--- a/apps/desktop/src/main/im/feishu/adapter.ts
+++ b/apps/desktop/src/main/im/feishu/adapter.ts
@@ -40,6 +40,7 @@ export function buildFeishuAdapter(
return {
channel: 'feishu',
im: feishuIm,
+ output: { kind: 'rich-card', im: feishuIm },
config,
ui,
sessions: {
diff --git a/apps/desktop/src/main/im/host.ts b/apps/desktop/src/main/im/host.ts
index 7750009763..08e88170bd 100644
--- a/apps/desktop/src/main/im/host.ts
+++ b/apps/desktop/src/main/im/host.ts
@@ -11,9 +11,10 @@
*/
import path from 'node:path';
-import { app, ipcMain, BrowserWindow, net } from 'electron';
+import { app, ipcMain, BrowserWindow, net, shell } from 'electron';
import { createIM, createDiscordIM, createFeishuIM, type IMHost } from '@cindy/im';
+import { TencentIlinkTransport } from '@cindy/wechat-ilink';
import { createLogger } from '../logger';
import { resolveSafe as resolveXdtImageUrl } from '../imageCacheStore';
@@ -28,6 +29,13 @@ import { t } from '../i18n';
import { discordUiText } from './discord/uiText';
import { imHostAccountScope } from './accountScopeBridge';
import { ownerScopedImSecrets } from './ownerScopedStorage';
+import { captureImAccountGeneration, isImAccountGenerationCurrent } from './accountBoundary';
+import { getDbClient } from '../localDb/client/current';
+import { WechatIM, WECHAT_AUTH_BASE_URL } from './wechat/WechatIM';
+import {
+ WECHAT_COMPATIBILITY_POLICY_PRODUCTION_CONFIG,
+ WechatCompatibilityPolicyService,
+} from './wechat/compatibilityPolicy';
const log = createLogger('im/host');
@@ -119,4 +127,47 @@ export const discordIm = createDiscordIM(host, {
expiredCardNotice: discordUiText.expiredCardNotice,
ownerNoticeText: (phase) => t(`settings.discordBot.ownerNotice.${phase}`),
});
-export const im = createIM([feishuIm, discordIm]);
+export const wechatCompatibilityPolicy = new WechatCompatibilityPolicyService({
+ ...WECHAT_COMPATIBILITY_POLICY_PRODUCTION_CONFIG,
+ cachePath: () =>
+ path.join(
+ app.getPath('userData'),
+ 'controlled-config',
+ 'wechat-compatibility-policy.v1.json',
+ ),
+ appVersion: () => app.getVersion(),
+ fetch: (input, init) => net.fetch(input, init),
+});
+export const wechatIm = new WechatIM({
+ host,
+ getDbClient,
+ createTransport: ({ credentials, onAuthorizationEvent }) =>
+ new TencentIlinkTransport({
+ baseUrl: credentials?.baseUrl ?? WECHAT_AUTH_BASE_URL,
+ ...(credentials
+ ? {
+ token: credentials.botToken,
+ appId: credentials.ilinkBotId,
+ }
+ : {}),
+ botAgent: `Cindy/${app.getVersion()}`,
+ fetch: (input, init) => net.fetch(input instanceof URL ? input.toString() : input, init),
+ ...(onAuthorizationEvent
+ ? {
+ authorizationObserver: {
+ onEvent: onAuthorizationEvent,
+ },
+ }
+ : {}),
+ }),
+ openAuthorizationUrl: (url) => shell.openExternal(url),
+ captureAccountGeneration: captureImAccountGeneration,
+ isAccountGenerationCurrent: isImAccountGenerationCurrent,
+ isCompatibilityDisabled: () => wechatCompatibilityPolicy.isDisabled(),
+});
+wechatCompatibilityPolicy.subscribe((decision) => {
+ void wechatIm.setCompatibilityDisabled(decision.disabled).catch(() => {
+ log.warn('failed to apply personal WeChat compatibility policy');
+ });
+});
+export const im = createIM([feishuIm, discordIm, wechatIm]);
diff --git a/apps/desktop/src/main/im/index.ts b/apps/desktop/src/main/im/index.ts
index da39fce0a9..8055259119 100644
--- a/apps/desktop/src/main/im/index.ts
+++ b/apps/desktop/src/main/im/index.ts
@@ -52,14 +52,15 @@
* the logged-in user's DbClient; a later login reconnects saved credentials.
*/
-import { ipcMain, BrowserWindow, type IpcMainEvent } from 'electron';
+import { ipcMain, BrowserWindow, dialog, type IpcMainEvent } from 'electron';
import { and, eq, like, ne, sql } from 'drizzle-orm';
import { getDbClient } from '../localDb/client/current';
import { sessions } from '../localDb/schema';
-import { im, feishuIm, discordIm } from './host';
+import { im, feishuIm, discordIm, wechatCompatibilityPolicy, wechatIm } from './host';
import { wireFeishuOrchestrator, type FeishuOrchestratorConfig } from './feishu';
import { wireDiscordOrchestrator } from './discord';
+import { wireWechatOrchestrator } from './wechat';
import { getImOrchestrator, listImOrchestrators } from './shared/orchestrator';
import { createSerializedConnectionLifecycle } from './connectionLifecycle';
import {
@@ -77,8 +78,14 @@ import { getAuthState } from '../authManager';
import { getUpdateStatus } from '../updateService';
import { createLogger } from '../logger';
+import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer';
+import {
+ readWechatChannelSettings,
+ resetWechatWorkingDir,
+ writeWechatWorkingDir,
+} from './wechat/channelSettings';
-export { im, feishuIm, discordIm } from './host';
+export { im, feishuIm, discordIm, wechatIm } from './host';
const log = createLogger('main:im');
@@ -139,7 +146,15 @@ const DISCORD_CONFIG: ImOrchestratorConfig = {
effortOverrides: IM_DEFAULT_EFFORT_OVERRIDES,
};
+const WECHAT_CONFIG: ImOrchestratorConfig = {
+ agentKind: IM_DEFAULT_SETTINGS.agentKind,
+ defaultModel: IM_DEFAULT_SETTINGS.agents[IM_DEFAULT_SETTINGS.agentKind].model,
+ defaultPermissionMode: IM_DEFAULT_SETTINGS.permissionMode,
+ effortOverrides: IM_DEFAULT_EFFORT_OVERRIDES,
+};
+
export function startImOrchestrators(): void {
+ wechatCompatibilityPolicy.start();
if (wired) return;
wired = true;
// Production bootstrap wires handlers before login/DbClient readiness.
@@ -155,6 +170,69 @@ export function startImOrchestrators(): void {
wireFeishuOrchestrator(feishuIm, FEISHU_CONFIG);
wireDiscordOrchestrator(discordIm, DISCORD_CONFIG);
+ wireWechatOrchestrator(wechatIm, WECHAT_CONFIG);
+
+ ipcMain.handle('wechatBot:get-state', (event) => {
+ assertTrustedAppRendererEvent(event);
+ return wechatIm.getState();
+ });
+ ipcMain.handle('wechatBot:authorize', (event) => {
+ assertTrustedAppRendererEvent(event);
+ return connectionLifecycle.runWhileStarted(() => wechatIm.authorize());
+ });
+ ipcMain.handle('wechatBot:cancel-authorization', (event) => {
+ assertTrustedAppRendererEvent(event);
+ wechatIm.cancelAuthorization();
+ return { ok: true };
+ });
+ ipcMain.handle('wechatBot:unbind', (event) => {
+ assertTrustedAppRendererEvent(event);
+ return connectionLifecycle.runWhileStarted(async () => {
+ await wechatIm.unbind();
+ return { ok: true };
+ });
+ });
+ ipcMain.handle('wechatBot:get-channel-settings', (event) => {
+ assertTrustedAppRendererEvent(event);
+ return readWechatChannelSettings();
+ });
+ ipcMain.handle('wechatBot:choose-working-directory', async (event) => {
+ assertTrustedAppRendererEvent(event);
+ const owner = BrowserWindow.fromWebContents(event.sender);
+ if (!owner || owner.isDestroyed()) throw new Error('WECHAT_SETTINGS_WINDOW_UNAVAILABLE');
+ const result = await dialog.showOpenDialog(owner, {
+ properties: ['openDirectory', 'createDirectory'],
+ });
+ if (result.canceled || !result.filePaths[0]) {
+ return { canceled: true as const, state: readWechatChannelSettings() };
+ }
+ try {
+ return {
+ canceled: false as const,
+ state: writeWechatWorkingDir(result.filePaths[0]),
+ };
+ } catch (error) {
+ log.warn('failed to save user-picked personal WeChat working directory', {
+ errorCode:
+ typeof error === 'object' &&
+ error !== null &&
+ 'code' in error &&
+ typeof (error as { code?: unknown }).code === 'string'
+ ? (error as { code: string }).code
+ : 'UNKNOWN',
+ errorMessage: error instanceof Error ? error.message : String(error),
+ });
+ throw new Error('WECHAT_WORKING_DIR_UPDATE_FAILED');
+ }
+ });
+ ipcMain.handle('wechatBot:reset-working-directory', (event) => {
+ assertTrustedAppRendererEvent(event);
+ try {
+ return resetWechatWorkingDir();
+ } catch {
+ throw new Error('WECHAT_WORKING_DIR_UPDATE_FAILED');
+ }
+ });
// bindingStore.preload() 故意不在这里跑 —— 它要 DbClient, 而 localDb 在
// 用户登录后才 ensureReady (worker spawn + db open + smoke 后才 setCurrentDbClient)。
@@ -312,6 +390,7 @@ async function reconcileOwnerScopedImWorkingDirs(): Promise<void> {
const db = getDbClient().drizzle;
const feishuAdapter = getImOrchestrator('feishu')?.adapter;
const discordAdapter = getImOrchestrator('discord')?.adapter;
+ const wechatAdapter = getImOrchestrator('wechat')?.adapter;
try {
if (feishuAdapter) {
@@ -347,6 +426,23 @@ async function reconcileOwnerScopedImWorkingDirs(): Promise<void> {
await db.update(sessions).set({ workingDir: scoped }).where(eq(sessions.id, row.id));
}
}
+
+ if (wechatAdapter) {
+ const rows = await db
+ .select({
+ id: sessions.id,
+ workingDir: sessions.workingDir,
+ botContextId: sessions.imBotContextId,
+ })
+ .from(sessions)
+ .where(eq(sessions.source, 'wechat'));
+ for (const row of rows) {
+ if (!row.botContextId) continue;
+ const scoped = wechatAdapter.sessions.ensureWorkingDir(row.botContextId);
+ if (row.workingDir === scoped) continue;
+ await db.update(sessions).set({ workingDir: scoped }).where(eq(sessions.id, row.id));
+ }
+ }
} catch (err) {
log.warn('IM owner-scoped working-dir reconciliation failed (non-fatal)', {
error: err instanceof Error ? err.message : String(err),
diff --git a/apps/desktop/src/main/im/messagePersistence.ts b/apps/desktop/src/main/im/messagePersistence.ts
index 14fc29a9fa..a89c0a124b 100644
--- a/apps/desktop/src/main/im/messagePersistence.ts
+++ b/apps/desktop/src/main/im/messagePersistence.ts
@@ -11,7 +11,7 @@
* 函数即可 — 这就是这俩 helper 的事
*
* 为什么不直接到处调 createMessage:
- * - clientId 生成、错误吞掉策略、content shape (text-only vs blocks-array)
+ * - clientId 生成、错误吞掉策略、content shape (text-only vs attachment object)
* 等样板逻辑在多个调用点会重复, 抽出来集中
* - B' (feishu_* session 写库) 和 C (接管 desktop session 时 feishu main 写库)
* 共用同一个 helper, 任何 schema 变更只改一处
@@ -34,7 +34,7 @@ const log = createLogger('im:msg-persist');
*
* content shape 对齐 desktop renderer 写 user 的方式:
* - 纯文本: content = string
- * - 带附件: content = [{ type:'text', text }, { type:'image'|'file', path, mimeType }, ...]
+ * - 带附件: content = { text, images: [...], files: [...] }
*
* 返回 clientId 让调用方有可能后续 update (如 SDK echo 回 uuid 时), MVP 阶段
* 调用方可以无视。
@@ -51,19 +51,24 @@ export async function persistUserMessage(args: {
if (attachments.length === 0) {
content = text;
} else {
- const blocks: Array<Record<string, unknown>> = [];
- if (text) blocks.push({ type: 'text', text });
- for (const att of attachments) {
- blocks.push({
- type: att.kind === 'image' ? 'image' : 'file',
- path: att.absPath,
- mimeType: att.mimeType,
- // cindy-media 地址:写进落库 JSON 让 createMessage 的
- // 媒体挂账钩子给 blob 补 session-attachment 引用(会话生命周期)。
- ...(att.url ? { url: att.url } : {}),
- });
- }
- content = blocks;
+ // Keep durable content aligned with renderer/lib/imageRef.ts. The media
+ // URL is retained so createMessage can pin the blob to this session.
+ content = {
+ text,
+ images: attachments
+ .filter((att) => att.kind === 'image')
+ .map((att) => ({
+ originalName: att.originalName,
+ mimeType: att.mimeType,
+ ...(att.url ? { url: att.url } : {}),
+ })),
+ files: attachments
+ .filter((att) => att.kind === 'file')
+ .map((att) => ({
+ name: att.originalName,
+ path: att.absPath,
+ })),
+ };
}
try {
diff --git a/apps/desktop/src/main/im/shared/__tests__/slashCommands.test.ts b/apps/desktop/src/main/im/shared/__tests__/slashCommands.test.ts
index d99be4d3cf..82bf748a1f 100644
--- a/apps/desktop/src/main/im/shared/__tests__/slashCommands.test.ts
+++ b/apps/desktop/src/main/im/shared/__tests__/slashCommands.test.ts
@@ -102,6 +102,13 @@ function makeHarness(
sendMarkdownText: mocks.sendMarkdownText,
sendInteractiveCard: mocks.sendInteractiveCard,
} as unknown as ChannelIM,
+ output: {
+ kind: 'rich-card',
+ im: {
+ sendMarkdownText: mocks.sendMarkdownText,
+ sendInteractiveCard: mocks.sendInteractiveCard,
+ } as unknown as ChannelIM,
+ },
config: {
agentKind: 'claude-code',
defaultModel: 'claude-opus-4-8',
diff --git a/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts b/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts
index 39f887d95a..135a882e3b 100644
--- a/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts
+++ b/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts
@@ -178,7 +178,10 @@ function createSessionHarness(
// mockRejectedValueOnce 整体替换实现, 抛错路径自然不会触发(正确)。
const send = vi.fn<HarnessSend>(async (message, opts) => {
const result = await sendImpl(message);
- if (result.accepted) await opts?.onAccepted?.();
+ if (result.accepted) {
+ await opts?.beforeProviderStart?.();
+ await opts?.onAccepted?.();
+ }
return result;
});
const isTurnRunning = vi.fn(() => false);
@@ -245,6 +248,7 @@ const fakeCards = {
const fakeAdapter: ImChannelAdapter = {
channel: 'feishu',
im: mocks.feishuIm as unknown as ChannelIM,
+ output: { kind: 'rich-card', im: mocks.feishuIm as unknown as ChannelIM },
config: {
agentKind: 'claude-code',
defaultModel: 'claude-opus-4-7',
@@ -1137,8 +1141,8 @@ describe('turnRunner send outcome policy (feishu adapter characterization)', ()
// desktop 聊天流才能像 Slack hook 会话一样看到完整过程。
expect(mocks.wireSessionToIpcExternal).toHaveBeenCalledTimes(1);
expect(mocks.persistAssistantMessage).not.toHaveBeenCalled();
- // 顺序不变量: wire(装 desktop interaction listener)必须先于渠道版
- // setInteractionListener 覆盖 — 颠倒会让渠道会话的 permission 卡死等 desktop。
+ // 顺序不变量:wire 先安装中央 Router 的 Desktop fallback;本 turn 只在
+ // beforeProviderStart 登记 route,不再覆盖/恢复 Session listener。
const wireOrder = mocks.wireSessionToIpcExternal.mock.invocationCallOrder[0];
const listenerMock = h.session.setInteractionListener as unknown as ReturnType<typeof vi.fn>;
expect(wireOrder).toBeLessThan(listenerMock.mock.invocationCallOrder[0]);
@@ -1146,6 +1150,126 @@ describe('turnRunner send outcome policy (feishu adapter characterization)', ()
expect(mocks.noteSilentStopUserSend).toHaveBeenCalledWith('feishu-session');
});
+ it('exposes accepted and terminal outcomes for an external durable queue', async () => {
+ const h = setupSession(async () => ({ accepted: true }));
+ const beforeProviderStart = vi.fn(async () => undefined);
+
+ const dispatch = await getRunner().dispatchAgentTurn({
+ botContextId: 'cli_test_bot',
+ userId: 'ou_user',
+ userMessageId: 'msg-external',
+ text: 'durable task',
+ attachments: [],
+ queueMode: 'external',
+ beforeProviderStart,
+ });
+
+ expect(dispatch.kind).toBe('accepted');
+ if (dispatch.kind !== 'accepted') throw new Error('expected accepted dispatch');
+ expect(dispatch.sessionId).toBe('feishu-session');
+ expect(dispatch.acceptedAt).toBeGreaterThan(0);
+ expect(beforeProviderStart).toHaveBeenCalledTimes(1);
+
+ h.emit({ type: 'text', data: { text: 'durable answer', isFinal: true } });
+ h.emit({ type: 'done', data: {} });
+
+ await expect(dispatch.terminal).resolves.toMatchObject({
+ kind: 'done',
+ text: 'durable answer',
+ });
+ });
+
+ it('reports the attached Desktop route before provider startup', async () => {
+ const h = setupAttachedSession(async () => ({ accepted: true }));
+ const onRouteResolved = vi.fn();
+ const beforeProviderStart = vi.fn(async () => undefined);
+
+ const dispatch = await getRunner().dispatchAgentTurn({
+ botContextId: 'cli_test_bot',
+ userId: 'ou_user',
+ userMessageId: 'msg-attached-route',
+ text: 'route this turn',
+ attachments: [],
+ queueMode: 'external',
+ onRouteResolved,
+ beforeProviderStart,
+ });
+
+ expect(dispatch.kind).toBe('accepted');
+ expect(onRouteResolved).toHaveBeenCalledWith('desktop-attached-session');
+ expect(onRouteResolved.mock.invocationCallOrder[0]).toBeLessThan(
+ beforeProviderStart.mock.invocationCallOrder[0]!,
+ );
+
+ h.emit({ type: 'done', data: {} });
+ if (dispatch.kind === 'accepted') await dispatch.terminal;
+ });
+
+ it('returns busy without copying external work into the in-memory queue', async () => {
+ const h = setupSession(async () => ({ accepted: true }));
+ const first = await getRunner().dispatchAgentTurn({
+ botContextId: 'cli_test_bot',
+ userId: 'ou_user',
+ userMessageId: 'msg-external-1',
+ text: 'first durable task',
+ attachments: [],
+ queueMode: 'external',
+ beforeProviderStart: async () => undefined,
+ });
+ expect(first.kind).toBe('accepted');
+
+ const second = await getRunner().dispatchAgentTurn({
+ botContextId: 'cli_test_bot',
+ userId: 'ou_user',
+ userMessageId: 'msg-external-2',
+ text: 'second durable task',
+ attachments: [],
+ queueMode: 'external',
+ beforeProviderStart: async () => undefined,
+ });
+
+ expect(second).toEqual({ kind: 'busy', reason: 'session_running' });
+ expect(h.send).toHaveBeenCalledTimes(1);
+ expect(mocks.feishuIm.sendMarkdownText).not.toHaveBeenCalledWith(
+ 'ou_user',
+ expect.stringContaining('排队'),
+ expect.anything(),
+ );
+
+ h.emit({ type: 'done', data: {} });
+ if (first.kind === 'accepted') await first.terminal;
+ });
+
+ it('commits one terminal payload for a chunked-text output driver', async () => {
+ const previousOutput = fakeAdapter.output;
+ const commitFinal = vi.fn(async () => undefined);
+ fakeAdapter.output = {
+ kind: 'chunked-text',
+ im: mocks.feishuIm as unknown as ChannelIM,
+ commitFinal,
+ };
+ try {
+ const h = setupSession(async () => ({ accepted: true }));
+ const { turnPromise } = await startDefaultTurn();
+ await turnPromise;
+
+ h.emit({ type: 'text', data: { text: 'complete text only', isFinal: true } });
+ h.emit({ type: 'done', data: {} });
+ await flushMicrotasks();
+
+ expect(mocks.feishuIm.startStreamingText).not.toHaveBeenCalled();
+ expect(commitFinal).toHaveBeenCalledTimes(1);
+ expect(commitFinal).toHaveBeenCalledWith({
+ userId: 'ou_user',
+ text: 'complete text only',
+ terminal: 'done',
+ threadTs: undefined,
+ });
+ } finally {
+ fakeAdapter.output = previousOutput;
+ }
+ });
+
it('holds the turn open on silentStop done and finalizes only when the guard settles without resume', async () => {
const handle = {
messageId: 'stream-ss',
diff --git a/apps/desktop/src/main/im/shared/__tests__/turnRunnerThreadRouting.test.ts b/apps/desktop/src/main/im/shared/__tests__/turnRunnerThreadRouting.test.ts
index aafc1cba0b..93165369d5 100644
--- a/apps/desktop/src/main/im/shared/__tests__/turnRunnerThreadRouting.test.ts
+++ b/apps/desktop/src/main/im/shared/__tests__/turnRunnerThreadRouting.test.ts
@@ -200,6 +200,7 @@ const fakeCards = {
const fakeAdapter: ImChannelAdapter = {
channel: 'slack',
im: mocks.slackIm as unknown as ChannelIM,
+ output: { kind: 'rich-card', im: mocks.slackIm as unknown as ChannelIM },
config: {
agentKind: 'claude-code',
defaultModel: 'claude-opus-4-7',
@@ -430,7 +431,9 @@ describe('turnRunner thread = session 路由(slack threadScoped)', () => {
await vi.waitFor(() => {
expect(stream.finalize).toHaveBeenCalledWith('late output');
expect(harness.unsubscribe).toHaveBeenCalledOnce();
- expect(mocks.installDesktopInteractionListener).toHaveBeenCalledWith(harness.session);
+ // Central InteractionRouter keeps the Session listener installed; detach
+ // only releases this turn's route and must not overwrite the listener.
+ expect(mocks.installDesktopInteractionListener).not.toHaveBeenCalled();
});
await rewire;
expect(rewireResolved).toBe(true);
diff --git a/apps/desktop/src/main/im/shared/pendingInteractions.ts b/apps/desktop/src/main/im/shared/pendingInteractions.ts
index 31268d4b56..bb1e826ade 100644
--- a/apps/desktop/src/main/im/shared/pendingInteractions.ts
+++ b/apps/desktop/src/main/im/shared/pendingInteractions.ts
@@ -88,6 +88,23 @@ export function resolvePending(
return { messageId: entry.messageId };
}
+/** Resolve one pending card with the safe decision used when its turn ends. */
+export function cancelPending(requestId: string, reason: string): boolean {
+ const entry = pending.get(requestId);
+ if (!entry) return false;
+ pending.delete(requestId);
+ if (entry.kind === 'ask_user_question') {
+ entry.resolve({ kind: 'ask_user_question', answers: {} });
+ return true;
+ }
+ if (entry.kind === 'plan_review') {
+ entry.resolve({ kind: 'plan_review', behavior: 'deny', reason, dismissed: true });
+ return true;
+ }
+ entry.resolve({ kind: 'permission', behavior: 'deny', reason });
+ return true;
+}
+
/** Reject all pending interactions (used on session close / error). */
export function rejectAllPending(reason: string): void {
for (const [, entry] of pending) {
diff --git a/apps/desktop/src/main/im/shared/sessionRepo.ts b/apps/desktop/src/main/im/shared/sessionRepo.ts
index 340f36c665..75b3c41a35 100644
--- a/apps/desktop/src/main/im/shared/sessionRepo.ts
+++ b/apps/desktop/src/main/im/shared/sessionRepo.ts
@@ -315,6 +315,10 @@ export async function resetSessionToDefaults(
providerId: defaults.providerId,
permissionMode: defaults.permissionMode,
fastMode: defaults.fastMode,
+ // Personal WeChat exposes a user-selected channel working directory.
+ // It applies only at the explicit `/new` boundary; existing context is
+ // never moved silently.
+ ...(channel === 'wechat' && defaults.workingDir ? { workingDir: defaults.workingDir } : {}),
sdkSessionId: null,
clearedAt: Date.now(),
updatedAt: Date.now(),
diff --git a/apps/desktop/src/main/im/shared/turnRunner.ts b/apps/desktop/src/main/im/shared/turnRunner.ts
index 7403ef3400..20f961197b 100644
--- a/apps/desktop/src/main/im/shared/turnRunner.ts
+++ b/apps/desktop/src/main/im/shared/turnRunner.ts
@@ -30,7 +30,7 @@
* 语义一致)。
*/
-import { createHash } from 'node:crypto';
+import { createHash, randomUUID } from 'node:crypto';
import path from 'node:path';
import { eq } from 'drizzle-orm';
@@ -59,6 +59,7 @@ import type {
InteractionDecision,
InteractionRequest,
Session as MakerSession,
+ TurnPermissionPolicy,
UserMessage,
} from '@cindy/maker-core';
import type { IMAttachment, InteractiveCardSpec, StreamingTextHandle } from '@cindy/im';
@@ -68,15 +69,23 @@ import { bindingStore } from '../binding';
import { buildImUserMessage } from './inboundMessage';
import {
wireSessionToIpcExternal,
- installDesktopInteractionListener,
takePendingInteractionsForSession,
noteSilentStopUserSend,
noteSilentStopSessionReset,
onSilentStopSettled,
} from '../../maker-ipc/register';
+import {
+ beginInteractionRoute,
+ type InteractionRouteLease,
+} from '../../maker-ipc/interactionRouter';
import { agentHandoffPending } from '../../maker-ipc/agentHandoffPendingSingleton';
import { prependHandoffToUserMessage } from '../../maker-ipc/agentHandoff';
-import { registerPending, registerPendingExternal, rejectAllPending } from './pendingInteractions';
+import {
+ cancelPending,
+ registerPending,
+ registerPendingExternal,
+ rejectAllPending,
+} from './pendingInteractions';
import { checkDestructiveToolCall } from '../../destructiveGuard';
import { readXdGatewayApiKey } from './apiKey';
import {
@@ -108,6 +117,8 @@ const PRE_DISPATCH_ACK_CLEANUP_TIMEOUT_MS = 1500;
const DISPATCH_RETRY_MS = 500;
interface TurnState {
+ /** Stable identity used by the central interaction router for this turn. */
+ turnId: string;
userId: string;
/** thread = session 模型的会话维度键(slack thread root ts);feishu undefined。 */
scopeKey?: string;
@@ -123,6 +134,8 @@ interface TurnState {
streamingHandlePromise: Promise<StreamingTextHandle> | null;
/** Real assistant text accumulated this turn. */
buffer: string;
+ /** Managed images discovered in tool output for durable text channels. */
+ mediaAbsPaths: string[];
done: boolean;
/** 过程展示(tool_use 时间线)状态 — 见 turnActivity.ts。 */
activity: TurnActivityState;
@@ -156,6 +169,14 @@ interface TurnState {
*/
headlessSetupClosed: boolean;
releaseHeadlessSetupTurn: (() => void) | null;
+ /** Active central interaction route; acquired at beforeProviderStart. */
+ interactionRouteLease: InteractionRouteLease | null;
+ /** Terminal classification consumed by chunked-text commitFinal. */
+ terminalKind: 'done' | 'aborted' | 'error';
+ terminalErrorCode: string | null;
+ queueMode: 'internal' | 'external';
+ terminalPromise: Promise<ImTurnTerminal>;
+ resolveTerminal: ((terminal: ImTurnTerminal) => void) | null;
}
/**
@@ -171,6 +192,9 @@ interface QueuedSend {
attachments: IMAttachment[];
/** 已给用户发过"排队中"提示 — 竞态 requeue 路径只提示一次。 */
notified: boolean;
+ queueMode: 'internal' | 'external';
+ beforeProviderStart?: () => Promise<void>;
+ turnPermissionPolicy?: TurnPermissionPolicy;
}
type DetachDrainOutcome = 'rewire' | 'cancelled';
@@ -250,23 +274,58 @@ type DefaultRouteTargetResolution =
| { target: RouteTarget; missingAuth?: never }
| { target: null; missingAuth: ImAuthRouteStatus & { agentKind: AgentKind; model: string } };
+export interface ImRunAgentTurnArgs {
+ botContextId: string;
+ userId: string;
+ /** 渠道 message id of the user's incoming message — used for emoji ack. */
+ userMessageId: string;
+ text: string;
+ attachments: IMAttachment[];
+ /** thread = session 模型的会话维度键(slack);feishu 不传。 */
+ scopeKey?: string;
+ outputCardMessageId?: string;
+ outputCardPrefix?: string;
+ onTurnComplete?: () => void;
+ /** Reports the concrete channel/default or attached Desktop session before provider startup. */
+ onRouteResolved?: (sessionId: string) => void;
+ /** Keep fire-and-forget work inside the ingress account's drain boundary. */
+ trackBackgroundTask?: (operation: () => Promise<void>) => void;
+ /** Optional per-turn host policy (personal WeChat routes confirmations to Desktop). */
+ turnPermissionPolicy?: TurnPermissionPolicy;
+}
+
+export interface ImTurnTerminal {
+ kind: 'done' | 'aborted' | 'error';
+ text: string;
+ completedAt: number;
+ errorCode?: string;
+}
+
+export type ImTurnDispatch =
+ | {
+ kind: 'accepted';
+ sessionId: string;
+ acceptedAt: number;
+ terminal: Promise<ImTurnTerminal>;
+ }
+ | {
+ kind: 'busy' | 'rejected';
+ reason: string;
+ };
+
/** createTurnRunner 返回的编排实例 — per channel 一个。 */
export interface ImTurnRunner {
- runAgentTurn(args: {
- botContextId: string;
- userId: string;
- /** 渠道 message id of the user's incoming message — used for emoji ack. */
- userMessageId: string;
- text: string;
- attachments: IMAttachment[];
- /** thread = session 模型的会话维度键(slack);feishu 不传。 */
- scopeKey?: string;
- outputCardMessageId?: string;
- outputCardPrefix?: string;
- onTurnComplete?: () => void;
- /** Keep fire-and-forget work inside the ingress account's drain boundary. */
- trackBackgroundTask?: (operation: () => Promise<void>) => void;
- }): Promise<void>;
+ runAgentTurn(args: ImRunAgentTurnArgs): Promise<void>;
+ /**
+ * Durable callers own their queue and receive an observable accepted/terminal
+ * contract. Busy work is never copied into turnRunner's in-memory sendQueue.
+ */
+ dispatchAgentTurn(
+ args: ImRunAgentTurnArgs & {
+ queueMode: 'external';
+ beforeProviderStart: () => Promise<void>;
+ },
+ ): Promise<ImTurnDispatch>;
resolveRouteTarget(
botContextId: string,
userId: string,
@@ -309,7 +368,7 @@ export function createTurnRunner(
cards: ImCardBuilders,
deps: ImTurnRunnerDeps = {},
): ImTurnRunner {
- const { im, ui, channel } = adapter;
+ const { im, output, ui, channel } = adapter;
/** 过程区耗时显示的低频刷新(5s)— 单个长工具调用期间状态行不冻结。 */
const ACTIVITY_TICK_MS = 5_000;
@@ -443,18 +502,25 @@ export function createTurnRunner(
// ── public entry point ──────────────────────────────────────────────────────
- async function runAgentTurn(args: {
- botContextId: string;
- userId: string;
- userMessageId: string;
- text: string;
- attachments: IMAttachment[];
- scopeKey?: string;
- outputCardMessageId?: string;
- outputCardPrefix?: string;
- onTurnComplete?: () => void;
- trackBackgroundTask?: (operation: () => Promise<void>) => void;
- }): Promise<void> {
+ async function runAgentTurn(args: ImRunAgentTurnArgs): Promise<void> {
+ await dispatchAgentTurnInternal({ ...args, queueMode: 'internal' });
+ }
+
+ async function dispatchAgentTurn(
+ args: ImRunAgentTurnArgs & {
+ queueMode: 'external';
+ beforeProviderStart: () => Promise<void>;
+ },
+ ): Promise<ImTurnDispatch> {
+ return dispatchAgentTurnInternal(args);
+ }
+
+ async function dispatchAgentTurnInternal(
+ args: ImRunAgentTurnArgs & {
+ queueMode: 'internal' | 'external';
+ beforeProviderStart?: () => Promise<void>;
+ },
+ ): Promise<ImTurnDispatch> {
const { botContextId, userId, userMessageId, text, attachments, scopeKey } = args;
// 路由分流 — 先查 binding: 命中走 desktop session (接管模式 C),
@@ -463,22 +529,27 @@ export function createTurnRunner(
if (!target) {
const created = await createAuthenticatedDefaultRouteTarget(botContextId, userId, scopeKey);
if (!created.target) {
- await replyMissingAuth(userId, created.missingAuth, scopeKey);
- return;
+ if (args.queueMode === 'internal') {
+ await replyMissingAuth(userId, created.missingAuth, scopeKey);
+ }
+ return { kind: 'rejected', reason: 'missing_auth' };
}
target = created.target;
}
const row = target.row;
+ args.onRouteResolved?.(row.id);
if (!target.authChecked) {
const auth = await checkImRouteAuthDetailed(row, undefined, authCheckDeps());
if (!auth.ok) {
- await replyMissingAuth(
- userId,
- { ...auth, agentKind: row.agentKind, model: row.model },
- scopeKey,
- target.attached,
- );
- return;
+ if (args.queueMode === 'internal') {
+ await replyMissingAuth(
+ userId,
+ { ...auth, agentKind: row.agentKind, model: row.model },
+ scopeKey,
+ target.attached,
+ );
+ }
+ return { kind: 'rejected', reason: 'missing_auth' };
}
}
@@ -517,13 +588,19 @@ export function createTurnRunner(
? ackProcessing(userMessageId)
: null;
+ let resolveTerminal!: (terminal: ImTurnTerminal) => void;
+ const terminalPromise = new Promise<ImTurnTerminal>((resolve) => {
+ resolveTerminal = resolve;
+ });
const turn: TurnState = {
+ turnId: randomUUID(),
userId,
scopeKey: target.scopeKey,
initialMessageText: text,
streamingHandle: null,
streamingHandlePromise: null,
buffer: '',
+ mediaAbsPaths: [],
done: false,
activity: createTurnActivity(Date.now()),
activityTicker: null,
@@ -535,6 +612,12 @@ export function createTurnRunner(
silentStopSettleUnsub: null,
headlessSetupClosed: false,
releaseHeadlessSetupTurn: null,
+ interactionRouteLease: null,
+ terminalKind: 'done',
+ terminalErrorCode: null,
+ queueMode: args.queueMode,
+ terminalPromise,
+ resolveTerminal,
};
let state: SessionState;
@@ -542,8 +625,12 @@ export function createTurnRunner(
state = await ensureSessionWired(target, userId);
} catch (err) {
if (isCredentialModeSwitchBusyError(err)) {
- await handleSessionWiringBusy(userId, turn);
- return;
+ if (args.queueMode === 'internal') {
+ await handleSessionWiringBusy(userId, turn);
+ } else {
+ await completeTurnCallbackAfterAck(turn);
+ }
+ return { kind: 'busy', reason: 'credential_mode_switch' };
}
throw err;
}
@@ -597,6 +684,9 @@ export function createTurnRunner(
text,
attachments,
notified: false,
+ queueMode: args.queueMode,
+ ...(args.beforeProviderStart ? { beforeProviderStart: args.beforeProviderStart } : {}),
+ ...(args.turnPermissionPolicy ? { turnPermissionPolicy: args.turnPermissionPolicy } : {}),
};
// turn 进行中(本 session 的本渠道 turn 未收口 / sendQueue 已有人排队 /
@@ -607,6 +697,10 @@ export function createTurnRunner(
state.sendQueue.length > 0 ||
state.makerSession.isTurnRunning()
) {
+ if (args.queueMode === 'external') {
+ await completeTurnCallbackAfterAck(turn);
+ return { kind: 'busy', reason: 'session_running' };
+ }
state.sendQueue.push(item);
log.info(`queued message for session=${row.id.slice(-8)} position=${state.sendQueue.length}`);
// 本渠道没有未收口的 turn(纯 desktop turn 在跑) → 派发只能靠它的 stray
@@ -617,10 +711,17 @@ export function createTurnRunner(
armDispatchRetry(state, userId);
}
await notifyQueuedPosition(userId, item, state.sendQueue.length);
- return;
+ return { kind: 'busy', reason: 'queued_internally' };
}
- await dispatchQueuedSend(state, userId, item);
+ const dispatch = await dispatchQueuedSend(state, userId, item);
+ if (dispatch.kind !== 'accepted') return dispatch;
+ return {
+ kind: 'accepted',
+ sessionId: row.id,
+ acceptedAt: dispatch.acceptedAt,
+ terminal: turn.terminalPromise,
+ };
}
/**
@@ -642,7 +743,9 @@ export function createTurnRunner(
state: SessionState,
userId: string,
item: QueuedSend,
- ): Promise<void> {
+ ): Promise<
+ { kind: 'accepted'; acceptedAt: number } | { kind: 'busy' | 'rejected'; reason: string }
+ > {
const rowId = item.rowId;
// 过程区耗时基准取真实派发时刻 — TurnState 创建时可能还要在 sendQueue 里
// 等上一轮跑完, 排队等待不该计入"第 N 步 · 耗时"显示
@@ -651,6 +754,7 @@ export function createTurnRunner(
log.info(
`enqueued turn for session=${rowId.slice(-8)} queueDepth=${state.queue.length} pendingSends=${state.sendQueue.length}`,
);
+ let acceptedAt = 0;
let releaseAgentSwitchLock = (): void => {};
try {
@@ -685,6 +789,41 @@ export function createTurnRunner(
: item.userMessage;
const sendResult = await state.makerSession.send(outgoingMessage as typeof item.userMessage, {
planMode: false,
+ ...(item.turnPermissionPolicy ? { turnPermissionPolicy: item.turnPermissionPolicy } : {}),
+ beforeProviderStart: async () => {
+ item.turn.interactionRouteLease =
+ item.turnPermissionPolicy?.confirmationSurface === 'desktop'
+ ? beginInteractionRoute(state.makerSession, {
+ route: {
+ sessionId: rowId,
+ turnId: item.turn.turnId,
+ origin: item.turnPermissionPolicy.origin,
+ interactionSurface: 'desktop',
+ ...(item.turnPermissionPolicy.confirmationTimeoutMs
+ ? {
+ timeoutMs: item.turnPermissionPolicy.confirmationTimeoutMs,
+ }
+ : {}),
+ ...(item.turnPermissionPolicy.onInteractionStateChange
+ ? {
+ onStateChange: item.turnPermissionPolicy.onInteractionStateChange,
+ }
+ : {}),
+ },
+ })
+ : beginInteractionRoute(state.makerSession, {
+ route: {
+ sessionId: rowId,
+ turnId: item.turn.turnId,
+ origin: { kind: 'im', channel },
+ interactionSurface: 'channel-card',
+ },
+ handle: handleInteractionFor(rowId, userId, state.scopeKey),
+ onCancel: (requestId) => cancelPending(requestId, 'interaction_route_released'),
+ });
+ await item.beforeProviderStart?.();
+ acceptedAt = Date.now();
+ },
// B' 阶段: 把渠道用户消息也写本地 messages 表 — 跟 desktop renderer
// 写自己 user message 等价 (renderer 走 IPC, 我们 main 端直接调函数)。
onAccepted: async () => {
@@ -698,11 +837,16 @@ export function createTurnRunner(
// 路径直接 session.send,必须额外调这里,否则守卫额度恒 0,首次
// silent-stop 就落"已耗尽"误导横幅且永不自动续跑)。
noteSilentStopUserSend(rowId);
- await persistUserMessage({
+ const persisted = await persistUserMessage({
sessionId: rowId,
text: item.text,
attachments: item.attachments,
});
+ await adapter.onUserMessagePersisted?.({
+ sessionId: rowId,
+ userMessageId: item.turn.userMessageId,
+ persisted: persisted !== null,
+ });
},
});
if (pendingHandoff && sendResult.accepted) {
@@ -719,16 +863,23 @@ export function createTurnRunner(
reason: outcome.reason,
context: outcome.context,
});
+ return { kind: 'rejected', reason: outcome.reason };
}
+ return { kind: 'accepted', acceptedAt: acceptedAt || Date.now() };
} catch (err) {
const normalized = normalizeSendError(err);
if (normalized.reason === 'SESSION_RUNNING') {
+ releaseTurnInteractionRoute(item.turn, 'session_running_race');
const i = state.queue.indexOf(item.turn);
if (i >= 0) state.queue.splice(i, 1);
if (state.detachDrainPromise) {
await completeTurnCallbackAfterAck(item.turn);
finishDeferredDetachIfIdle(state);
- return;
+ return { kind: 'busy', reason: 'session_detaching' };
+ }
+ if (item.queueMode === 'external') {
+ await completeTurnCallbackAfterAck(item.turn);
+ return { kind: 'busy', reason: 'session_running' };
}
state.sendQueue.unshift(item);
log.info(
@@ -736,7 +887,7 @@ export function createTurnRunner(
);
await notifyQueuedPosition(userId, item, 1);
armDispatchRetry(state, userId);
- return;
+ return { kind: 'busy', reason: 'queued_internally' };
}
await handleSendPreDispatchFailure(state, userId, {
turn: item.turn,
@@ -745,6 +896,7 @@ export function createTurnRunner(
context: buildSendContext(rowId),
error: normalized.error,
});
+ return { kind: 'rejected', reason: normalized.reason };
} finally {
releaseAgentSwitchLock();
}
@@ -806,11 +958,9 @@ export function createTurnRunner(
}
}
state.unsubscribers = [];
- previous.setInteractionListener(null);
state.makerSession = current;
wireSessionToIpcExternal(current);
state.unsubscribers.push(current.onEvent(handleEventFor(sessionId, userId)));
- current.setInteractionListener(handleInteractionFor(sessionId, userId, state.scopeKey));
sessionStates.set(sessionId, state);
}
@@ -1005,7 +1155,7 @@ export function createTurnRunner(
// 全空,实时也看不到(scheduler / hook-control 两条 headless 链路同款老坑,
// 先例见 scheduler-host/runner.ts 与 hook-control/session-runner.ts)。
// assistant 文本自此由 messagePersistBroadcaster 单点落库,本模块不再自写
- // (见 handleTurnDoneAsync)。wireSessionToIpcExternal 内部用 wiredSessionIds
+ // (见 handleTurnDoneAsync)。wireSessionToIpcExternal 内部用 wiredSessionsById
// 守重,重复调安全。下方 setInteractionListener 会把 wire 装上的 desktop
// interaction listener 覆盖回渠道卡片版,顺序不能颠倒。
wireSessionToIpcExternal(makerSession);
@@ -1029,12 +1179,6 @@ export function createTurnRunner(
// (如果存在) 并存。事件 fan-out 给 streamingHandle / 渠道卡片。
state.unsubscribers.push(makerSession.onEvent(handleEventFor(row.id, userId)));
- // setInteractionListener 是 single-listener: 这一调会覆盖上方
- // wireSessionToIpcExternal 装上的 desktop 版 — 渠道会话(含接管期间)的
- // permission / ask / plan 都走渠道卡片审批, 这正是设计。detach 时
- // executeDetach 会调 installDesktopInteractionListener 还原。
- makerSession.setInteractionListener(handleInteractionFor(row.id, userId, target.scopeKey));
-
// 接管模式: 把 desktop 那边已经在等的 InteractionRequest "原地搬到渠道"。
// 场景: 用户在 desktop 触发了 agent → agent 发出 permission/ask/plan 卡片 →
// desktop 卡片显示在等用户答 → 用户改用渠道 /ctr 接管。这种情况下 SDK 那侧
@@ -1558,6 +1702,10 @@ export function createTurnRunner(
/** 处理一条 scheduler-origin stray 事件,转播到远程控制 thread。 */
function transpondScheduledEvent(state: SessionState, event: AgentEvent): void {
+ // Durable text channels need an inbound context token to address replies.
+ // A desktop-originated scheduler turn has no such token, so it cannot be
+ // safely mirrored and must never fall through to rich-card primitives.
+ if (output.kind === 'chunked-text') return;
// 首条事件惰性建转播态(避免给空 turn 开卡)。
if (!state.scheduledTranspond) {
const origin = event.turnOrigin;
@@ -1673,7 +1821,26 @@ export function createTurnRunner(
release?.();
}
+ function releaseTurnInteractionRoute(turn: TurnState, reason: string): void {
+ const lease = turn.interactionRouteLease;
+ turn.interactionRouteLease = null;
+ lease?.release(reason);
+ }
+
+ function settleTurnTerminal(turn: TurnState): void {
+ const resolve = turn.resolveTerminal;
+ if (!resolve) return;
+ turn.resolveTerminal = null;
+ resolve({
+ kind: turn.terminalKind,
+ text: turn.buffer,
+ completedAt: Date.now(),
+ ...(turn.terminalErrorCode ? { errorCode: turn.terminalErrorCode } : {}),
+ });
+ }
+
function completeTurnCallback(turn: TurnState): void {
+ releaseTurnInteractionRoute(turn, 'turn_terminal');
releaseAttachedImTurnHeadless(turn);
// terminal done/error 的普通收口路径。撤 ack 是不等待的尽力清理,
// 失败由 cancelAckReaction 内部吞掉;pre-dispatch failure 需要更严格
@@ -1695,6 +1862,7 @@ export function createTurnRunner(
}
async function completeTurnCallbackAfterAck(turn: TurnState): Promise<void> {
+ releaseTurnInteractionRoute(turn, 'turn_not_dispatched');
releaseAttachedImTurnHeadless(turn);
await waitForAckCleanupBounded(cancelAckReaction(turn));
invokeTurnCompleteCallback(turn);
@@ -1746,12 +1914,14 @@ export function createTurnRunner(
// pre-dispatch failure 按「有界等待撤 ack → 回调 → 通知」收口。渠道 reaction
// 接口异常挂起时不能卡住 per-user 串行锁,所以这里等到超时就继续失败提示。
await completeTurnCallbackAfterAck(failure.turn);
- try {
- await im.sendText(userId, `❌ 启动 agent 失败:${failure.reason}`, {
- threadTs: state.scopeKey,
- });
- } catch {
- /* 忽略失败:派发失败提示不能再阻塞收口。 */
+ if (failure.turn.queueMode === 'internal') {
+ try {
+ await im.sendText(userId, `❌ 启动 agent 失败:${failure.reason}`, {
+ threadTs: state.scopeKey,
+ });
+ } catch {
+ /* 忽略失败:派发失败提示不能再阻塞收口。 */
+ }
}
if (finishDeferredDetachIfIdle(state)) return;
// 一条 pre-dispatch failure 不能卡死后面的排队消息 — 继续放行。
@@ -1867,17 +2037,53 @@ export function createTurnRunner(
// than each calling startStreamingText (which would mint a new card per
// call and produce a flood of orphan messages).
turn.streamingHandlePromise = (async () => {
- const handle = turn.outputCardMessageId
- ? patchedCardHandle(turn.outputCardMessageId)
- : await im.startStreamingText(turn.userId, undefined, {
- threadTs: turn.scopeKey,
- });
+ const handle =
+ output.kind === 'chunked-text'
+ ? chunkedTextHandle(turn)
+ : turn.outputCardMessageId
+ ? patchedCardHandle(turn.outputCardMessageId)
+ : await output.im.startStreamingText(turn.userId, undefined, {
+ threadTs: turn.scopeKey,
+ });
turn.streamingHandle = handle;
return handle;
})();
return turn.streamingHandlePromise;
}
+ function chunkedTextHandle(turn: TurnState): StreamingTextHandle {
+ let closed = false;
+ return {
+ messageId: `chunked:${turn.turnId}`,
+ append() {
+ // TurnState.buffer is the source of truth; chunked channels do not stream.
+ },
+ replace() {
+ // Best-effort progress remains in memory until terminal commit.
+ },
+ async finalize(finalText: string) {
+ if (closed) return;
+ closed = true;
+ if (output.kind === 'chunked-text') {
+ await output.commitFinal({
+ userId: turn.userId,
+ text: finalText,
+ terminal: turn.terminalKind,
+ threadTs: turn.scopeKey,
+ ...(turn.mediaAbsPaths.length > 0 ? { mediaAbsPaths: turn.mediaAbsPaths } : {}),
+ ...(turn.terminalErrorCode ? { errorCode: turn.terminalErrorCode } : {}),
+ });
+ }
+ },
+ addExtraImageAbsPath(absPath: string) {
+ if (!turn.mediaAbsPaths.includes(absPath)) turn.mediaAbsPaths.push(absPath);
+ },
+ close() {
+ closed = true;
+ },
+ };
+ }
+
/**
* silent-stop done: translator 判定上游用空内容 assistant 消息把"干到一半"的
* turn 静默收尾(done.data.silentStop=true)。wire 进 desktop 管线后,
@@ -1925,11 +2131,22 @@ export function createTurnRunner(
// wireSessionToIpcExternal,由 messagePersistBroadcaster 单点落库(含
// tool_use / tool_result / thinking 过程消息,desktop 重开历史能完整回放)。
// 这里再写一份会产生重复记录。
+ if (!turn.streamingHandle && turn.streamingHandlePromise) {
+ try {
+ await turn.streamingHandlePromise;
+ } catch {
+ // The terminal branch below handles the missing output surface.
+ }
+ }
if (turn.streamingHandle) {
try {
const finalView = composeStreamingView(turn) || '_(空回复)_';
await turn.streamingHandle.finalize(finalView);
} catch (err) {
+ if (output.kind === 'chunked-text') {
+ turn.terminalKind = 'error';
+ turn.terminalErrorCode = 'terminal_output_commit_failed';
+ }
log.warn(
`streamingHandle.finalize failed (non-fatal): ${err instanceof Error ? err.message : String(err)}`,
);
@@ -1938,11 +2155,24 @@ export function createTurnRunner(
// No streamed text at all — send a one-shot text so the user knows the
// turn ended. (Rare; normally agents emit at least one text block.)
try {
- await im.sendText(userId, '✅ (本轮无文本输出)', { threadTs: state.scopeKey });
+ if (output.kind === 'chunked-text') {
+ await output.commitFinal({
+ userId,
+ text: '✅ (本轮无文本输出)',
+ terminal: turn.terminalKind,
+ threadTs: state.scopeKey,
+ ...(turn.mediaAbsPaths.length > 0 ? { mediaAbsPaths: turn.mediaAbsPaths } : {}),
+ });
+ } else {
+ await output.im.sendText(userId, '✅ (本轮无文本输出)', {
+ threadTs: state.scopeKey,
+ });
+ }
} catch {
/* swallow */
}
}
+ settleTurnTerminal(turn);
log.info(
`turn done for session=...${(state.makerSession.id ?? '').slice(-8)}, queueDepth=${state.queue.length}`,
);
@@ -1965,6 +2195,10 @@ export function createTurnRunner(
log.error(`turn error: ${msg}`);
if (turn) clearSilentStopSettleWait(turn);
if (turn) clearActivityTicker(turn);
+ if (turn) {
+ turn.terminalKind = 'error';
+ turn.terminalErrorCode = 'agent_turn_error';
+ }
if (turn) completeTurnCallback(turn);
if (turn?.streamingHandle) {
try {
@@ -1976,11 +2210,25 @@ export function createTurnRunner(
}
} else {
try {
- await im.sendText(userId, `❌ 错误:${msg}`, { threadTs: state.scopeKey });
+ if (output.kind === 'chunked-text') {
+ await output.commitFinal({
+ userId,
+ text: `❌ 错误:${msg}`,
+ terminal: 'error',
+ threadTs: state.scopeKey,
+ errorCode: turn?.terminalErrorCode ?? 'agent_turn_error',
+ ...(turn && turn.mediaAbsPaths.length > 0 ? { mediaAbsPaths: turn.mediaAbsPaths } : {}),
+ });
+ } else {
+ await output.im.sendText(userId, `❌ 错误:${msg}`, {
+ threadTs: state.scopeKey,
+ });
+ }
} catch {
/* swallow */
}
}
+ if (turn) settleTurnTerminal(turn);
if (finishDeferredDetachIfIdle(state)) return;
// error 收口同样要继续放行排队消息 — 一条失败不能卡死后面的队列。
maybeDispatchNextQueued(state, userId);
@@ -2015,6 +2263,39 @@ export function createTurnRunner(
`interaction request kind=${req.kind} requestId=...${req.requestId.slice(-8)} session=...${localSessionId.slice(-8)}`,
);
+ if (output.kind === 'chunked-text') {
+ if (adapter.handleTextInteraction) {
+ if (req.kind === 'permission') {
+ const guard = checkDestructiveToolCall(req.toolName, req.input);
+ if (guard.destructive) {
+ log.warn(`destructive tool blocked: ${req.toolName} (${guard.reason})`);
+ return {
+ kind: 'permission',
+ behavior: 'deny',
+ reason: `[destructiveGuard] ${guard.reason}`,
+ };
+ }
+ }
+ return adapter.handleTextInteraction(userId, req);
+ }
+ if (req.kind === 'ask_user_question') {
+ return { kind: 'ask_user_question', answers: {} };
+ }
+ if (req.kind === 'plan_review') {
+ return {
+ kind: 'plan_review',
+ behavior: 'deny',
+ reason: 'desktop_confirmation_not_installed',
+ dismissed: true,
+ };
+ }
+ return {
+ kind: 'permission',
+ behavior: 'deny',
+ reason: 'desktop_confirmation_not_installed',
+ };
+ }
+
// ── destructive guard ────────────────────────────────────────────────
// 即使 permissionMode='auto' 让 SDK classifier 放行了一些工具,我们仍要
// 兜底拦掉删除类操作 —— 老系统 denyDestructive 行为对齐
@@ -2203,9 +2484,6 @@ export function createTurnRunner(
function detachSessionStateNow(sessionId: string, state: SessionState): void {
sessionStates.delete(sessionId);
cleanupSessionState(state);
- // 还原 desktop 版 interaction listener — 接管期间被本渠道版覆盖了,
- // 不还原 desktop renderer 永远收不到 permission 弹窗。
- installDesktopInteractionListener(state.makerSession);
settleDetachDrain(state, 'rewire');
log.info(`detached ${channel} hook from session=${sessionId.slice(-8)}`);
}
@@ -2269,6 +2547,7 @@ export function createTurnRunner(
// 不产生任何事件,不重置的话守卫照样自动续跑,用户喊停后 agent 原地复活。
// 重置后守卫判 superseded → settle('skip') → 挂起 turn 经现有订阅按 done 收口。
noteSilentStopSessionReset(state.makerSession.id);
+ if (state.queue[0]) state.queue[0].terminalKind = 'aborted';
await state.makerSession.abort();
log.info(
`!stop aborted turn for session=...${state.makerSession.id.slice(-8)} droppedQueued=${droppedQueued}`,
@@ -2314,11 +2593,17 @@ export function createTurnRunner(
/* swallow */
}
}
- state.makerSession.setInteractionListener(null);
+ for (const turn of state.queue) {
+ releaseTurnInteractionRoute(turn, 'session_cleanup');
+ turn.terminalKind = 'aborted';
+ turn.terminalErrorCode ??= 'session_cleanup';
+ settleTurnTerminal(turn);
+ }
}
return {
runAgentTurn,
+ dispatchAgentTurn,
resolveRouteTarget,
hasAuthForRoute: (row) => hasAuthForImRoute(row, undefined, authCheckDeps()),
getAuthStatusForRoute: (row) => checkImRouteAuthDetailed(row, undefined, authCheckDeps()),
diff --git a/apps/desktop/src/main/im/shared/types.ts b/apps/desktop/src/main/im/shared/types.ts
index 24a8b45b5e..efc1fd2eba 100644
--- a/apps/desktop/src/main/im/shared/types.ts
+++ b/apps/desktop/src/main/im/shared/types.ts
@@ -17,11 +17,17 @@
* 不存在静默回退
*/
-import type { AgentKind, Effort, PermissionMode } from '@cindy/maker-core';
-import type { ChannelIM, IMUnsupportedEntry } from '@cindy/im';
+import type {
+ AgentKind,
+ Effort,
+ InteractionDecision,
+ InteractionRequest,
+ PermissionMode,
+} from '@cindy/maker-core';
+import type { ChannelIM, ImOutputDriver, IMUnsupportedEntry } from '@cindy/im';
/** 渠道名 — 同时是 sessions.source 列值与 IdentityKey.channel 的值域。 */
-export type ImChannelName = 'feishu' | 'slack' | 'discord';
+export type ImChannelName = 'feishu' | 'slack' | 'discord' | 'wechat';
/**
* IM 编排层的产品默认配置(由 main/im/index.ts 产品接线层注入)。
@@ -83,6 +89,8 @@ export interface ImChannelAdapter {
channel: ImChannelName;
/** 收发能力(@cindy/im ChannelIM 契约)。 */
im: ChannelIM;
+ /** Terminal output strategy; existing channels use rich-card. */
+ output: ImOutputDriver;
config: ImOrchestratorConfig;
ui: ImUiTextPack;
sessions: ImSessionNamespace;
@@ -102,6 +110,20 @@ export interface ImChannelAdapter {
* threadScoped 渠道会收到 scopeKey(thread root ts), 供 MCP 出站定位 thread。
*/
buildVendorOptions(userId: string, scopeKey?: string): Record<string, unknown>;
+ /**
+ * Text-only channels can still resolve agent interactions without rich cards.
+ * The callback owns channel-specific correlation and parsing.
+ */
+ handleTextInteraction?(
+ userId: string,
+ request: InteractionRequest,
+ ): Promise<InteractionDecision>;
+ /** Durable channels may promote task-scoped attachments after message persistence succeeds. */
+ onUserMessagePersisted?(args: {
+ sessionId: string;
+ userMessageId: string | null;
+ persisted: boolean;
+ }): Promise<void>;
}
// ── UI 文案包 ─────────────────────────────────────────────────────────────────
diff --git a/apps/desktop/src/main/im/wechat/WechatIM.ts b/apps/desktop/src/main/im/wechat/WechatIM.ts
new file mode 100644
index 0000000000..791be00baa
--- /dev/null
+++ b/apps/desktop/src/main/im/wechat/WechatIM.ts
@@ -0,0 +1,1934 @@
+import { createHash, randomBytes, randomUUID } from 'node:crypto';
+import fs from 'node:fs/promises';
+import path from 'node:path';
+
+import {
+ BaseIM,
+ type IMCardActionEvent,
+ type IMHost,
+ type IMMessageEvent,
+ type IMStatus,
+ type RichChannelIM,
+ type SendFileResult,
+ type StreamingTextHandle,
+} from '@cindy/im';
+import {
+ asWechatIlinkError,
+ chunkWechatText,
+ filterWechatMarkdown,
+ WECHAT_MEDIA_MAX_BYTES,
+ WechatIlinkError,
+ type WechatAuthorizationEvent,
+ type WechatCredentials,
+ type WechatInboundMessage,
+ type WechatTransport,
+} from '@cindy/wechat-ilink';
+import type { InteractionDecision, InteractionRequest } from '@cindy/maker-core';
+
+import type { ImSessionRepo } from '../shared/sessionRepo';
+import type { ImOrchestratorConfig } from '../shared/types';
+import type { ImFinalOutput } from '@cindy/im';
+import type { ImTurnRunner } from '../shared/turnRunner';
+import { createWechatTurnPermissionPolicy } from './permissionPolicy';
+import { WechatTaskStore, type WechatActiveBinding, type WechatTask } from './taskStore';
+import type { DbClient } from '../../localDb/client/DbClient';
+import {
+ removeUncommittedWechatFiles,
+ removeReleasedWechatFiles,
+ stageWechatTaskMedia,
+ type WechatTaskAttachment,
+} from './mediaStaging';
+
+const CREDENTIAL_PREFIX = 'wechat_credentials_';
+const DATA_KEY_NAME = 'wechat_data_key_v1';
+const AUTH_BASE_URL = 'https://ilinkai.weixin.qq.com';
+const EMPTY_POLL_DELAY_MS = 100;
+const IDLE_PUMP_DELAY_MS = 200;
+const RECONNECT_DELAYS_MS = [1_000, 2_000, 5_000, 10_000, 30_000] as const;
+
+export type WechatBotPhase =
+ | 'disconnected'
+ | 'authorizing'
+ | 'waiting_confirmation'
+ | 'connected'
+ | 'reconnecting'
+ | 'needs_reauth'
+ | 'disabled_by_policy'
+ | 'error';
+
+export interface WechatBotState {
+ phase: WechatBotPhase;
+ bound: boolean;
+ connectedAt?: number;
+ lastInboundAt?: number;
+ queuedTasks: number;
+ errorCode?: string;
+}
+
+interface StoredWechatCredentials {
+ botToken: string;
+ ilinkBotId: string;
+ userId: string;
+ baseUrl: string;
+ boundAt: number;
+ bindingEpoch: string;
+}
+
+interface WechatTaskPayload {
+ text: string;
+ attachments: WechatTaskAttachment[];
+ unsupportedMedia: string[];
+}
+
+interface ActiveTask {
+ task: WechatTask;
+ routeSessionId?: string;
+ terminalCommitted: boolean;
+}
+
+interface PendingWechatInteraction {
+ request: InteractionRequest;
+ resolve: (decision: InteractionDecision) => void;
+ timer: NodeJS.Timeout;
+}
+
+interface TurnRuntime {
+ runner: ImTurnRunner;
+ repo: ImSessionRepo;
+ config: ImOrchestratorConfig;
+ resetSessionToDefaults(
+ sessionId: string,
+ config: ImOrchestratorConfig,
+ prepared: Awaited<ReturnType<ImSessionRepo['prepareNewSession']>>,
+ ): Promise<void>;
+}
+
+export interface WechatIMDeps {
+ host: IMHost;
+ getDbClient(): DbClient;
+ createTransport(args: {
+ credentials: StoredWechatCredentials | null;
+ onAuthorizationEvent?: (event: WechatAuthorizationEvent) => void;
+ }): WechatTransport;
+ openAuthorizationUrl(url: string): Promise<void>;
+ captureAccountGeneration(): number | null;
+ isAccountGenerationCurrent(generation: number): boolean;
+ isCompatibilityDisabled(): boolean;
+ now?: () => number;
+}
+
+/**
+ * Main-process personal WeChat connector.
+ *
+ * The class implements the rich interface only because the existing shared
+ * turn runner still carries legacy card methods in its adapter type. Its
+ * output driver is always `chunked-text`; every card method fails loudly so a
+ * future regression cannot silently send a fake card over personal WeChat.
+ */
+export class WechatIM extends BaseIM implements RichChannelIM {
+ readonly #deps: WechatIMDeps;
+ readonly #statusHandlers = new Set<(status: IMStatus) => void>();
+ readonly #messageHandlers = new Set<(event: IMMessageEvent) => void>();
+ readonly #activeTasks = new Map<string, ActiveTask>();
+ readonly #pendingInteractions = new Map<string, PendingWechatInteraction>();
+ #state: Omit<WechatBotState, 'bound'> = { phase: 'disconnected', queuedTasks: 0 };
+ #hasBinding = false;
+ #store: WechatTaskStore | null = null;
+ #turnRuntime: TurnRuntime | null = null;
+ #epoch: {
+ binding: WechatActiveBinding;
+ credentials: StoredWechatCredentials;
+ transport: WechatTransport;
+ abort: AbortController;
+ drain: Promise<void>;
+ generation: number;
+ } | null = null;
+ #authorizationAbort: AbortController | null = null;
+ #pollBarrier: Promise<void> = Promise.resolve();
+ #compatibilityDisabled = false;
+ #compatibilityRevision = 0;
+ #lifecycleBarrier: Promise<void> = Promise.resolve();
+
+ constructor(deps: WechatIMDeps) {
+ super('wechat', deps.host);
+ this.#deps = deps;
+ this.#compatibilityDisabled = deps.isCompatibilityDisabled();
+ }
+
+ attachTurnRuntime(runtime: TurnRuntime): void {
+ if (this.#turnRuntime) throw new Error('WeChat turn runtime already attached.');
+ this.#turnRuntime = runtime;
+ }
+
+ getState(): WechatBotState {
+ return { ...this.#state, bound: this.#hasBinding };
+ }
+
+ async init(): Promise<void> {
+ await this.setCompatibilityDisabled(this.#deps.isCompatibilityDisabled());
+ const revision = this.#compatibilityRevision;
+ await this.#queueLifecycle(async () => {
+ if (this.#store && !this.#compatibilityDisabled) return;
+ await this.#resumeStoredBinding(revision);
+ });
+ }
+
+ setCompatibilityDisabled(disabled: boolean): Promise<void> {
+ if (disabled === this.#compatibilityDisabled) return this.#lifecycleBarrier;
+ this.#compatibilityDisabled = disabled;
+ const revision = ++this.#compatibilityRevision;
+ if (disabled) {
+ this.cancelAuthorization();
+ this.#epoch?.abort.abort();
+ this.#setState({
+ phase: 'disabled_by_policy',
+ queuedTasks: this.#state.queuedTasks,
+ });
+ }
+ return this.#queueLifecycle(() => this.#applyCompatibilityDisabled(disabled, revision));
+ }
+
+ async #applyCompatibilityDisabled(disabled: boolean, revision: number): Promise<void> {
+ if (revision !== this.#compatibilityRevision || disabled !== this.#compatibilityDisabled) return;
+ if (disabled) {
+ const stopped = this.#stopEpoch();
+ this.#setState({
+ phase: 'disabled_by_policy',
+ queuedTasks: this.#state.queuedTasks,
+ });
+ await stopped;
+ return;
+ }
+ if (!this.#hasBinding) {
+ this.#setState({ phase: 'disconnected', queuedTasks: 0 });
+ return;
+ }
+ await this.#resumeStoredBinding(revision);
+ }
+
+ async #resumeStoredBinding(revision: number): Promise<void> {
+ const active = await this.#readActiveBindingWithoutKey();
+ if (!this.#isCompatibilityRevisionCurrent(revision)) return;
+ if (!active) {
+ this.#hasBinding = false;
+ this.#setState({
+ phase: this.#compatibilityDisabled ? 'disabled_by_policy' : 'disconnected',
+ queuedTasks: 0,
+ });
+ return;
+ }
+ this.#hasBinding = true;
+ if (this.#compatibilityDisabled) {
+ this.#setState({ phase: 'disabled_by_policy', queuedTasks: 0 });
+ return;
+ }
+ const key = this.#readDataKey();
+ const credentials = this.#readCredentials(active.bindingEpoch);
+ if (!key || !credentials) {
+ this.#setState({
+ phase: 'needs_reauth',
+ queuedTasks: 0,
+ errorCode: 'credentials_missing',
+ });
+ return;
+ }
+ if (!this.#store) {
+ this.#store = new WechatTaskStore(this.#deps.getDbClient(), key);
+ await this.#store.stopAll({
+ bindingEpoch: active.bindingEpoch,
+ now: this.#now(),
+ errorCode: 'PROCESS_RESTARTED',
+ });
+ }
+ if (!this.#isCompatibilityRevisionAllowed(revision)) return;
+ await this.#stopEpoch();
+ if (!this.#isCompatibilityRevisionAllowed(revision)) return;
+ await this.#startEpoch(active, credentials, revision);
+ }
+
+ dispose(): Promise<void> {
+ this.cancelAuthorization();
+ return this.#queueLifecycle(async () => {
+ await this.#stopEpoch();
+ this.#store?.destroy();
+ this.#store = null;
+ this.#activeTasks.clear();
+ this.#hasBinding = false;
+ this.#setState({ phase: 'disconnected', queuedTasks: 0 });
+ });
+ }
+
+ registerIpc(): void {
+ // Registered in Desktop Main with a trusted-renderer sender check.
+ }
+
+ async authorize(): Promise<{ started: true }> {
+ if (this.#deps.isCompatibilityDisabled() && !this.#compatibilityDisabled) {
+ await this.setCompatibilityDisabled(true);
+ }
+ if (this.#compatibilityDisabled) {
+ this.#setState({
+ phase: 'disabled_by_policy',
+ queuedTasks: this.#state.queuedTasks,
+ });
+ throw new Error('WECHAT_DISABLED_BY_POLICY');
+ }
+ const compatibilityRevision = this.#compatibilityRevision;
+ if (!this.host.secrets.isAvailable()) {
+ throw new Error('WECHAT_SAFE_STORAGE_UNAVAILABLE');
+ }
+ const generation = this.#deps.captureAccountGeneration();
+ if (generation === null) throw new Error('WECHAT_ACCOUNT_SCOPE_CLOSED');
+ this.cancelAuthorization();
+ const abort = new AbortController();
+ this.#authorizationAbort = abort;
+ this.#setState({ ...this.#state, phase: 'authorizing', errorCode: undefined });
+ const transport = this.#deps.createTransport({
+ credentials: null,
+ onAuthorizationEvent: (event) => {
+ if (
+ this.#authorizationAbort !== abort ||
+ !this.#isCompatibilityRevisionAllowed(compatibilityRevision)
+ ) {
+ return;
+ }
+ if (event.status === 'waiting' || event.status === 'scanned') {
+ this.#setState({ ...this.#state, phase: 'waiting_confirmation' });
+ } else if (event.status === 'qr-refreshed') {
+ void this.#deps.openAuthorizationUrl(event.challenge.qrCodeUrl);
+ }
+ },
+ });
+
+ void (async () => {
+ try {
+ const challenge = await transport.beginAuthorization(abort.signal);
+ if (
+ this.#authorizationAbort !== abort ||
+ !this.#isGenerationCurrent(generation) ||
+ !this.#isCompatibilityRevisionAllowed(compatibilityRevision)
+ ) {
+ return;
+ }
+ this.#setState({ ...this.#state, phase: 'waiting_confirmation' });
+ await this.#deps.openAuthorizationUrl(challenge.qrCodeUrl);
+ const credentials = await transport.waitAuthorization(challenge, abort.signal);
+ if (
+ this.#authorizationAbort !== abort ||
+ !this.#isGenerationCurrent(generation) ||
+ !this.#isCompatibilityRevisionAllowed(compatibilityRevision)
+ ) {
+ return;
+ }
+ await this.#queueLifecycle(() =>
+ this.#activateAuthorizedCredentials(credentials, generation, compatibilityRevision),
+ );
+ } catch (error) {
+ const safe = asWechatIlinkError(error);
+ if (
+ safe.code !== 'ABORTED' &&
+ this.#isGenerationCurrent(generation) &&
+ this.#isCompatibilityRevisionAllowed(compatibilityRevision)
+ ) {
+ this.#setState({
+ ...this.#state,
+ phase: safe.code === 'AUTH_REPLACED' ? 'needs_reauth' : 'error',
+ errorCode: safe.code.toLowerCase(),
+ });
+ }
+ } finally {
+ if (this.#authorizationAbort === abort) this.#authorizationAbort = null;
+ }
+ })();
+ return { started: true };
+ }
+
+ cancelAuthorization(): void {
+ this.#authorizationAbort?.abort();
+ this.#authorizationAbort = null;
+ if (this.#state.phase === 'authorizing' || this.#state.phase === 'waiting_confirmation') {
+ this.#setState({
+ ...this.#state,
+ phase: authorizationCancelPhase(Boolean(this.#epoch), this.#hasBinding),
+ });
+ }
+ }
+
+ unbind(): Promise<void> {
+ this.cancelAuthorization();
+ return this.#queueLifecycle(() => this.#unbind());
+ }
+
+ async #unbind(): Promise<void> {
+ const active = this.#epoch?.binding ?? (await this.#readActiveBindingWithoutKey());
+ if (!active) {
+ this.#setState({
+ phase: this.#compatibilityDisabled ? 'disabled_by_policy' : 'disconnected',
+ queuedTasks: 0,
+ });
+ return;
+ }
+ const key = this.#readDataKey();
+ if (!key) throw new Error('WECHAT_DATA_KEY_UNAVAILABLE');
+ const store = this.#store ?? new WechatTaskStore(this.#deps.getDbClient(), key);
+ // Stop the live agent turn while its binding is still valid. Closing the
+ // rows first lets a late terminal callback race with cleanup and leaves
+ // the attached Desktop session running after the user has unbound.
+ await this.#stopEpoch();
+ await store.closeBindingEpoch(active.bindingEpoch, this.#now());
+ const cleanup = await store.unbindCleanup(active.bindingEpoch);
+ await removeReleasedWechatFiles(cleanup.filePaths);
+ this.host.secrets.remove(`${CREDENTIAL_PREFIX}${active.bindingEpoch}`);
+ this.host.secrets.remove(DATA_KEY_NAME);
+ store.destroy();
+ this.#store = null;
+ this.#hasBinding = false;
+ this.#setState({
+ phase: this.#compatibilityDisabled ? 'disabled_by_policy' : 'disconnected',
+ queuedTasks: 0,
+ });
+ }
+
+ onMessage(handler: (event: IMMessageEvent) => void): () => void {
+ this.#messageHandlers.add(handler);
+ return () => this.#messageHandlers.delete(handler);
+ }
+
+ onStatusChange(handler: (status: IMStatus) => void): () => void {
+ this.#statusHandlers.add(handler);
+ return () => this.#statusHandlers.delete(handler);
+ }
+
+ onCardAction(handler: (event: IMCardActionEvent) => void): () => void {
+ void handler;
+ return () => undefined;
+ }
+
+ getStatus(): IMStatus {
+ if (this.#state.phase === 'connected') {
+ return { kind: 'connected', appId: this.#epoch?.credentials.ilinkBotId ?? 'wechat' };
+ }
+ if (
+ this.#state.phase === 'authorizing' ||
+ this.#state.phase === 'waiting_confirmation' ||
+ this.#state.phase === 'reconnecting'
+ ) {
+ return { kind: 'connecting' };
+ }
+ if (this.#state.phase === 'error' || this.#state.phase === 'needs_reauth') {
+ return { kind: 'error', reason: this.#state.errorCode ?? 'wechat_error' };
+ }
+ return { kind: 'idle' };
+ }
+
+ async sendText(userId: string, text: string): Promise<{ messageId: string }> {
+ const active = this.#activeTasks.get(userId);
+ const epoch = this.#epoch;
+ if (!epoch || this.#compatibilityDisabled || epoch.abort.signal.aborted) {
+ throw new Error('WECHAT_NO_ACTIVE_CONTEXT');
+ }
+ const contextToken =
+ active?.task.contextToken ??
+ (
+ await this.#requireStore().getLatestPeerContext({
+ bindingEpoch: epoch.binding.bindingEpoch,
+ peerId: userId,
+ })
+ )?.contextToken;
+ if (!contextToken) throw new Error('WECHAT_PEER_NOT_KNOWN');
+ const clientId = randomUUID();
+ await epoch.transport.sendMessage(
+ {
+ peerId: userId,
+ text,
+ contextToken,
+ clientId,
+ },
+ epoch.abort.signal,
+ );
+ return { messageId: clientId };
+ }
+
+ async getMostRecentPeerId(): Promise<string | null> {
+ const epoch = this.#epoch;
+ if (!epoch || this.#compatibilityDisabled || epoch.abort.signal.aborted) return null;
+ return this.#requireStore().getMostRecentPeer(epoch.binding.bindingEpoch);
+ }
+
+ getActivePeerIdForSession(sessionId: string | undefined): string | null {
+ if (!sessionId) return null;
+ const peers = [...this.#activeTasks.entries()]
+ .filter(
+ ([, active]) => (active.routeSessionId ?? active.task.sessionId) === sessionId,
+ )
+ .map(([peerId]) => peerId);
+ return peers.length === 1 ? peers[0]! : null;
+ }
+
+ async handleTextInteraction(
+ userId: string,
+ request: InteractionRequest,
+ ): Promise<InteractionDecision> {
+ const previous = this.#pendingInteractions.get(userId);
+ if (previous) {
+ clearTimeout(previous.timer);
+ previous.resolve(defaultWechatInteractionDecision(previous.request, 'replaced_by_new_request'));
+ }
+
+ let resolvePending!: (decision: InteractionDecision) => void;
+ const result = new Promise<InteractionDecision>((resolve) => {
+ resolvePending = resolve;
+ });
+ const timer = setTimeout(() => {
+ this.#pendingInteractions.delete(userId);
+ resolvePending(defaultWechatInteractionDecision(request, 'wechat_interaction_timeout'));
+ }, 10 * 60_000);
+ timer.unref?.();
+ this.#pendingInteractions.set(userId, { request, resolve: resolvePending, timer });
+ try {
+ await this.sendText(userId, formatWechatInteractionPrompt(request));
+ } catch (error) {
+ const pending = this.#pendingInteractions.get(userId);
+ if (pending?.request.requestId === request.requestId) {
+ clearTimeout(pending.timer);
+ this.#pendingInteractions.delete(userId);
+ }
+ return defaultWechatInteractionDecision(
+ request,
+ error instanceof Error ? error.message : 'wechat_interaction_send_failed',
+ );
+ }
+ return result;
+ }
+
+ sendMarkdownText(userId: string, markdown: string): Promise<{ messageId: string }> {
+ return this.sendText(userId, filterWechatMarkdown(markdown));
+ }
+
+ async sendFile(userId: string, absPath: string, displayName?: string): Promise<SendFileResult> {
+ const epoch = this.#epoch;
+ if (!epoch || this.#compatibilityDisabled || epoch.abort.signal.aborted) {
+ return { ok: false, reason: 'SEND_FAIL' };
+ }
+ const contextToken =
+ this.#activeTasks.get(userId)?.task.contextToken ??
+ (
+ await this.#requireStore().getLatestPeerContext({
+ bindingEpoch: epoch.binding.bindingEpoch,
+ peerId: userId,
+ })
+ )?.contextToken;
+ if (!contextToken) return { ok: false, reason: 'SEND_FAIL' };
+ let uploadedSuccessfully = false;
+ try {
+ const local = await readOutboundWechatFile(absPath, displayName);
+ if (this.#compatibilityDisabled || epoch.abort.signal.aborted) {
+ return { ok: false, reason: 'SEND_FAIL' };
+ }
+ const uploaded = await epoch.transport.uploadMedia(
+ {
+ peerId: userId,
+ bytes: local.bytes,
+ fileName: local.fileName,
+ kind: local.kind,
+ },
+ epoch.abort.signal,
+ );
+ uploadedSuccessfully = true;
+ if (this.#compatibilityDisabled || epoch.abort.signal.aborted) {
+ return { ok: false, reason: 'SEND_FAIL' };
+ }
+ const clientId = randomUUID();
+ await epoch.transport.sendMedia(
+ {
+ peerId: userId,
+ contextToken,
+ clientId,
+ uploaded,
+ },
+ epoch.abort.signal,
+ );
+ return { ok: true, messageId: clientId };
+ } catch (error) {
+ const code =
+ error instanceof Error && 'code' in error
+ ? String((error as NodeJS.ErrnoException).code)
+ : '';
+ if (code === 'ENOENT') return { ok: false, reason: 'NOT_FOUND' };
+ if (code === 'WECHAT_FILE_EMPTY') return { ok: false, reason: 'EMPTY' };
+ if (code === 'WECHAT_FILE_TOO_LARGE') return { ok: false, reason: 'TOO_LARGE' };
+ return { ok: false, reason: uploadedSuccessfully ? 'SEND_FAIL' : 'UPLOAD_FAIL' };
+ }
+ }
+
+ sendInteractiveCard(): Promise<{ messageId: string }> {
+ return Promise.reject(new Error('WECHAT_RICH_OUTPUT_UNSUPPORTED'));
+ }
+
+ updateInteractiveCard(): Promise<void> {
+ return Promise.reject(new Error('WECHAT_RICH_OUTPUT_UNSUPPORTED'));
+ }
+
+ patchMarkdownCard(): Promise<void> {
+ return Promise.reject(new Error('WECHAT_RICH_OUTPUT_UNSUPPORTED'));
+ }
+
+ startStreamingText(
+ userId: string,
+ initial?: string,
+ opts?: { threadTs?: string },
+ ): Promise<StreamingTextHandle> {
+ void userId;
+ void initial;
+ void opts;
+ return Promise.reject(new Error('WECHAT_RICH_OUTPUT_UNSUPPORTED'));
+ }
+
+ async commitFinal(output: ImFinalOutput): Promise<void> {
+ const active = this.#activeTasks.get(output.userId);
+ if (!active) throw new Error('WECHAT_NO_ACTIVE_TASK');
+ const chunks = chunkWechatText(normalizeFinalOutputText(output.text));
+ const kind =
+ output.terminal === 'done'
+ ? ('final' as const)
+ : output.terminal === 'aborted'
+ ? ('interrupted' as const)
+ : ('error' as const);
+ const result = await this.#requireStore().commitTerminal({
+ bindingEpoch: active.task.bindingEpoch,
+ taskId: active.task.id,
+ now: this.#now(),
+ outbox: chunks.map((chunk, index) => ({
+ id: randomUUID(),
+ clientId: randomUUID(),
+ kind,
+ chunkIndex: index,
+ text: chunk,
+ ...(index === 0 && output.mediaAbsPaths?.length
+ ? {
+ mediaJson: JSON.stringify(
+ output.mediaAbsPaths.slice(0, 4).map((absPath) => ({
+ absPath,
+ clientId: randomUUID(),
+ })),
+ ),
+ }
+ : {}),
+ })),
+ });
+ if (!result.committed) throw new Error('WECHAT_TERMINAL_COMMIT_REJECTED');
+ active.terminalCommitted = true;
+ }
+
+ async onUserMessagePersisted(args: {
+ sessionId: string;
+ userMessageId: string | null;
+ persisted: boolean;
+ }): Promise<void> {
+ const bindingEpoch = this.#epoch?.binding.bindingEpoch;
+ if (!args.persisted || !args.userMessageId || !bindingEpoch) return;
+ try {
+ await this.#requireStore().promoteTaskAttachments({
+ bindingEpoch,
+ taskId: args.userMessageId,
+ sessionId: args.sessionId,
+ now: this.#now(),
+ });
+ } catch (error) {
+ this.log.warn('WeChat attachment promotion requires repair', {
+ task: shortId(args.userMessageId),
+ code: machineErrorCode(error),
+ });
+ }
+ }
+
+ async #activateAuthorizedCredentials(
+ raw: WechatCredentials,
+ generation: number,
+ compatibilityRevision: number,
+ ): Promise<void> {
+ if (
+ !this.#isGenerationCurrent(generation) ||
+ !this.#isCompatibilityRevisionAllowed(compatibilityRevision)
+ ) {
+ return;
+ }
+ const bindingEpoch = randomUUID();
+ const stored: StoredWechatCredentials = {
+ botToken: raw.token,
+ ilinkBotId: raw.botId,
+ userId: raw.userId,
+ baseUrl: raw.baseUrl,
+ boundAt: this.#now(),
+ bindingEpoch,
+ };
+ const key = this.#readDataKey() ?? randomBytes(32);
+ if (!this.host.secrets.write(DATA_KEY_NAME, Buffer.from(key).toString('base64'))) {
+ throw new Error('WECHAT_DATA_KEY_WRITE_FAILED');
+ }
+ if (!this.host.secrets.write(`${CREDENTIAL_PREFIX}${bindingEpoch}`, JSON.stringify(stored))) {
+ throw new Error('WECHAT_CREDENTIAL_WRITE_FAILED');
+ }
+ const store = this.#store ?? new WechatTaskStore(this.#deps.getDbClient(), key);
+ this.#store = store;
+ const previous = await store.getActiveBinding();
+ const activated = await store.activateBindingEpoch({
+ bindingEpoch,
+ expectedActiveEpoch: previous?.bindingEpoch ?? null,
+ now: this.#now(),
+ });
+ if (
+ !activated.activated ||
+ !this.#isGenerationCurrent(generation) ||
+ !this.#isCompatibilityRevisionAllowed(compatibilityRevision)
+ ) {
+ let restoredPrevious = false;
+ if (activated.activated) {
+ if (previous) {
+ const rollback = await store.activateBindingEpoch({
+ bindingEpoch: previous.bindingEpoch,
+ expectedActiveEpoch: bindingEpoch,
+ initialCursor: previous.cursor,
+ now: this.#now(),
+ });
+ restoredPrevious = rollback.activated;
+ } else {
+ await store.closeBindingEpoch(bindingEpoch, this.#now());
+ }
+ }
+ this.host.secrets.remove(`${CREDENTIAL_PREFIX}${bindingEpoch}`);
+ this.#hasBinding = activated.activated
+ ? restoredPrevious
+ : activated.activeBindingEpoch !== null;
+ throw new Error('WECHAT_BINDING_EPOCH_STALE');
+ }
+ this.#hasBinding = true;
+ await this.#stopEpoch();
+ if (previous) {
+ await store.closeBindingEpoch(previous.bindingEpoch, this.#now());
+ const cleanup = await store.unbindCleanup(previous.bindingEpoch);
+ await removeReleasedWechatFiles(cleanup.filePaths);
+ this.host.secrets.remove(`${CREDENTIAL_PREFIX}${previous.bindingEpoch}`);
+ }
+ if (!this.#isCompatibilityRevisionAllowed(compatibilityRevision)) return;
+ await this.#startEpoch({ bindingEpoch, cursor: '' }, stored, compatibilityRevision);
+ }
+
+ async #startEpoch(
+ binding: WechatActiveBinding,
+ credentials: StoredWechatCredentials,
+ compatibilityRevision: number,
+ ): Promise<void> {
+ if (!this.#isCompatibilityRevisionAllowed(compatibilityRevision)) return;
+ const generation = this.#deps.captureAccountGeneration();
+ if (generation === null) throw new Error('WECHAT_ACCOUNT_SCOPE_CLOSED');
+ const abort = new AbortController();
+ const transport = this.#deps.createTransport({ credentials });
+ try {
+ await transport.notifyStart(abort.signal);
+ } catch (error) {
+ if (abort.signal.aborted) return;
+ this.log.warn('WeChat start notification failed; continuing with polling', {
+ code: machineErrorCode(error),
+ });
+ }
+ if (
+ abort.signal.aborted ||
+ !this.#isGenerationCurrent(generation) ||
+ !this.#isCompatibilityRevisionAllowed(compatibilityRevision)
+ ) {
+ return;
+ }
+ const drain = Promise.allSettled([
+ this.#pollLoop(binding, transport, abort.signal, generation),
+ this.#taskPump(binding, abort.signal, generation),
+ this.#outboxLoop(binding, transport, abort.signal, generation),
+ ]).then(() => undefined);
+ this.#epoch = { binding, credentials, transport, abort, drain, generation };
+ const queuedTasks = await this.#requireStore().countQueuedTasks(binding.bindingEpoch);
+ if (!this.#isCompatibilityRevisionAllowed(compatibilityRevision)) {
+ await this.#stopEpoch();
+ return;
+ }
+ this.#setState({
+ phase: 'connected',
+ connectedAt: this.#now(),
+ queuedTasks,
+ });
+ }
+
+ async #stopEpoch(): Promise<void> {
+ const epoch = this.#epoch;
+ this.#epoch = null;
+ if (!epoch) return;
+ epoch.abort.abort();
+ for (const [peerId, pending] of this.#pendingInteractions) {
+ clearTimeout(pending.timer);
+ pending.resolve(defaultWechatInteractionDecision(pending.request, 'wechat_binding_stopped'));
+ this.#pendingInteractions.delete(peerId);
+ }
+ await stopActiveWechatTurns(
+ this.#turnRuntime?.runner ?? null,
+ epoch.credentials.ilinkBotId,
+ this.#activeTasks.keys(),
+ );
+ await epoch.drain;
+ try {
+ await epoch.transport.notifyStop(new AbortController().signal);
+ } catch (error) {
+ this.log.warn('WeChat stop notification failed', {
+ code: machineErrorCode(error),
+ });
+ }
+ this.#activeTasks.clear();
+ }
+
+ async #pollLoop(
+ binding: WechatActiveBinding,
+ transport: WechatTransport,
+ signal: AbortSignal,
+ generation: number,
+ ): Promise<void> {
+ let cursor = binding.cursor;
+ let failures = 0;
+ while (!signal.aborted && this.#isGenerationCurrent(generation)) {
+ try {
+ const result = await transport.poll(cursor, signal);
+ const now = this.#now();
+ const preparedInputs = await Promise.all(
+ result.messages.map((message, index) =>
+ this.#toTaskInput(binding.bindingEpoch, message, transport, signal, now, index),
+ ),
+ );
+ const interactionIndexes = new Set(
+ result.messages
+ .map((message, index) =>
+ this.#pendingInteractions.has(message.senderId) &&
+ message.text.trim() !== '/stop' &&
+ message.text.trim() !== '/stop all'
+ ? index
+ : -1,
+ )
+ .filter((index) => index >= 0),
+ );
+ const normalPreparedInputs = preparedInputs.filter(
+ (_input, index) => !interactionIndexes.has(index),
+ );
+ const inputs = normalPreparedInputs.map((input) => input.message);
+ const mediaBlobs = normalPreparedInputs.flatMap((input) => input.mediaBlobs);
+ const mediaRefs = normalPreparedInputs.flatMap((input) => input.mediaRefs);
+ const fileAttachments = normalPreparedInputs.flatMap((input) => input.fileAttachments);
+ const allFileAttachments = preparedInputs.flatMap((input) => input.fileAttachments);
+ let releasePollBarrier!: () => void;
+ this.#pollBarrier = new Promise<void>((resolve) => {
+ releasePollBarrier = resolve;
+ });
+ let committed;
+ try {
+ committed = await this.#requireStore().commitPollBatch({
+ bindingEpoch: binding.bindingEpoch,
+ expectedCursor: cursor,
+ nextCursor: result.cursor,
+ now,
+ messages: inputs,
+ mediaBlobs,
+ mediaRefs,
+ fileAttachments,
+ });
+ await removeUncommittedWechatFiles(
+ allFileAttachments,
+ acceptedPollTaskIds(committed),
+ );
+ if (committed.committed) {
+ for (const message of result.messages) {
+ await this.#requireStore().refreshPendingOutboxContext({
+ bindingEpoch: binding.bindingEpoch,
+ peerId: message.senderId,
+ contextToken: message.contextToken,
+ now,
+ });
+ }
+ }
+ if (committed.committed) {
+ for (let index = 0; index < result.messages.length; index += 1) {
+ const message = result.messages[index];
+ const task = preparedInputs[index]?.message;
+ const command = message?.text.trim();
+ if (!message || !task || (command !== '/stop' && command !== '/stop all')) {
+ continue;
+ }
+ await this.#requireStore().cancelForCommand({
+ bindingEpoch: binding.bindingEpoch,
+ commandTaskId: task.id,
+ ...(command === '/stop' ? { peerId: message.senderId } : {}),
+ now,
+ });
+ if (command === '/stop all') {
+ await this.#turnRuntime?.runner.disposeAllSessions();
+ } else {
+ await this.#turnRuntime?.runner.stopActiveTurn({
+ botContextId: this.#epoch?.credentials.ilinkBotId ?? '',
+ userId: message.senderId,
+ });
+ }
+ const pending = this.#pendingInteractions.get(message.senderId);
+ if (pending) {
+ clearTimeout(pending.timer);
+ pending.resolve(
+ defaultWechatInteractionDecision(pending.request, 'wechat_user_stopped'),
+ );
+ this.#pendingInteractions.delete(message.senderId);
+ }
+ }
+ }
+ for (const index of interactionIndexes) {
+ const message = result.messages[index];
+ if (message) {
+ await this.#handleInteractionReplyMessage(message, transport, signal);
+ }
+ }
+ } finally {
+ releasePollBarrier();
+ }
+ if (!committed.committed) return;
+ cursor = result.cursor;
+ failures = 0;
+ if (result.messages.length > 0) {
+ this.#setState({
+ ...this.#state,
+ phase: 'connected',
+ lastInboundAt: now,
+ queuedTasks: await this.#requireStore().countQueuedTasks(binding.bindingEpoch),
+ });
+ } else {
+ await delay(EMPTY_POLL_DELAY_MS, signal);
+ }
+ } catch (error) {
+ if (signal.aborted) return;
+ const safe = asWechatIlinkError(error);
+ if (safe.code === 'AUTH_REPLACED' || safe.code === 'AUTH_EXPIRED') {
+ this.#setState({
+ ...this.#state,
+ phase: 'needs_reauth',
+ errorCode: safe.code.toLowerCase(),
+ });
+ return;
+ }
+ if (!safe.retryable) {
+ this.#setState({
+ ...this.#state,
+ phase: 'error',
+ errorCode: safe.code.toLowerCase(),
+ });
+ return;
+ }
+ this.#setState({
+ ...this.#state,
+ phase: 'reconnecting',
+ errorCode: safe.code.toLowerCase(),
+ });
+ const backoff = RECONNECT_DELAYS_MS[Math.min(failures, RECONNECT_DELAYS_MS.length - 1)];
+ failures += 1;
+ await delay(withJitter(backoff), signal);
+ }
+ }
+ }
+
+ async #taskPump(
+ binding: WechatActiveBinding,
+ signal: AbortSignal,
+ generation: number,
+ ): Promise<void> {
+ while (!signal.aborted && this.#isGenerationCurrent(generation)) {
+ await this.#pollBarrier;
+ const task = await this.#requireStore().leaseNextTask({
+ bindingEpoch: binding.bindingEpoch,
+ now: this.#now(),
+ });
+ if (!task) {
+ await delay(IDLE_PUMP_DELAY_MS, signal);
+ continue;
+ }
+ try {
+ await this.#processTask(task);
+ } catch (error) {
+ this.log.warn('WeChat task processing failed', {
+ task: shortId(task.id),
+ code: machineErrorCode(error),
+ });
+ const interrupted = await this.#requireStore().commitInterrupted({
+ bindingEpoch: task.bindingEpoch,
+ taskId: task.id,
+ now: this.#now(),
+ errorCode: machineErrorCode(error),
+ });
+ if (!interrupted) {
+ await this.#requireStore().releaseDispatch(task.bindingEpoch, task.id);
+ }
+ }
+ this.#setState({
+ ...this.#state,
+ queuedTasks: await this.#requireStore().countQueuedTasks(binding.bindingEpoch),
+ });
+ }
+ }
+
+ async #processTask(task: WechatTask): Promise<void> {
+ const runtime = this.#turnRuntime;
+ if (!runtime) throw new Error('WECHAT_TURN_RUNTIME_NOT_ATTACHED');
+ const payload = parseTaskPayload(task.payloadJson);
+ const command = payload.text.trim();
+ if (
+ this.#pendingInteractions.has(task.peerId) &&
+ command !== '/stop' &&
+ command !== '/stop all'
+ ) {
+ await this.#processInteractionReply(task, payload.text);
+ return;
+ }
+ if (command === '/stop' || command === '/stop all') {
+ const pending = this.#pendingInteractions.get(task.peerId);
+ if (pending) {
+ clearTimeout(pending.timer);
+ pending.resolve(defaultWechatInteractionDecision(pending.request, 'wechat_user_stopped'));
+ this.#pendingInteractions.delete(task.peerId);
+ }
+ }
+ if (command.startsWith('/')) {
+ await this.#processCommand(task, command);
+ return;
+ }
+ const prompt =
+ payload.unsupportedMedia.length > 0
+ ? `${payload.text}\n\n(微信消息还包含当前版本暂不支持的媒体,本轮仅处理文字。)`
+ : payload.text;
+ if (!hasWechatTaskContent(prompt, payload.attachments)) {
+ await this.#commitSimpleReply(task, '当前版本暂不支持处理这类微信媒体。');
+ return;
+ }
+
+ const active: ActiveTask = { task, terminalCommitted: false };
+ this.#activeTasks.set(task.peerId, active);
+ const stopTyping = await this.#startTyping(task);
+ let dispatch;
+ try {
+ dispatch = await runtime.runner.dispatchAgentTurn({
+ botContextId: this.#epoch?.credentials.ilinkBotId ?? '',
+ userId: task.peerId,
+ userMessageId: task.id,
+ text: prompt,
+ attachments: payload.attachments,
+ queueMode: 'external',
+ beforeProviderStart: async () => {
+ const accepted = await this.#requireStore().markAccepted(task.bindingEpoch, task.id);
+ if (!accepted) throw new Error('WECHAT_ACCEPT_CAS_REJECTED');
+ },
+ onRouteResolved: (sessionId) => {
+ if (this.#activeTasks.get(task.peerId) === active) {
+ active.routeSessionId = sessionId;
+ }
+ },
+ turnPermissionPolicy: createWechatTurnPermissionPolicy(task.id, {
+ onInteractionStateChange: (state) => {
+ if (state === 'waiting') {
+ void this.#requireStore().setWaitingDesktop(task.bindingEpoch, task.id, true);
+ } else {
+ void this.#requireStore().setWaitingDesktop(task.bindingEpoch, task.id, false);
+ }
+ },
+ }),
+ });
+ } catch (error) {
+ await stopTyping();
+ throw error;
+ }
+
+ if (dispatch.kind !== 'accepted') {
+ await stopTyping();
+ this.#activeTasks.delete(task.peerId);
+ if (dispatch.kind === 'busy') {
+ await this.#requireStore().releaseDispatch(task.bindingEpoch, task.id);
+ await delay(IDLE_PUMP_DELAY_MS);
+ } else {
+ await this.#commitPreDispatchFailure(task, dispatch.reason);
+ }
+ return;
+ }
+ let terminal;
+ try {
+ terminal = await dispatch.terminal;
+ } finally {
+ await stopTyping();
+ }
+ this.#activeTasks.delete(task.peerId);
+ if (!active.terminalCommitted) {
+ await this.#requireStore().commitInterrupted({
+ bindingEpoch: task.bindingEpoch,
+ taskId: task.id,
+ now: this.#now(),
+ errorCode: safeMachineCode(terminal.errorCode ?? 'terminal_output_missing'),
+ });
+ }
+ await this.#flushCurrentOutbox(task.bindingEpoch);
+ }
+
+ async #processInteractionReply(task: WechatTask, text: string): Promise<void> {
+ const pending = this.#pendingInteractions.get(task.peerId);
+ if (!pending) return;
+ const accepted = await this.#requireStore().markAccepted(task.bindingEpoch, task.id);
+ if (!accepted) throw new Error('WECHAT_ACCEPT_CAS_REJECTED');
+ const decision = parseWechatInteractionReply(pending.request, text);
+ if (!decision) {
+ await this.#commitInteractionReply(
+ task,
+ '回复格式不正确。请按上一条消息提示回复;权限确认只支持“允许”或“拒绝”。',
+ );
+ await this.#flushCurrentOutbox(task.bindingEpoch);
+ return;
+ }
+ clearTimeout(pending.timer);
+ this.#pendingInteractions.delete(task.peerId);
+ pending.resolve(decision);
+ await this.#commitAcceptedReply(task, '已收到你的选择,继续处理。');
+ await this.#flushCurrentOutbox(task.bindingEpoch);
+ }
+
+ async #handleInteractionReplyMessage(
+ message: WechatInboundMessage,
+ transport: WechatTransport,
+ signal: AbortSignal,
+ ): Promise<void> {
+ const pending = this.#pendingInteractions.get(message.senderId);
+ if (!pending) return;
+ const decision = parseWechatInteractionReply(pending.request, message.text);
+ if (decision) {
+ clearTimeout(pending.timer);
+ this.#pendingInteractions.delete(message.senderId);
+ pending.resolve(decision);
+ }
+ try {
+ await transport.sendMessage(
+ {
+ peerId: message.senderId,
+ text: decision
+ ? '已收到你的选择,继续处理。'
+ : '回复格式不正确。请按上一条消息提示回复;权限确认只支持“允许”或“拒绝”。',
+ contextToken: message.contextToken,
+ clientId: randomUUID(),
+ },
+ signal,
+ );
+ } catch {
+ // Interaction acknowledgement is best effort; the decision itself has
+ // already been correlated in memory and the agent will produce its next
+ // durable response.
+ }
+ }
+
+ async #commitInteractionReply(task: WechatTask, text: string): Promise<void> {
+ const result = await this.#requireStore().commitTerminal({
+ bindingEpoch: task.bindingEpoch,
+ taskId: task.id,
+ now: this.#now(),
+ outbox: chunkWechatText(text).map((chunk, index) => ({
+ id: randomUUID(),
+ clientId: randomUUID(),
+ kind: 'final',
+ chunkIndex: index,
+ text: chunk,
+ })),
+ });
+ if (!result.committed) throw new Error('WECHAT_INTERACTION_REPLY_REJECTED');
+ }
+
+ async #startTyping(task: WechatTask): Promise<() => Promise<void>> {
+ const epoch = this.#epoch;
+ if (!epoch || this.#compatibilityDisabled || epoch.abort.signal.aborted) {
+ return async () => undefined;
+ }
+ let ticket: string;
+ try {
+ ticket = await epoch.transport.getTypingTicket(
+ task.peerId,
+ task.contextToken,
+ epoch.abort.signal,
+ );
+ await epoch.transport.setTyping(task.peerId, ticket, true, epoch.abort.signal);
+ } catch {
+ return async () => undefined;
+ }
+
+ let stopped = false;
+ let busy = false;
+ let nextHeartbeatAt = this.#now() + 60_000;
+ const timer = setInterval(() => {
+ if (stopped || busy || this.#compatibilityDisabled || epoch.abort.signal.aborted) return;
+ busy = true;
+ void (async () => {
+ try {
+ await epoch.transport.setTyping(task.peerId, ticket, true, epoch.abort.signal);
+ if (this.#now() >= nextHeartbeatAt) {
+ await epoch.transport.sendMessage(
+ {
+ peerId: task.peerId,
+ text: '任务仍在处理中…',
+ contextToken: task.contextToken,
+ clientId: randomUUID(),
+ },
+ epoch.abort.signal,
+ );
+ nextHeartbeatAt = this.#now() + 120_000;
+ }
+ } catch {
+ // Presence is best effort and must never fail the task.
+ } finally {
+ busy = false;
+ }
+ })();
+ }, 5_000);
+ timer.unref?.();
+
+ return async () => {
+ if (stopped) return;
+ stopped = true;
+ clearInterval(timer);
+ try {
+ await epoch.transport.setTyping(task.peerId, ticket, false, epoch.abort.signal);
+ } catch {
+ // Best-effort presence cleanup.
+ }
+ };
+ }
+
+ async #processCommand(task: WechatTask, command: string): Promise<void> {
+ const runtime = this.#turnRuntime;
+ if (!runtime) throw new Error('WECHAT_TURN_RUNTIME_NOT_ATTACHED');
+ switch (command) {
+ case '/help':
+ await this.#commitSimpleReply(
+ task,
+ '可用命令:/new 新对话;/stop 停止当前任务;/stop all 停止全部任务;/status 查看状态;/help 查看帮助。',
+ );
+ return;
+ case '/status':
+ await this.#commitSimpleReply(
+ task,
+ `Cindy 微信连接正常,当前队列 ${this.#state.queuedTasks} 条。`,
+ );
+ return;
+ case '/stop':
+ case '/stop all':
+ await this.#commitSimpleReply(task, '已停止任务。');
+ return;
+ case '/new': {
+ const accepted = await this.#requireStore().markAccepted(task.bindingEpoch, task.id);
+ if (!accepted) throw new Error('WECHAT_ACCEPT_CAS_REJECTED');
+ const prepared = await runtime.repo.prepareNewSession(
+ this.#epoch?.credentials.ilinkBotId ?? '',
+ task.peerId,
+ );
+ const existing = await runtime.repo.findActiveSession(
+ this.#epoch?.credentials.ilinkBotId ?? '',
+ task.peerId,
+ );
+ const row =
+ existing ??
+ (await runtime.repo.createSession(
+ this.#epoch?.credentials.ilinkBotId ?? '',
+ task.peerId,
+ undefined,
+ prepared,
+ ));
+ if (existing) {
+ await runtime.resetSessionToDefaults(row.id, runtime.config, prepared);
+ }
+ await runtime.runner.disposeOneSession(row.id);
+ await this.#requireStore().advanceConversationEpoch(
+ task.bindingEpoch,
+ task.id,
+ task.peerId,
+ );
+ const active: ActiveTask = { task, terminalCommitted: false };
+ this.#activeTasks.set(task.peerId, active);
+ await this.commitFinal({
+ userId: task.peerId,
+ text: '已开始一段新对话。',
+ terminal: 'done',
+ });
+ this.#activeTasks.delete(task.peerId);
+ await this.#flushCurrentOutbox(task.bindingEpoch);
+ return;
+ }
+ default:
+ await this.#commitSimpleReply(task, '未知命令。发送 /help 查看可用命令。');
+ }
+ }
+
+ async #commitSimpleReply(task: WechatTask, text: string): Promise<void> {
+ const accepted = await this.#requireStore().markAccepted(task.bindingEpoch, task.id);
+ if (!accepted) throw new Error('WECHAT_ACCEPT_CAS_REJECTED');
+ await this.#commitAcceptedReply(task, text);
+ await this.#flushCurrentOutbox(task.bindingEpoch);
+ }
+
+ async #commitAcceptedReply(task: WechatTask, text: string): Promise<void> {
+ const existing = this.#activeTasks.get(task.peerId);
+ if (existing && existing.task.id !== task.id) {
+ await this.#commitInteractionReply(task, text);
+ return;
+ }
+ const active: ActiveTask = { task, terminalCommitted: false };
+ this.#activeTasks.set(task.peerId, active);
+ try {
+ await this.commitFinal({ userId: task.peerId, text, terminal: 'done' });
+ } finally {
+ this.#activeTasks.delete(task.peerId);
+ }
+ }
+
+ async #commitPreDispatchFailure(task: WechatTask, reason: string): Promise<void> {
+ const text =
+ reason.includes('TURN_PERMISSION_POLICY_UNSUPPORTED') ||
+ reason.includes('unsupported_turn_permission')
+ ? '当前会话使用“完全访问”权限,个人微信暂不支持该模式。请在 Cindy 中改为“自动”或“每次询问”。'
+ : reason === 'missing_auth'
+ ? '当前 Agent 尚未完成授权,请先在 Cindy 中连接模型服务。'
+ : '这条消息暂时无法启动,请稍后重试。';
+ const chunks = chunkWechatText(text);
+ await this.#requireStore().commitPreDispatchFailure({
+ bindingEpoch: task.bindingEpoch,
+ taskId: task.id,
+ now: this.#now(),
+ errorCode: safeMachineCode(reason),
+ outbox: chunks.map((chunk, index) => ({
+ id: randomUUID(),
+ clientId: randomUUID(),
+ kind: 'error',
+ chunkIndex: index,
+ text: chunk,
+ })),
+ });
+ await this.#flushCurrentOutbox(task.bindingEpoch);
+ }
+
+ async #outboxLoop(
+ binding: WechatActiveBinding,
+ transport: WechatTransport,
+ signal: AbortSignal,
+ generation: number,
+ ): Promise<void> {
+ while (!signal.aborted && this.#isGenerationCurrent(generation)) {
+ await this.#flushOutbox(transport, binding.bindingEpoch, signal);
+ await delay(1_000, signal);
+ }
+ }
+
+ async #flushCurrentOutbox(bindingEpoch: string): Promise<void> {
+ const epoch = this.#epoch;
+ if (!epoch || epoch.binding.bindingEpoch !== bindingEpoch) return;
+ await this.#flushOutbox(epoch.transport, bindingEpoch, epoch.abort.signal);
+ }
+
+ async #flushOutbox(
+ transport: WechatTransport,
+ bindingEpoch: string,
+ signal: AbortSignal,
+ ): Promise<void> {
+ if (!this.#isSendEpochCurrent(bindingEpoch, signal)) return;
+ const store = this.#requireStore();
+ for (const item of await store.listDueOutbox(bindingEpoch, this.#now())) {
+ if (!this.#isSendEpochCurrent(bindingEpoch, signal)) return;
+ for (let immediateAttempt = 0; immediateAttempt < 3; immediateAttempt += 1) {
+ if (!this.#isSendEpochCurrent(bindingEpoch, signal)) return;
+ if (!(await store.claimOutbox(bindingEpoch, item.id))) break;
+ if (!this.#isSendEpochCurrent(bindingEpoch, signal)) {
+ await store.recordOutboxFailure({
+ bindingEpoch,
+ outboxId: item.id,
+ nextRetryAt: this.#now(),
+ terminal: false,
+ errorCode: 'ABORTED',
+ });
+ return;
+ }
+ try {
+ await this.#sendOutboxItem(transport, bindingEpoch, item, signal);
+ await store.markOutboxDelivered(bindingEpoch, item.id, this.#now());
+ break;
+ } catch (error) {
+ const failure = classifyOutboxSendError(error);
+ const retryNow = failure.retryable && immediateAttempt < 2;
+ await store.recordOutboxFailure({
+ bindingEpoch,
+ outboxId: item.id,
+ nextRetryAt: failure.retryable
+ ? retryNow
+ ? this.#now()
+ : this.#now() + retryDelay(item.attempts + immediateAttempt + 1)
+ : this.#now(),
+ terminal: !failure.retryable,
+ errorCode: failure.code,
+ });
+ if (failure.code === 'AUTH_REPLACED' || failure.code === 'AUTH_EXPIRED') {
+ this.#setState({
+ ...this.#state,
+ phase: 'needs_reauth',
+ errorCode: failure.code.toLowerCase(),
+ });
+ return;
+ }
+ if (!retryNow) break;
+ }
+ }
+ }
+ }
+
+ async #sendOutboxItem(
+ transport: WechatTransport,
+ bindingEpoch: string,
+ item: Awaited<ReturnType<WechatTaskStore['listDueOutbox']>>[number],
+ signal: AbortSignal,
+ ): Promise<void> {
+ this.#assertSendEpochCurrent(bindingEpoch, signal);
+ const peerId = await this.#peerIdForTask(bindingEpoch, item.taskId);
+ this.#assertSendEpochCurrent(bindingEpoch, signal);
+ if (item.text) {
+ await transport.sendMessage(
+ {
+ peerId,
+ text: item.text,
+ contextToken: item.contextToken,
+ clientId: item.clientId,
+ },
+ signal,
+ );
+ }
+ for (const media of parseOutboxMedia(item.mediaJson)) {
+ this.#assertSendEpochCurrent(bindingEpoch, signal);
+ const local = await readOutboundWechatFile(media.absPath);
+ this.#assertSendEpochCurrent(bindingEpoch, signal);
+ const uploaded = await transport.uploadMedia(
+ {
+ peerId,
+ bytes: local.bytes,
+ fileName: local.fileName,
+ kind: local.kind,
+ },
+ signal,
+ );
+ this.#assertSendEpochCurrent(bindingEpoch, signal);
+ await transport.sendMedia(
+ {
+ peerId,
+ contextToken: item.contextToken,
+ clientId: media.clientId,
+ uploaded,
+ },
+ signal,
+ );
+ }
+ }
+
+ async #peerIdForTask(bindingEpoch: string, taskId: string): Promise<string> {
+ const row = await this.#deps.getDbClient().queryOne<{ peerId: string }>(
+ `SELECT peer_id AS peerId
+ FROM wechat_inbox
+ WHERE binding_epoch = ? AND id = ?`,
+ [bindingEpoch, taskId],
+ );
+ if (!row?.peerId) throw new Error('WECHAT_OUTBOX_TASK_MISSING');
+ return row.peerId;
+ }
+
+ async #toTaskInput(
+ bindingEpoch: string,
+ message: WechatInboundMessage,
+ transport: WechatTransport,
+ signal: AbortSignal,
+ receivedAt: number,
+ index: number,
+ ) {
+ const runtime = this.#turnRuntime;
+ if (!runtime) throw new Error('WECHAT_TURN_RUNTIME_NOT_ATTACHED');
+ const botId = this.#epoch?.credentials.ilinkBotId ?? 'wechat';
+ const prepared = await runtime.repo.prepareNewSession(botId, message.senderId);
+ const existing = await runtime.repo.findActiveSession(botId, message.senderId);
+ const session =
+ existing ?? (await runtime.repo.createSession(botId, message.senderId, undefined, prepared));
+ const epoch = await this.#requireStore().getConversationEpoch(bindingEpoch, message.senderId);
+ const taskId = randomUUID();
+ const staged = await stageWechatTaskMedia({
+ bindingEpoch,
+ taskId,
+ sessionId: session.id,
+ media: [...(message.quote?.media ?? []), ...message.media],
+ transport,
+ signal,
+ now: receivedAt,
+ });
+ const quote = formatWechatQuote(message);
+ return {
+ message: {
+ id: taskId,
+ platformMessageId: message.messageId,
+ platformSeq: platformSequence(message, receivedAt, index),
+ peerId: message.senderId,
+ receivedAt,
+ platformCreatedAt: message.createdAt ?? receivedAt,
+ sessionId: session.id,
+ conversationEpoch: epoch,
+ payloadJson: JSON.stringify({
+ text: quote ? `${quote}\n${message.text}`.trim() : message.text,
+ attachments: staged.attachments,
+ unsupportedMedia: staged.unsupportedMedia,
+ } satisfies WechatTaskPayload),
+ contextToken: message.contextToken,
+ overloadReply: {
+ outboxId: randomUUID(),
+ clientId: randomUUID(),
+ text: '当前微信任务较多,请稍后再试。',
+ },
+ },
+ mediaBlobs: staged.mediaBlobs,
+ mediaRefs: staged.mediaRefs,
+ fileAttachments: staged.fileAttachments,
+ };
+ }
+
+ async #readActiveBindingWithoutKey(): Promise<WechatActiveBinding | null> {
+ const row = await this.#deps.getDbClient().queryOne<{
+ bindingEpoch: string;
+ cursor: string;
+ }>(
+ `SELECT binding_epoch AS bindingEpoch, sync_cursor AS cursor
+ FROM wechat_sync_state
+ WHERE is_active = 1
+ LIMIT 1`,
+ );
+ return row ?? null;
+ }
+
+ #readDataKey(): Buffer | null {
+ const raw = this.host.secrets.read(DATA_KEY_NAME);
+ if (!raw) return null;
+ try {
+ const key = Buffer.from(raw, 'base64');
+ return key.byteLength === 32 ? key : null;
+ } catch {
+ return null;
+ }
+ }
+
+ #readCredentials(bindingEpoch: string): StoredWechatCredentials | null {
+ const raw = this.host.secrets.read(`${CREDENTIAL_PREFIX}${bindingEpoch}`);
+ if (!raw) return null;
+ try {
+ const value = JSON.parse(raw) as Partial<StoredWechatCredentials>;
+ return value.bindingEpoch === bindingEpoch &&
+ typeof value.botToken === 'string' &&
+ value.botToken &&
+ typeof value.ilinkBotId === 'string' &&
+ value.ilinkBotId &&
+ typeof value.userId === 'string' &&
+ value.userId &&
+ typeof value.baseUrl === 'string' &&
+ value.baseUrl.startsWith('https://') &&
+ typeof value.boundAt === 'number'
+ ? (value as StoredWechatCredentials)
+ : null;
+ } catch {
+ return null;
+ }
+ }
+
+ #requireStore(): WechatTaskStore {
+ if (!this.#store) throw new Error('WECHAT_STORE_NOT_READY');
+ return this.#store;
+ }
+
+ #queueLifecycle<T>(operation: () => Promise<T>): Promise<T> {
+ const result = this.#lifecycleBarrier.then(operation);
+ this.#lifecycleBarrier = result.then(
+ () => undefined,
+ () => undefined,
+ );
+ return result;
+ }
+
+ #isCompatibilityRevisionCurrent(revision: number): boolean {
+ return revision === this.#compatibilityRevision;
+ }
+
+ #isCompatibilityRevisionAllowed(revision: number): boolean {
+ return this.#isCompatibilityRevisionCurrent(revision) && !this.#compatibilityDisabled;
+ }
+
+ #isSendEpochCurrent(bindingEpoch: string, signal: AbortSignal): boolean {
+ const epoch = this.#epoch;
+ return (
+ !this.#compatibilityDisabled &&
+ !signal.aborted &&
+ epoch?.binding.bindingEpoch === bindingEpoch &&
+ epoch.abort.signal === signal
+ );
+ }
+
+ #assertSendEpochCurrent(bindingEpoch: string, signal: AbortSignal): void {
+ if (!this.#isSendEpochCurrent(bindingEpoch, signal)) {
+ throw new WechatIlinkError('ABORTED', 'The WeChat send epoch was stopped.', true);
+ }
+ }
+
+ #isGenerationCurrent(generation: number): boolean {
+ return this.#deps.isAccountGenerationCurrent(generation);
+ }
+
+ #setState(state: Omit<WechatBotState, 'bound'>): void {
+ this.#state = state;
+ this.host.ipc.broadcast('wechatBot:state-changed', this.getState());
+ const status = this.getStatus();
+ for (const handler of this.#statusHandlers) handler(status);
+ }
+
+ #now(): number {
+ return this.#deps.now?.() ?? Date.now();
+ }
+}
+
+export const WECHAT_AUTH_BASE_URL = AUTH_BASE_URL;
+
+export function sessionIdFor(botId: string, peerId: string): string {
+ const digest = createHash('sha256').update(`${botId}\0${peerId}`).digest('hex').slice(0, 32);
+ return `wechat_${digest}`;
+}
+
+function parseTaskPayload(raw: string): WechatTaskPayload {
+ const value = JSON.parse(raw) as Partial<WechatTaskPayload>;
+ const attachments = value.attachments ?? [];
+ if (
+ typeof value.text !== 'string' ||
+ !Array.isArray(attachments) ||
+ !attachments.every(isWechatTaskAttachment) ||
+ !Array.isArray(value.unsupportedMedia) ||
+ !value.unsupportedMedia.every((item) => typeof item === 'string')
+ ) {
+ throw new Error('WECHAT_TASK_PAYLOAD_INVALID');
+ }
+ return {
+ text: value.text,
+ attachments,
+ unsupportedMedia: value.unsupportedMedia,
+ };
+}
+
+function isWechatTaskAttachment(value: unknown): value is WechatTaskAttachment {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
+ const item = value as Partial<WechatTaskAttachment>;
+ return (
+ (item.kind === 'image' || item.kind === 'file') &&
+ (item.storage === 'cindy-media' || item.storage === 'file') &&
+ typeof item.absPath === 'string' &&
+ typeof item.originalName === 'string' &&
+ typeof item.mimeType === 'string' &&
+ (item.url === undefined || typeof item.url === 'string')
+ );
+}
+
+function formatWechatQuote(message: WechatInboundMessage): string {
+ const quote = message.quote;
+ if (!quote) return '';
+ const details = [quote.title?.trim(), quote.text?.trim()].filter((item): item is string =>
+ Boolean(item),
+ );
+ if (quote.media.length > 0) details.push(`附件 ${quote.media.length} 个`);
+ return details.length > 0 ? `[引用:${details.join('|')}]` : '';
+}
+
+function platformSequence(
+ message: WechatInboundMessage,
+ receivedAt: number,
+ index: number,
+): number {
+ const parsed = Number.parseInt(message.messageId, 10);
+ if (Number.isSafeInteger(parsed)) return parsed;
+ return (message.createdAt ?? receivedAt) * 100 + index;
+}
+
+function acceptedPollTaskIds(
+ result: Awaited<ReturnType<WechatTaskStore['commitPollBatch']>>,
+): ReadonlySet<string> {
+ if (!result.committed) return new Set();
+ const rejected = new Set(result.rejectedTaskIds);
+ return new Set(result.insertedTaskIds.filter((taskId) => !rejected.has(taskId)));
+}
+
+const PERMANENT_OUTBOX_ERROR_CODES = new Set([
+ 'ENOENT',
+ 'WECHAT_FILE_EMPTY',
+ 'WECHAT_FILE_TOO_LARGE',
+ 'WECHAT_OUTBOX_MEDIA_INVALID',
+ 'WECHAT_OUTBOX_TASK_MISSING',
+]);
+
+function classifyOutboxSendError(error: unknown): { code: string; retryable: boolean } {
+ const explicitCode =
+ error instanceof Error && 'code' in error
+ ? String((error as NodeJS.ErrnoException).code ?? '')
+ : '';
+ const localCode = explicitCode || (error instanceof Error ? error.message : '');
+ if (PERMANENT_OUTBOX_ERROR_CODES.has(localCode)) {
+ return { code: safeMachineCode(localCode), retryable: false };
+ }
+ const safe = asWechatIlinkError(error);
+ return { code: safe.code, retryable: safe.retryable };
+}
+
+async function stopActiveWechatTurns(
+ runner: ImTurnRunner | null,
+ botContextId: string,
+ peerIds: Iterable<string>,
+): Promise<void> {
+ if (!runner) return;
+ await Promise.all(
+ [...new Set(peerIds)].map((userId) => runner.stopActiveTurn({ botContextId, userId })),
+ );
+}
+
+function retryDelay(attempt: number): number {
+ return [1_000, 5_000, 30_000, 120_000][Math.min(Math.max(attempt - 1, 0), 3)];
+}
+
+interface OutboxMedia {
+ absPath: string;
+ clientId: string;
+}
+
+function parseOutboxMedia(raw: string): OutboxMedia[] {
+ let value: unknown;
+ try {
+ value = JSON.parse(raw);
+ } catch {
+ throw new Error('WECHAT_OUTBOX_MEDIA_INVALID');
+ }
+ if (
+ !Array.isArray(value) ||
+ value.length > 4 ||
+ !value.every(
+ (item) =>
+ item &&
+ typeof item === 'object' &&
+ !Array.isArray(item) &&
+ typeof (item as Partial<OutboxMedia>).absPath === 'string' &&
+ path.isAbsolute((item as Partial<OutboxMedia>).absPath!) &&
+ typeof (item as Partial<OutboxMedia>).clientId === 'string' &&
+ (item as Partial<OutboxMedia>).clientId!.length > 0,
+ )
+ ) {
+ throw new Error('WECHAT_OUTBOX_MEDIA_INVALID');
+ }
+ return value as OutboxMedia[];
+}
+
+async function readOutboundWechatFile(
+ absPath: string,
+ displayName?: string,
+): Promise<{
+ bytes: Uint8Array;
+ fileName: string;
+ kind: 'image' | 'video' | 'file';
+}> {
+ if (!path.isAbsolute(absPath)) {
+ throw Object.assign(new Error('WeChat outbound path must be absolute.'), {
+ code: 'ENOENT',
+ });
+ }
+ const handle = await fs.open(absPath, 'r');
+ try {
+ const stat = await handle.stat();
+ if (!stat.isFile()) {
+ throw Object.assign(new Error('WeChat outbound path is not a regular file.'), {
+ code: 'ENOENT',
+ });
+ }
+ if (stat.size === 0) {
+ throw Object.assign(new Error('WeChat outbound file is empty.'), {
+ code: 'WECHAT_FILE_EMPTY',
+ });
+ }
+ if (stat.size > WECHAT_MEDIA_MAX_BYTES) {
+ throw Object.assign(new Error('WeChat outbound file exceeds 5 MB.'), {
+ code: 'WECHAT_FILE_TOO_LARGE',
+ });
+ }
+ const bytes = await handle.readFile();
+ if (bytes.byteLength !== stat.size) {
+ throw new Error('WECHAT_OUTBOUND_FILE_CHANGED');
+ }
+ return {
+ bytes,
+ fileName: sanitizeOutboundFileName(displayName ?? path.basename(absPath)),
+ kind: detectOutboundWechatKind(bytes),
+ };
+ } finally {
+ await handle.close();
+ }
+}
+
+function sanitizeOutboundFileName(input: string): string {
+ const value = path
+ .basename(input.normalize('NFKC'))
+ .replace(/\p{Cc}/gu, '_')
+ .replace(/[<>:"/\\|?*]/g, '_')
+ .replace(/[. ]+$/g, '')
+ .trim()
+ .slice(0, 180);
+ return value || 'cindy-file.bin';
+}
+
+function detectOutboundWechatKind(bytes: Uint8Array): 'image' | 'video' | 'file' {
+ const ascii = (offset: number, value: string): boolean =>
+ bytes.length >= offset + value.length &&
+ Array.from(value).every((char, index) => bytes[offset + index] === char.charCodeAt(0));
+ if (
+ (bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) ||
+ (bytes.length >= 8 && bytes[0] === 0x89 && ascii(1, 'PNG\r\n\u001a\n')) ||
+ ascii(0, 'GIF87a') ||
+ ascii(0, 'GIF89a') ||
+ (ascii(0, 'RIFF') && ascii(8, 'WEBP'))
+ ) {
+ return 'image';
+ }
+ return ascii(4, 'ftyp') ? 'video' : 'file';
+}
+
+function withJitter(value: number): number {
+ return Math.round(value * (0.8 + Math.random() * 0.4));
+}
+
+function shortId(value: string): string {
+ return createHash('sha256').update(value).digest('hex').slice(0, 8);
+}
+
+function safeMachineCode(value: string): string {
+ const normalized = value
+ .toUpperCase()
+ .replace(/[^A-Z0-9_]+/g, '_')
+ .slice(0, 64);
+ return normalized || 'PRE_DISPATCH_REJECTED';
+}
+
+function normalizeFinalOutputText(text: string): string {
+ return filterWechatMarkdown(text) || '✅ (本轮无文本输出)';
+}
+
+function hasWechatTaskContent(text: string, attachments: readonly WechatTaskAttachment[]): boolean {
+ return text.trim().length > 0 || attachments.length > 0;
+}
+
+function formatWechatInteractionPrompt(request: InteractionRequest): string {
+ if (request.kind === 'permission') {
+ return `需要确认工具“${request.displayName ?? request.toolName}”。
+回复“允许”执行一次,或回复“拒绝”取消本次操作。微信内不支持永久授权。`;
+ }
+ if (request.kind === 'plan_review') {
+ const plan = request.plan.length > 6_000 ? `${request.plan.slice(0, 6_000)}…` : request.plan;
+ return `Agent 提交了一份执行计划:
+
+${plan}
+
+回复“批准”继续,或回复“拒绝”取消。`;
+ }
+ const question = request.questions[0];
+ if (!question) return 'Agent 正在等待你的回答,但没有可显示的问题。请回复“继续”。';
+ const options = (question.options ?? [])
+ .slice(0, 9)
+ .map((option, index) => `${index + 1}. ${option.label}`)
+ .join('\n');
+ return `Agent 需要你的回答:
+${question.question}
+${options ? `\n${options}\n` : ''}
+请回复选项序号,或直接输入你的回答。`;
+}
+
+function defaultWechatInteractionDecision(
+ request: InteractionRequest,
+ reason: string,
+): InteractionDecision {
+ if (request.kind === 'ask_user_question') {
+ return { kind: 'ask_user_question', answers: {} };
+ }
+ if (request.kind === 'plan_review') {
+ return { kind: 'plan_review', behavior: 'deny', reason };
+ }
+ return { kind: 'permission', behavior: 'deny', reason };
+}
+
+function parseWechatInteractionReply(
+ request: InteractionRequest,
+ rawText: string,
+): InteractionDecision | null {
+ const text = rawText.trim();
+ if (!text) return null;
+ const normalized = text.toLowerCase();
+ if (request.kind === 'permission') {
+ if (['允许', '同意', '确认', 'allow', 'yes', 'y'].includes(normalized)) {
+ return { kind: 'permission', behavior: 'allow' };
+ }
+ if (['拒绝', '不允许', '取消', 'deny', 'no', 'n'].includes(normalized)) {
+ return { kind: 'permission', behavior: 'deny', reason: 'wechat_user_denied' };
+ }
+ return null;
+ }
+ if (request.kind === 'plan_review') {
+ if (['批准', '同意', '确认', '继续', 'approve', 'allow', 'yes', 'y'].includes(normalized)) {
+ return { kind: 'plan_review', behavior: 'allow' };
+ }
+ if (['拒绝', '取消', 'deny', 'no', 'n'].includes(normalized)) {
+ return { kind: 'plan_review', behavior: 'deny', reason: 'wechat_user_denied' };
+ }
+ return null;
+ }
+ const question = request.questions[0];
+ if (!question) return { kind: 'ask_user_question', answers: {} };
+ const index = Number.parseInt(text, 10);
+ const option = Number.isInteger(index) && index >= 1 ? question.options?.[index - 1] : undefined;
+ return {
+ kind: 'ask_user_question',
+ answers: { [question.question]: option?.label ?? text },
+ };
+}
+
+function authorizationCancelPhase(hasEpoch: boolean, hasBinding: boolean): WechatBotPhase {
+ if (hasEpoch) return 'connected';
+ return hasBinding ? 'needs_reauth' : 'disconnected';
+}
+
+function machineErrorCode(error: unknown): string {
+ return error instanceof Error ? safeMachineCode(error.message) : 'unknown_error';
+}
+
+export const __testing = {
+ acceptedPollTaskIds,
+ authorizationCancelPhase,
+ classifyOutboxSendError,
+ hasWechatTaskContent,
+ normalizeFinalOutputText,
+ formatWechatInteractionPrompt,
+ parseWechatInteractionReply,
+ stopActiveWechatTurns,
+};
+
+function delay(ms: number, signal?: AbortSignal): Promise<void> {
+ if (signal?.aborted) return Promise.resolve();
+ return new Promise((resolve) => {
+ const timer = setTimeout(resolve, ms);
+ signal?.addEventListener(
+ 'abort',
+ () => {
+ clearTimeout(timer);
+ resolve();
+ },
+ { once: true },
+ );
+ });
+}
diff --git a/apps/desktop/src/main/im/wechat/__tests__/WechatIM.test.ts b/apps/desktop/src/main/im/wechat/__tests__/WechatIM.test.ts
new file mode 100644
index 0000000000..82663f8f8f
--- /dev/null
+++ b/apps/desktop/src/main/im/wechat/__tests__/WechatIM.test.ts
@@ -0,0 +1,434 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { IMHost } from '@cindy/im';
+import {
+ WechatIlinkError,
+ type WechatCredentials,
+ type WechatTransport,
+} from '@cindy/wechat-ilink';
+
+import type { DbClient } from '../../../localDb/client/DbClient';
+import { __testing, sessionIdFor, WechatIM, type WechatIMDeps } from '../WechatIM';
+
+const mediaMocks = vi.hoisted(() => ({
+ removeReleasedWechatFiles: vi.fn(async () => undefined),
+}));
+
+vi.mock('../mediaStaging', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('../mediaStaging')>();
+ return {
+ ...actual,
+ removeReleasedWechatFiles: mediaMocks.removeReleasedWechatFiles,
+ };
+});
+
+describe('WechatIM host boundary', () => {
+ beforeEach(() => {
+ mediaMocks.removeReleasedWechatFiles.mockClear();
+ });
+
+ it('derives a stable session id without exposing either platform identifier', () => {
+ const first = sessionIdFor('bot-secret-id', 'peer-secret-id');
+ expect(first).toBe(sessionIdFor('bot-secret-id', 'peer-secret-id'));
+ expect(first).toMatch(/^wechat_[a-f0-9]{32}$/);
+ expect(first).not.toContain('bot-secret-id');
+ expect(first).not.toContain('peer-secret-id');
+ });
+
+ it('fails closed before starting authorization when safeStorage is unavailable', async () => {
+ const createTransport = vi.fn();
+ const im = new WechatIM(
+ deps({
+ host: host({ secretAvailable: false }),
+ createTransport,
+ }),
+ );
+
+ await expect(im.authorize()).rejects.toThrow('WECHAT_SAFE_STORAGE_UNAVAILABLE');
+ expect(createTransport).not.toHaveBeenCalled();
+ });
+
+ it('never emulates rich cards for the chunked-text WeChat channel', async () => {
+ const im = new WechatIM(deps());
+
+ await expect(im.sendInteractiveCard()).rejects.toThrow('WECHAT_RICH_OUTPUT_UNSUPPORTED');
+ await expect(im.updateInteractiveCard()).rejects.toThrow('WECHAT_RICH_OUTPUT_UNSUPPORTED');
+ await expect(im.patchMarkdownCard()).rejects.toThrow('WECHAT_RICH_OUTPUT_UNSUPPORTED');
+ await expect(im.startStreamingText('peer')).rejects.toThrow('WECHAT_RICH_OUTPUT_UNSUPPORTED');
+ });
+
+ it('uses the shared empty-output copy after filtering the final text', () => {
+ expect(__testing.normalizeFinalOutputText('')).toBe('✅ (本轮无文本输出)');
+ expect(__testing.normalizeFinalOutputText('hello')).toBe('hello');
+ });
+
+ it('dispatches attachment-only WeChat messages to the agent', () => {
+ expect(__testing.hasWechatTaskContent('', [])).toBe(false);
+ expect(
+ __testing.hasWechatTaskContent('', [
+ {
+ kind: 'image',
+ absPath: 'wechat-image.png',
+ storage: 'cindy-media',
+ },
+ ] as never),
+ ).toBe(true);
+ });
+
+ it('keeps staged files only for accepted poll tasks', () => {
+ const accepted = __testing.acceptedPollTaskIds({
+ committed: true,
+ insertedTaskIds: ['accepted', 'overload'],
+ duplicateTaskIds: ['duplicate'],
+ rejectedTaskIds: ['overload'],
+ });
+ expect([...accepted]).toEqual(['accepted']);
+ expect(
+ [...__testing.acceptedPollTaskIds({
+ committed: false,
+ reason: 'stale-cursor',
+ activeBindingEpoch: 'binding-1',
+ currentCursor: 'newer',
+ })],
+ ).toEqual([]);
+ });
+
+ it('marks permanent local outbox failures terminal while retaining transport retries', () => {
+ expect(
+ __testing.classifyOutboxSendError(
+ Object.assign(new Error('missing attachment'), { code: 'ENOENT' }),
+ ),
+ ).toEqual({ code: 'ENOENT', retryable: false });
+ expect(
+ __testing.classifyOutboxSendError(
+ new WechatIlinkError('NETWORK_ERROR', 'temporary network failure', true),
+ ),
+ ).toEqual({ code: 'NETWORK_ERROR', retryable: true });
+ });
+
+ it('stops every active peer before an epoch can finish shutting down', async () => {
+ const stopActiveTurn = vi.fn(async () => ({ stopped: true }));
+ await __testing.stopActiveWechatTurns(
+ { stopActiveTurn } as never,
+ 'bot-1',
+ ['peer-1', 'peer-1', 'peer-2'],
+ );
+ expect(stopActiveTurn).toHaveBeenCalledTimes(2);
+ expect(stopActiveTurn).toHaveBeenCalledWith({
+ botContextId: 'bot-1',
+ userId: 'peer-1',
+ });
+ expect(stopActiveTurn).toHaveBeenCalledWith({
+ botContextId: 'bot-1',
+ userId: 'peer-2',
+ });
+ });
+
+ it('returns to needs_reauth when cancelling an authorization for an existing binding', () => {
+ expect(__testing.authorizationCancelPhase(false, true)).toBe('needs_reauth');
+ expect(__testing.authorizationCancelPhase(false, false)).toBe('disconnected');
+ expect(__testing.authorizationCancelPhase(true, true)).toBe('connected');
+ });
+
+ it('parses one-shot permission and question replies from plain WeChat text', () => {
+ const permission = __testing.parseWechatInteractionReply(
+ { kind: 'permission', requestId: 'r1', toolName: 'Bash', input: {} },
+ '允许',
+ );
+ expect(permission).toEqual({ kind: 'permission', behavior: 'allow' });
+
+ const question = __testing.parseWechatInteractionReply(
+ {
+ kind: 'ask_user_question',
+ requestId: 'r2',
+ questions: [
+ {
+ question: '选择环境',
+ options: [{ label: '测试' }, { label: '生产' }],
+ },
+ ],
+ },
+ '2',
+ );
+ expect(question).toEqual({
+ kind: 'ask_user_question',
+ answers: { 选择环境: '生产' },
+ });
+ });
+
+ it('fails closed before authorization when the signed compatibility policy disables it', async () => {
+ const createTransport = vi.fn();
+ const im = new WechatIM(
+ deps({
+ createTransport,
+ isCompatibilityDisabled: () => true,
+ }),
+ );
+
+ await expect(im.authorize()).rejects.toThrow('WECHAT_DISABLED_BY_POLICY');
+ expect(im.getState()).toMatchObject({
+ phase: 'disabled_by_policy',
+ bound: false,
+ });
+ expect(createTransport).not.toHaveBeenCalled();
+ });
+
+ it('applies and clears a runtime compatibility disable without starting a transport', async () => {
+ let disabled = false;
+ const im = new WechatIM(
+ deps({
+ isCompatibilityDisabled: () => disabled,
+ }),
+ );
+
+ disabled = true;
+ await im.setCompatibilityDisabled(true);
+ expect(im.getState()).toMatchObject({ phase: 'disabled_by_policy', bound: false });
+
+ disabled = false;
+ await im.setCompatibilityDisabled(false);
+ expect(im.getState()).toMatchObject({ phase: 'disconnected', bound: false });
+ });
+
+ it('drops late authorization credentials after a compatibility revision changes', async () => {
+ const testHost = host();
+ let resolveCredentials!: (credentials: WechatCredentials) => void;
+ const waitAuthorization = vi.fn(
+ () =>
+ new Promise<WechatCredentials>((resolve) => {
+ resolveCredentials = resolve;
+ }),
+ );
+ const authorizationTransport = {
+ beginAuthorization: vi.fn(async () => ({
+ id: 'challenge',
+ qrCodeUrl: 'https://ilinkai.weixin.qq.com/qr/challenge',
+ createdAt: 1,
+ })),
+ waitAuthorization,
+ } as unknown as WechatTransport;
+ const createTransport = vi.fn(() => authorizationTransport);
+ const im = new WechatIM(deps({ host: testHost, createTransport }));
+
+ await im.authorize();
+ await vi.waitFor(() => expect(waitAuthorization).toHaveBeenCalledOnce());
+ await im.setCompatibilityDisabled(true);
+ resolveCredentials({
+ token: 'late-token',
+ botId: 'late-bot',
+ userId: 'late-user',
+ baseUrl: 'https://ilinkai.weixin.qq.com',
+ });
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(createTransport).toHaveBeenCalledOnce();
+ expect(testHost.secrets.write).not.toHaveBeenCalled();
+ expect(im.getState()).toMatchObject({ phase: 'disabled_by_policy', bound: false });
+ });
+
+ it('rolls back a newly activated binding when the account generation becomes stale', async () => {
+ const previous = { bindingEpoch: 'binding-previous', cursor: 'cursor-previous' };
+ let activationFinished = false;
+ let newBindingEpoch = '';
+ const activateCalls: Array<Record<string, unknown>> = [];
+ const db = fakeDb({
+ queryOne: vi.fn(async (sql: string) =>
+ sql.includes('FROM wechat_sync_state') ? previous : undefined,
+ ) as DbClient['queryOne'],
+ tx: vi.fn(async (name: string, args: Record<string, unknown>) => {
+ if (name !== 'wechatActivateBindingEpoch') return null;
+ activateCalls.push(args);
+ if (activateCalls.length === 1) {
+ newBindingEpoch = String(args.bindingEpoch);
+ activationFinished = true;
+ return {
+ activated: true,
+ previousActiveEpoch: previous.bindingEpoch,
+ activeBindingEpoch: newBindingEpoch,
+ };
+ }
+ return {
+ activated: true,
+ previousActiveEpoch: newBindingEpoch,
+ activeBindingEpoch: previous.bindingEpoch,
+ };
+ }),
+ });
+ const testHost = host({
+ secretRead: (name) =>
+ name === 'wechat_data_key_v1' ? Buffer.alloc(32, 1).toString('base64') : null,
+ });
+ const authorizationTransport = authorizationTransportReturning({
+ token: 'new-token',
+ botId: 'new-bot',
+ userId: 'new-user',
+ baseUrl: 'https://ilinkai.weixin.qq.com',
+ });
+ const createTransport = vi.fn(() => authorizationTransport);
+ const im = new WechatIM(
+ deps({
+ host: testHost,
+ getDbClient: () => db,
+ createTransport,
+ isAccountGenerationCurrent: () => !activationFinished,
+ }),
+ );
+
+ await im.authorize();
+ await vi.waitFor(() => expect(activateCalls).toHaveLength(2));
+
+ expect(activateCalls[1]).toMatchObject({
+ bindingEpoch: previous.bindingEpoch,
+ expectedActiveEpoch: newBindingEpoch,
+ initialCursor: previous.cursor,
+ });
+ expect(testHost.secrets.remove).toHaveBeenCalledWith(
+ `wechat_credentials_${newBindingEpoch}`,
+ );
+ expect(createTransport).toHaveBeenCalledOnce();
+ await im.dispose();
+ });
+
+ it('removes staged files returned while replacing the previous binding', async () => {
+ const previous = { bindingEpoch: 'binding-previous', cursor: 'cursor-previous' };
+ const released = ['C:\\wechat-staged\\old-file.pdf'];
+ const db = fakeDb({
+ query: vi.fn(async () => []),
+ queryOne: vi.fn(async (sql: string) => {
+ if (sql.includes('FROM wechat_sync_state')) return previous;
+ if (sql.includes('COUNT(*) AS count')) return { count: 0 };
+ return undefined;
+ }) as DbClient['queryOne'],
+ tx: vi.fn(async (name: string, args: Record<string, unknown>) => {
+ switch (name) {
+ case 'wechatActivateBindingEpoch':
+ return {
+ activated: true,
+ previousActiveEpoch: previous.bindingEpoch,
+ activeBindingEpoch: String(args.bindingEpoch),
+ };
+ case 'wechatCloseBindingEpoch':
+ return { closed: true };
+ case 'wechatUnbindCleanup':
+ return { deletedTasks: 1, deletedMediaRefs: 0, filePaths: released };
+ case 'wechatLeaseNextTask':
+ return null;
+ default:
+ return null;
+ }
+ }),
+ });
+ const testHost = host({
+ secretRead: (name) =>
+ name === 'wechat_data_key_v1' ? Buffer.alloc(32, 2).toString('base64') : null,
+ });
+ const authTransport = authorizationTransportReturning({
+ token: 'new-token',
+ botId: 'new-bot',
+ userId: 'new-user',
+ baseUrl: 'https://ilinkai.weixin.qq.com',
+ });
+ const liveTransport = blockingLiveTransport();
+ const createTransport = vi
+ .fn()
+ .mockReturnValueOnce(authTransport)
+ .mockReturnValueOnce(liveTransport);
+ const im = new WechatIM(
+ deps({
+ host: testHost,
+ getDbClient: () => db,
+ createTransport,
+ }),
+ );
+
+ await im.authorize();
+ await vi.waitFor(() =>
+ expect(mediaMocks.removeReleasedWechatFiles).toHaveBeenCalledWith(released),
+ );
+ await vi.waitFor(() => expect(im.getState().phase).toBe('connected'));
+
+ await im.dispose();
+ });
+});
+
+function deps(overrides: Partial<WechatIMDeps> & { host?: IMHost } = {}): WechatIMDeps {
+ return {
+ host: overrides.host ?? host(),
+ getDbClient: overrides.getDbClient ?? (() => fakeDb()),
+ createTransport:
+ overrides.createTransport ??
+ (() => {
+ throw new Error('transport should not be created');
+ }),
+ openAuthorizationUrl: overrides.openAuthorizationUrl ?? vi.fn(),
+ captureAccountGeneration: overrides.captureAccountGeneration ?? (() => 1),
+ isAccountGenerationCurrent:
+ overrides.isAccountGenerationCurrent ?? ((generation) => generation === 1),
+ isCompatibilityDisabled: overrides.isCompatibilityDisabled ?? (() => false),
+ now: overrides.now ?? (() => 100),
+ };
+}
+
+function host(
+ options: {
+ secretAvailable?: boolean;
+ secretRead?: (name: string) => string | null;
+ } = {},
+): IMHost {
+ return {
+ secrets: {
+ isAvailable: () => options.secretAvailable ?? true,
+ read: vi.fn(options.secretRead ?? (() => null)),
+ write: vi.fn(() => true),
+ remove: vi.fn(),
+ },
+ ipc: {
+ handle: vi.fn(),
+ broadcast: vi.fn(),
+ },
+ paths: {
+ feishuMediaDir: 'unused',
+ },
+ httpPostForm: vi.fn(),
+ };
+}
+
+function fakeDb(overrides: Partial<DbClient> = {}): DbClient {
+ return {
+ tx: overrides.tx ?? vi.fn(),
+ query: overrides.query ?? vi.fn(),
+ queryOne: overrides.queryOne ?? vi.fn(),
+ exec: overrides.exec ?? vi.fn(),
+ drizzle: {} as DbClient['drizzle'],
+ vecAvailable: false,
+ dispose: overrides.dispose ?? vi.fn(),
+ };
+}
+
+function authorizationTransportReturning(credentials: WechatCredentials): WechatTransport {
+ return {
+ beginAuthorization: vi.fn(async () => ({
+ id: 'challenge',
+ qrCodeUrl: 'https://ilinkai.weixin.qq.com/qr/challenge',
+ createdAt: 1,
+ })),
+ waitAuthorization: vi.fn(async () => credentials),
+ } as unknown as WechatTransport;
+}
+
+function blockingLiveTransport(): WechatTransport {
+ return {
+ notifyStart: vi.fn(async () => undefined),
+ notifyStop: vi.fn(async () => undefined),
+ poll: vi.fn(
+ (_cursor: string, signal: AbortSignal) =>
+ new Promise((_resolve, reject) => {
+ signal.addEventListener(
+ 'abort',
+ () => reject(Object.assign(new Error('aborted'), { name: 'AbortError' })),
+ { once: true },
+ );
+ }),
+ ),
+ } as unknown as WechatTransport;
+}
diff --git a/apps/desktop/src/main/im/wechat/__tests__/channelSettings.test.ts b/apps/desktop/src/main/im/wechat/__tests__/channelSettings.test.ts
new file mode 100644
index 0000000000..2d841ab562
--- /dev/null
+++ b/apps/desktop/src/main/im/wechat/__tests__/channelSettings.test.ts
@@ -0,0 +1,91 @@
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import {
+ readWechatChannelSettings,
+ resetWechatWorkingDir,
+ resolveWechatWorkingDir,
+ writeWechatWorkingDir,
+} from '../channelSettings';
+
+let root = '';
+
+beforeEach(() => {
+ root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-wechat-channel-settings-'));
+});
+
+afterEach(() => {
+ fs.rmSync(root, { recursive: true, force: true });
+});
+
+describe('personal WeChat channel settings', () => {
+ it('persists only a directory selected from an absolute existing path', () => {
+ const selected = path.join(root, 'project');
+ const replacement = path.join(root, 'replacement');
+ fs.mkdirSync(selected);
+ fs.mkdirSync(replacement);
+
+ writeWechatWorkingDir(selected, root);
+ const state = writeWechatWorkingDir(replacement, root);
+
+ expect(state.workingDir).toBe(fs.realpathSync.native(replacement).replace(/\\/g, '/'));
+ expect(state.workingDirAvailable).toBe(true);
+ expect(readWechatChannelSettings(root)).toEqual(state);
+ });
+
+ it('falls back to a managed directory when the selected directory disappears', () => {
+ const selected = path.join(root, 'project');
+ fs.mkdirSync(selected);
+ writeWechatWorkingDir(selected, root);
+ fs.rmSync(selected, { recursive: true });
+
+ expect(readWechatChannelSettings(root).workingDirAvailable).toBe(false);
+ const resolved = resolveWechatWorkingDir('bot-1', root);
+ expect(resolved).toBe(path.join(root, 'im-working-dir', 'wechat-bot-1'));
+ expect(fs.statSync(resolved).isDirectory()).toBe(true);
+ });
+
+ it('maps unsafe external bot ids to stable managed directory names', () => {
+ const managedRoot = path.join(root, 'im-working-dir');
+ const unsafeIds = ['../../escape', 'nested/bot', 'nested\\bot', 'bot:name'];
+
+ for (const botId of unsafeIds) {
+ const first = resolveWechatWorkingDir(botId, root);
+ const second = resolveWechatWorkingDir(botId, root);
+ expect(first).toBe(second);
+ expect(path.dirname(first)).toBe(managedRoot);
+ expect(path.basename(first)).toMatch(/^wechat-external-[a-f0-9]{24}$/);
+ expect(fs.statSync(first).isDirectory()).toBe(true);
+ }
+
+ expect(resolveWechatWorkingDir('bot-1', root)).toBe(
+ path.join(managedRoot, 'wechat-bot-1'),
+ );
+ expect(fs.existsSync(path.join(root, 'escape'))).toBe(false);
+ });
+
+ it('reset removes the override and restores the managed directory', () => {
+ const selected = path.join(root, 'project');
+ fs.mkdirSync(selected);
+ writeWechatWorkingDir(selected, root);
+
+ expect(resetWechatWorkingDir(root)).toEqual({
+ version: 1,
+ workingDir: null,
+ workingDirAvailable: true,
+ });
+ expect(resolveWechatWorkingDir('bot-2', root)).toBe(
+ path.join(root, 'im-working-dir', 'wechat-bot-2'),
+ );
+ });
+
+ it('rejects relative paths and files', () => {
+ expect(() => writeWechatWorkingDir('relative', root)).toThrow('WECHAT_WORKING_DIR_INVALID');
+ const file = path.join(root, 'file.txt');
+ fs.writeFileSync(file, 'x');
+ expect(() => writeWechatWorkingDir(file, root)).toThrow('WECHAT_WORKING_DIR_NOT_DIRECTORY');
+ });
+});
diff --git a/apps/desktop/src/main/im/wechat/__tests__/compatibilityPolicy.test.ts b/apps/desktop/src/main/im/wechat/__tests__/compatibilityPolicy.test.ts
new file mode 100644
index 0000000000..dcbaa7668c
--- /dev/null
+++ b/apps/desktop/src/main/im/wechat/__tests__/compatibilityPolicy.test.ts
@@ -0,0 +1,420 @@
+import { createPublicKey, generateKeyPairSync, sign, type KeyObject } from 'node:crypto';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ WECHAT_COMPATIBILITY_MANIFEST_MAX_BYTES,
+ WechatCompatibilityPolicyService,
+ canonicalizeWechatCompatibilityManifestPayload,
+ evaluateWechatCompatibilityManifest,
+ parseAndVerifyWechatCompatibilityManifest,
+ type WechatCompatibilityManifest,
+ type WechatCompatibilityManifestPayload,
+} from '../compatibilityPolicy';
+
+const NOW = 2_000_000_000_000;
+const MANIFEST_URL = 'https://config.cindy.example/compat/wechat/v1.json';
+const HELP_PREFIX = 'https://support.cindy.example/help/wechat/';
+
+let root = '';
+let privateKey: KeyObject;
+let publicKey: KeyObject;
+let publicKeySpkiBase64 = '';
+
+beforeEach(() => {
+ root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-wechat-policy-'));
+ const pair = generateKeyPairSync('ed25519');
+ privateKey = pair.privateKey;
+ publicKey = pair.publicKey;
+ publicKeySpkiBase64 = publicKey.export({ format: 'der', type: 'spki' }).toString('base64');
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+ fs.rmSync(root, { recursive: true, force: true });
+});
+
+describe('personal WeChat compatibility policy', () => {
+ it('matches an independent fixed canonical JSON and Ed25519 signature vector', () => {
+ const canonical =
+ '{"expiresAt":2000003600000,"generatedAt":1999999940000,"rules":[{"action":"disable","maxVersion":"2.0.0","minVersion":"1.0.0","reason":"protocol_incompatible"}],"schemaVersion":1,"sequence":1}';
+ const vectorPublicKey = createPublicKey({
+ key: Buffer.from('MCowBQYDK2VwAyEAizSW8guHE66iKKL/AxC/hqHM5iHJKzrOvgXNK1Vke3g=', 'base64'),
+ format: 'der',
+ type: 'spki',
+ });
+ const payload = basePayload();
+ const signature =
+ 'ZoIVg5vU5KGrA5/O1aZhp2l0ekES87M76I3FHxYhvyAE4VpO7OVAgmkS+2JE1WcLewICAgtkX2NqqcSi3Z7lDA==';
+
+ expect(canonicalizeWechatCompatibilityManifestPayload(payload)).toBe(canonical);
+ expect(
+ parseAndVerifyWechatCompatibilityManifest(
+ Buffer.from(JSON.stringify({ ...payload, signature })),
+ vectorPublicKey,
+ [],
+ NOW,
+ ),
+ ).toMatchObject({ sequence: 1, signature });
+ });
+
+ it('verifies canonical Ed25519 payloads and matches inclusive semver ranges', () => {
+ const bytes = signedManifest({
+ rules: [
+ {
+ minVersion: '1.1.20',
+ maxVersion: '1.1.21',
+ action: 'disable',
+ reason: 'protocol_incompatible',
+ helpUrl: `${HELP_PREFIX}protocol`,
+ },
+ ],
+ });
+
+ const manifest = parseAndVerifyWechatCompatibilityManifest(
+ bytes,
+ publicKey,
+ [HELP_PREFIX],
+ NOW,
+ );
+ expect(evaluateWechatCompatibilityManifest(manifest, '1.1.21', NOW)).toEqual({
+ disabled: true,
+ sequence: 1,
+ reasonCode: 'protocol_incompatible',
+ helpUrl: `${HELP_PREFIX}protocol`,
+ });
+ expect(evaluateWechatCompatibilityManifest(manifest, '1.1.22', NOW)).toEqual({
+ disabled: false,
+ sequence: 1,
+ });
+ });
+
+ it('rejects tampering, unknown fields, future timestamps, and untrusted help URLs', () => {
+ const signed = JSON.parse(Buffer.from(signedManifest()).toString('utf8')) as Record<
+ string,
+ unknown
+ >;
+ const tampered = structuredClone(signed) as {
+ rules: Array<Record<string, unknown>>;
+ };
+ tampered.rules[0].reason = 'tampered';
+ expect(() =>
+ parseAndVerifyWechatCompatibilityManifest(
+ Buffer.from(JSON.stringify(tampered)),
+ publicKey,
+ [HELP_PREFIX],
+ NOW,
+ ),
+ ).toThrow('SIGNATURE_INVALID');
+
+ expect(() =>
+ parseAndVerifyWechatCompatibilityManifest(
+ Buffer.from(JSON.stringify({ ...signed, endpoint: 'https://evil.invalid' })),
+ publicKey,
+ [HELP_PREFIX],
+ NOW,
+ ),
+ ).toThrow('UNKNOWN_FIELD');
+
+ expect(() =>
+ parseAndVerifyWechatCompatibilityManifest(
+ signedManifest({ generatedAt: NOW + 6 * 60 * 1_000, expiresAt: NOW + 60 * 60 * 1_000 }),
+ publicKey,
+ [HELP_PREFIX],
+ NOW,
+ ),
+ ).toThrow('GENERATED_AT_IN_FUTURE');
+
+ expect(() =>
+ parseAndVerifyWechatCompatibilityManifest(
+ signedManifest({
+ rules: [
+ {
+ minVersion: '1.0.0',
+ maxVersion: '2.0.0',
+ action: 'disable',
+ reason: 'protocol_incompatible',
+ helpUrl: 'https://evil.invalid/help',
+ },
+ ],
+ }),
+ publicKey,
+ [HELP_PREFIX],
+ NOW,
+ ),
+ ).toThrow('HELP_URL_INVALID');
+
+ expect(() =>
+ parseAndVerifyWechatCompatibilityManifest(
+ signedManifest({
+ rules: [
+ {
+ minVersion: '1.0.0',
+ maxVersion: '2.0.0',
+ action: 'disable',
+ reason: 'protocol_incompatible',
+ helpUrl: 'https://support.cindy.example/help/wechat-evil',
+ },
+ ],
+ }),
+ publicKey,
+ ['https://support.cindy.example/help/wechat'],
+ NOW,
+ ),
+ ).toThrow('HELP_URL_INVALID');
+
+ expect(() =>
+ parseAndVerifyWechatCompatibilityManifest(
+ signedManifest({
+ rules: [
+ {
+ minVersion: '1.0.0',
+ maxVersion: '2.0.0',
+ action: 'disable',
+ reason: 'protocol_incompatible',
+ helpUrl: 'https://support.cindy.example/help/wechat/%2fadmin',
+ },
+ ],
+ }),
+ publicKey,
+ [HELP_PREFIX],
+ NOW,
+ ),
+ ).toThrow('HELP_URL_INVALID');
+
+ const rsaPublicKey = generateKeyPairSync('rsa', { modulusLength: 2048 }).publicKey;
+ expect(() =>
+ parseAndVerifyWechatCompatibilityManifest(signedManifest(), rsaPublicKey, [HELP_PREFIX], NOW),
+ ).toThrow('PUBLIC_KEY_INVALID');
+ });
+
+ it('keeps the last verified decision when a network response attempts sequence rollback', async () => {
+ const cachePath = path.join(root, 'policy.json');
+ const sequenceTwo = signedManifest({ sequence: 2 });
+ const first = service({
+ cachePath,
+ fetch: vi.fn(async () => response(sequenceTwo, { type: 'Application/JSON; Charset=UTF-8' })),
+ });
+ await first.refresh();
+ expect(first.getDecision()).toMatchObject({ disabled: true, sequence: 2 });
+ expect(fs.readFileSync(cachePath)).toEqual(sequenceTwo);
+
+ const sequenceOne = signedManifest({ sequence: 1 });
+ const rollback = service({
+ cachePath,
+ fetch: vi.fn(async () => response(sequenceOne)),
+ });
+ await rollback.refresh();
+ expect(rollback.getDecision()).toMatchObject({ disabled: true, sequence: 2 });
+ expect(fs.readFileSync(cachePath)).toEqual(sequenceTwo);
+ });
+
+ it('applies a verified remote decision even when its cache cannot be persisted', async () => {
+ const cacheParent = path.join(root, 'cache-parent');
+ const cachePath = path.join(cacheParent, 'policy.json');
+ fs.writeFileSync(cacheParent, 'not a directory');
+ const policy = service({
+ cachePath,
+ fetch: vi.fn(async () => response(signedManifest({ sequence: 2 }))),
+ });
+
+ await expect(policy.refresh()).resolves.toBeUndefined();
+ expect(policy.getDecision()).toMatchObject({ disabled: true, sequence: 2 });
+ });
+
+ it('fails open after the last verified cached manifest expires', async () => {
+ const cachePath = path.join(root, 'policy.json');
+ fs.writeFileSync(cachePath, signedManifest({ expiresAt: NOW }));
+ const policy = service({
+ cachePath,
+ manifestUrl: null,
+ fetch: vi.fn(),
+ });
+
+ await policy.refresh();
+
+ expect(policy.getDecision()).toEqual({ disabled: false, sequence: 1 });
+ });
+
+ it('publishes fail-open immediately when an active cached disable naturally expires', async () => {
+ vi.useFakeTimers();
+ let now = NOW;
+ const cachePath = path.join(root, 'policy.json');
+ fs.writeFileSync(cachePath, signedManifest({ expiresAt: NOW + 1_000 }));
+ const policy = service({
+ cachePath,
+ manifestUrl: null,
+ fetch: vi.fn(),
+ now: () => now,
+ });
+ const decisions: boolean[] = [];
+ policy.subscribe((decision) => decisions.push(decision.disabled));
+
+ await policy.refresh();
+ expect(policy.getDecision()).toMatchObject({ disabled: true, sequence: 1 });
+
+ now = NOW + 1_000;
+ await vi.advanceTimersByTimeAsync(1_000);
+
+ expect(policy.getDecision()).toEqual({ disabled: false, sequence: 1 });
+ expect(decisions).toEqual([false, true, false]);
+ });
+
+ it('rejects oversized or non-JSON responses without replacing the cache', async () => {
+ const cachePath = path.join(root, 'policy.json');
+ const valid = signedManifest({ sequence: 3 });
+ fs.writeFileSync(cachePath, valid);
+
+ const oversized = service({
+ cachePath,
+ fetch: vi.fn(async () =>
+ response(new Uint8Array(0), {
+ contentLength: String(WECHAT_COMPATIBILITY_MANIFEST_MAX_BYTES + 1),
+ }),
+ ),
+ });
+ await oversized.refresh();
+ expect(oversized.getDecision()).toMatchObject({ disabled: true, sequence: 3 });
+ expect(fs.readFileSync(cachePath)).toEqual(valid);
+
+ const spoofedLength = service({
+ cachePath,
+ fetch: vi.fn(async () =>
+ response(new Uint8Array(WECHAT_COMPATIBILITY_MANIFEST_MAX_BYTES + 1), {
+ contentLength: '1',
+ }),
+ ),
+ });
+ await spoofedLength.refresh();
+ expect(spoofedLength.getDecision()).toMatchObject({ disabled: true, sequence: 3 });
+ expect(fs.readFileSync(cachePath)).toEqual(valid);
+
+ const wrongType = service({
+ cachePath,
+ fetch: vi.fn(async () => response(signedManifest({ sequence: 4 }), { type: 'text/html' })),
+ });
+ await wrongType.refresh();
+ expect(wrongType.getDecision()).toMatchObject({ disabled: true, sequence: 3 });
+ expect(fs.readFileSync(cachePath)).toEqual(valid);
+ });
+
+ it('never downloads policy code or endpoint overrides because the schema is exact', () => {
+ const payload = basePayload();
+ const raw = {
+ ...payload,
+ rules: [
+ {
+ ...payload.rules[0],
+ endpoint: 'https://evil.invalid',
+ },
+ ],
+ };
+ const signature = sign(
+ null,
+ Buffer.from(canonicalizeWechatCompatibilityManifestPayload(payload)),
+ privateKey,
+ ).toString('base64');
+
+ expect(() =>
+ parseAndVerifyWechatCompatibilityManifest(
+ Buffer.from(JSON.stringify({ ...raw, signature })),
+ publicKey,
+ [HELP_PREFIX],
+ NOW,
+ ),
+ ).toThrow('UNKNOWN_FIELD');
+ });
+});
+
+function basePayload(
+ overrides: Partial<WechatCompatibilityManifestPayload> = {},
+): WechatCompatibilityManifestPayload {
+ return {
+ schemaVersion: 1,
+ sequence: 1,
+ generatedAt: NOW - 60_000,
+ expiresAt: NOW + 60 * 60 * 1_000,
+ rules: [
+ {
+ minVersion: '1.0.0',
+ maxVersion: '2.0.0',
+ action: 'disable',
+ reason: 'protocol_incompatible',
+ },
+ ],
+ ...overrides,
+ };
+}
+
+function signedManifest(overrides: Partial<WechatCompatibilityManifestPayload> = {}): Buffer {
+ const payload = basePayload(overrides);
+ const signature = sign(
+ null,
+ Buffer.from(canonicalizeWechatCompatibilityManifestPayload(payload)),
+ privateKey,
+ ).toString('base64');
+ const manifest: WechatCompatibilityManifest = { ...payload, signature };
+ return Buffer.from(JSON.stringify(manifest));
+}
+
+function service({
+ cachePath,
+ fetch,
+ manifestUrl = MANIFEST_URL,
+ now = () => NOW,
+}: {
+ cachePath: string;
+ fetch: ReturnType<typeof vi.fn>;
+ manifestUrl?: string | null;
+ now?: () => number;
+}): WechatCompatibilityPolicyService {
+ return new WechatCompatibilityPolicyService({
+ manifestUrl,
+ publicKeySpkiBase64,
+ trustedHelpUrlPrefixes: [HELP_PREFIX],
+ cachePath: () => cachePath,
+ appVersion: () => '1.1.21',
+ fetch,
+ now,
+ refreshIntervalMs: 0,
+ });
+}
+
+function response(
+ bytes: Uint8Array,
+ options: { type?: string; contentLength?: string } = {},
+): {
+ ok: boolean;
+ status: number;
+ headers: { get(name: string): string | null };
+ body: ReadableStream<Uint8Array>;
+ arrayBuffer(): Promise<ArrayBuffer>;
+} {
+ return {
+ ok: true,
+ status: 200,
+ headers: {
+ get(name) {
+ if (name.toLowerCase() === 'content-type') return options.type ?? 'application/json';
+ if (name.toLowerCase() === 'content-length') {
+ return options.contentLength ?? String(bytes.byteLength);
+ }
+ return null;
+ },
+ },
+ body: new ReadableStream({
+ start(controller) {
+ controller.enqueue(bytes);
+ controller.close();
+ },
+ }),
+ async arrayBuffer() {
+ const copy = new Uint8Array(bytes.byteLength);
+ copy.set(bytes);
+ return copy.buffer;
+ },
+ };
+}
diff --git a/apps/desktop/src/main/im/wechat/__tests__/contextCrypto.test.ts b/apps/desktop/src/main/im/wechat/__tests__/contextCrypto.test.ts
new file mode 100644
index 0000000000..e74533f886
--- /dev/null
+++ b/apps/desktop/src/main/im/wechat/__tests__/contextCrypto.test.ts
@@ -0,0 +1,47 @@
+import { randomBytes } from 'node:crypto';
+
+import { describe, expect, it } from 'vitest';
+
+import {
+ decryptWechatContextToken,
+ encryptWechatContextToken,
+ WechatContextCryptoError,
+} from '../contextCrypto.js';
+
+describe('WeChat context token encryption', () => {
+ it('round-trips with AES-256-GCM without persisting plaintext', () => {
+ const key = randomBytes(32);
+ const encrypted = encryptWechatContextToken('context-token-secret', key, 'epoch-1', 'task-1');
+
+ expect(JSON.stringify(encrypted)).not.toContain('context-token-secret');
+ expect(decryptWechatContextToken(encrypted, key, 'epoch-1', 'task-1')).toBe(
+ 'context-token-secret',
+ );
+ });
+
+ it('binds ciphertext to both binding epoch and task id', () => {
+ const key = randomBytes(32);
+ const encrypted = encryptWechatContextToken('secret', key, 'epoch-1', 'task-1');
+
+ expect(() => decryptWechatContextToken(encrypted, key, 'epoch-2', 'task-1')).toThrowError(
+ WechatContextCryptoError,
+ );
+ expect(() => decryptWechatContextToken(encrypted, key, 'epoch-1', 'task-2')).toThrowError(
+ WechatContextCryptoError,
+ );
+ });
+
+ it('fails closed for malformed values and invalid key length', () => {
+ expect(() =>
+ encryptWechatContextToken('secret', randomBytes(16), 'epoch-1', 'task-1'),
+ ).toThrowError(WechatContextCryptoError);
+ expect(() =>
+ decryptWechatContextToken(
+ { nonce: 'bad', ciphertext: 'bad', tag: 'bad' },
+ randomBytes(32),
+ 'epoch-1',
+ 'task-1',
+ ),
+ ).toThrowError(WechatContextCryptoError);
+ });
+});
diff --git a/apps/desktop/src/main/im/wechat/__tests__/mediaStaging.test.ts b/apps/desktop/src/main/im/wechat/__tests__/mediaStaging.test.ts
new file mode 100644
index 0000000000..b513eb2abb
--- /dev/null
+++ b/apps/desktop/src/main/im/wechat/__tests__/mediaStaging.test.ts
@@ -0,0 +1,159 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { WechatTransport } from '@cindy/wechat-ilink';
+
+const mocks = vi.hoisted(() => ({
+ decodeWechatSilkToWav: vi.fn(),
+ ingestMedia: vi.fn(),
+ resolveSafe: vi.fn(),
+}));
+
+vi.mock('../silkDecoder', () => ({
+ decodeWechatSilkToWav: mocks.decodeWechatSilkToWav,
+}));
+
+vi.mock('../../../cindy-media/blobStore', () => ({
+ resolveSafe: mocks.resolveSafe,
+}));
+
+vi.mock('../../../cindy-media/ingest', () => ({
+ ingestMedia: mocks.ingestMedia,
+}));
+
+import { __testing, stageWechatTaskMedia } from '../mediaStaging';
+import { pcmS16leToWav, WavOutputLimitError } from '../silkWav';
+
+describe('WeChat media staging validation', () => {
+ beforeEach(() => {
+ mocks.decodeWechatSilkToWav.mockReset();
+ mocks.ingestMedia.mockReset();
+ mocks.resolveSafe.mockReset();
+ });
+
+ it('detects supported image bytes instead of trusting platform metadata', () => {
+ const png = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
+ expect(__testing.detectWechatMedia({ kind: 'image' }, png)).toEqual({
+ attachmentKind: 'image',
+ fileName: 'wechat-image.png',
+ mimeType: 'image/png',
+ storage: 'cindy-media',
+ });
+ expect(__testing.detectWechatMedia({ kind: 'image' }, Buffer.from('not-image'))).toBeNull();
+ });
+
+ it('requires the declared voice encoding to match the downloaded bytes', () => {
+ expect(
+ __testing.detectWechatMedia({ kind: 'voice', voiceEncoding: 8 }, Buffer.from('OggSvoice')),
+ ).toMatchObject({ mimeType: 'audio/ogg' });
+ expect(
+ __testing.detectWechatMedia({ kind: 'voice', voiceEncoding: 7 }, Buffer.from('OggSvoice')),
+ ).toBeNull();
+ });
+
+ it('sanitizes platform filenames before creating owner-scoped paths', () => {
+ expect(__testing.sanitizeAttachmentName('../../secret?.pdf', 'fallback.bin')).toBe(
+ '.._.._secret_.pdf',
+ );
+ expect(__testing.sanitizeAttachmentName('... ', 'fallback.bin')).toBe('fallback.bin');
+ });
+
+ it('wraps worker-decoded mono PCM in a valid 24 kHz WAV container', () => {
+ const wav = Buffer.from(pcmS16leToWav(Buffer.from([1, 0, 2, 0]), 24_000));
+ expect(wav.subarray(0, 4).toString('ascii')).toBe('RIFF');
+ expect(wav.subarray(8, 12).toString('ascii')).toBe('WAVE');
+ expect(wav.readUInt32LE(24)).toBe(24_000);
+ expect(wav.readUInt16LE(22)).toBe(1);
+ expect(wav.readUInt16LE(34)).toBe(16);
+ expect(wav.subarray(44)).toEqual(Buffer.from([1, 0, 2, 0]));
+ });
+
+ it('rejects oversized PCM before allocating its WAV output', () => {
+ expect(() => pcmS16leToWav(Buffer.from([1, 0]), 24_000, 45)).toThrow(
+ WavOutputLimitError,
+ );
+ });
+
+ it('records a staged media blob before exposing its attachment', async () => {
+ const hash = 'a'.repeat(64);
+ mocks.ingestMedia.mockResolvedValueOnce({
+ hash,
+ ext: '.png',
+ mimeType: 'image/png',
+ bytes: 8,
+ url: `cindy-media://blobs/${hash}.png`,
+ deduplicated: false,
+ refIds: [],
+ });
+ mocks.resolveSafe.mockReturnValueOnce({ absPath: 'C:\\media\\wechat-image.png' });
+
+ const result = await stageWechatTaskMedia(
+ stageArgs({
+ media: [{ kind: 'image' }],
+ downloadMedia: vi
+ .fn()
+ .mockResolvedValue(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])),
+ }),
+ );
+
+ expect(mocks.ingestMedia).toHaveBeenCalledWith({
+ buffer: expect.any(Uint8Array),
+ mimeType: 'image/png',
+ isCache: false,
+ refs: [],
+ });
+ expect(mocks.ingestMedia.mock.invocationCallOrder[0]).toBeLessThan(
+ mocks.resolveSafe.mock.invocationCallOrder[0]!,
+ );
+ expect(result.mediaRefs).toHaveLength(1);
+ });
+
+ it('distinguishes download, decode, and staging failures', async () => {
+ const downloadFailed = await stageWechatTaskMedia(
+ stageArgs({
+ media: [{ kind: 'image' }],
+ downloadMedia: vi.fn().mockRejectedValue(new Error('network unavailable')),
+ }),
+ );
+ expect(downloadFailed.unsupportedMedia).toEqual(['image:download-failed']);
+
+ mocks.decodeWechatSilkToWav.mockRejectedValueOnce(
+ new Error('WECHAT_SILK_DECODE_FAILED'),
+ );
+ const decodeFailed = await stageWechatTaskMedia(
+ stageArgs({
+ media: [{ kind: 'voice', voiceEncoding: 6 }],
+ downloadMedia: vi.fn().mockResolvedValue(Buffer.from('silk')),
+ }),
+ );
+ expect(decodeFailed.unsupportedMedia).toEqual(['voice:decode-failed']);
+
+ mocks.ingestMedia.mockRejectedValueOnce(new Error('disk full'));
+ const stagingFailed = await stageWechatTaskMedia(
+ stageArgs({
+ media: [{ kind: 'image' }],
+ downloadMedia: vi
+ .fn()
+ .mockResolvedValue(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])),
+ }),
+ );
+ expect(stagingFailed.unsupportedMedia).toEqual(['image:staging-failed']);
+ });
+});
+
+function stageArgs({
+ media,
+ downloadMedia,
+}: {
+ media: Parameters<typeof stageWechatTaskMedia>[0]['media'];
+ downloadMedia: ReturnType<typeof vi.fn>;
+}): Parameters<typeof stageWechatTaskMedia>[0] {
+ return {
+ bindingEpoch: 'binding-1',
+ taskId: 'task-1',
+ sessionId: 'session-1',
+ media,
+ transport: { downloadMedia } as unknown as WechatTransport,
+ signal: new AbortController().signal,
+ now: 100,
+ };
+}
diff --git a/apps/desktop/src/main/im/wechat/__tests__/permissionPolicy.test.ts b/apps/desktop/src/main/im/wechat/__tests__/permissionPolicy.test.ts
new file mode 100644
index 0000000000..975ce69d84
--- /dev/null
+++ b/apps/desktop/src/main/im/wechat/__tests__/permissionPolicy.test.ts
@@ -0,0 +1,68 @@
+import { describe, expect, it } from 'vitest';
+import type { Capabilities } from '@cindy/maker-core';
+
+import {
+ createWechatTurnPermissionPolicy,
+ supportsWechatTurnPermissionMode,
+} from '../permissionPolicy';
+
+describe('personal WeChat turn permission policy', () => {
+ it('forces destructive shell and wrapped MCP actions through Desktop', () => {
+ const policy = createWechatTurnPermissionPolicy('task-1');
+
+ expect(policy.origin).toEqual({
+ kind: 'im',
+ channel: 'wechat',
+ taskId: 'task-1',
+ });
+ expect(
+ policy.forceConfirmToolCall('Bash', { command: 'rm -rf build' }),
+ ).toBe(true);
+ expect(
+ policy.forceConfirmToolCall('mcp__cindy_contacts__call_tool', {
+ name: 'contacts_delete',
+ args: { id: 'contact-1' },
+ }),
+ ).toBe(true);
+ expect(
+ policy.forceConfirmToolCall('mcp:cindy_contacts', {
+ toolParams: {
+ name: 'contacts_merge',
+ args: { sourceId: 'a', targetId: 'b' },
+ },
+ }),
+ ).toBe(true);
+ });
+
+ it('keeps read-only calls automatic but treats opaque Codex writes conservatively', () => {
+ const policy = createWechatTurnPermissionPolicy('task-2');
+
+ expect(policy.forceConfirmToolCall('Read', { path: 'README.md' })).toBe(false);
+ expect(
+ policy.forceConfirmToolCall('mcp:cindy_contacts', {
+ toolParams: { name: 'contacts_search', args: { query: 'Carol' } },
+ }),
+ ).toBe(false);
+ expect(policy.forceConfirmToolCall('file_change', { grantRoot: null })).toBe(true);
+ expect(
+ policy.forceConfirmToolCall('permissions', { permissions: { network: true } }),
+ ).toBe(true);
+ });
+
+ it('honors the provider capability gate without silently downgrading Full Access', () => {
+ const capabilities = {
+ turnPermissionPolicy: {
+ supported: { supported: true },
+ unsupportedPermissionModes: ['bypassPermissions'],
+ },
+ } as Capabilities;
+
+ expect(supportsWechatTurnPermissionMode(capabilities, 'auto')).toBe(true);
+ expect(
+ supportsWechatTurnPermissionMode(capabilities, 'bypassPermissions'),
+ ).toBe(false);
+ expect(
+ supportsWechatTurnPermissionMode({} as Capabilities, 'ask'),
+ ).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/main/im/wechat/__tests__/silkDecoder.test.ts b/apps/desktop/src/main/im/wechat/__tests__/silkDecoder.test.ts
new file mode 100644
index 0000000000..085fcd87fc
--- /dev/null
+++ b/apps/desktop/src/main/im/wechat/__tests__/silkDecoder.test.ts
@@ -0,0 +1,17 @@
+import { Buffer } from 'node:buffer';
+
+import { describe, expect, it } from 'vitest';
+
+import { __testing } from '../silkDecoder';
+
+describe('SILK decoder input preparation', () => {
+ it('copies Buffer-backed input before it can be transferred', () => {
+ const source = Buffer.from([1, 2, 3, 4]);
+ const copy = __testing.copySilkBytes(source);
+
+ source[0] = 9;
+
+ expect(copy).toEqual(new Uint8Array([1, 2, 3, 4]));
+ expect(copy.buffer).not.toBe(source.buffer);
+ });
+});
diff --git a/apps/desktop/src/main/im/wechat/__tests__/taskStore.test.ts b/apps/desktop/src/main/im/wechat/__tests__/taskStore.test.ts
new file mode 100644
index 0000000000..23e86a0afd
--- /dev/null
+++ b/apps/desktop/src/main/im/wechat/__tests__/taskStore.test.ts
@@ -0,0 +1,149 @@
+import { randomBytes } from 'node:crypto';
+
+import { describe, expect, it, vi } from 'vitest';
+
+import type { DbClient } from '../../../localDb/client/DbClient.js';
+import { encryptWechatContextToken } from '../contextCrypto.js';
+import { WechatTaskStore } from '../taskStore.js';
+
+describe('WechatTaskStore', () => {
+ it('encrypts context before crossing the DbClient boundary and applies the 30 minute TTL', async () => {
+ const tx = vi.fn().mockResolvedValue({
+ committed: true,
+ insertedTaskIds: ['task-1'],
+ duplicateTaskIds: [],
+ rejectedTaskIds: [],
+ });
+ const store = new WechatTaskStore(fakeDb(tx), randomBytes(32));
+
+ await store.commitPollBatch({
+ bindingEpoch: 'epoch-1',
+ expectedCursor: '',
+ nextCursor: 'cursor-1',
+ now: 100,
+ messages: [
+ {
+ id: 'task-1',
+ platformMessageId: 'platform-1',
+ platformSeq: 1,
+ peerId: 'peer-1',
+ receivedAt: 100,
+ platformCreatedAt: 90,
+ sessionId: 'session-1',
+ conversationEpoch: 0,
+ payloadJson: '{"text":"hello"}',
+ contextToken: 'plain-context-secret',
+ },
+ ],
+ });
+
+ const [, args] = tx.mock.calls[0] as [string, Record<string, unknown>];
+ expect(tx.mock.calls[0]?.[0]).toBe('wechatCommitPollBatch');
+ expect(JSON.stringify(args)).not.toContain('plain-context-secret');
+ expect(args.messages).toEqual([
+ expect.objectContaining({
+ id: 'task-1',
+ expiresAt: 1_800_100,
+ context: {
+ nonce: expect.any(String),
+ ciphertext: expect.any(String),
+ tag: expect.any(String),
+ },
+ }),
+ ]);
+ });
+
+ it('decrypts a leased task only inside the main-process store', async () => {
+ const key = randomBytes(32);
+ const tx = vi.fn().mockResolvedValue({
+ id: 'task-1',
+ bindingEpoch: 'epoch-1',
+ peerId: 'peer-1',
+ sessionId: 'session-1',
+ conversationEpoch: 0,
+ payloadJson: '{}',
+ context: encryptWechatContextToken('plain-context-secret', key, 'epoch-1', 'task-1'),
+ attempts: 1,
+ receivedAt: 100,
+ expiresAt: 1_800_100,
+ });
+ const store = new WechatTaskStore(fakeDb(tx), key);
+
+ await expect(store.leaseNextTask({ bindingEpoch: 'epoch-1', now: 200 })).resolves.toMatchObject(
+ {
+ id: 'task-1',
+ contextToken: 'plain-context-secret',
+ },
+ );
+ });
+
+ it('returns decrypted context with each due durable outbox item', async () => {
+ const key = randomBytes(32);
+ const encrypted = encryptWechatContextToken('fresh-send-context', key, 'epoch-1', 'task-1');
+ const query = vi.fn().mockResolvedValue([
+ {
+ id: 'outbox-1',
+ bindingEpoch: 'epoch-1',
+ taskId: 'task-1',
+ clientId: 'client-1',
+ kind: 'final',
+ chunkIndex: 0,
+ text: 'done',
+ mediaJson: '[]',
+ attempts: 0,
+ contextNonce: encrypted.nonce,
+ contextCiphertext: encrypted.ciphertext,
+ contextTag: encrypted.tag,
+ },
+ ]);
+ const store = new WechatTaskStore(fakeDb(vi.fn(), query), key);
+
+ await expect(store.listDueOutbox('epoch-1', 200)).resolves.toEqual([
+ expect.objectContaining({
+ id: 'outbox-1',
+ contextToken: 'fresh-send-context',
+ }),
+ ]);
+ });
+
+ it('re-encrypts a newer peer token separately for every pending reply task', async () => {
+ const tx = vi.fn().mockResolvedValue({ refreshedTasks: 2, outboxWoken: 2 });
+ const query = vi.fn().mockResolvedValue([
+ { taskId: 'task-1' },
+ { taskId: 'task-2' },
+ ]);
+ const store = new WechatTaskStore(fakeDb(tx, query), randomBytes(32));
+
+ await store.refreshPendingOutboxContext({
+ bindingEpoch: 'epoch-1',
+ peerId: 'peer-1',
+ contextToken: 'new-peer-context',
+ now: 300,
+ });
+
+ expect(tx).toHaveBeenCalledWith(
+ 'wechatRefreshOutboxContexts',
+ expect.objectContaining({
+ bindingEpoch: 'epoch-1',
+ peerId: 'peer-1',
+ contexts: [
+ { taskId: 'task-1', context: expect.any(Object) },
+ { taskId: 'task-2', context: expect.any(Object) },
+ ],
+ }),
+ );
+ expect(JSON.stringify(tx.mock.calls[0]?.[1])).not.toContain('new-peer-context');
+ });
+});
+
+function fakeDb(tx: ReturnType<typeof vi.fn>, query: ReturnType<typeof vi.fn> = vi.fn()): DbClient {
+ return {
+ tx,
+ query,
+ queryOne: vi.fn(),
+ exec: vi.fn(),
+ drizzle: {} as DbClient['drizzle'],
+ vecAvailable: false,
+ dispose: vi.fn(),
+ } as unknown as DbClient;
+}
diff --git a/apps/desktop/src/main/im/wechat/__tests__/uiText.test.ts b/apps/desktop/src/main/im/wechat/__tests__/uiText.test.ts
new file mode 100644
index 0000000000..fdcc3d9caa
--- /dev/null
+++ b/apps/desktop/src/main/im/wechat/__tests__/uiText.test.ts
@@ -0,0 +1,25 @@
+import { describe, expect, it } from 'vitest';
+
+import { ui } from '../uiText';
+
+describe('WeChat UI text', () => {
+ it('uses WeChat-specific copy for channel-sensitive replies', () => {
+ const channelCopy = [
+ ui.slash.help,
+ ui.slash.detachedBySlash,
+ ui.slash.detachedByRevoke,
+ ui.agent.authMissing?.({
+ agentKind: 'codex',
+ model: 'gpt',
+ providerId: 'openai',
+ providerLabel: 'OpenAI',
+ missing: 'provider-key',
+ }),
+ ...ui.cards.control.takeoverLoadingPrompts.map((prompt) => prompt('会话')),
+ ...ui.cards.control.sessionAttachedOneshotPrompts,
+ ].join('\n');
+
+ expect(channelCopy).toContain('微信');
+ expect(channelCopy).not.toMatch(/Discord|飞书/);
+ });
+});
diff --git a/apps/desktop/src/main/im/wechat/adapter.ts b/apps/desktop/src/main/im/wechat/adapter.ts
new file mode 100644
index 0000000000..62779a2596
--- /dev/null
+++ b/apps/desktop/src/main/im/wechat/adapter.ts
@@ -0,0 +1,47 @@
+import type { RichChannelIM } from '@cindy/im';
+
+import type { ImChannelAdapter, ImOrchestratorConfig } from '../shared/types';
+import { resolveWechatWorkingDir } from './channelSettings';
+import { ui } from './uiText';
+import { sessionIdFor, type WechatIM } from './WechatIM';
+
+function ensureWorkingDir(botId: string): string {
+ return resolveWechatWorkingDir(botId);
+}
+
+export function buildWechatAdapter(
+ wechatIm: WechatIM,
+ config: ImOrchestratorConfig,
+): ImChannelAdapter {
+ return {
+ channel: 'wechat',
+ // The shared adapter type still includes rich-card methods. WechatIM makes
+ // those methods fail closed, while this output discriminator guarantees
+ // normal turn output only invokes commitFinal.
+ im: wechatIm as RichChannelIM,
+ output: {
+ kind: 'chunked-text',
+ im: wechatIm,
+ commitFinal: (output) => wechatIm.commitFinal(output),
+ },
+ config,
+ ui,
+ sessions: {
+ source: 'wechat',
+ sessionIdFor,
+ defaultTitle: (peerId) => `微信 · ${peerId.slice(-6)}`,
+ generatedTitlePrefix: '微信 · ',
+ workspaceKind: 'dialogue',
+ ensureWorkingDir,
+ extraInsertColumns: (botId, peerId) => ({
+ imBotContextId: botId,
+ imUserId: peerId,
+ }),
+ },
+ processingEmoji: '',
+ buildVendorOptions: (userId) => ({ source: 'wechat', wechatPeerId: userId }),
+ handleTextInteraction: (userId, request) =>
+ wechatIm.handleTextInteraction(userId, request),
+ onUserMessagePersisted: (args) => wechatIm.onUserMessagePersisted(args),
+ };
+}
diff --git a/apps/desktop/src/main/im/wechat/channelSettings.ts b/apps/desktop/src/main/im/wechat/channelSettings.ts
new file mode 100644
index 0000000000..37c2a7bdd9
--- /dev/null
+++ b/apps/desktop/src/main/im/wechat/channelSettings.ts
@@ -0,0 +1,160 @@
+/**
+ * Owner-scoped, non-secret settings for the personal WeChat channel.
+ *
+ * A working directory can only enter this store after the user selected it in
+ * a native directory picker. Missing/inaccessible saved directories fall back
+ * to the channel-managed directory instead of breaking inbound messages.
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import { createHash, randomUUID } from 'node:crypto';
+
+import { normalizeWorkingDirForStorage } from '../../../shared/workingDir';
+import { createLogger, maskPath } from '../../logger';
+import { ownerScopedImUserDataPath } from '../ownerScopedStorage';
+
+const log = createLogger('im/wechat/channel-settings');
+const SETTINGS_VERSION = 1;
+
+export interface WechatChannelSettings {
+ version: typeof SETTINGS_VERSION;
+ workingDir: string | null;
+}
+
+export interface WechatChannelSettingsState extends WechatChannelSettings {
+ workingDirAvailable: boolean;
+}
+
+const DEFAULTS: WechatChannelSettings = {
+ version: SETTINGS_VERSION,
+ workingDir: null,
+};
+
+function settingsFilePath(rootPath?: string): string {
+ return rootPath
+ ? path.join(rootPath, 'wechat-channel.json')
+ : ownerScopedImUserDataPath('wechat-channel.json');
+}
+
+export function readWechatChannelSettings(rootPath?: string): WechatChannelSettingsState {
+ const file = settingsFilePath(rootPath);
+ try {
+ if (!fs.existsSync(file)) return { ...DEFAULTS, workingDirAvailable: true };
+ const normalized = normalizeSettings(JSON.parse(fs.readFileSync(file, 'utf8')));
+ return {
+ ...normalized,
+ workingDirAvailable:
+ normalized.workingDir === null || isAccessibleDirectory(normalized.workingDir),
+ };
+ } catch (error) {
+ log.warn('failed to read WeChat channel settings; using defaults', {
+ path: maskPath(file),
+ errorCode: nodeErrorCode(error),
+ });
+ return { ...DEFAULTS, workingDirAvailable: true };
+ }
+}
+
+export function writeWechatWorkingDir(
+ selectedPath: string,
+ rootPath?: string,
+): WechatChannelSettingsState {
+ const workingDir = normalizeSelectedDirectory(selectedPath);
+ writeSettings({ ...DEFAULTS, workingDir }, rootPath);
+ return readWechatChannelSettings(rootPath);
+}
+
+export function resetWechatWorkingDir(rootPath?: string): WechatChannelSettingsState {
+ const file = settingsFilePath(rootPath);
+ try {
+ fs.rmSync(file, { force: true });
+ } catch (error) {
+ log.warn('failed to reset WeChat channel settings', {
+ path: maskPath(file),
+ errorCode: nodeErrorCode(error),
+ });
+ throw error;
+ }
+ return { ...DEFAULTS, workingDirAvailable: true };
+}
+
+export function resolveWechatWorkingDir(botId: string, rootPath?: string): string {
+ const configured = readWechatChannelSettings(rootPath);
+ if (configured.workingDir && configured.workingDirAvailable) return configured.workingDir;
+
+ const managedDirName = managedWorkingDirName(botId);
+ const dir = rootPath
+ ? path.join(rootPath, 'im-working-dir', managedDirName)
+ : ownerScopedImUserDataPath('im-working-dir', managedDirName);
+ fs.mkdirSync(dir, { recursive: true });
+ return dir;
+}
+
+function managedWorkingDirName(botId: string): string {
+ if (/^[A-Za-z0-9_-]{1,128}$/.test(botId)) return `wechat-${botId}`;
+ const digest = createHash('sha256').update(botId).digest('hex').slice(0, 24);
+ return `wechat-external-${digest}`;
+}
+
+function normalizeSelectedDirectory(selectedPath: string): string {
+ if (typeof selectedPath !== 'string' || !path.isAbsolute(selectedPath)) {
+ throw new Error('WECHAT_WORKING_DIR_INVALID');
+ }
+ const realPath = fs.realpathSync.native(selectedPath);
+ if (!fs.statSync(realPath).isDirectory()) throw new Error('WECHAT_WORKING_DIR_NOT_DIRECTORY');
+ const normalized = normalizeWorkingDirForStorage(realPath);
+ if (!normalized) throw new Error('WECHAT_WORKING_DIR_INVALID');
+ return normalized;
+}
+
+function normalizeSettings(raw: unknown): WechatChannelSettings {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return { ...DEFAULTS };
+ const input = raw as Record<string, unknown>;
+ const workingDir =
+ typeof input.workingDir === 'string' && path.isAbsolute(input.workingDir)
+ ? normalizeWorkingDirForStorage(input.workingDir)
+ : null;
+ return {
+ version: SETTINGS_VERSION,
+ workingDir,
+ };
+}
+
+function isAccessibleDirectory(candidate: string): boolean {
+ try {
+ return fs.statSync(candidate).isDirectory();
+ } catch {
+ return false;
+ }
+}
+
+function nodeErrorCode(error: unknown): string {
+ return typeof error === 'object' &&
+ error !== null &&
+ 'code' in error &&
+ typeof (error as { code?: unknown }).code === 'string'
+ ? (error as { code: string }).code
+ : 'UNKNOWN';
+}
+
+function writeSettings(settings: WechatChannelSettings, rootPath?: string): void {
+ const file = settingsFilePath(rootPath);
+ const tmp = `${file}.${randomUUID()}.tmp`;
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ try {
+ fs.writeFileSync(tmp, `${JSON.stringify(settings, null, 2)}\n`, {
+ encoding: 'utf8',
+ flag: 'wx',
+ });
+ fs.renameSync(tmp, file);
+ } finally {
+ fs.rmSync(tmp, { force: true });
+ }
+}
+
+export const __testing = {
+ managedWorkingDirName,
+ normalizeSettings,
+ normalizeSelectedDirectory,
+};
diff --git a/apps/desktop/src/main/im/wechat/compatibilityPolicy.ts b/apps/desktop/src/main/im/wechat/compatibilityPolicy.ts
new file mode 100644
index 0000000000..9ace853dbf
--- /dev/null
+++ b/apps/desktop/src/main/im/wechat/compatibilityPolicy.ts
@@ -0,0 +1,690 @@
+import {
+ createPublicKey,
+ randomUUID,
+ verify as verifySignature,
+ type KeyObject,
+} from 'node:crypto';
+import fs from 'node:fs';
+import path from 'node:path';
+
+import { createLogger, maskPath } from '../../logger';
+
+const log = createLogger('im/wechat/compatibility-policy');
+
+export const WECHAT_COMPATIBILITY_MANIFEST_MAX_BYTES = 32 * 1024;
+const MAX_CLOCK_SKEW_MS = 5 * 60 * 1_000;
+const DEFAULT_REFRESH_INTERVAL_MS = 6 * 60 * 60 * 1_000;
+const DEFAULT_FETCH_TIMEOUT_MS = 10_000;
+const MAX_RULES = 64;
+const MAX_TIMER_DELAY_MS = 2_147_000_000;
+
+export interface WechatCompatibilityRule {
+ minVersion: string;
+ maxVersion: string;
+ action: 'disable';
+ reason: string;
+ helpUrl?: string;
+}
+
+export interface WechatCompatibilityManifestPayload {
+ schemaVersion: 1;
+ sequence: number;
+ generatedAt: number;
+ expiresAt: number;
+ rules: WechatCompatibilityRule[];
+}
+
+export interface WechatCompatibilityManifest extends WechatCompatibilityManifestPayload {
+ signature: string;
+}
+
+export interface WechatCompatibilityDecision {
+ disabled: boolean;
+ sequence?: number;
+ reasonCode?: string;
+ helpUrl?: string;
+}
+
+interface ResponseLike {
+ ok: boolean;
+ status: number;
+ headers: {
+ get(name: string): string | null;
+ };
+ body: ReadableStream<Uint8Array> | null;
+ arrayBuffer(): Promise<ArrayBuffer>;
+}
+
+type FetchLike = (
+ input: string,
+ init: {
+ method: 'GET';
+ cache: 'no-store';
+ redirect: 'error';
+ signal: AbortSignal;
+ },
+) => Promise<ResponseLike>;
+
+export interface WechatCompatibilityPolicyOptions {
+ manifestUrl: string | null;
+ publicKeySpkiBase64: string | null;
+ trustedHelpUrlPrefixes: readonly string[];
+ cachePath(): string;
+ appVersion(): string;
+ fetch: FetchLike;
+ now?: () => number;
+ refreshIntervalMs?: number;
+ fetchTimeoutMs?: number;
+}
+
+/**
+ * Production values intentionally live in source instead of environment or
+ * remote endpoint configuration. A release may populate these only after the
+ * independent signing key and immutable HTTPS location have been provisioned.
+ */
+export const WECHAT_COMPATIBILITY_POLICY_PRODUCTION_CONFIG = Object.freeze({
+ manifestUrl: null,
+ publicKeySpkiBase64: null,
+ trustedHelpUrlPrefixes: [] as readonly string[],
+});
+
+export class WechatCompatibilityPolicyService {
+ readonly #options: Required<
+ Pick<WechatCompatibilityPolicyOptions, 'now' | 'refreshIntervalMs' | 'fetchTimeoutMs'>
+ > &
+ Omit<WechatCompatibilityPolicyOptions, 'now' | 'refreshIntervalMs' | 'fetchTimeoutMs'>;
+ readonly #listeners = new Set<(decision: WechatCompatibilityDecision) => void>();
+ #decision: WechatCompatibilityDecision = { disabled: false };
+ #lastSequence = 0;
+ #cacheLoaded = false;
+ #started = false;
+ #refreshTimer: ReturnType<typeof setInterval> | null = null;
+ #expiryTimer: ReturnType<typeof setTimeout> | null = null;
+ #decisionExpiresAt: number | null = null;
+ #refreshInFlight: Promise<void> | null = null;
+
+ constructor(options: WechatCompatibilityPolicyOptions) {
+ this.#options = {
+ ...options,
+ now: options.now ?? Date.now,
+ refreshIntervalMs: options.refreshIntervalMs ?? DEFAULT_REFRESH_INTERVAL_MS,
+ fetchTimeoutMs: options.fetchTimeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS,
+ };
+ }
+
+ start(): void {
+ if (this.#started) return;
+ this.#started = true;
+ this.#loadCacheOnce();
+ this.#scheduleDecisionExpiry();
+ void this.refresh();
+ if (
+ this.#options.manifestUrl &&
+ this.#options.publicKeySpkiBase64 &&
+ this.#options.refreshIntervalMs > 0
+ ) {
+ this.#refreshTimer = setInterval(() => void this.refresh(), this.#options.refreshIntervalMs);
+ this.#refreshTimer.unref?.();
+ }
+ }
+
+ stop(): void {
+ this.#started = false;
+ if (this.#refreshTimer) clearInterval(this.#refreshTimer);
+ this.#refreshTimer = null;
+ if (this.#expiryTimer) clearTimeout(this.#expiryTimer);
+ this.#expiryTimer = null;
+ }
+
+ getDecision(): WechatCompatibilityDecision {
+ return { ...this.#decision };
+ }
+
+ isDisabled(): boolean {
+ return this.#decision.disabled;
+ }
+
+ subscribe(listener: (decision: WechatCompatibilityDecision) => void): () => void {
+ this.#listeners.add(listener);
+ listener(this.getDecision());
+ return () => this.#listeners.delete(listener);
+ }
+
+ async refresh(): Promise<void> {
+ if (this.#refreshInFlight) return this.#refreshInFlight;
+ this.#refreshInFlight = this.#refreshInternal().finally(() => {
+ this.#refreshInFlight = null;
+ });
+ return this.#refreshInFlight;
+ }
+
+ #loadCacheOnce(): void {
+ if (this.#cacheLoaded) return;
+ this.#cacheLoaded = true;
+ const publicKey = this.#publicKey();
+ if (!publicKey) return;
+ const cachePath = this.#options.cachePath();
+ try {
+ const bytes = fs.readFileSync(cachePath);
+ if (bytes.byteLength > WECHAT_COMPATIBILITY_MANIFEST_MAX_BYTES) {
+ throw new Error('MANIFEST_TOO_LARGE');
+ }
+ this.#acceptVerifiedBytes(bytes, publicKey, false);
+ } catch (error) {
+ if (nodeErrorCode(error) !== 'ENOENT') {
+ log.warn('ignored invalid cached personal WeChat compatibility policy', {
+ path: maskPath(cachePath),
+ errorCode: safePolicyErrorCode(error),
+ });
+ }
+ }
+ }
+
+ async #refreshInternal(): Promise<void> {
+ this.#loadCacheOnce();
+ const publicKey = this.#publicKey();
+ const manifestUrl = normalizeBuiltInManifestUrl(this.#options.manifestUrl);
+ if (!publicKey || !manifestUrl) return;
+
+ const abort = new AbortController();
+ const timeout = setTimeout(() => abort.abort(), this.#options.fetchTimeoutMs);
+ try {
+ const response = await this.#options.fetch(manifestUrl, {
+ method: 'GET',
+ cache: 'no-store',
+ redirect: 'error',
+ signal: abort.signal,
+ });
+ if (!response.ok) throw new Error('HTTP_STATUS_REJECTED');
+ const contentType = response.headers
+ .get('content-type')
+ ?.split(';', 1)[0]
+ ?.trim()
+ .toLowerCase();
+ if (contentType !== 'application/json') throw new Error('CONTENT_TYPE_REJECTED');
+ const contentLength = parseContentLength(response.headers.get('content-length'));
+ if (contentLength !== null && contentLength > WECHAT_COMPATIBILITY_MANIFEST_MAX_BYTES) {
+ throw new Error('MANIFEST_TOO_LARGE');
+ }
+ const bytes = await readBoundedResponseBody(
+ response,
+ WECHAT_COMPATIBILITY_MANIFEST_MAX_BYTES,
+ );
+ this.#acceptVerifiedBytes(bytes, publicKey, true);
+ } catch (error) {
+ log.warn('personal WeChat compatibility policy refresh failed open', {
+ errorCode: safePolicyErrorCode(error),
+ });
+ } finally {
+ clearTimeout(timeout);
+ }
+ }
+
+ #acceptVerifiedBytes(bytes: Uint8Array, publicKey: KeyObject, persist: boolean): void {
+ const manifest = parseAndVerifyWechatCompatibilityManifest(
+ bytes,
+ publicKey,
+ this.#options.trustedHelpUrlPrefixes,
+ this.#options.now(),
+ );
+ if (manifest.sequence < this.#lastSequence) throw new Error('SEQUENCE_ROLLBACK');
+ this.#lastSequence = manifest.sequence;
+ const decision = evaluateWechatCompatibilityManifest(
+ manifest,
+ this.#options.appVersion(),
+ this.#options.now(),
+ );
+ this.#setDecision(decision);
+ this.#decisionExpiresAt = decision.disabled ? manifest.expiresAt : null;
+ this.#scheduleDecisionExpiry();
+ if (persist) {
+ try {
+ writeCacheAtomic(this.#options.cachePath(), bytes);
+ } catch (error) {
+ log.warn('failed to persist personal WeChat compatibility policy cache', {
+ errorCode: safePolicyErrorCode(error),
+ });
+ }
+ }
+ }
+
+ #publicKey(): KeyObject | null {
+ const encoded = this.#options.publicKeySpkiBase64;
+ if (!encoded) return null;
+ try {
+ const key = createPublicKey({
+ key: decodeStrictBase64(encoded, 'PUBLIC_KEY_INVALID'),
+ format: 'der',
+ type: 'spki',
+ });
+ if (key.asymmetricKeyType !== 'ed25519') throw new Error('PUBLIC_KEY_INVALID');
+ return key;
+ } catch {
+ log.error('personal WeChat compatibility policy public key is invalid');
+ return null;
+ }
+ }
+
+ #setDecision(next: WechatCompatibilityDecision): void {
+ if (
+ next.disabled === this.#decision.disabled &&
+ next.sequence === this.#decision.sequence &&
+ next.reasonCode === this.#decision.reasonCode &&
+ next.helpUrl === this.#decision.helpUrl
+ ) {
+ return;
+ }
+ this.#decision = next;
+ for (const listener of this.#listeners) listener(this.getDecision());
+ }
+
+ #scheduleDecisionExpiry(): void {
+ if (this.#expiryTimer) clearTimeout(this.#expiryTimer);
+ this.#expiryTimer = null;
+ const expiresAt = this.#decisionExpiresAt;
+ if (!this.#decision.disabled || expiresAt === null) return;
+ const remaining = expiresAt - this.#options.now();
+ if (remaining <= 0) {
+ this.#decisionExpiresAt = null;
+ this.#setDecision({ disabled: false, sequence: this.#decision.sequence });
+ return;
+ }
+ this.#expiryTimer = setTimeout(
+ () => {
+ this.#expiryTimer = null;
+ this.#scheduleDecisionExpiry();
+ },
+ Math.min(remaining, MAX_TIMER_DELAY_MS),
+ );
+ this.#expiryTimer.unref?.();
+ }
+}
+
+export function parseAndVerifyWechatCompatibilityManifest(
+ bytes: Uint8Array,
+ publicKey: KeyObject,
+ trustedHelpUrlPrefixes: readonly string[],
+ now: number,
+): WechatCompatibilityManifest {
+ if (bytes.byteLength > WECHAT_COMPATIBILITY_MANIFEST_MAX_BYTES) {
+ throw new Error('MANIFEST_TOO_LARGE');
+ }
+ if (publicKey.asymmetricKeyType !== 'ed25519') throw new Error('PUBLIC_KEY_INVALID');
+ let raw: unknown;
+ try {
+ raw = JSON.parse(Buffer.from(bytes).toString('utf8'));
+ } catch {
+ throw new Error('MANIFEST_JSON_INVALID');
+ }
+ const manifest = validateManifest(raw, trustedHelpUrlPrefixes);
+ if (manifest.generatedAt > now + MAX_CLOCK_SKEW_MS) throw new Error('GENERATED_AT_IN_FUTURE');
+ const signature = decodeStrictBase64(manifest.signature, 'SIGNATURE_INVALID');
+ const payload: WechatCompatibilityManifestPayload = {
+ schemaVersion: manifest.schemaVersion,
+ sequence: manifest.sequence,
+ generatedAt: manifest.generatedAt,
+ expiresAt: manifest.expiresAt,
+ rules: manifest.rules,
+ };
+ const verified = verifySignature(
+ null,
+ Buffer.from(canonicalizeWechatCompatibilityManifestPayload(payload), 'utf8'),
+ publicKey,
+ signature,
+ );
+ if (!verified) throw new Error('SIGNATURE_INVALID');
+ return manifest;
+}
+
+export function canonicalizeWechatCompatibilityManifestPayload(
+ payload: WechatCompatibilityManifestPayload,
+): string {
+ return canonicalJson(payload);
+}
+
+export function evaluateWechatCompatibilityManifest(
+ manifest: WechatCompatibilityManifest,
+ appVersion: string,
+ now: number,
+): WechatCompatibilityDecision {
+ if (now >= manifest.expiresAt) return { disabled: false, sequence: manifest.sequence };
+ const version = parseSemver(appVersion);
+ if (!version) return { disabled: false, sequence: manifest.sequence };
+ const matched = manifest.rules.find(
+ (rule) =>
+ compareSemver(version, parseSemverRequired(rule.minVersion)) >= 0 &&
+ compareSemver(version, parseSemverRequired(rule.maxVersion)) <= 0,
+ );
+ if (!matched) return { disabled: false, sequence: manifest.sequence };
+ return {
+ disabled: true,
+ sequence: manifest.sequence,
+ reasonCode: matched.reason,
+ ...(matched.helpUrl ? { helpUrl: matched.helpUrl } : {}),
+ };
+}
+
+function validateManifest(
+ raw: unknown,
+ trustedHelpUrlPrefixes: readonly string[],
+): WechatCompatibilityManifest {
+ const input = requireRecord(raw, 'MANIFEST_SHAPE_INVALID');
+ requireExactKeys(input, [
+ 'schemaVersion',
+ 'sequence',
+ 'generatedAt',
+ 'expiresAt',
+ 'rules',
+ 'signature',
+ ]);
+ if (input.schemaVersion !== 1) throw new Error('SCHEMA_VERSION_UNSUPPORTED');
+ const sequence = requireSafeInteger(input.sequence, 1, 'SEQUENCE_INVALID');
+ const generatedAt = requireSafeInteger(input.generatedAt, 0, 'GENERATED_AT_INVALID');
+ const expiresAt = requireSafeInteger(input.expiresAt, 1, 'EXPIRES_AT_INVALID');
+ if (expiresAt <= generatedAt) throw new Error('EXPIRY_RANGE_INVALID');
+ if (!Array.isArray(input.rules) || input.rules.length > MAX_RULES) {
+ throw new Error('RULES_INVALID');
+ }
+ const rules = input.rules.map((rule) => validateRule(rule, trustedHelpUrlPrefixes));
+ if (typeof input.signature !== 'string') throw new Error('SIGNATURE_INVALID');
+ return {
+ schemaVersion: 1,
+ sequence,
+ generatedAt,
+ expiresAt,
+ rules,
+ signature: input.signature,
+ };
+}
+
+function validateRule(
+ raw: unknown,
+ trustedHelpUrlPrefixes: readonly string[],
+): WechatCompatibilityRule {
+ const input = requireRecord(raw, 'RULE_INVALID');
+ requireExactKeys(input, ['minVersion', 'maxVersion', 'action', 'reason', 'helpUrl'], true);
+ if (typeof input.minVersion !== 'string' || typeof input.maxVersion !== 'string') {
+ throw new Error('VERSION_RANGE_INVALID');
+ }
+ const minVersion = parseSemver(input.minVersion);
+ const maxVersion = parseSemver(input.maxVersion);
+ if (!minVersion || !maxVersion || compareSemver(minVersion, maxVersion) > 0) {
+ throw new Error('VERSION_RANGE_INVALID');
+ }
+ if (input.action !== 'disable') throw new Error('ACTION_INVALID');
+ if (
+ typeof input.reason !== 'string' ||
+ !/^[a-z0-9](?:[a-z0-9._-]{0,62}[a-z0-9])?$/.test(input.reason)
+ ) {
+ throw new Error('REASON_INVALID');
+ }
+ let helpUrl: string | undefined;
+ if (input.helpUrl !== undefined) {
+ if (
+ typeof input.helpUrl !== 'string' ||
+ !isTrustedHelpUrl(input.helpUrl, trustedHelpUrlPrefixes)
+ ) {
+ throw new Error('HELP_URL_INVALID');
+ }
+ helpUrl = input.helpUrl;
+ }
+ return {
+ minVersion: input.minVersion,
+ maxVersion: input.maxVersion,
+ action: 'disable',
+ reason: input.reason,
+ ...(helpUrl ? { helpUrl } : {}),
+ };
+}
+
+function normalizeBuiltInManifestUrl(value: string | null): string | null {
+ if (!value) return null;
+ try {
+ const url = new URL(value);
+ if (
+ url.protocol !== 'https:' ||
+ url.username ||
+ url.password ||
+ url.hash ||
+ url.search ||
+ !url.pathname.endsWith('.json')
+ ) {
+ return null;
+ }
+ return url.toString();
+ } catch {
+ return null;
+ }
+}
+
+function isTrustedHelpUrl(value: string, prefixes: readonly string[]): boolean {
+ try {
+ const candidate = new URL(value);
+ if (
+ candidate.protocol !== 'https:' ||
+ candidate.username ||
+ candidate.password ||
+ candidate.hash ||
+ candidate.search
+ ) {
+ return false;
+ }
+ if (/%(?:2f|5c)/i.test(candidate.pathname)) return false;
+ return prefixes.some((prefix) => {
+ const trusted = new URL(prefix);
+ if (
+ trusted.protocol !== 'https:' ||
+ trusted.username ||
+ trusted.password ||
+ trusted.hash ||
+ trusted.search ||
+ /%(?:2f|5c)/i.test(trusted.pathname)
+ ) {
+ return false;
+ }
+ const trustedPath = trusted.pathname.endsWith('/')
+ ? trusted.pathname
+ : `${trusted.pathname}/`;
+ return (
+ candidate.origin === trusted.origin &&
+ (candidate.pathname === trusted.pathname || candidate.pathname.startsWith(trustedPath))
+ );
+ });
+ } catch {
+ return false;
+ }
+}
+
+async function readBoundedResponseBody(
+ response: ResponseLike,
+ maxBytes: number,
+): Promise<Uint8Array> {
+ if (!response.body) {
+ const bytes = new Uint8Array(await response.arrayBuffer());
+ if (bytes.byteLength > maxBytes) throw new Error('MANIFEST_TOO_LARGE');
+ return bytes;
+ }
+ const reader = response.body.getReader();
+ const chunks: Uint8Array[] = [];
+ let total = 0;
+ try {
+ while (true) {
+ const result = await reader.read();
+ if (result.done) break;
+ total += result.value.byteLength;
+ if (total > maxBytes) {
+ await reader.cancel();
+ throw new Error('MANIFEST_TOO_LARGE');
+ }
+ chunks.push(result.value);
+ }
+ } finally {
+ reader.releaseLock();
+ }
+ const bytes = new Uint8Array(total);
+ let offset = 0;
+ for (const chunk of chunks) {
+ bytes.set(chunk, offset);
+ offset += chunk.byteLength;
+ }
+ return bytes;
+}
+
+function writeCacheAtomic(file: string, bytes: Uint8Array): void {
+ const tmp = `${file}.${randomUUID()}.tmp`;
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ try {
+ fs.writeFileSync(tmp, bytes, { flag: 'wx' });
+ fs.renameSync(tmp, file);
+ } finally {
+ fs.rmSync(tmp, { force: true });
+ }
+}
+
+function canonicalJson(value: unknown): string {
+ if (value === null || typeof value === 'boolean' || typeof value === 'string') {
+ return JSON.stringify(value);
+ }
+ if (typeof value === 'number') {
+ if (!Number.isSafeInteger(value)) throw new Error('CANONICAL_NUMBER_INVALID');
+ return String(value);
+ }
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`;
+ if (typeof value === 'object') {
+ const input = value as Record<string, unknown>;
+ return `{${Object.keys(input)
+ .filter((key) => input[key] !== undefined)
+ .sort()
+ .map((key) => `${JSON.stringify(key)}:${canonicalJson(input[key])}`)
+ .join(',')}}`;
+ }
+ throw new Error('CANONICAL_VALUE_INVALID');
+}
+
+interface ParsedSemver {
+ core: readonly [number, number, number];
+ prerelease: readonly (number | string)[];
+}
+
+function parseSemver(value: string): ParsedSemver | null {
+ const match =
+ /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/.exec(
+ value,
+ );
+ if (!match) return null;
+ const core = [Number(match[1]), Number(match[2]), Number(match[3])] as const;
+ if (core.some((part) => !Number.isSafeInteger(part))) return null;
+ const prerelease = match[4]
+ ? match[4].split('.').map((part) => {
+ if (/^\d+$/.test(part) && !/^(0|[1-9]\d*)$/.test(part)) {
+ return Number.NaN;
+ }
+ if (/^(0|[1-9]\d*)$/.test(part)) {
+ const numeric = Number(part);
+ return Number.isSafeInteger(numeric) ? numeric : part;
+ }
+ return part;
+ })
+ : [];
+ if (prerelease.some((part) => typeof part === 'number' && !Number.isSafeInteger(part))) {
+ return null;
+ }
+ return { core, prerelease };
+}
+
+function parseSemverRequired(value: string): ParsedSemver {
+ const parsed = parseSemver(value);
+ if (!parsed) throw new Error('VERSION_RANGE_INVALID');
+ return parsed;
+}
+
+function compareSemver(left: ParsedSemver, right: ParsedSemver): number {
+ for (let index = 0; index < 3; index += 1) {
+ if (left.core[index] !== right.core[index]) {
+ return left.core[index] < right.core[index] ? -1 : 1;
+ }
+ }
+ if (left.prerelease.length === 0 || right.prerelease.length === 0) {
+ if (left.prerelease.length === right.prerelease.length) return 0;
+ return left.prerelease.length === 0 ? 1 : -1;
+ }
+ const length = Math.max(left.prerelease.length, right.prerelease.length);
+ for (let index = 0; index < length; index += 1) {
+ const a = left.prerelease[index];
+ const b = right.prerelease[index];
+ if (a === undefined || b === undefined) return a === undefined ? -1 : 1;
+ if (a === b) continue;
+ if (typeof a === 'number' && typeof b === 'string') return -1;
+ if (typeof a === 'string' && typeof b === 'number') return 1;
+ return a < b ? -1 : 1;
+ }
+ return 0;
+}
+
+function requireRecord(value: unknown, code: string): Record<string, unknown> {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error(code);
+ return value as Record<string, unknown>;
+}
+
+function requireExactKeys(
+ input: Record<string, unknown>,
+ allowed: readonly string[],
+ optionalHelpUrl = false,
+): void {
+ const allowedSet = new Set(allowed);
+ if (Object.keys(input).some((key) => !allowedSet.has(key))) throw new Error('UNKNOWN_FIELD');
+ for (const key of allowed) {
+ if (optionalHelpUrl && key === 'helpUrl') continue;
+ if (!(key in input)) throw new Error('MISSING_FIELD');
+ }
+}
+
+function requireSafeInteger(value: unknown, minimum: number, code: string): number {
+ if (!Number.isSafeInteger(value) || (value as number) < minimum) throw new Error(code);
+ return value as number;
+}
+
+function decodeStrictBase64(value: string, code: string): Buffer {
+ if (!/^[A-Za-z0-9+/]+={0,2}$/.test(value) || value.length % 4 !== 0) {
+ throw new Error(code);
+ }
+ const decoded = Buffer.from(value, 'base64');
+ if (decoded.toString('base64') !== value) throw new Error(code);
+ return decoded;
+}
+
+function parseContentLength(value: string | null): number | null {
+ if (value === null) return null;
+ if (!/^(0|[1-9]\d*)$/.test(value)) throw new Error('CONTENT_LENGTH_INVALID');
+ const parsed = Number(value);
+ if (!Number.isSafeInteger(parsed)) throw new Error('CONTENT_LENGTH_INVALID');
+ return parsed;
+}
+
+function nodeErrorCode(error: unknown): string | null {
+ const code =
+ typeof error === 'object' &&
+ error !== null &&
+ 'code' in error &&
+ typeof (error as { code?: unknown }).code === 'string'
+ ? (error as { code: string }).code
+ : null;
+ return code && /^[A-Z][A-Z0-9_]{1,63}$/.test(code) ? code : null;
+}
+
+function safePolicyErrorCode(error: unknown): string {
+ const code = nodeErrorCode(error);
+ if (code) return code;
+ if (error instanceof Error && /^[A-Z][A-Z0-9_]{1,63}$/.test(error.message)) {
+ return error.message;
+ }
+ return 'POLICY_REFRESH_FAILED';
+}
+
+export const __testing = {
+ compareSemver,
+ isTrustedHelpUrl,
+ normalizeBuiltInManifestUrl,
+ parseSemver,
+ readBoundedResponseBody,
+};
diff --git a/apps/desktop/src/main/im/wechat/contextCrypto.ts b/apps/desktop/src/main/im/wechat/contextCrypto.ts
new file mode 100644
index 0000000000..45eb884cb7
--- /dev/null
+++ b/apps/desktop/src/main/im/wechat/contextCrypto.ts
@@ -0,0 +1,91 @@
+import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto';
+
+import type { WechatEncryptedContext } from '../../localDb/client/tx/types.js';
+
+const KEY_BYTES = 32;
+const NONCE_BYTES = 12;
+const TAG_BYTES = 16;
+
+export class WechatContextCryptoError extends Error {
+ readonly code = 'WECHAT_CONTEXT_CRYPTO_FAILED';
+
+ constructor(message: string) {
+ super(message);
+ this.name = 'WechatContextCryptoError';
+ }
+}
+
+export function encryptWechatContextToken(
+ token: string,
+ dataKey: Uint8Array,
+ bindingEpoch: string,
+ taskId: string,
+): WechatEncryptedContext {
+ if (!token) throw new WechatContextCryptoError('Context token is empty.');
+ const key = normalizeKey(dataKey);
+ const nonce = randomBytes(NONCE_BYTES);
+ const cipher = createCipheriv('aes-256-gcm', key, nonce, { authTagLength: TAG_BYTES });
+ cipher.setAAD(contextAad(bindingEpoch, taskId));
+ const ciphertext = Buffer.concat([cipher.update(token, 'utf8'), cipher.final()]);
+ return {
+ nonce: nonce.toString('base64'),
+ ciphertext: ciphertext.toString('base64'),
+ tag: cipher.getAuthTag().toString('base64'),
+ };
+}
+
+export function decryptWechatContextToken(
+ encrypted: WechatEncryptedContext,
+ dataKey: Uint8Array,
+ bindingEpoch: string,
+ taskId: string,
+): string {
+ try {
+ const key = normalizeKey(dataKey);
+ const nonce = decodeExactBase64(encrypted.nonce, NONCE_BYTES, 'nonce');
+ const tag = decodeExactBase64(encrypted.tag, TAG_BYTES, 'tag');
+ const ciphertext = decodeBase64(encrypted.ciphertext, 'ciphertext');
+ const decipher = createDecipheriv('aes-256-gcm', key, nonce, {
+ authTagLength: TAG_BYTES,
+ });
+ decipher.setAAD(contextAad(bindingEpoch, taskId));
+ decipher.setAuthTag(tag);
+ return Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString('utf8');
+ } catch (error) {
+ if (error instanceof WechatContextCryptoError) throw error;
+ throw new WechatContextCryptoError('Stored WeChat context could not be decrypted.');
+ }
+}
+
+function normalizeKey(dataKey: Uint8Array): Buffer {
+ if (dataKey.byteLength !== KEY_BYTES) {
+ throw new WechatContextCryptoError('WeChat data key must be 32 bytes.');
+ }
+ return Buffer.from(dataKey);
+}
+
+function contextAad(bindingEpoch: string, taskId: string): Buffer {
+ if (!bindingEpoch || !taskId) {
+ throw new WechatContextCryptoError('Binding epoch and task id are required.');
+ }
+ return Buffer.from(`cindy-wechat-context-v1\0${bindingEpoch}\0${taskId}`, 'utf8');
+}
+
+function decodeBase64(value: string, label: string): Buffer {
+ if (!value || !/^[A-Za-z0-9+/]+={0,2}$/.test(value)) {
+ throw new WechatContextCryptoError(`Stored ${label} is invalid.`);
+ }
+ const decoded = Buffer.from(value, 'base64');
+ if (decoded.toString('base64') !== value) {
+ throw new WechatContextCryptoError(`Stored ${label} is not canonical base64.`);
+ }
+ return decoded;
+}
+
+function decodeExactBase64(value: string, bytes: number, label: string): Buffer {
+ const decoded = decodeBase64(value, label);
+ if (decoded.byteLength !== bytes) {
+ throw new WechatContextCryptoError(`Stored ${label} has an invalid length.`);
+ }
+ return decoded;
+}
diff --git a/apps/desktop/src/main/im/wechat/index.ts b/apps/desktop/src/main/im/wechat/index.ts
new file mode 100644
index 0000000000..df69b9469f
--- /dev/null
+++ b/apps/desktop/src/main/im/wechat/index.ts
@@ -0,0 +1,19 @@
+import type { ImOrchestratorConfig } from '../shared/types';
+import { createImOrchestrator } from '../shared/orchestrator';
+import { resetSessionToDefaults } from '../shared/sessionRepo';
+import { buildWechatAdapter } from './adapter';
+import type { WechatIM } from './WechatIM';
+
+export function wireWechatOrchestrator(wechatIm: WechatIM, config: ImOrchestratorConfig): void {
+ const orchestrator = createImOrchestrator(buildWechatAdapter(wechatIm, config));
+ wechatIm.attachTurnRuntime({
+ runner: orchestrator.turnRunner,
+ repo: orchestrator.repo,
+ config,
+ resetSessionToDefaults: (sessionId, nextConfig, prepared) =>
+ resetSessionToDefaults(sessionId, nextConfig, prepared, 'wechat'),
+ });
+}
+
+export { WechatIM, WECHAT_AUTH_BASE_URL } from './WechatIM';
+export type { WechatBotPhase, WechatBotState, WechatIMDeps } from './WechatIM';
diff --git a/apps/desktop/src/main/im/wechat/mediaStaging.ts b/apps/desktop/src/main/im/wechat/mediaStaging.ts
new file mode 100644
index 0000000000..b47512b848
--- /dev/null
+++ b/apps/desktop/src/main/im/wechat/mediaStaging.ts
@@ -0,0 +1,332 @@
+import { randomUUID } from 'node:crypto';
+import fs from 'node:fs/promises';
+import path from 'node:path';
+
+import type { IMAttachment } from '@cindy/im';
+import type { WechatMediaRef, WechatTransport } from '@cindy/wechat-ilink';
+
+import * as blobStore from '../../cindy-media/blobStore';
+import { ingestMedia } from '../../cindy-media/ingest';
+import type {
+ WechatPollFileAttachmentInput,
+ WechatPollMediaBlobInput,
+ WechatPollMediaRefInput,
+} from '../../localDb/client/tx/types';
+import { ownerScopedImUserDataPath } from '../ownerScopedStorage';
+import { decodeWechatSilkToWav } from './silkDecoder';
+
+const MAX_ATTACHMENTS_PER_MESSAGE = 4;
+
+export interface WechatTaskAttachment extends IMAttachment {
+ storage: 'cindy-media' | 'file';
+}
+
+export interface StagedWechatTaskMedia {
+ attachments: WechatTaskAttachment[];
+ unsupportedMedia: string[];
+ mediaBlobs: WechatPollMediaBlobInput[];
+ mediaRefs: WechatPollMediaRefInput[];
+ fileAttachments: WechatPollFileAttachmentInput[];
+}
+
+export async function stageWechatTaskMedia(args: {
+ bindingEpoch: string;
+ taskId: string;
+ sessionId: string;
+ media: readonly WechatMediaRef[];
+ transport: WechatTransport;
+ signal: AbortSignal;
+ now: number;
+}): Promise<StagedWechatTaskMedia> {
+ const result: StagedWechatTaskMedia = {
+ attachments: [],
+ unsupportedMedia: [],
+ mediaBlobs: [],
+ mediaRefs: [],
+ fileAttachments: [],
+ };
+ const selected = args.media.slice(0, MAX_ATTACHMENTS_PER_MESSAGE);
+ if (args.media.length > selected.length) {
+ result.unsupportedMedia.push(`attachment-limit:${args.media.length - selected.length}`);
+ }
+
+ for (const ref of selected) {
+ let bytes: Uint8Array;
+ try {
+ bytes = await args.transport.downloadMedia(ref, args.signal);
+ } catch (error) {
+ if (args.signal.aborted) throw error;
+ result.unsupportedMedia.push(`${ref.kind}:download-failed`);
+ continue;
+ }
+ if (ref.kind === 'voice' && ref.voiceEncoding === 6) {
+ try {
+ bytes = await decodeWechatSilkToWav(bytes, args.signal);
+ } catch (error) {
+ if (args.signal.aborted) throw error;
+ result.unsupportedMedia.push(`${ref.kind}:decode-failed`);
+ continue;
+ }
+ }
+ const detected = detectWechatMedia(ref, bytes);
+ if (!detected) {
+ result.unsupportedMedia.push(`${ref.kind}:unsupported-format`);
+ continue;
+ }
+ try {
+ if (detected.storage === 'cindy-media') {
+ // Poll commit happens after downloads finish. Ingest with no refs
+ // before exposing the URL so duplicate, overload, stale-cursor, and
+ // interaction-only paths leave a recycler-visible zero-ref ledger row
+ // instead of an untracked content-addressed file.
+ const written = await ingestMedia({
+ buffer: bytes,
+ mimeType: detected.mimeType,
+ isCache: false,
+ refs: [],
+ });
+ const resolved = blobStore.resolveSafe(written.url);
+ result.attachments.push({
+ kind: detected.attachmentKind,
+ absPath: resolved.absPath,
+ originalName: detected.fileName,
+ mimeType: detected.mimeType,
+ url: written.url,
+ storage: 'cindy-media',
+ });
+ result.mediaBlobs.push({
+ hash: written.hash,
+ ext: written.ext,
+ mimeType: written.mimeType,
+ bytes: written.bytes,
+ isCache: false,
+ createdAt: args.now,
+ lastAccessAt: args.now,
+ });
+ result.mediaRefs.push({
+ id: randomUUID(),
+ hash: written.hash,
+ taskId: args.taskId,
+ label: detected.fileName,
+ createdAt: args.now,
+ });
+ continue;
+ }
+
+ const root = ownerScopedImUserDataPath(
+ 'im-attachments',
+ 'wechat',
+ 'sessions',
+ args.sessionId,
+ );
+ await fs.mkdir(root, { recursive: true });
+ const fileName = `${args.taskId}-${randomUUID()}-${detected.fileName}`;
+ const absPath = path.resolve(root, fileName);
+ const resolvedRoot = path.resolve(root);
+ if (!absPath.startsWith(`${resolvedRoot}${path.sep}`)) {
+ throw new Error('WECHAT_ATTACHMENT_PATH_OUT_OF_BOUNDS');
+ }
+ await fs.writeFile(absPath, bytes, { flag: 'wx' });
+ result.attachments.push({
+ kind: 'file',
+ absPath,
+ originalName: detected.fileName,
+ mimeType: detected.mimeType,
+ storage: 'file',
+ });
+ result.fileAttachments.push({
+ id: randomUUID(),
+ taskId: args.taskId,
+ sessionId: args.sessionId,
+ absPath,
+ originalName: detected.fileName,
+ mimeType: detected.mimeType,
+ bytes: bytes.byteLength,
+ createdAt: args.now,
+ });
+ } catch (error) {
+ if (args.signal.aborted) throw error;
+ result.unsupportedMedia.push(`${ref.kind}:staging-failed`);
+ }
+ }
+ return result;
+}
+
+export async function removeUncommittedWechatFiles(
+ staged: readonly WechatPollFileAttachmentInput[],
+ insertedTaskIds: ReadonlySet<string>,
+): Promise<void> {
+ await Promise.all(
+ staged
+ .filter((entry) => !insertedTaskIds.has(entry.taskId))
+ .map((entry) => fs.rm(entry.absPath, { force: true }).catch(() => undefined)),
+ );
+}
+
+export async function removeReleasedWechatFiles(filePaths: readonly string[]): Promise<void> {
+ const root = path.resolve(ownerScopedImUserDataPath('im-attachments', 'wechat', 'sessions'));
+ await Promise.all(
+ filePaths.map(async (candidate) => {
+ const resolved = path.resolve(candidate);
+ if (!resolved.startsWith(`${root}${path.sep}`)) return;
+ await fs.rm(resolved, { force: true }).catch(() => undefined);
+ }),
+ );
+}
+
+export async function removeWechatSessionAttachmentDir(sessionId: string): Promise<void> {
+ const root = path.resolve(ownerScopedImUserDataPath('im-attachments', 'wechat', 'sessions'));
+ const target = path.resolve(root, sessionId);
+ if (!target.startsWith(`${root}${path.sep}`)) return;
+ await fs.rm(target, { recursive: true, force: true });
+}
+
+interface DetectedMedia {
+ attachmentKind: IMAttachment['kind'];
+ fileName: string;
+ mimeType: string;
+ storage: 'cindy-media' | 'file';
+}
+
+function detectWechatMedia(ref: WechatMediaRef, bytes: Uint8Array): DetectedMedia | null {
+ switch (ref.kind) {
+ case 'image': {
+ const image = detectImage(bytes);
+ return image
+ ? {
+ attachmentKind: 'image',
+ fileName: `wechat-image${image.ext}`,
+ mimeType: image.mimeType,
+ storage: 'cindy-media',
+ }
+ : null;
+ }
+ case 'video':
+ return isMp4(bytes)
+ ? {
+ attachmentKind: 'file',
+ fileName: sanitizeAttachmentName(ref.fileName, 'wechat-video.mp4'),
+ mimeType: 'video/mp4',
+ storage: 'cindy-media',
+ }
+ : null;
+ case 'voice': {
+ if (
+ ref.voiceEncoding === 6 &&
+ startsWithAscii(bytes, 'RIFF') &&
+ startsWithAscii(bytes.subarray(8), 'WAVE')
+ ) {
+ return {
+ attachmentKind: 'file',
+ fileName: 'wechat-voice.wav',
+ mimeType: 'audio/wav',
+ storage: 'cindy-media',
+ };
+ }
+ if (ref.voiceEncoding === 7 && isMp3(bytes)) {
+ return {
+ attachmentKind: 'file',
+ fileName: 'wechat-voice.mp3',
+ mimeType: 'audio/mpeg',
+ storage: 'cindy-media',
+ };
+ }
+ if (ref.voiceEncoding === 8 && startsWithAscii(bytes, 'OggS')) {
+ return {
+ attachmentKind: 'file',
+ fileName: 'wechat-voice.ogg',
+ mimeType: 'audio/ogg',
+ storage: 'cindy-media',
+ };
+ }
+ return null;
+ }
+ case 'file': {
+ const fileName = sanitizeAttachmentName(ref.fileName, 'wechat-file.bin');
+ return {
+ attachmentKind: 'file',
+ fileName,
+ mimeType: mimeForFileName(fileName),
+ storage: 'file',
+ };
+ }
+ }
+}
+
+function sanitizeAttachmentName(input: string | undefined, fallback: string): string {
+ const normalized = (input ?? '')
+ .normalize('NFKC')
+ .replace(/\p{Cc}/gu, '')
+ .replace(/[<>:"/\\|?*]/g, '_')
+ .replace(/[. ]+$/g, '')
+ .trim();
+ const leaf = path.basename(normalized).slice(0, 180);
+ return leaf && leaf !== '.' && leaf !== '..' ? leaf : fallback;
+}
+
+function detectImage(bytes: Uint8Array): { ext: string; mimeType: string } | null {
+ if (
+ bytes.length >= 8 &&
+ bytes[0] === 0x89 &&
+ startsWithAscii(bytes.subarray(1), 'PNG\r\n\u001a\n')
+ ) {
+ return { ext: '.png', mimeType: 'image/png' };
+ }
+ if (bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) {
+ return { ext: '.jpg', mimeType: 'image/jpeg' };
+ }
+ if (startsWithAscii(bytes, 'GIF87a') || startsWithAscii(bytes, 'GIF89a')) {
+ return { ext: '.gif', mimeType: 'image/gif' };
+ }
+ if (
+ bytes.length >= 12 &&
+ startsWithAscii(bytes, 'RIFF') &&
+ startsWithAscii(bytes.subarray(8), 'WEBP')
+ ) {
+ return { ext: '.webp', mimeType: 'image/webp' };
+ }
+ return null;
+}
+
+function isMp4(bytes: Uint8Array): boolean {
+ return bytes.length >= 12 && startsWithAscii(bytes.subarray(4), 'ftyp');
+}
+
+function isMp3(bytes: Uint8Array): boolean {
+ return (
+ startsWithAscii(bytes, 'ID3') ||
+ (bytes.length >= 2 && bytes[0] === 0xff && (bytes[1]! & 0xe0) === 0xe0)
+ );
+}
+
+function startsWithAscii(bytes: Uint8Array, value: string): boolean {
+ if (bytes.length < value.length) return false;
+ for (let index = 0; index < value.length; index += 1) {
+ if (bytes[index] !== value.charCodeAt(index)) return false;
+ }
+ return true;
+}
+
+function mimeForFileName(fileName: string): string {
+ const ext = path.extname(fileName).toLowerCase();
+ return (
+ {
+ '.txt': 'text/plain',
+ '.md': 'text/markdown',
+ '.json': 'application/json',
+ '.pdf': 'application/pdf',
+ '.zip': 'application/zip',
+ '.doc': 'application/msword',
+ '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
+ '.xls': 'application/vnd.ms-excel',
+ '.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
+ '.ppt': 'application/vnd.ms-powerpoint',
+ '.pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
+ }[ext] ?? 'application/octet-stream'
+ );
+}
+
+export const __testing = {
+ detectWechatMedia,
+ sanitizeAttachmentName,
+};
diff --git a/apps/desktop/src/main/im/wechat/permissionPolicy.ts b/apps/desktop/src/main/im/wechat/permissionPolicy.ts
new file mode 100644
index 0000000000..366c5c9438
--- /dev/null
+++ b/apps/desktop/src/main/im/wechat/permissionPolicy.ts
@@ -0,0 +1,72 @@
+import type {
+ Capabilities,
+ PermissionMode,
+ TurnPermissionPolicy,
+} from '@cindy/maker-core';
+
+import { checkDestructiveToolCall } from '../../destructiveGuard';
+
+function record(value: unknown): Record<string, unknown> | null {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
+ return value as Record<string, unknown>;
+}
+
+/**
+ * Personal WeChat has no structured card UI. Interaction requests are rendered
+ * as one-shot text prompts by the channel adapter; the destructive guard still
+ * blocks unsafe calls before a prompt can be approved.
+ */
+export function createWechatTurnPermissionPolicy(
+ taskId: string,
+ options?: {
+ onInteractionStateChange?: TurnPermissionPolicy['onInteractionStateChange'];
+ },
+): TurnPermissionPolicy {
+ return {
+ origin: { kind: 'im', channel: 'wechat', taskId },
+ confirmationSurface: 'channel',
+ confirmationTimeoutMs: 30 * 60 * 1_000,
+ ...(options?.onInteractionStateChange
+ ? { onInteractionStateChange: options.onInteractionStateChange }
+ : {}),
+ forceConfirmToolCall(toolName, input) {
+ const direct = checkDestructiveToolCall(toolName, record(input));
+ if (direct.destructive) return true;
+
+ // Claude call_tool wrappers put the inner action directly in input.name.
+ // Codex MCP elicitation wraps it in input.toolParams.name.
+ const outer = record(input);
+ const nested = record(outer?.toolParams);
+ const innerName =
+ typeof nested?.name === 'string'
+ ? nested.name
+ : typeof outer?.name === 'string'
+ ? outer.name
+ : null;
+ const innerInput = nested ?? outer;
+ if (
+ innerName &&
+ (checkDestructiveToolCall(innerName, innerInput).destructive ||
+ /(?:^|_)(?:merge|system_write|overwrite)(?:_|$)/i.test(innerName))
+ ) {
+ return true;
+ }
+
+ // Codex does not expose the patch body in fileChangeApproval, and a
+ // permissions escalation can authorize an opaque write. Confirm these
+ // conservatively rather than auto-approving a possible deletion.
+ return toolName === 'file_change' || toolName === 'permissions';
+ },
+ };
+}
+
+export function supportsWechatTurnPermissionMode(
+ capabilities: Capabilities,
+ mode: PermissionMode,
+): boolean {
+ const policy = capabilities.turnPermissionPolicy;
+ return (
+ policy?.supported.supported === true &&
+ !policy.unsupportedPermissionModes.includes(mode)
+ );
+}
diff --git a/apps/desktop/src/main/im/wechat/silkDecoder.ts b/apps/desktop/src/main/im/wechat/silkDecoder.ts
new file mode 100644
index 0000000000..89412eaf8e
--- /dev/null
+++ b/apps/desktop/src/main/im/wechat/silkDecoder.ts
@@ -0,0 +1,77 @@
+import { randomUUID } from 'node:crypto';
+import path from 'node:path';
+// eslint-disable-next-line no-restricted-imports -- SILK decoding is CPU-isolated and never touches the database.
+import { Worker } from 'node:worker_threads';
+
+const SILK_SAMPLE_RATE = 24_000;
+const SILK_DECODE_TIMEOUT_MS = 30_000;
+
+export async function decodeWechatSilkToWav(
+ silk: Uint8Array,
+ signal: AbortSignal,
+): Promise<Uint8Array> {
+ if (signal.aborted) throw new Error('WECHAT_SILK_DECODE_ABORTED');
+ const worker = new Worker(path.join(__dirname, 'silkWorker.js'));
+ const id = randomUUID();
+ const bytes = copySilkBytes(silk);
+ try {
+ return await new Promise<Uint8Array>((resolve, reject) => {
+ let settled = false;
+ const finish = (operation: () => void): void => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ signal.removeEventListener('abort', onAbort);
+ operation();
+ };
+ const timer = setTimeout(() => {
+ finish(() => reject(new Error('WECHAT_SILK_DECODE_TIMEOUT')));
+ }, SILK_DECODE_TIMEOUT_MS);
+ timer.unref?.();
+ const onAbort = (): void => finish(() => reject(new Error('WECHAT_SILK_DECODE_ABORTED')));
+ signal.addEventListener('abort', onAbort, { once: true });
+ worker.once('error', (error) => finish(() => reject(error)));
+ worker.once(
+ 'message',
+ (response: { id?: unknown; ok?: unknown; bytes?: unknown; errorCode?: unknown }) => {
+ if (response.id !== id) {
+ finish(() => reject(new Error('WECHAT_SILK_DECODE_FAILED')));
+ return;
+ }
+ if (response.ok !== true) {
+ const errorCode =
+ typeof response.errorCode === 'string' && response.errorCode.length > 0
+ ? response.errorCode
+ : 'WECHAT_SILK_DECODE_FAILED';
+ finish(() => reject(new Error(errorCode)));
+ return;
+ }
+ const responseBytes = response.bytes;
+ if (!(responseBytes instanceof ArrayBuffer)) {
+ finish(() => reject(new Error('WECHAT_SILK_DECODE_FAILED')));
+ return;
+ }
+ finish(() => resolve(new Uint8Array(responseBytes)));
+ },
+ );
+ worker.once('exit', (code) => {
+ if (code !== 0) {
+ finish(() => reject(new Error('WECHAT_SILK_WORKER_EXITED')));
+ }
+ });
+ worker.postMessage({ id, bytes: bytes.buffer, sampleRate: SILK_SAMPLE_RATE }, [bytes.buffer]);
+ });
+ } finally {
+ await worker.terminate();
+ }
+}
+
+function copySilkBytes(silk: Uint8Array): Uint8Array<ArrayBuffer> {
+ const bytes = new Uint8Array(new ArrayBuffer(silk.byteLength));
+ bytes.set(silk);
+ return bytes;
+}
+
+export const __testing = {
+ copySilkBytes,
+};
diff --git a/apps/desktop/src/main/im/wechat/silkWav.ts b/apps/desktop/src/main/im/wechat/silkWav.ts
new file mode 100644
index 0000000000..776d798381
--- /dev/null
+++ b/apps/desktop/src/main/im/wechat/silkWav.ts
@@ -0,0 +1,40 @@
+const WAV_HEADER_BYTE_LENGTH = 44;
+
+export class WavOutputLimitError extends Error {
+ constructor() {
+ super('WAV output exceeds the configured byte limit.');
+ this.name = 'WavOutputLimitError';
+ }
+}
+
+export function pcmS16leToWav(
+ pcm: Uint8Array,
+ sampleRate: number,
+ maxOutputByteLength?: number,
+): Uint8Array {
+ if (pcm.byteLength === 0 || pcm.byteLength % 2 !== 0) {
+ throw new Error('Invalid PCM payload.');
+ }
+ if (
+ maxOutputByteLength !== undefined &&
+ pcm.byteLength > maxOutputByteLength - WAV_HEADER_BYTE_LENGTH
+ ) {
+ throw new WavOutputLimitError();
+ }
+ const result = Buffer.allocUnsafe(WAV_HEADER_BYTE_LENGTH + pcm.byteLength);
+ result.write('RIFF', 0, 'ascii');
+ result.writeUInt32LE(36 + pcm.byteLength, 4);
+ result.write('WAVE', 8, 'ascii');
+ result.write('fmt ', 12, 'ascii');
+ result.writeUInt32LE(16, 16);
+ result.writeUInt16LE(1, 20);
+ result.writeUInt16LE(1, 22);
+ result.writeUInt32LE(sampleRate, 24);
+ result.writeUInt32LE(sampleRate * 2, 28);
+ result.writeUInt16LE(2, 32);
+ result.writeUInt16LE(16, 34);
+ result.write('data', 36, 'ascii');
+ result.writeUInt32LE(pcm.byteLength, 40);
+ result.set(pcm, 44);
+ return result;
+}
diff --git a/apps/desktop/src/main/im/wechat/silkWorker.ts b/apps/desktop/src/main/im/wechat/silkWorker.ts
new file mode 100644
index 0000000000..4bae5adfe9
--- /dev/null
+++ b/apps/desktop/src/main/im/wechat/silkWorker.ts
@@ -0,0 +1,27 @@
+// eslint-disable-next-line no-restricted-imports -- dedicated non-DB worker entry for bounded SILK/WASM decoding.
+import { parentPort } from 'node:worker_threads';
+
+import { decode } from 'silk-wasm';
+import { pcmS16leToWav, WavOutputLimitError } from './silkWav';
+
+const port = parentPort;
+if (!port) throw new Error('WeChat SILK decoder must run in a worker thread.');
+
+const SILK_OUTPUT_LIMIT_ERROR = 'SILK_OUTPUT_LIMIT_EXCEEDED';
+const SILK_OUTPUT_LIMIT_BYTES = 20 * 1024 * 1024;
+
+port.once('message', async (request: { id: string; bytes: ArrayBuffer; sampleRate: number }) => {
+ try {
+ const decoded = await decode(new Uint8Array(request.bytes), request.sampleRate);
+ const wav = pcmS16leToWav(decoded.data, request.sampleRate, SILK_OUTPUT_LIMIT_BYTES);
+ const transferable = new Uint8Array(wav.byteLength);
+ transferable.set(wav);
+ port.postMessage({ id: request.id, ok: true, bytes: transferable.buffer }, [
+ transferable.buffer,
+ ]);
+ } catch (error) {
+ const errorCode =
+ error instanceof WavOutputLimitError ? SILK_OUTPUT_LIMIT_ERROR : 'SILK_DECODE_FAILED';
+ port.postMessage({ id: request.id, ok: false, errorCode });
+ }
+});
diff --git a/apps/desktop/src/main/im/wechat/taskStore.ts b/apps/desktop/src/main/im/wechat/taskStore.ts
new file mode 100644
index 0000000000..a58e5d8b72
--- /dev/null
+++ b/apps/desktop/src/main/im/wechat/taskStore.ts
@@ -0,0 +1,472 @@
+import type { DbClient } from '../../localDb/client/DbClient.js';
+import type {
+ WechatActivateBindingEpochResult,
+ WechatCancelForCommandResult,
+ WechatCommitPollBatchResult,
+ WechatCommitTerminalResult,
+ WechatMarkOutboxDeliveredResult,
+ WechatOutboxChunkInput,
+ WechatOutboxKind,
+ WechatPollFileAttachmentInput,
+ WechatPollMediaBlobInput,
+ WechatPollMediaRefInput,
+ WechatRecordOutboxFailureResult,
+ WechatPromoteTaskAttachmentsResult,
+ WechatStopAllResult,
+ WechatUnbindCleanupResult,
+} from '../../localDb/client/tx/types.js';
+import { decryptWechatContextToken, encryptWechatContextToken } from './contextCrypto.js';
+
+const DEFAULT_TASK_TTL_MS = 30 * 60_000;
+const DEFAULT_LEASE_MS = 60_000;
+
+export interface WechatInboundTaskInput {
+ id: string;
+ platformMessageId: string;
+ platformSeq: number;
+ peerId: string;
+ receivedAt: number;
+ platformCreatedAt: number;
+ sessionId: string;
+ conversationEpoch: number;
+ payloadJson: string;
+ contextToken: string;
+ overloadReply?: {
+ outboxId: string;
+ clientId: string;
+ text: string;
+ };
+}
+
+export interface WechatCommitBatchInput {
+ bindingEpoch: string;
+ expectedCursor: string;
+ nextCursor: string;
+ now: number;
+ messages: WechatInboundTaskInput[];
+ mediaBlobs?: WechatPollMediaBlobInput[];
+ mediaRefs?: WechatPollMediaRefInput[];
+ fileAttachments?: WechatPollFileAttachmentInput[];
+ maxQueuedTasks?: number;
+}
+
+export interface WechatTask {
+ id: string;
+ bindingEpoch: string;
+ peerId: string;
+ sessionId: string;
+ conversationEpoch: number;
+ payloadJson: string;
+ contextToken: string;
+ attempts: number;
+ receivedAt: number;
+ expiresAt: number;
+}
+
+export interface WechatOutboxRecord {
+ id: string;
+ taskId: string;
+ clientId: string;
+ kind: WechatOutboxKind;
+ chunkIndex: number;
+ text: string;
+ mediaJson: string;
+ attempts: number;
+ contextToken: string;
+}
+
+export interface WechatActiveBinding {
+ bindingEpoch: string;
+ cursor: string;
+}
+
+interface WechatOutboxRow extends Omit<WechatOutboxRecord, 'contextToken'> {
+ bindingEpoch: string;
+ contextNonce: string;
+ contextCiphertext: string;
+ contextTag: string;
+}
+
+export class WechatTaskStore {
+ readonly #db: DbClient;
+ readonly #dataKey: Buffer;
+
+ constructor(db: DbClient, dataKey: Uint8Array) {
+ if (dataKey.byteLength !== 32) throw new Error('WeChat data key must be 32 bytes.');
+ this.#db = db;
+ this.#dataKey = Buffer.from(dataKey);
+ }
+
+ destroy(): void {
+ this.#dataKey.fill(0);
+ }
+
+ async getActiveBinding(): Promise<WechatActiveBinding | null> {
+ const row = await this.#db.queryOne<{ bindingEpoch: string; cursor: string }>(
+ `SELECT binding_epoch AS bindingEpoch, sync_cursor AS cursor
+ FROM wechat_sync_state
+ WHERE is_active = 1
+ LIMIT 1`,
+ );
+ return row ?? null;
+ }
+
+ async getConversationEpoch(bindingEpoch: string, peerId: string): Promise<number> {
+ const row = await this.#db.queryOne<{ conversationEpoch: number }>(
+ `SELECT COALESCE(MAX(conversation_epoch), 0) AS conversationEpoch
+ FROM wechat_inbox
+ WHERE binding_epoch = ? AND peer_id = ?`,
+ [bindingEpoch, peerId],
+ );
+ return row?.conversationEpoch ?? 0;
+ }
+
+ /**
+ * Return the most recently received context for a peer. Context tokens are
+ * encrypted at rest and are intentionally only addressable through the
+ * currently active binding epoch, so proactive sends cannot target an
+ * arbitrary WeChat id or a stale binding.
+ */
+ async getLatestPeerContext(args: {
+ bindingEpoch: string;
+ peerId: string;
+ }): Promise<{ contextToken: string; sessionId: string | null } | null> {
+ const row = await this.#db.queryOne<{
+ taskId: string;
+ sessionId: string | null;
+ contextNonce: string;
+ contextCiphertext: string;
+ contextTag: string;
+ }>(
+ `SELECT id AS taskId,
+ session_id AS sessionId,
+ context_nonce AS contextNonce,
+ context_ciphertext AS contextCiphertext,
+ context_tag AS contextTag
+ FROM wechat_inbox
+ WHERE binding_epoch = ? AND peer_id = ?
+ ORDER BY received_at DESC, rowid DESC
+ LIMIT 1`,
+ [args.bindingEpoch, args.peerId],
+ );
+ if (!row) return null;
+ return {
+ contextToken: decryptWechatContextToken(
+ {
+ nonce: row.contextNonce,
+ ciphertext: row.contextCiphertext,
+ tag: row.contextTag,
+ },
+ this.#dataKey,
+ args.bindingEpoch,
+ row.taskId,
+ ),
+ sessionId: row.sessionId,
+ };
+ }
+
+ async getMostRecentPeer(bindingEpoch: string): Promise<string | null> {
+ const row = await this.#db.queryOne<{ peerId: string }>(
+ `SELECT peer_id AS peerId
+ FROM wechat_inbox
+ WHERE binding_epoch = ?
+ ORDER BY received_at DESC, rowid DESC
+ LIMIT 1`,
+ [bindingEpoch],
+ );
+ return row?.peerId ?? null;
+ }
+
+ async advanceConversationEpoch(
+ bindingEpoch: string,
+ taskId: string,
+ peerId: string,
+ ): Promise<number> {
+ const current = await this.getConversationEpoch(bindingEpoch, peerId);
+ const next = current + 1;
+ const result = await this.#db.exec(
+ `UPDATE wechat_inbox
+ SET conversation_epoch = ?
+ WHERE binding_epoch = ? AND id = ? AND peer_id = ?`,
+ [next, bindingEpoch, taskId, peerId],
+ );
+ if (result.changes !== 1) throw new Error('WECHAT_CONVERSATION_EPOCH_STALE');
+ return next;
+ }
+
+ async countQueuedTasks(bindingEpoch: string): Promise<number> {
+ const row = await this.#db.queryOne<{ count: number }>(
+ `SELECT COUNT(*) AS count
+ FROM wechat_inbox
+ WHERE binding_epoch = ?
+ AND status IN ('pending', 'dispatching', 'accepted_running', 'waiting_desktop')`,
+ [bindingEpoch],
+ );
+ return row?.count ?? 0;
+ }
+
+ activateBindingEpoch(args: {
+ bindingEpoch: string;
+ expectedActiveEpoch: string | null;
+ initialCursor?: string;
+ now: number;
+ }): Promise<WechatActivateBindingEpochResult> {
+ return this.#db.tx('wechatActivateBindingEpoch', {
+ bindingEpoch: args.bindingEpoch,
+ expectedActiveEpoch: args.expectedActiveEpoch,
+ initialCursor: args.initialCursor ?? '',
+ now: args.now,
+ });
+ }
+
+ commitPollBatch(input: WechatCommitBatchInput): Promise<WechatCommitPollBatchResult> {
+ return this.#db.tx('wechatCommitPollBatch', {
+ bindingEpoch: input.bindingEpoch,
+ expectedCursor: input.expectedCursor,
+ nextCursor: input.nextCursor,
+ now: input.now,
+ messages: input.messages.map((message) => ({
+ id: message.id,
+ platformMessageId: message.platformMessageId,
+ platformSeq: message.platformSeq,
+ peerId: message.peerId,
+ receivedAt: message.receivedAt,
+ platformCreatedAt: message.platformCreatedAt,
+ expiresAt: message.receivedAt + DEFAULT_TASK_TTL_MS,
+ sessionId: message.sessionId,
+ conversationEpoch: message.conversationEpoch,
+ payloadJson: message.payloadJson,
+ context: encryptWechatContextToken(
+ message.contextToken,
+ this.#dataKey,
+ input.bindingEpoch,
+ message.id,
+ ),
+ overloadReply: message.overloadReply,
+ })),
+ mediaBlobs: input.mediaBlobs ?? [],
+ mediaRefs: input.mediaRefs ?? [],
+ fileAttachments: input.fileAttachments ?? [],
+ maxQueuedTasks: input.maxQueuedTasks,
+ });
+ }
+
+ async leaseNextTask(args: {
+ bindingEpoch: string;
+ now: number;
+ leaseMs?: number;
+ }): Promise<WechatTask | null> {
+ const leased = await this.#db.tx('wechatLeaseNextTask', {
+ bindingEpoch: args.bindingEpoch,
+ now: args.now,
+ leaseUntil: args.now + (args.leaseMs ?? DEFAULT_LEASE_MS),
+ });
+ if (!leased) return null;
+ return {
+ id: leased.id,
+ bindingEpoch: leased.bindingEpoch,
+ peerId: leased.peerId,
+ sessionId: leased.sessionId,
+ conversationEpoch: leased.conversationEpoch,
+ payloadJson: leased.payloadJson,
+ contextToken: decryptWechatContextToken(
+ leased.context,
+ this.#dataKey,
+ leased.bindingEpoch,
+ leased.id,
+ ),
+ attempts: leased.attempts,
+ receivedAt: leased.receivedAt,
+ expiresAt: leased.expiresAt,
+ };
+ }
+
+ markAccepted(bindingEpoch: string, taskId: string): Promise<boolean> {
+ return this.#db.tx('wechatMarkAccepted', { bindingEpoch, taskId });
+ }
+
+ promoteTaskAttachments(args: {
+ bindingEpoch: string;
+ taskId: string;
+ sessionId: string;
+ now: number;
+ }): Promise<WechatPromoteTaskAttachmentsResult> {
+ return this.#db.tx('wechatPromoteTaskAttachments', args);
+ }
+
+ async refreshPendingOutboxContext(args: {
+ bindingEpoch: string;
+ peerId: string;
+ contextToken: string;
+ now: number;
+ }): Promise<void> {
+ const rows = await this.#db.query<{ taskId: string }>(
+ `SELECT DISTINCT i.id AS taskId
+ FROM wechat_inbox i
+ INNER JOIN wechat_outbox o
+ ON o.binding_epoch = i.binding_epoch AND o.task_id = i.id
+ WHERE i.binding_epoch = ? AND i.peer_id = ? AND i.status = 'delivery_pending'
+ AND o.status = 'pending'`,
+ [args.bindingEpoch, args.peerId],
+ );
+ if (rows.length === 0) return;
+ await this.#db.tx('wechatRefreshOutboxContexts', {
+ bindingEpoch: args.bindingEpoch,
+ peerId: args.peerId,
+ now: args.now,
+ contexts: rows.map(({ taskId }) => ({
+ taskId,
+ context: encryptWechatContextToken(
+ args.contextToken,
+ this.#dataKey,
+ args.bindingEpoch,
+ taskId,
+ ),
+ })),
+ });
+ }
+
+ releaseDispatch(bindingEpoch: string, taskId: string): Promise<boolean> {
+ return this.#db.tx('wechatReleaseDispatch', { bindingEpoch, taskId });
+ }
+
+ setWaitingDesktop(bindingEpoch: string, taskId: string, waiting: boolean): Promise<boolean> {
+ return this.#db.tx('wechatSetWaitingDesktop', { bindingEpoch, taskId, waiting });
+ }
+
+ commitInterrupted(args: {
+ bindingEpoch: string;
+ taskId: string;
+ now: number;
+ errorCode: string;
+ outbox?: WechatOutboxChunkInput[];
+ contextToken?: string;
+ }): Promise<boolean> {
+ const { contextToken, ...txArgs } = args;
+ return this.#db.tx('wechatCommitInterrupted', {
+ ...txArgs,
+ context:
+ contextToken === undefined
+ ? undefined
+ : encryptWechatContextToken(contextToken, this.#dataKey, args.bindingEpoch, args.taskId),
+ });
+ }
+
+ commitPreDispatchFailure(args: {
+ bindingEpoch: string;
+ taskId: string;
+ now: number;
+ errorCode: string;
+ outbox: WechatOutboxChunkInput[];
+ }): Promise<boolean> {
+ return this.#db.tx('wechatCommitPreDispatchFailure', args);
+ }
+
+ cancelForCommand(args: {
+ bindingEpoch: string;
+ commandTaskId: string;
+ peerId?: string;
+ now: number;
+ }): Promise<WechatCancelForCommandResult> {
+ return this.#db.tx('wechatCancelForCommand', args);
+ }
+
+ commitTerminal(args: {
+ bindingEpoch: string;
+ taskId: string;
+ now: number;
+ outbox: WechatOutboxChunkInput[];
+ }): Promise<WechatCommitTerminalResult> {
+ return this.#db.tx('wechatCommitTerminal', args);
+ }
+
+ async listDueOutbox(
+ bindingEpoch: string,
+ now: number,
+ limit = 20,
+ ): Promise<WechatOutboxRecord[]> {
+ const rows = await this.#db.query<WechatOutboxRow>(
+ `SELECT
+ o.id,
+ o.binding_epoch AS bindingEpoch,
+ o.task_id AS taskId,
+ o.client_id AS clientId,
+ o.kind,
+ o.chunk_index AS chunkIndex,
+ o.text,
+ o.media_json AS mediaJson,
+ o.attempts,
+ i.context_nonce AS contextNonce,
+ i.context_ciphertext AS contextCiphertext,
+ i.context_tag AS contextTag
+ FROM wechat_outbox o
+ INNER JOIN wechat_inbox i
+ ON i.binding_epoch = o.binding_epoch AND i.id = o.task_id
+ WHERE o.binding_epoch = ? AND o.status = 'pending' AND o.next_retry_at <= ?
+ ORDER BY o.created_at ASC, o.chunk_index ASC
+ LIMIT ?`,
+ [bindingEpoch, now, Math.max(1, Math.min(100, Math.floor(limit)))],
+ );
+ return rows.map(({ contextNonce, contextCiphertext, contextTag, ...row }) => ({
+ ...row,
+ contextToken: decryptWechatContextToken(
+ {
+ nonce: contextNonce,
+ ciphertext: contextCiphertext,
+ tag: contextTag,
+ },
+ this.#dataKey,
+ row.bindingEpoch,
+ row.taskId,
+ ),
+ }));
+ }
+
+ async claimOutbox(bindingEpoch: string, outboxId: string): Promise<boolean> {
+ const result = await this.#db.exec(
+ `UPDATE wechat_outbox
+ SET status = 'sending', attempts = attempts + 1
+ WHERE binding_epoch = ? AND id = ? AND status = 'pending'`,
+ [bindingEpoch, outboxId],
+ );
+ return result.changes === 1;
+ }
+
+ markOutboxDelivered(
+ bindingEpoch: string,
+ outboxId: string,
+ deliveredAt: number,
+ ): Promise<WechatMarkOutboxDeliveredResult> {
+ return this.#db.tx('wechatMarkOutboxDelivered', {
+ bindingEpoch,
+ outboxId,
+ deliveredAt,
+ });
+ }
+
+ recordOutboxFailure(args: {
+ bindingEpoch: string;
+ outboxId: string;
+ nextRetryAt: number;
+ terminal: boolean;
+ errorCode: string;
+ }): Promise<WechatRecordOutboxFailureResult> {
+ return this.#db.tx('wechatRecordOutboxFailure', args);
+ }
+
+ stopAll(args: {
+ bindingEpoch: string;
+ now: number;
+ errorCode: string;
+ }): Promise<WechatStopAllResult> {
+ return this.#db.tx('wechatStopAll', args);
+ }
+
+ closeBindingEpoch(bindingEpoch: string, now: number): Promise<{ closed: boolean }> {
+ return this.#db.tx('wechatCloseBindingEpoch', { bindingEpoch, now });
+ }
+
+ unbindCleanup(bindingEpoch: string): Promise<WechatUnbindCleanupResult> {
+ return this.#db.tx('wechatUnbindCleanup', { bindingEpoch });
+ }
+}
diff --git a/apps/desktop/src/main/im/wechat/uiText.ts b/apps/desktop/src/main/im/wechat/uiText.ts
new file mode 100644
index 0000000000..fe712758ee
--- /dev/null
+++ b/apps/desktop/src/main/im/wechat/uiText.ts
@@ -0,0 +1,180 @@
+/**
+ * Personal WeChat channel copy. Keep this pack independent from other IM
+ * channels so channel-specific wording cannot leak into WeChat replies.
+ */
+import type { IMUnsupportedEntry } from '@cindy/im';
+
+import type { ImUiTextPack } from '../shared/types';
+
+export const ui = {
+ slash: {
+ new: '🌱 新存档已开 — 之前的对话清掉了,从头聊~',
+ help: `🤖 我能帮你做这些:
+
+/new 开个新存档(清掉当前对话上下文)
+/model 换个模型上场
+/permission 调一下权限模式(auto / bypass / ask 等)
+/ctr 远程接管 desktop 上的某个工作区(接管中再发可直接换会话)
+/exctr 结束接管,回到我们俩的微信私聊
+/help 看看我会啥
+
+任务跑着想让它停?直接发 \`!stop\`,我会立刻中止当前任务、把排队的消息也撤掉,会话保留可继续。
+
+平时直接发消息就行,我在听~`,
+ unknownCommand: (cmd: string) =>
+ `没认出 \`${cmd}\` 这个命令 🤔\n我能听懂的: /new、/model、/permission、/ctr、/exctr、/help`,
+ detachedBySlash: '🚪 接管结束,咱们回到微信私聊。下次想远程操控 desktop 再 /ctr',
+ detachedByRevoke: '⚠️ 你在 desktop 那边把接管收回去了,后续消息回到我们俩的微信私聊。',
+ notAttached: '🤷 你现在没在接管任何会话,/exctr 闲着也没事可干。',
+ },
+ agent: {
+ completedNoText: '✅ 跑完啦(这一轮 agent 没说话)',
+ runtimeError: (errMsg: string) => `⚠️ Agent 翻车了:${errMsg.slice(0, 200)}`,
+ sendInternalError: (errMsg: string) => `❌ 内部出 bug 了:${errMsg}`,
+ apiKeyMissing:
+ '⚠️ Cindy AI Key 还没配呢~\n去 desktop 的 Settings → 模型供应商里连接 Cindy AI,再来 ping 我',
+ authMissing: ({ providerLabel, providerId, missing, agentKind, model, attached }) => {
+ const provider = providerLabel ?? providerId ?? '当前供应商';
+ const reason =
+ missing === 'gateway-key'
+ ? '需要先配置 Cindy AI Key'
+ : missing === 'provider-key'
+ ? '还没有配置该供应商的 API Key'
+ : missing === 'provider-disconnected'
+ ? '未连接或连接已失效'
+ : `需要先登录 ${agentKind} 凭证`;
+ const message = `⚠️ 当前微信会话使用供应商「${provider}」(${model}),${reason}。`;
+ return attached
+ ? `${message}\n请在 desktop 的 Settings → 模型供应商中修复认证后,直接继续发送消息。`
+ : `${message}\n“新会话配置”只影响新会话;修改后请发送 \`/new\`,再继续聊天。`;
+ },
+ controlInProgress:
+ '🎮 你 /ctr 还在选择中呢 — 先把上面那张卡片操作完(或点 🚪 退出),再来发别的~',
+ credentialBusy:
+ '⏳ 本地 agent 正在跑另一轮,暂时不能切换凭证模式。等上一轮结束后再发一次就行。',
+ queuedNotice: (position: number) =>
+ position <= 1
+ ? '⏳ 上一轮还在跑,这条先排队——跑完自动接上。想直接叫停就发 `!stop`'
+ : `⏳ 上一轮还在跑,这条排在第 ${position} 位——会按顺序发给 agent。想直接叫停就发 \`!stop\``,
+ stopDone: (droppedQueued: number) =>
+ droppedQueued > 0
+ ? `⏹ 已叫停当前任务,排队中的 ${droppedQueued} 条消息也一并撤了。会话还在——想继续随时发新指令~`
+ : '⏹ 已叫停当前任务。会话还在——想继续随时发新指令~',
+ stopIdle: '🤷 现在没有正在跑的任务,`!stop` 落了个空。等有活儿要停的时候再喊我~',
+ scheduledTaskHeader: (name: string | null) => (name ? `🤖 自动任务「${name}」` : '🤖 自动任务'),
+ unsupportedOnly: (entries: IMUnsupportedEntry[]) =>
+ `🙏 这条消息我吞不下:\n${entries.map((entry) => `• ${entry.label}`).join('\n')}\n\n` +
+ '我能消化的: 文本、图片(jpg/png/gif/webp)、PDF、代码与配置类文本文件。',
+ unsupportedNotice: (entries: IMUnsupportedEntry[]) =>
+ `ℹ️ 以下内容我消化不了,先丢一边了:\n${entries.map((entry) => `• ${entry.label}`).join('\n')}\n\n` +
+ '其它部分收到啦,正在处理~',
+ },
+ cards: {
+ permission: {
+ title: (toolName: string) => `🔧 工具调用:${toolName}`,
+ paramsLabel: '**参数预览**',
+ btnAllowOnce: '✅ 仅本次允许',
+ btnAllowAlways: '✅ 总是允许',
+ btnDeny: '❌ 拒绝',
+ resolvedAllowOnce: '✅ 已允许(仅本次)',
+ resolvedAllowAlways: '✅ 已允许(这个工具以后都放行)',
+ resolvedDeny: '❌ 已拒绝',
+ },
+ ask: {
+ title: (header: string) => `❓ ${header}`,
+ noOptionsHint: '_(这个问题没有预设选项,直接发文字回我吧)_',
+ resolved: (optionLabel: string) => `✅ 已选:${optionLabel}`,
+ },
+ plan: {
+ title: '📋 我打算这么干',
+ btnApprove: '✅ 干吧',
+ btnReject: '❌ 等等',
+ resolvedApproved: '✅ 已批准,开干',
+ resolvedRejected: '❌ 已暂停',
+ },
+ model: {
+ title: '🤖 换个模型',
+ currentLine: (label: string, effort: string | null, description: string) =>
+ effort
+ ? `**当前**:${label} · effort \`${effort}\`\n_${description}_`
+ : `**当前**:${label}\n_${description}_`,
+ hint: '点下面切换。我会自动给所选模型用最高 effort 跑',
+ optionLabel: (providerName: string, label: string, effort: string | null) =>
+ effort ? `${providerName} / ${label} · ${effort}` : `${providerName} / ${label}`,
+ resolved: (label: string, effort: string | null) =>
+ effort ? `✅ 已切到 ${label}(effort:${effort})` : `✅ 已切到 ${label}`,
+ failed: (reason: string) => `❌ 模型没切过去:${reason}`,
+ },
+ permissionMode: {
+ title: '🛡️ 调一下权限模式',
+ currentLine: (label: string, description: string) => `**当前**:${label}\n_${description}_`,
+ hint: '点下面切换。auto = 常规放行+敏感操作弹卡片;bypass = 全放行;ask/default/plan/acceptEdits = 走卡片审批',
+ optionLabel: (label: string) => label,
+ resolved: (label: string) => `✅ 权限模式切到 ${label} 了`,
+ failed: (reason: string) => `❌ 权限模式没切过去:${reason}`,
+ fullAccessConfirmTitle: '⚠️ 确认开启 Full access?',
+ fullAccessConfirmBody:
+ 'Full access 会关闭工作区沙箱并跳过常规审批。Cindy 可以修改工作区外的文件、执行联网命令且不再询问;内置高风险操作仍会要求确认。',
+ btnConfirmFullAccess: '开启 Full access',
+ btnCancelFullAccess: '保留当前权限',
+ fullAccessCancelled: '已取消,保留当前权限',
+ },
+ control: {
+ title: '🎮 挑个工作区上号',
+ emptyBody: '_暂时还没有可接管的工作区~ 在 desktop 端打开/创建一个会话再来_',
+ hint: '点工作区往下走;点 🚪 退出 取消这次',
+ attachedSwitchHint: (sessionTitle: string) =>
+ `🎮 当前接管中:**${sessionTitle}**\n选个新会话直接换乘;点 🚪 退出则保持现状`,
+ btnExit: '🚪 撤了',
+ resolvedExit: '🚪 走了,下次想远程操控再 /ctr',
+ sessionPickerTitle: (displayName: string) => `🎮 ${displayName} 里的存档`,
+ sessionPickerHint: '挑个会话继续打 · ➕ 新建 开新存档 · ↩️ 后退 换工作区 · 🚪 退出 取消',
+ sessionPickerEmptyBody: (displayName: string) =>
+ `_工作区 **${displayName}** 这边还没有 active 会话~ 不如点 ➕ 新建 开一个?_`,
+ btnNew: '➕ 新建',
+ btnBack: '↩️ 后退',
+ resolvedSessionPick: (sessionTitle: string, workspaceName: string) =>
+ `🎯 上号了:**${sessionTitle}**(${workspaceName})\n接下来你发消息我就直接进这个会话;想撤随时 \`/exctr\``,
+ resolvedNewSession: (workspaceName: string) =>
+ `✨ 新存档已建 + 接管完成(在 **${workspaceName}** 里)\n直接发指令开聊;想退就 \`/exctr\``,
+ attachFailed: (reason: string) => `❌ 没接上:${reason}`,
+ sessionBusyOldCardPlaceholder: '⏳ 那个会话还在跑——下方给你刷了张新卡片,重选一下吧',
+ sessionBusyPrompts: [
+ (sessionTitle: string) =>
+ `⏳ **${sessionTitle}** 这会儿正在 BOSS 战~\nagent 还在思考/敲代码,等它这把打完再 \`/ctr\` 上号`,
+ (sessionTitle: string) =>
+ `🚧 抢不进去——**${sessionTitle}** 还有一回合没收尾。\n喝口水等几秒,agent 把手头这把跑完就来叫你`,
+ (sessionTitle: string) =>
+ `🤖 **${sessionTitle}** 正忙着呢——agent 还在键盘上飞舞,强插会让它分神。\n稍等几秒再 \`/ctr\` 试一下`,
+ (sessionTitle: string) =>
+ `☕ 别急别急——**${sessionTitle}** 这一局还没打完。\nagent 干完手头的事,指挥权立刻交给你`,
+ ],
+ takeoverLoadingPrompts: [
+ (sessionTitle: string) =>
+ `⏳ 正在让你接管 **${sessionTitle}**…\n_📦 加载存档元数据_ · _🔌 接通 agent 通道_ · _🧠 复盘上回合战况_\n_三两秒就好,咖啡别一口闷完_`,
+ (sessionTitle: string) =>
+ `🎮 登入 **${sessionTitle}** 中…\n_早期版本里,等不及的玩家会狂点微信图标,但其实并没有用_`,
+ (sessionTitle: string) =>
+ `⌛ **${sessionTitle}** 加载中… 99%\n_这条进度条是真的——正在翻你们上回合聊了啥_`,
+ (sessionTitle: string) =>
+ `🛰️ 正在与 **${sessionTitle}** 建立连接…\n_(WiFi 信号好像有点弱…哦不,是在想该怎么给你 brief)_`,
+ ],
+ sessionAttachedOneshotPrompts: [
+ '我刚通过微信远程上号了——简单同步下战况:上回合咋样、当前在哪一步,然后问我下一步咋走。',
+ '我接力了——一句话过下进度,告诉我现在到哪、刚做了啥,再问我要不要继续推进或者换方向。',
+ 'Hi 我从微信接手了——快速 brief 一下当前形势、最新结果是啥,最后问我下一步指令。',
+ '切到我了——简单复盘下,告诉我现在是什么阶段,然后问我要不要继续干。',
+ ],
+ newSessionWelcomePrompts: [
+ (workspaceName: string) =>
+ `🎯 接管 + 开档 一气呵成——**${workspaceName}** 已就位,agent 待命中。\n发第一条指令开聊;想撤随时 \`/exctr\``,
+ (workspaceName: string) =>
+ `✨ 新存档已建——工作目录 **${workspaceName}** 已经备好,agent 等你发话。\n第一条消息开打;\`/exctr\` 随时退出`,
+ (workspaceName: string) =>
+ `🎮 准备就绪——在 **${workspaceName}** 给你开了个全新存档。\n要做啥告诉我,agent 在线~ \`/exctr\` 收手`,
+ (workspaceName: string) =>
+ `🆕 全新开局——**${workspaceName}** 工作目录已经 ready。\n第一条指令开聊;不想玩了就 \`/exctr\``,
+ ],
+ },
+ },
+} satisfies ImUiTextPack;
diff --git a/apps/desktop/src/main/localDb/__tests__/migrationReplay.test.ts b/apps/desktop/src/main/localDb/__tests__/migrationReplay.test.ts
index c0edfab93a..e3cf320e3b 100644
--- a/apps/desktop/src/main/localDb/__tests__/migrationReplay.test.ts
+++ b/apps/desktop/src/main/localDb/__tests__/migrationReplay.test.ts
@@ -108,7 +108,12 @@ describeMigrationReplay('migration replay', () => {
.prepare(
`SELECT name FROM sqlite_master
WHERE type='index'
- AND name IN ('uniq_active_team_per_lead', 'uniq_orca_workers_focused_per_team')
+ AND name IN (
+ 'uniq_active_team_per_lead',
+ 'uniq_orca_workers_focused_per_team',
+ 'uniq_wechat_inbox_running_session',
+ 'uniq_wechat_sync_active'
+ )
ORDER BY name`,
)
.pluck()
@@ -122,7 +127,13 @@ describeMigrationReplay('migration replay', () => {
expect(partialIndexes).toEqual([
'uniq_active_team_per_lead',
'uniq_orca_workers_focused_per_team',
+ 'uniq_wechat_inbox_running_session',
+ 'uniq_wechat_sync_active',
]);
+ expect(tableExists(db, 'wechat_sync_state')).toBe(true);
+ expect(tableExists(db, 'wechat_inbox')).toBe(true);
+ expect(tableExists(db, 'wechat_outbox')).toBe(true);
+ expect(tableExists(db, 'wechat_file_attachments')).toBe(true);
} finally {
cleanup();
}
diff --git a/apps/desktop/src/main/localDb/client/tx/types.ts b/apps/desktop/src/main/localDb/client/tx/types.ts
index 712ebd0ece..df188c02ba 100644
--- a/apps/desktop/src/main/localDb/client/tx/types.ts
+++ b/apps/desktop/src/main/localDb/client/tx/types.ts
@@ -20,6 +20,23 @@ export type DbTxName =
| 'message.delete'
| 'im.deleteBindings'
| 'im.replaceBinding'
+ | 'wechatActivateBindingEpoch'
+ | 'wechatCommitPollBatch'
+ | 'wechatLeaseNextTask'
+ | 'wechatReleaseDispatch'
+ | 'wechatMarkAccepted'
+ | 'wechatSetWaitingDesktop'
+ | 'wechatCommitPreDispatchFailure'
+ | 'wechatCancelForCommand'
+ | 'wechatCommitInterrupted'
+ | 'wechatCommitTerminal'
+ | 'wechatMarkOutboxDelivered'
+ | 'wechatRecordOutboxFailure'
+ | 'wechatStopAll'
+ | 'wechatCloseBindingEpoch'
+ | 'wechatPromoteTaskAttachments'
+ | 'wechatRefreshOutboxContexts'
+ | 'wechatUnbindCleanup'
| 'session.importShare';
export interface CodexImportMessagesArgs {
@@ -181,7 +198,10 @@ export interface OrcaReserveWorkerCreationArgs {
export type OrcaReserveWorkerCreationResult =
| { ok: true; occupiedSlotsBefore: number }
- | { ok: false; errorCode: 'DUPLICATE_LABEL' | 'WORKER_CREATION_IN_PROGRESS' | 'WORKER_LIMIT_HARD_EXCEEDED' };
+ | {
+ ok: false;
+ errorCode: 'DUPLICATE_LABEL' | 'WORKER_CREATION_IN_PROGRESS' | 'WORKER_LIMIT_HARD_EXCEEDED';
+ };
export interface OrcaReleaseWorkerCreationReservationArgs {
reservationId: string;
@@ -356,6 +376,285 @@ export interface ImDeleteBindingsArgs {
}>;
}
+export type WechatInboxStatus =
+ | 'pending'
+ | 'dispatching'
+ | 'accepted_running'
+ | 'waiting_desktop'
+ | 'delivery_pending'
+ | 'completed'
+ | 'interrupted'
+ | 'cancelled'
+ | 'expired'
+ | 'failed_terminal'
+ | 'rejected_overload';
+
+export type WechatOutboxKind = 'final' | 'error' | 'interrupted' | 'overload';
+
+export interface WechatEncryptedContext {
+ nonce: string;
+ ciphertext: string;
+ tag: string;
+}
+
+export interface WechatActivateBindingEpochArgs {
+ bindingEpoch: string;
+ expectedActiveEpoch: string | null;
+ initialCursor: string;
+ now: number;
+}
+
+export interface WechatActivateBindingEpochResult {
+ activated: boolean;
+ previousActiveEpoch: string | null;
+ activeBindingEpoch: string | null;
+}
+
+export interface WechatPollInboxInput {
+ id: string;
+ platformMessageId: string;
+ platformSeq: number;
+ peerId: string;
+ receivedAt: number;
+ platformCreatedAt: number;
+ expiresAt: number;
+ sessionId: string;
+ conversationEpoch: number;
+ payloadJson: string;
+ context: WechatEncryptedContext;
+ overloadReply?: {
+ outboxId: string;
+ clientId: string;
+ text: string;
+ };
+}
+
+export interface WechatPollMediaBlobInput {
+ hash: string;
+ ext: string;
+ mimeType: string;
+ bytes: number;
+ isCache: boolean;
+ createdAt: number;
+ lastAccessAt: number;
+}
+
+export interface WechatPollMediaRefInput {
+ id: string;
+ hash: string;
+ taskId: string;
+ label: string | null;
+ createdAt: number;
+}
+
+export interface WechatPollFileAttachmentInput {
+ id: string;
+ taskId: string;
+ sessionId: string;
+ absPath: string;
+ originalName: string;
+ mimeType: string;
+ bytes: number;
+ createdAt: number;
+}
+
+export interface WechatCommitPollBatchArgs {
+ bindingEpoch: string;
+ expectedCursor: string;
+ nextCursor: string;
+ now: number;
+ messages: WechatPollInboxInput[];
+ mediaBlobs: WechatPollMediaBlobInput[];
+ mediaRefs: WechatPollMediaRefInput[];
+ fileAttachments: WechatPollFileAttachmentInput[];
+ maxQueuedTasks?: number;
+}
+
+export type WechatCommitPollBatchResult =
+ | {
+ committed: true;
+ insertedTaskIds: string[];
+ duplicateTaskIds: string[];
+ rejectedTaskIds: string[];
+ }
+ | {
+ committed: false;
+ reason: 'stale-epoch' | 'stale-cursor';
+ activeBindingEpoch: string | null;
+ currentCursor: string | null;
+ };
+
+export interface WechatLeaseNextTaskArgs {
+ bindingEpoch: string;
+ now: number;
+ leaseUntil: number;
+}
+
+export interface WechatLeasedTask {
+ id: string;
+ bindingEpoch: string;
+ peerId: string;
+ sessionId: string;
+ conversationEpoch: number;
+ payloadJson: string;
+ context: WechatEncryptedContext;
+ attempts: number;
+ receivedAt: number;
+ expiresAt: number;
+}
+
+export interface WechatMarkAcceptedArgs {
+ bindingEpoch: string;
+ taskId: string;
+}
+
+export interface WechatReleaseDispatchArgs {
+ bindingEpoch: string;
+ taskId: string;
+}
+
+export interface WechatSetWaitingDesktopArgs {
+ bindingEpoch: string;
+ taskId: string;
+ waiting: boolean;
+}
+
+export interface WechatOutboxChunkInput {
+ id: string;
+ clientId: string;
+ kind: WechatOutboxKind;
+ chunkIndex: number;
+ text: string;
+ mediaJson?: string;
+}
+
+export interface WechatCommitInterruptedArgs {
+ bindingEpoch: string;
+ taskId: string;
+ now: number;
+ errorCode: string;
+ outbox?: WechatOutboxChunkInput[];
+ context?: WechatEncryptedContext;
+}
+
+export interface WechatCommitPreDispatchFailureArgs {
+ bindingEpoch: string;
+ taskId: string;
+ now: number;
+ errorCode: string;
+ outbox: WechatOutboxChunkInput[];
+}
+
+export interface WechatCancelForCommandArgs {
+ bindingEpoch: string;
+ commandTaskId: string;
+ peerId?: string;
+ now: number;
+}
+
+export interface WechatCancelForCommandResult {
+ cancelled: number;
+ interrupted: number;
+}
+
+export interface WechatCommitTerminalArgs {
+ bindingEpoch: string;
+ taskId: string;
+ now: number;
+ outbox: WechatOutboxChunkInput[];
+}
+
+export interface WechatCommitTerminalResult {
+ committed: boolean;
+ alreadyCommitted: boolean;
+}
+
+export interface WechatMarkOutboxDeliveredArgs {
+ bindingEpoch: string;
+ outboxId: string;
+ deliveredAt: number;
+}
+
+export interface WechatMarkOutboxDeliveredResult {
+ changed: boolean;
+ taskId: string | null;
+ taskCompleted: boolean;
+}
+
+export interface WechatRecordOutboxFailureArgs {
+ bindingEpoch: string;
+ outboxId: string;
+ nextRetryAt: number;
+ terminal: boolean;
+ errorCode: string;
+}
+
+export interface WechatRecordOutboxFailureResult {
+ changed: boolean;
+ taskId: string | null;
+ taskFailed: boolean;
+}
+
+export interface WechatStopAllArgs {
+ bindingEpoch: string;
+ now: number;
+ errorCode: string;
+}
+
+export interface WechatStopAllResult {
+ requeued: number;
+ interrupted: number;
+ expired: number;
+ repaired: number;
+}
+
+export interface WechatCloseBindingEpochArgs {
+ bindingEpoch: string;
+ now: number;
+}
+
+export interface WechatCloseBindingEpochResult {
+ closed: boolean;
+}
+
+export interface WechatPromoteTaskAttachmentsArgs {
+ bindingEpoch: string;
+ taskId: string;
+ sessionId: string;
+ now: number;
+}
+
+export interface WechatPromoteTaskAttachmentsResult {
+ eligible: boolean;
+ promotedMediaRefs: number;
+ promotedFiles: number;
+}
+
+export interface WechatRefreshOutboxContextsArgs {
+ bindingEpoch: string;
+ peerId: string;
+ now: number;
+ contexts: Array<{
+ taskId: string;
+ context: WechatEncryptedContext;
+ }>;
+}
+
+export interface WechatRefreshOutboxContextsResult {
+ refreshedTasks: number;
+ outboxWoken: number;
+}
+
+export interface WechatUnbindCleanupArgs {
+ bindingEpoch: string;
+}
+
+export interface WechatUnbindCleanupResult {
+ deletedTasks: number;
+ deletedMediaRefs: number;
+ filePaths: string[];
+}
+
export type DbTxArgsByName = {
'codex.importMessages': CodexImportMessagesArgs;
'claude.importMessages': ClaudeImportMessagesArgs;
@@ -378,6 +677,23 @@ export type DbTxArgsByName = {
'message.delete': MessageDeleteArgs;
'im.deleteBindings': ImDeleteBindingsArgs;
'im.replaceBinding': ImReplaceBindingArgs;
+ wechatActivateBindingEpoch: WechatActivateBindingEpochArgs;
+ wechatCommitPollBatch: WechatCommitPollBatchArgs;
+ wechatLeaseNextTask: WechatLeaseNextTaskArgs;
+ wechatReleaseDispatch: WechatReleaseDispatchArgs;
+ wechatMarkAccepted: WechatMarkAcceptedArgs;
+ wechatSetWaitingDesktop: WechatSetWaitingDesktopArgs;
+ wechatCommitPreDispatchFailure: WechatCommitPreDispatchFailureArgs;
+ wechatCancelForCommand: WechatCancelForCommandArgs;
+ wechatCommitInterrupted: WechatCommitInterruptedArgs;
+ wechatCommitTerminal: WechatCommitTerminalArgs;
+ wechatMarkOutboxDelivered: WechatMarkOutboxDeliveredArgs;
+ wechatRecordOutboxFailure: WechatRecordOutboxFailureArgs;
+ wechatStopAll: WechatStopAllArgs;
+ wechatCloseBindingEpoch: WechatCloseBindingEpochArgs;
+ wechatPromoteTaskAttachments: WechatPromoteTaskAttachmentsArgs;
+ wechatRefreshOutboxContexts: WechatRefreshOutboxContextsArgs;
+ wechatUnbindCleanup: WechatUnbindCleanupArgs;
'session.importShare': SessionImportShareArgs;
};
@@ -403,5 +719,22 @@ export type DbTxResultByName = {
'message.delete': MessageDeleteResult;
'im.deleteBindings': undefined;
'im.replaceBinding': undefined;
+ wechatActivateBindingEpoch: WechatActivateBindingEpochResult;
+ wechatCommitPollBatch: WechatCommitPollBatchResult;
+ wechatLeaseNextTask: WechatLeasedTask | null;
+ wechatReleaseDispatch: boolean;
+ wechatMarkAccepted: boolean;
+ wechatSetWaitingDesktop: boolean;
+ wechatCommitPreDispatchFailure: boolean;
+ wechatCancelForCommand: WechatCancelForCommandResult;
+ wechatCommitInterrupted: boolean;
+ wechatCommitTerminal: WechatCommitTerminalResult;
+ wechatMarkOutboxDelivered: WechatMarkOutboxDeliveredResult;
+ wechatRecordOutboxFailure: WechatRecordOutboxFailureResult;
+ wechatStopAll: WechatStopAllResult;
+ wechatCloseBindingEpoch: WechatCloseBindingEpochResult;
+ wechatPromoteTaskAttachments: WechatPromoteTaskAttachmentsResult;
+ wechatRefreshOutboxContexts: WechatRefreshOutboxContextsResult;
+ wechatUnbindCleanup: WechatUnbindCleanupResult;
'session.importShare': { messageCount: number };
};
diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.ts
index 2b75f46dfc..1a314f2bbe 100644
--- a/apps/desktop/src/main/localDb/ipc/sessions.ts
+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts
@@ -28,6 +28,7 @@ import { ensureProjectGitInitialized } from '../../git-snapshot/projectGitBootst
import { readGitSafetySettings } from '../../maker-host/git-safety-settings-store';
import * as imageCacheStore from '../../imageCacheStore';
import { removeSessionRefs as removeSessionMediaRefs } from '../../cindy-media/ledger';
+import { removeWechatSessionAttachmentDir } from '../../im/wechat/mediaStaging';
import { upsertRecentWorkdir } from './recentWorkdirs';
import { createLogger } from '../../logger';
import { DESKTOP_VISIBLE_SESSION_SOURCES } from '../../../shared/sessionSource.js';
@@ -1110,6 +1111,12 @@ export async function patchSessionMetaInDb(
err: err instanceof Error ? err.message : String(err),
});
});
+ void removeWechatSessionAttachmentDir(sessionId).catch((err) => {
+ log.warn('WeChat session attachment cleanup failed', {
+ sessionId,
+ err: err instanceof Error ? err.message : String(err),
+ });
+ });
}
removeHookAttachmentDir(sessionId, patch.status);
scheduleWorktreeRecycleForStatusChange(sessionId, patch.status);
diff --git a/apps/desktop/src/main/localDb/schema.ts b/apps/desktop/src/main/localDb/schema.ts
index e4d263b026..3ee58d42e5 100644
--- a/apps/desktop/src/main/localDb/schema.ts
+++ b/apps/desktop/src/main/localDb/schema.ts
@@ -26,6 +26,7 @@ const SESSION_SOURCES = [
'slack',
'telegram',
'discord',
+ 'wechat',
'scheduler',
'learn',
'shared',
@@ -512,6 +513,148 @@ export const imBindings = sqliteTable(
}),
);
+/**
+ * Personal WeChat reliable-ingress state.
+ *
+ * Credentials never enter SQLite. The binding epoch is an opaque generation id
+ * that lets late poll/pump callbacks fail closed after reconnect or unbind.
+ */
+export const wechatSyncState = sqliteTable(
+ 'wechat_sync_state',
+ {
+ bindingEpoch: text('binding_epoch').primaryKey(),
+ isActive: integer('is_active', { mode: 'boolean' }).notNull().default(false),
+ syncCursor: text('sync_cursor').notNull().default(''),
+ lastPollAt: integer('last_poll_at'),
+ lastErrorCode: text('last_error_code'),
+ updatedAt: integer('updated_at').notNull(),
+ },
+ (t) => ({
+ oneActiveEpoch: uniqueIndex('uniq_wechat_sync_active')
+ .on(t.isActive)
+ .where(sql`${t.isActive} = 1`),
+ }),
+);
+
+export const wechatInbox = sqliteTable(
+ 'wechat_inbox',
+ {
+ id: text('id').primaryKey(),
+ bindingEpoch: text('binding_epoch')
+ .notNull()
+ .references(() => wechatSyncState.bindingEpoch, { onDelete: 'cascade' }),
+ platformMessageId: text('platform_message_id').notNull(),
+ platformSeq: integer('platform_seq').notNull(),
+ peerId: text('peer_id').notNull(),
+ receivedAt: integer('received_at').notNull(),
+ platformCreatedAt: integer('platform_created_at').notNull(),
+ expiresAt: integer('expires_at').notNull(),
+ status: text('status', {
+ enum: [
+ 'pending',
+ 'dispatching',
+ 'accepted_running',
+ 'waiting_desktop',
+ 'delivery_pending',
+ 'completed',
+ 'interrupted',
+ 'cancelled',
+ 'expired',
+ 'failed_terminal',
+ 'rejected_overload',
+ ],
+ })
+ .notNull()
+ .default('pending'),
+ leaseUntil: integer('lease_until'),
+ sessionId: text('session_id').references(() => sessions.id, { onDelete: 'set null' }),
+ conversationEpoch: integer('conversation_epoch').notNull().default(0),
+ payloadJson: text('payload_json').notNull(),
+ /** AES-256-GCM fields. The data key is owner-scoped and kept in safeStorage. */
+ contextNonce: text('context_nonce').notNull(),
+ contextCiphertext: text('context_ciphertext').notNull(),
+ contextTag: text('context_tag').notNull(),
+ attempts: integer('attempts').notNull().default(0),
+ lastErrorCode: text('last_error_code'),
+ },
+ (t) => ({
+ platformMessage: uniqueIndex('uniq_wechat_inbox_platform_message').on(
+ t.bindingEpoch,
+ t.platformMessageId,
+ ),
+ byQueue: index('idx_wechat_inbox_queue').on(t.bindingEpoch, t.status, t.receivedAt),
+ byLease: index('idx_wechat_inbox_lease').on(t.bindingEpoch, t.leaseUntil),
+ byConversation: index('idx_wechat_inbox_conversation').on(
+ t.bindingEpoch,
+ t.peerId,
+ t.conversationEpoch,
+ ),
+ oneRunningPerSession: uniqueIndex('uniq_wechat_inbox_running_session')
+ .on(t.bindingEpoch, t.sessionId)
+ .where(
+ sql`${t.sessionId} IS NOT NULL AND ${t.status} IN ('dispatching', 'accepted_running', 'waiting_desktop', 'delivery_pending')`,
+ ),
+ }),
+);
+
+export const wechatOutbox = sqliteTable(
+ 'wechat_outbox',
+ {
+ id: text('id').primaryKey(),
+ bindingEpoch: text('binding_epoch')
+ .notNull()
+ .references(() => wechatSyncState.bindingEpoch, { onDelete: 'cascade' }),
+ taskId: text('task_id')
+ .notNull()
+ .references(() => wechatInbox.id, { onDelete: 'cascade' }),
+ clientId: text('client_id').notNull(),
+ kind: text('kind', { enum: ['final', 'error', 'interrupted', 'overload'] }).notNull(),
+ chunkIndex: integer('chunk_index').notNull(),
+ text: text('text').notNull(),
+ mediaJson: text('media_json').notNull().default('[]'),
+ status: text('status', {
+ enum: ['pending', 'sending', 'delivered', 'failed_terminal'],
+ })
+ .notNull()
+ .default('pending'),
+ attempts: integer('attempts').notNull().default(0),
+ nextRetryAt: integer('next_retry_at').notNull(),
+ createdAt: integer('created_at').notNull(),
+ deliveredAt: integer('delivered_at'),
+ },
+ (t) => ({
+ clientId: uniqueIndex('uniq_wechat_outbox_client_id').on(t.bindingEpoch, t.clientId),
+ byDelivery: index('idx_wechat_outbox_delivery').on(t.bindingEpoch, t.status, t.nextRetryAt),
+ byTask: index('idx_wechat_outbox_task').on(t.bindingEpoch, t.taskId, t.chunkIndex),
+ }),
+);
+
+export const wechatFileAttachments = sqliteTable(
+ 'wechat_file_attachments',
+ {
+ id: text('id').primaryKey(),
+ bindingEpoch: text('binding_epoch')
+ .notNull()
+ .references(() => wechatSyncState.bindingEpoch, { onDelete: 'cascade' }),
+ taskId: text('task_id')
+ .notNull()
+ .references(() => wechatInbox.id, { onDelete: 'cascade' }),
+ sessionId: text('session_id').references(() => sessions.id, { onDelete: 'set null' }),
+ absPath: text('abs_path').notNull(),
+ originalName: text('original_name').notNull(),
+ mimeType: text('mime_type').notNull(),
+ bytes: integer('bytes').notNull(),
+ status: text('status', { enum: ['staged', 'promoted', 'released'] })
+ .notNull()
+ .default('staged'),
+ promotedAt: integer('promoted_at'),
+ createdAt: integer('created_at').notNull(),
+ },
+ (t) => ({
+ byTask: index('idx_wechat_file_attachments_task').on(t.bindingEpoch, t.taskId),
+ }),
+);
+
/**
* scheduler 模块 (Phase 2): cron 定时任务表。
*
diff --git a/apps/desktop/src/main/localDb/worker/opHandlers/__tests__/wechatTx.test.ts b/apps/desktop/src/main/localDb/worker/opHandlers/__tests__/wechatTx.test.ts
new file mode 100644
index 0000000000..76bcf65e35
--- /dev/null
+++ b/apps/desktop/src/main/localDb/worker/opHandlers/__tests__/wechatTx.test.ts
@@ -0,0 +1,845 @@
+import { readFileSync } from 'node:fs';
+import path from 'node:path';
+
+import Database from 'better-sqlite3';
+import { afterEach, describe, expect, it } from 'vitest';
+
+import { tx } from '../tx.js';
+
+const HASH = 'a'.repeat(64);
+const CONTEXT = {
+ nonce: Buffer.alloc(12, 1).toString('base64'),
+ ciphertext: Buffer.from('encrypted-context').toString('base64'),
+ tag: Buffer.alloc(16, 2).toString('base64'),
+};
+
+const databases: Database.Database[] = [];
+
+afterEach(() => {
+ for (const db of databases.splice(0)) db.close();
+});
+
+describe('WeChat reliable worker transactions', () => {
+ it('uses binding epoch and cursor CAS to reject stale callbacks', () => {
+ const db = createDb();
+
+ expect(activate(db, 'epoch-1', null)).toEqual({
+ activated: true,
+ previousActiveEpoch: null,
+ activeBindingEpoch: 'epoch-1',
+ });
+ expect(activate(db, 'epoch-2', null)).toEqual({
+ activated: false,
+ previousActiveEpoch: 'epoch-1',
+ activeBindingEpoch: 'epoch-1',
+ });
+ expect(activate(db, 'epoch-2', 'epoch-1')).toEqual({
+ activated: true,
+ previousActiveEpoch: 'epoch-1',
+ activeBindingEpoch: 'epoch-2',
+ });
+ expect(
+ runTx(db, 'wechatCloseBindingEpoch', {
+ bindingEpoch: 'epoch-1',
+ now: 101,
+ }),
+ ).toEqual({ closed: true });
+
+ expect(
+ commitBatch(db, {
+ bindingEpoch: 'epoch-1',
+ expectedCursor: '',
+ nextCursor: 'stale',
+ messages: [message('stale-task', 'stale-platform', 'session-1')],
+ }),
+ ).toEqual({
+ committed: false,
+ reason: 'stale-epoch',
+ activeBindingEpoch: 'epoch-2',
+ currentCursor: '',
+ });
+ expect(count(db, 'wechat_inbox')).toBe(0);
+ });
+
+ it('commits inbox, media ledger, overload reply and cursor atomically', () => {
+ const db = createDb();
+ activate(db, 'epoch-1', null);
+
+ const result = commitBatch(db, {
+ bindingEpoch: 'epoch-1',
+ expectedCursor: '',
+ nextCursor: 'cursor-1',
+ maxQueuedTasks: 1,
+ messages: [
+ message('task-1', 'platform-1', 'session-1'),
+ {
+ ...message('task-2', 'platform-2', 'session-2'),
+ overloadReply: {
+ outboxId: 'outbox-overload-2',
+ clientId: 'overload-2',
+ text: '系统繁忙,请稍后再试。',
+ },
+ },
+ ],
+ mediaBlobs: [
+ {
+ hash: HASH,
+ ext: '.png',
+ mimeType: 'image/png',
+ bytes: 4,
+ isCache: true,
+ createdAt: 100,
+ lastAccessAt: 100,
+ },
+ ],
+ mediaRefs: [
+ {
+ id: 'media-ref-1',
+ hash: HASH,
+ taskId: 'task-1',
+ label: 'image',
+ createdAt: 100,
+ },
+ ],
+ });
+
+ expect(result).toEqual({
+ committed: true,
+ insertedTaskIds: ['task-1', 'task-2'],
+ duplicateTaskIds: [],
+ rejectedTaskIds: ['task-2'],
+ });
+ expect(
+ db
+ .prepare('SELECT id, status FROM wechat_inbox WHERE binding_epoch = ? ORDER BY id')
+ .all('epoch-1'),
+ ).toEqual([
+ { id: 'task-1', status: 'pending' },
+ { id: 'task-2', status: 'rejected_overload' },
+ ]);
+ expect(
+ db
+ .prepare('SELECT sync_cursor AS cursor FROM wechat_sync_state WHERE binding_epoch = ?')
+ .get('epoch-1'),
+ ).toEqual({ cursor: 'cursor-1' });
+ expect(count(db, 'media_blobs')).toBe(1);
+ expect(count(db, 'media_refs')).toBe(1);
+ expect(
+ db.prepare('SELECT task_id AS taskId, kind, status FROM wechat_outbox ORDER BY id').all(),
+ ).toEqual([{ taskId: 'task-2', kind: 'overload', status: 'pending' }]);
+
+ expect(
+ commitBatch(db, {
+ bindingEpoch: 'epoch-1',
+ expectedCursor: 'cursor-1',
+ nextCursor: 'cursor-2',
+ messages: [message('different-local-id', 'platform-1', 'session-1')],
+ }),
+ ).toEqual({
+ committed: true,
+ insertedTaskIds: [],
+ duplicateTaskIds: ['task-1'],
+ rejectedTaskIds: [],
+ });
+ expect(count(db, 'wechat_inbox')).toBe(2);
+ });
+
+ it('keeps stop commands pending when the normal inbox queue is full', () => {
+ const db = createDb();
+ activate(db, 'epoch-1', null);
+
+ expect(
+ commitBatch(db, {
+ maxQueuedTasks: 1,
+ nextCursor: 'cursor-1',
+ messages: [message('seed-task', 'platform-seed', 'session-1')],
+ }),
+ ).toMatchObject({ committed: true });
+
+ const result = commitBatch(db, {
+ expectedCursor: 'cursor-1',
+ nextCursor: 'cursor-2',
+ maxQueuedTasks: 1,
+ messages: [
+ {
+ ...message('stop-task', 'platform-stop', 'session-1'),
+ payloadJson: JSON.stringify({ text: '/stop' }),
+ },
+ {
+ ...message('stop-all-task', 'platform-stop-all', 'session-2'),
+ payloadJson: JSON.stringify({ text: '/stop all' }),
+ },
+ {
+ ...message('normal-task', 'platform-normal', 'session-2'),
+ overloadReply: {
+ outboxId: 'outbox-overload-normal',
+ clientId: 'overload-normal',
+ text: 'overloaded',
+ },
+ },
+ ],
+ });
+
+ expect(result).toEqual({
+ committed: true,
+ insertedTaskIds: ['stop-task', 'stop-all-task', 'normal-task'],
+ duplicateTaskIds: [],
+ rejectedTaskIds: ['normal-task'],
+ });
+ expect(db.prepare('SELECT id, status FROM wechat_inbox ORDER BY id').all()).toEqual([
+ { id: 'normal-task', status: 'rejected_overload' },
+ { id: 'seed-task', status: 'pending' },
+ { id: 'stop-all-task', status: 'pending' },
+ { id: 'stop-task', status: 'pending' },
+ ]);
+ });
+
+ it('rolls back the whole poll batch when media accounting is invalid', () => {
+ const db = createDb();
+ activate(db, 'epoch-1', null);
+
+ expect(() =>
+ commitBatch(db, {
+ bindingEpoch: 'epoch-1',
+ expectedCursor: '',
+ nextCursor: 'must-not-commit',
+ messages: [message('task-1', 'platform-1', 'session-1')],
+ mediaRefs: [
+ {
+ id: 'missing-ref',
+ hash: HASH,
+ taskId: 'task-1',
+ label: null,
+ createdAt: 100,
+ },
+ ],
+ }),
+ ).toThrowError(/unknown hash/);
+ expect(count(db, 'wechat_inbox')).toBe(0);
+ expect(db.prepare('SELECT sync_cursor FROM wechat_sync_state').pluck().get()).toBe('');
+ });
+
+ it('promotes accepted task attachments to the session before terminal cleanup', () => {
+ const db = createDb();
+ activate(db, 'epoch-1', null);
+ commitBatch(db, {
+ bindingEpoch: 'epoch-1',
+ messages: [message('task-1', 'platform-1', 'session-1')],
+ mediaBlobs: [
+ {
+ hash: HASH,
+ ext: '.png',
+ mimeType: 'image/png',
+ bytes: 4,
+ isCache: false,
+ createdAt: 100,
+ lastAccessAt: 100,
+ },
+ ],
+ mediaRefs: [
+ {
+ id: 'media-ref-1',
+ hash: HASH,
+ taskId: 'task-1',
+ label: 'wechat-image.png',
+ createdAt: 100,
+ },
+ ],
+ fileAttachments: [
+ {
+ id: 'file-1',
+ taskId: 'task-1',
+ sessionId: 'session-1',
+ absPath: 'C:\\safe\\report.pdf',
+ originalName: 'report.pdf',
+ mimeType: 'application/pdf',
+ bytes: 4,
+ createdAt: 100,
+ },
+ ],
+ });
+ lease(db, 'epoch-1', 200);
+ expect(
+ runTx(db, 'wechatMarkAccepted', {
+ bindingEpoch: 'epoch-1',
+ taskId: 'task-1',
+ }),
+ ).toBe(true);
+
+ expect(
+ runTx(db, 'wechatPromoteTaskAttachments', {
+ bindingEpoch: 'epoch-1',
+ taskId: 'task-1',
+ sessionId: 'session-1',
+ now: 201,
+ }),
+ ).toEqual({
+ eligible: true,
+ promotedMediaRefs: 1,
+ promotedFiles: 1,
+ });
+ expect(db.prepare('SELECT ref_kind AS refKind, ref_id AS refId FROM media_refs').all()).toEqual(
+ [{ refKind: 'session-attachment', refId: 'session-1' }],
+ );
+ expect(
+ db.prepare('SELECT status, promoted_at AS promotedAt FROM wechat_file_attachments').get(),
+ ).toEqual({ status: 'promoted', promotedAt: 201 });
+ });
+
+ it('refreshes pending replies with a newer peer context token and wakes delivery', () => {
+ const db = createDb();
+ activate(db, 'epoch-1', null);
+ commitBatch(db, {
+ messages: [message('task-1', 'platform-1', 'session-1')],
+ });
+ lease(db, 'epoch-1', 200);
+ runTx(db, 'wechatMarkAccepted', {
+ bindingEpoch: 'epoch-1',
+ taskId: 'task-1',
+ });
+ runTx(db, 'wechatCommitTerminal', {
+ bindingEpoch: 'epoch-1',
+ taskId: 'task-1',
+ now: 201,
+ outbox: [outbox('outbox-1', 'client-1', 0, 'reply')],
+ });
+ db.prepare('UPDATE wechat_outbox SET next_retry_at = 9999').run();
+ const replacement = {
+ nonce: Buffer.alloc(12, 8).toString('base64'),
+ ciphertext: Buffer.from('replacement-context').toString('base64'),
+ tag: Buffer.alloc(16, 9).toString('base64'),
+ };
+
+ expect(
+ runTx(db, 'wechatRefreshOutboxContexts', {
+ bindingEpoch: 'epoch-1',
+ peerId: 'peer-session-1',
+ now: 202,
+ contexts: [{ taskId: 'task-1', context: replacement }],
+ }),
+ ).toEqual({ refreshedTasks: 1, outboxWoken: 1 });
+ expect(
+ db
+ .prepare(
+ `SELECT context_nonce AS nonce, context_ciphertext AS ciphertext,
+ context_tag AS tag
+ FROM wechat_inbox WHERE id = 'task-1'`,
+ )
+ .get(),
+ ).toEqual(replacement);
+ expect(db.prepare('SELECT next_retry_at FROM wechat_outbox').pluck().get()).toBe(202);
+ });
+
+ it('repairs accepted attachment ownership conservatively after a process restart', () => {
+ const db = createDb();
+ activate(db, 'epoch-1', null);
+ commitBatch(db, {
+ messages: [message('task-1', 'platform-1', 'session-1')],
+ mediaBlobs: [
+ {
+ hash: HASH,
+ ext: '.png',
+ mimeType: 'image/png',
+ bytes: 4,
+ isCache: false,
+ createdAt: 100,
+ lastAccessAt: 100,
+ },
+ ],
+ mediaRefs: [
+ {
+ id: 'media-ref-1',
+ hash: HASH,
+ taskId: 'task-1',
+ label: 'image',
+ createdAt: 100,
+ },
+ ],
+ });
+ lease(db, 'epoch-1', 200);
+ runTx(db, 'wechatMarkAccepted', {
+ bindingEpoch: 'epoch-1',
+ taskId: 'task-1',
+ });
+
+ runTx(db, 'wechatStopAll', {
+ bindingEpoch: 'epoch-1',
+ now: 201,
+ errorCode: 'PROCESS_RESTARTED',
+ });
+ expect(readTaskStatus(db, 'task-1')).toBe('interrupted');
+ expect(db.prepare('SELECT ref_kind AS refKind, ref_id AS refId FROM media_refs').all()).toEqual(
+ [{ refKind: 'session-attachment', refId: 'session-1' }],
+ );
+ });
+
+ it('replays only pre-accepted work and interrupts accepted work after recovery', () => {
+ const db = createDb();
+ activate(db, 'epoch-1', null);
+ commitBatch(db, {
+ bindingEpoch: 'epoch-1',
+ expectedCursor: '',
+ nextCursor: 'cursor-1',
+ messages: [message('task-1', 'platform-1', 'session-1')],
+ });
+
+ const firstLease = lease(db, 'epoch-1', 200);
+ expect(firstLease).toMatchObject({ id: 'task-1', attempts: 1 });
+ expect(
+ runTx(db, 'wechatStopAll', {
+ bindingEpoch: 'epoch-1',
+ now: 201,
+ errorCode: 'PROCESS_RESTARTED',
+ }),
+ ).toMatchObject({ requeued: 1, interrupted: 0 });
+
+ const secondLease = lease(db, 'epoch-1', 202);
+ expect(secondLease).toMatchObject({ id: 'task-1', attempts: 2 });
+ expect(
+ runTx(db, 'wechatMarkAccepted', {
+ bindingEpoch: 'epoch-1',
+ taskId: 'task-1',
+ }),
+ ).toBe(true);
+ expect(
+ runTx(db, 'wechatStopAll', {
+ bindingEpoch: 'epoch-1',
+ now: 203,
+ errorCode: 'PROCESS_RESTARTED',
+ }),
+ ).toMatchObject({ requeued: 0, interrupted: 1 });
+ expect(lease(db, 'epoch-1', 204)).toBeNull();
+ expect(readTaskStatus(db, 'task-1')).toBe('interrupted');
+ expect(
+ runTx(db, 'wechatCommitInterrupted', {
+ bindingEpoch: 'epoch-1',
+ taskId: 'task-1',
+ now: 205,
+ errorCode: 'PROCESS_RESTARTED',
+ context: {
+ nonce: Buffer.alloc(12, 3).toString('base64'),
+ ciphertext: Buffer.from('fresh-context').toString('base64'),
+ tag: Buffer.alloc(16, 4).toString('base64'),
+ },
+ outbox: [
+ {
+ ...outbox('interrupted-outbox', 'interrupted-client', 0, '任务已中断。'),
+ kind: 'interrupted',
+ },
+ ],
+ }),
+ ).toBe(true);
+ expect(readTaskStatus(db, 'task-1')).toBe('delivery_pending');
+ });
+
+ it('releases a busy pre-dispatch lease and persists Desktop-waiting state', () => {
+ const db = createDb();
+ activate(db, 'epoch-1', null);
+ commitBatch(db, {
+ bindingEpoch: 'epoch-1',
+ expectedCursor: '',
+ nextCursor: 'cursor-1',
+ messages: [message('task-1', 'platform-1', 'session-1')],
+ });
+
+ lease(db, 'epoch-1', 200);
+ expect(
+ runTx(db, 'wechatReleaseDispatch', {
+ bindingEpoch: 'epoch-1',
+ taskId: 'task-1',
+ }),
+ ).toBe(true);
+ expect(readTaskStatus(db, 'task-1')).toBe('pending');
+
+ lease(db, 'epoch-1', 201);
+ expect(
+ runTx(db, 'wechatMarkAccepted', {
+ bindingEpoch: 'epoch-1',
+ taskId: 'task-1',
+ }),
+ ).toBe(true);
+ expect(
+ runTx(db, 'wechatSetWaitingDesktop', {
+ bindingEpoch: 'epoch-1',
+ taskId: 'task-1',
+ waiting: true,
+ }),
+ ).toBe(true);
+ expect(readTaskStatus(db, 'task-1')).toBe('waiting_desktop');
+ expect(
+ runTx(db, 'wechatSetWaitingDesktop', {
+ bindingEpoch: 'epoch-1',
+ taskId: 'task-1',
+ waiting: false,
+ }),
+ ).toBe(true);
+ expect(readTaskStatus(db, 'task-1')).toBe('accepted_running');
+ });
+
+ it('commits a pre-dispatch rejection without crossing the accepted barrier', () => {
+ const db = createDb();
+ activate(db, 'epoch-1', null);
+ commitBatch(db, {
+ bindingEpoch: 'epoch-1',
+ expectedCursor: '',
+ nextCursor: 'cursor-1',
+ messages: [message('task-1', 'platform-1', 'session-1')],
+ });
+ lease(db, 'epoch-1', 200);
+
+ expect(
+ runTx(db, 'wechatCommitPreDispatchFailure', {
+ bindingEpoch: 'epoch-1',
+ taskId: 'task-1',
+ now: 201,
+ errorCode: 'UNSUPPORTED_PERMISSION_MODE',
+ outbox: [
+ {
+ ...outbox('outbox-error', 'client-error', 0, '请修改权限模式。'),
+ kind: 'error',
+ },
+ ],
+ }),
+ ).toBe(true);
+ expect(readTaskStatus(db, 'task-1')).toBe('delivery_pending');
+ expect(
+ db.prepare('SELECT kind, text FROM wechat_outbox WHERE task_id = ?').get('task-1'),
+ ).toEqual({ kind: 'error', text: '请修改权限模式。' });
+ });
+
+ it('lets a stop command interrupt its peer without consuming the command task', () => {
+ const db = createDb();
+ activate(db, 'epoch-1', null);
+ commitBatch(db, {
+ bindingEpoch: 'epoch-1',
+ expectedCursor: '',
+ nextCursor: 'cursor-1',
+ messages: [message('active-task', 'platform-1', 'session-1')],
+ });
+ expect(lease(db, 'epoch-1', 200)).toMatchObject({ id: 'active-task' });
+ runTx(db, 'wechatMarkAccepted', {
+ bindingEpoch: 'epoch-1',
+ taskId: 'active-task',
+ });
+ commitBatch(db, {
+ bindingEpoch: 'epoch-1',
+ expectedCursor: 'cursor-1',
+ nextCursor: 'cursor-2',
+ messages: [
+ {
+ ...message('stop-command', 'platform-2', 'session-1'),
+ payloadJson: JSON.stringify({ text: '/stop' }),
+ },
+ message('other-peer-task', 'platform-3', 'session-2'),
+ ],
+ });
+
+ expect(
+ runTx(db, 'wechatCancelForCommand', {
+ bindingEpoch: 'epoch-1',
+ commandTaskId: 'stop-command',
+ peerId: 'peer-session-1',
+ now: 201,
+ }),
+ ).toEqual({ cancelled: 0, interrupted: 1 });
+ expect(readTaskStatus(db, 'active-task')).toBe('interrupted');
+ expect(readTaskStatus(db, 'stop-command')).toBe('pending');
+ expect(readTaskStatus(db, 'other-peer-task')).toBe('pending');
+ expect(lease(db, 'epoch-1', 202)).toMatchObject({ id: 'stop-command' });
+ });
+
+ it('commits every final chunk before delivery_pending and completes after all deliveries', () => {
+ const db = createDb();
+ activate(db, 'epoch-1', null);
+ commitBatch(db, {
+ bindingEpoch: 'epoch-1',
+ expectedCursor: '',
+ nextCursor: 'cursor-1',
+ messages: [message('task-1', 'platform-1', 'session-1')],
+ mediaBlobs: [
+ {
+ hash: HASH,
+ ext: '.png',
+ mimeType: 'image/png',
+ bytes: 4,
+ isCache: true,
+ createdAt: 100,
+ lastAccessAt: 100,
+ },
+ ],
+ mediaRefs: [
+ {
+ id: 'media-ref-1',
+ hash: HASH,
+ taskId: 'task-1',
+ label: null,
+ createdAt: 100,
+ },
+ ],
+ });
+ lease(db, 'epoch-1', 200);
+ runTx(db, 'wechatMarkAccepted', {
+ bindingEpoch: 'epoch-1',
+ taskId: 'task-1',
+ });
+
+ expect(
+ runTx(db, 'wechatCommitTerminal', {
+ bindingEpoch: 'epoch-1',
+ taskId: 'task-1',
+ now: 300,
+ outbox: [
+ outbox('outbox-1', 'client-1', 0, 'part 1'),
+ outbox('outbox-2', 'client-2', 1, 'part 2'),
+ ],
+ }),
+ ).toEqual({ committed: true, alreadyCommitted: false });
+ expect(readTaskStatus(db, 'task-1')).toBe('delivery_pending');
+ expect(count(db, 'wechat_outbox')).toBe(2);
+
+ expect(
+ runTx(db, 'wechatMarkOutboxDelivered', {
+ bindingEpoch: 'epoch-1',
+ outboxId: 'outbox-1',
+ deliveredAt: 301,
+ }),
+ ).toEqual({ changed: true, taskId: 'task-1', taskCompleted: false });
+ expect(readTaskStatus(db, 'task-1')).toBe('delivery_pending');
+ expect(count(db, 'media_refs')).toBe(1);
+
+ expect(
+ runTx(db, 'wechatMarkOutboxDelivered', {
+ bindingEpoch: 'epoch-1',
+ outboxId: 'outbox-2',
+ deliveredAt: 302,
+ }),
+ ).toEqual({ changed: true, taskId: 'task-1', taskCompleted: true });
+ expect(readTaskStatus(db, 'task-1')).toBe('completed');
+ expect(count(db, 'media_refs')).toBe(0);
+ });
+
+ it('rolls back terminal outbox on a chunk conflict and repairs impossible delivery state', () => {
+ const db = createDb();
+ activate(db, 'epoch-1', null);
+ commitBatch(db, {
+ bindingEpoch: 'epoch-1',
+ expectedCursor: '',
+ nextCursor: 'cursor-1',
+ messages: [message('task-1', 'platform-1', 'session-1')],
+ });
+ lease(db, 'epoch-1', 200);
+ runTx(db, 'wechatMarkAccepted', {
+ bindingEpoch: 'epoch-1',
+ taskId: 'task-1',
+ });
+ db.prepare(
+ `INSERT INTO wechat_outbox
+ (id, binding_epoch, task_id, client_id, kind, chunk_index, text,
+ media_json, status, attempts, next_retry_at, created_at)
+ VALUES ('occupied', 'epoch-1', 'task-1', 'duplicate-client', 'final', 9,
+ 'occupied', '[]', 'delivered', 0, 0, 0)`,
+ ).run();
+
+ expect(() =>
+ runTx(db, 'wechatCommitTerminal', {
+ bindingEpoch: 'epoch-1',
+ taskId: 'task-1',
+ now: 300,
+ outbox: [
+ outbox('new-1', 'new-client', 0, 'part 1'),
+ outbox('new-2', 'duplicate-client', 1, 'part 2'),
+ ],
+ }),
+ ).toThrow();
+ expect(readTaskStatus(db, 'task-1')).toBe('accepted_running');
+ expect(
+ db.prepare("SELECT COUNT(*) FROM wechat_outbox WHERE id LIKE 'new-%'").pluck().get(),
+ ).toBe(0);
+
+ db.prepare("UPDATE wechat_inbox SET status = 'delivery_pending' WHERE id = 'task-1'").run();
+ db.prepare("DELETE FROM wechat_outbox WHERE task_id = 'task-1'").run();
+ expect(
+ runTx(db, 'wechatStopAll', {
+ bindingEpoch: 'epoch-1',
+ now: 400,
+ errorCode: 'PROCESS_RESTARTED',
+ }),
+ ).toMatchObject({ repaired: 1 });
+ expect(readTaskStatus(db, 'task-1')).toBe('interrupted');
+ });
+
+ it('retries transient outbox failures and terminates the task on permanent failure', () => {
+ const db = createDb();
+ activate(db, 'epoch-1', null);
+ commitBatch(db, {
+ bindingEpoch: 'epoch-1',
+ expectedCursor: '',
+ nextCursor: 'cursor-1',
+ messages: [message('task-1', 'platform-1', 'session-1')],
+ });
+ lease(db, 'epoch-1', 200);
+ runTx(db, 'wechatMarkAccepted', {
+ bindingEpoch: 'epoch-1',
+ taskId: 'task-1',
+ });
+ runTx(db, 'wechatCommitTerminal', {
+ bindingEpoch: 'epoch-1',
+ taskId: 'task-1',
+ now: 300,
+ outbox: [outbox('outbox-1', 'client-1', 0, 'result')],
+ });
+ db.prepare("UPDATE wechat_outbox SET status = 'sending' WHERE id = 'outbox-1'").run();
+
+ expect(
+ runTx(db, 'wechatRecordOutboxFailure', {
+ bindingEpoch: 'epoch-1',
+ outboxId: 'outbox-1',
+ nextRetryAt: 400,
+ terminal: false,
+ errorCode: 'NETWORK_TIMEOUT',
+ }),
+ ).toEqual({ changed: true, taskId: 'task-1', taskFailed: false });
+ expect(db.prepare("SELECT status FROM wechat_outbox WHERE id = 'outbox-1'").pluck().get()).toBe(
+ 'pending',
+ );
+ expect(readTaskStatus(db, 'task-1')).toBe('delivery_pending');
+
+ db.prepare("UPDATE wechat_outbox SET status = 'sending' WHERE id = 'outbox-1'").run();
+ expect(
+ runTx(db, 'wechatRecordOutboxFailure', {
+ bindingEpoch: 'epoch-1',
+ outboxId: 'outbox-1',
+ nextRetryAt: 500,
+ terminal: true,
+ errorCode: 'AUTH_REPLACED',
+ }),
+ ).toEqual({ changed: true, taskId: 'task-1', taskFailed: true });
+ expect(readTaskStatus(db, 'task-1')).toBe('failed_terminal');
+ });
+
+ it('closes an epoch before cleanup and cascades durable rows', () => {
+ const db = createDb();
+ activate(db, 'epoch-1', null);
+ commitBatch(db, {
+ bindingEpoch: 'epoch-1',
+ expectedCursor: '',
+ nextCursor: 'cursor-1',
+ messages: [message('task-1', 'platform-1', 'session-1')],
+ });
+
+ expect(() => runTx(db, 'wechatUnbindCleanup', { bindingEpoch: 'epoch-1' })).toThrowError(
+ /must be closed/,
+ );
+ expect(
+ runTx(db, 'wechatCloseBindingEpoch', {
+ bindingEpoch: 'epoch-1',
+ now: 200,
+ }),
+ ).toEqual({ closed: true });
+ expect(readTaskStatus(db, 'task-1')).toBe('cancelled');
+ expect(runTx(db, 'wechatUnbindCleanup', { bindingEpoch: 'epoch-1' })).toEqual({
+ deletedTasks: 1,
+ deletedMediaRefs: 0,
+ filePaths: [],
+ });
+ expect(count(db, 'wechat_sync_state')).toBe(0);
+ expect(count(db, 'wechat_inbox')).toBe(0);
+ });
+});
+
+function createDb(): Database.Database {
+ const db = new Database(':memory:');
+ databases.push(db);
+ db.pragma('foreign_keys = ON');
+ db.exec(`
+ CREATE TABLE sessions (id TEXT PRIMARY KEY NOT NULL);
+ CREATE TABLE media_blobs (
+ hash TEXT PRIMARY KEY NOT NULL,
+ ext TEXT NOT NULL,
+ mime_type TEXT NOT NULL,
+ bytes INTEGER NOT NULL,
+ is_cache INTEGER DEFAULT 0 NOT NULL,
+ created_at INTEGER NOT NULL,
+ last_access_at INTEGER NOT NULL
+ );
+ CREATE TABLE media_refs (
+ id TEXT PRIMARY KEY NOT NULL,
+ hash TEXT NOT NULL REFERENCES media_blobs(hash) ON DELETE CASCADE,
+ ref_kind TEXT NOT NULL,
+ ref_id TEXT NOT NULL,
+ origin_session_id TEXT,
+ origin_kind TEXT,
+ origin_id TEXT,
+ label TEXT,
+ created_at INTEGER NOT NULL
+ );
+ INSERT INTO sessions (id) VALUES ('session-1'), ('session-2');
+ `);
+ const migrationPath = path.resolve(__dirname, '../../../../../../drizzle/0082_daffy_calypso.sql');
+ db.exec(readFileSync(migrationPath, 'utf8').replaceAll('--> statement-breakpoint', ''));
+ return db;
+}
+
+function activate(db: Database.Database, bindingEpoch: string, expectedActiveEpoch: string | null) {
+ return runTx(db, 'wechatActivateBindingEpoch', {
+ bindingEpoch,
+ expectedActiveEpoch,
+ initialCursor: '',
+ now: 100,
+ });
+}
+
+function commitBatch(db: Database.Database, overrides: Record<string, unknown>) {
+ return runTx(db, 'wechatCommitPollBatch', {
+ bindingEpoch: 'epoch-1',
+ expectedCursor: '',
+ nextCursor: 'cursor-1',
+ now: 100,
+ messages: [],
+ mediaBlobs: [],
+ mediaRefs: [],
+ fileAttachments: [],
+ ...overrides,
+ });
+}
+
+function message(id: string, platformMessageId: string, sessionId: string) {
+ return {
+ id,
+ platformMessageId,
+ platformSeq: 1,
+ peerId: `peer-${sessionId}`,
+ receivedAt: 100,
+ platformCreatedAt: 99,
+ expiresAt: 1_800_100,
+ sessionId,
+ conversationEpoch: 0,
+ payloadJson: JSON.stringify({ text: id }),
+ context: CONTEXT,
+ };
+}
+
+function lease(db: Database.Database, bindingEpoch: string, now: number) {
+ return runTx(db, 'wechatLeaseNextTask', {
+ bindingEpoch,
+ now,
+ leaseUntil: now + 60_000,
+ });
+}
+
+function outbox(id: string, clientId: string, chunkIndex: number, text: string) {
+ return { id, clientId, kind: 'final', chunkIndex, text };
+}
+
+function runTx(db: Database.Database, name: string, args: Record<string, unknown>): unknown {
+ return tx(db, { name, args });
+}
+
+function count(db: Database.Database, table: string): number {
+ if (!/^[a-z_]+$/.test(table)) throw new Error('invalid test table');
+ return Number(db.prepare(`SELECT COUNT(*) FROM ${table}`).pluck().get());
+}
+
+function readTaskStatus(db: Database.Database, taskId: string): string {
+ return String(db.prepare('SELECT status FROM wechat_inbox WHERE id = ?').pluck().get(taskId));
+}
diff --git a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts
index 36bec8feac..e3aa175184 100644
--- a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts
+++ b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts
@@ -5,6 +5,25 @@ import type Database from 'better-sqlite3';
import type { DbTxName } from '../../client/tx/types.js';
import { normalizeWorkingDirForStorage } from '../../../../shared/workingDir.js';
+import {
+ wechatActivateBindingEpoch,
+ wechatCancelForCommand,
+ wechatCloseBindingEpoch,
+ wechatCommitInterrupted,
+ wechatCommitPreDispatchFailure,
+ wechatCommitPollBatch,
+ wechatCommitTerminal,
+ wechatLeaseNextTask,
+ wechatMarkAccepted,
+ wechatMarkOutboxDelivered,
+ wechatPromoteTaskAttachments,
+ wechatRefreshOutboxContexts,
+ wechatRecordOutboxFailure,
+ wechatReleaseDispatch,
+ wechatSetWaitingDesktop,
+ wechatStopAll,
+ wechatUnbindCleanup,
+} from './wechatTx.js';
const LOCAL_DUPLICATE_WINDOW_MS = 5 * 60 * 1000;
const MAX_ATTEMPTS = 5;
@@ -58,6 +77,40 @@ export function tx(db: Database.Database, args: unknown): unknown {
return imDeleteBindings(db, txArgs);
case 'im.replaceBinding':
return imReplaceBinding(db, txArgs);
+ case 'wechatActivateBindingEpoch':
+ return wechatActivateBindingEpoch(db, txArgs);
+ case 'wechatCommitPollBatch':
+ return wechatCommitPollBatch(db, txArgs);
+ case 'wechatLeaseNextTask':
+ return wechatLeaseNextTask(db, txArgs);
+ case 'wechatReleaseDispatch':
+ return wechatReleaseDispatch(db, txArgs);
+ case 'wechatMarkAccepted':
+ return wechatMarkAccepted(db, txArgs);
+ case 'wechatSetWaitingDesktop':
+ return wechatSetWaitingDesktop(db, txArgs);
+ case 'wechatCommitPreDispatchFailure':
+ return wechatCommitPreDispatchFailure(db, txArgs);
+ case 'wechatCancelForCommand':
+ return wechatCancelForCommand(db, txArgs);
+ case 'wechatCommitInterrupted':
+ return wechatCommitInterrupted(db, txArgs);
+ case 'wechatCommitTerminal':
+ return wechatCommitTerminal(db, txArgs);
+ case 'wechatMarkOutboxDelivered':
+ return wechatMarkOutboxDelivered(db, txArgs);
+ case 'wechatRecordOutboxFailure':
+ return wechatRecordOutboxFailure(db, txArgs);
+ case 'wechatStopAll':
+ return wechatStopAll(db, txArgs);
+ case 'wechatCloseBindingEpoch':
+ return wechatCloseBindingEpoch(db, txArgs);
+ case 'wechatPromoteTaskAttachments':
+ return wechatPromoteTaskAttachments(db, txArgs);
+ case 'wechatRefreshOutboxContexts':
+ return wechatRefreshOutboxContexts(db, txArgs);
+ case 'wechatUnbindCleanup':
+ return wechatUnbindCleanup(db, txArgs);
case 'session.importShare':
return sessionImportShare(db, txArgs);
default:
diff --git a/apps/desktop/src/main/localDb/worker/opHandlers/wechatTx.ts b/apps/desktop/src/main/localDb/worker/opHandlers/wechatTx.ts
new file mode 100644
index 0000000000..5e891fb2b6
--- /dev/null
+++ b/apps/desktop/src/main/localDb/worker/opHandlers/wechatTx.ts
@@ -0,0 +1,1373 @@
+import type Database from 'better-sqlite3';
+
+import type {
+ WechatActivateBindingEpochResult,
+ WechatCancelForCommandResult,
+ WechatCommitPollBatchResult,
+ WechatCommitTerminalResult,
+ WechatInboxStatus,
+ WechatLeasedTask,
+ WechatMarkOutboxDeliveredResult,
+ WechatOutboxChunkInput,
+ WechatPromoteTaskAttachmentsResult,
+ WechatRefreshOutboxContextsResult,
+ WechatRecordOutboxFailureResult,
+ WechatStopAllResult,
+ WechatUnbindCleanupResult,
+} from '../../client/tx/types.js';
+
+const DEFAULT_MAX_QUEUED_TASKS = 20;
+const MAX_POLL_MESSAGES = 100;
+const MAX_MEDIA_ITEMS = 1_000;
+const MAX_OUTBOX_CHUNKS = 100;
+const ACTIVE_QUEUE_STATUSES = [
+ 'pending',
+ 'dispatching',
+ 'accepted_running',
+ 'waiting_desktop',
+] as const;
+const CONTROL_COMMANDS = new Set(['/stop', '/stop all']);
+const RUNNING_STATUSES = [
+ 'dispatching',
+ 'accepted_running',
+ 'waiting_desktop',
+ 'delivery_pending',
+] as const;
+
+interface ActiveEpochRow {
+ bindingEpoch: string;
+ syncCursor: string;
+}
+
+interface InboxStatusRow {
+ status: WechatInboxStatus;
+}
+
+interface OutboxTaskRow {
+ taskId: string;
+ status: string;
+}
+
+export function wechatActivateBindingEpoch(
+ db: Database.Database,
+ args: unknown,
+): WechatActivateBindingEpochResult {
+ const payload = asRecord(args, 'wechatActivateBindingEpoch args');
+ const bindingEpoch = expectId(payload.bindingEpoch, 'bindingEpoch');
+ const expectedActiveEpoch = nullableId(payload.expectedActiveEpoch, 'expectedActiveEpoch');
+ const initialCursor = expectString(payload.initialCursor, 'initialCursor', 65_536);
+ const now = expectTimestamp(payload.now, 'now');
+
+ const transaction = db.transaction((): WechatActivateBindingEpochResult => {
+ const active = readActiveEpoch(db);
+ if ((active?.bindingEpoch ?? null) !== expectedActiveEpoch) {
+ return {
+ activated: false,
+ previousActiveEpoch: active?.bindingEpoch ?? null,
+ activeBindingEpoch: active?.bindingEpoch ?? null,
+ };
+ }
+
+ db.prepare(
+ 'UPDATE wechat_sync_state SET is_active = 0, updated_at = ? WHERE is_active = 1',
+ ).run(now);
+ db.prepare(
+ `INSERT INTO wechat_sync_state
+ (binding_epoch, is_active, sync_cursor, last_poll_at, last_error_code, updated_at)
+ VALUES (?, 1, ?, NULL, NULL, ?)
+ ON CONFLICT(binding_epoch) DO UPDATE SET
+ is_active = 1,
+ last_error_code = NULL,
+ updated_at = excluded.updated_at`,
+ ).run(bindingEpoch, initialCursor, now);
+
+ return {
+ activated: true,
+ previousActiveEpoch: active?.bindingEpoch ?? null,
+ activeBindingEpoch: bindingEpoch,
+ };
+ });
+ return transaction();
+}
+
+export function wechatCommitPollBatch(
+ db: Database.Database,
+ args: unknown,
+): WechatCommitPollBatchResult {
+ const payload = asRecord(args, 'wechatCommitPollBatch args');
+ const bindingEpoch = expectId(payload.bindingEpoch, 'bindingEpoch');
+ const expectedCursor = expectString(payload.expectedCursor, 'expectedCursor', 65_536);
+ const nextCursor = expectString(payload.nextCursor, 'nextCursor', 65_536);
+ const now = expectTimestamp(payload.now, 'now');
+ const messages = expectArray(payload.messages, 'messages');
+ const mediaBlobs = expectArray(payload.mediaBlobs, 'mediaBlobs');
+ const mediaRefs = expectArray(payload.mediaRefs, 'mediaRefs');
+ const fileAttachments = expectArray(payload.fileAttachments, 'fileAttachments');
+ const maxQueuedTasks =
+ payload.maxQueuedTasks === undefined
+ ? DEFAULT_MAX_QUEUED_TASKS
+ : expectInteger(payload.maxQueuedTasks, 'maxQueuedTasks', 1, 100);
+
+ enforceArrayLimit(messages, 'messages', MAX_POLL_MESSAGES);
+ enforceArrayLimit(mediaBlobs, 'mediaBlobs', MAX_MEDIA_ITEMS);
+ enforceArrayLimit(mediaRefs, 'mediaRefs', MAX_MEDIA_ITEMS);
+ enforceArrayLimit(fileAttachments, 'fileAttachments', MAX_MEDIA_ITEMS);
+
+ const transaction = db.transaction((): WechatCommitPollBatchResult => {
+ const active = readActiveEpoch(db);
+ if (active?.bindingEpoch !== bindingEpoch) {
+ return {
+ committed: false,
+ reason: 'stale-epoch',
+ activeBindingEpoch: active?.bindingEpoch ?? null,
+ currentCursor: active?.syncCursor ?? null,
+ };
+ }
+ if (active.syncCursor !== expectedCursor) {
+ return {
+ committed: false,
+ reason: 'stale-cursor',
+ activeBindingEpoch: active.bindingEpoch,
+ currentCursor: active.syncCursor,
+ };
+ }
+
+ let queuedTasks = Number(
+ db
+ .prepare(
+ `SELECT COUNT(*) FROM wechat_inbox
+ WHERE binding_epoch = ? AND status IN (${sqlPlaceholders(ACTIVE_QUEUE_STATUSES.length)})`,
+ )
+ .pluck()
+ .get(bindingEpoch, ...ACTIVE_QUEUE_STATUSES),
+ );
+ const insertedTaskIds: string[] = [];
+ const duplicateTaskIds: string[] = [];
+ const rejectedTaskIds: string[] = [];
+ const acceptedTaskIds = new Set<string>();
+ const insertInbox = db.prepare(
+ `INSERT OR IGNORE INTO wechat_inbox (
+ id, binding_epoch, platform_message_id, platform_seq, peer_id,
+ received_at, platform_created_at, expires_at, status, lease_until,
+ session_id, conversation_epoch, payload_json, context_nonce,
+ context_ciphertext, context_tag, attempts, last_error_code
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?, 0, NULL)`,
+ );
+ const findDuplicate = db.prepare(
+ `SELECT id FROM wechat_inbox
+ WHERE binding_epoch = ? AND platform_message_id = ?`,
+ );
+ const insertOutbox = prepareOutboxInsert(db);
+
+ for (let index = 0; index < messages.length; index += 1) {
+ const message = parsePollMessage(messages[index], index);
+ const isControlCommand = isWechatControlCommand(message.payloadJson);
+ const status: WechatInboxStatus =
+ queuedTasks >= maxQueuedTasks && !isControlCommand ? 'rejected_overload' : 'pending';
+ const result = insertInbox.run(
+ message.id,
+ bindingEpoch,
+ message.platformMessageId,
+ message.platformSeq,
+ message.peerId,
+ message.receivedAt,
+ message.platformCreatedAt,
+ message.expiresAt,
+ status,
+ message.sessionId,
+ message.conversationEpoch,
+ message.payloadJson,
+ message.context.nonce,
+ message.context.ciphertext,
+ message.context.tag,
+ );
+ if (result.changes === 0) {
+ const existing = findDuplicate.get(bindingEpoch, message.platformMessageId) as
+ { id: string } | undefined;
+ if (!existing) throw invariantViolation('inbox dedupe row disappeared');
+ duplicateTaskIds.push(existing.id);
+ continue;
+ }
+
+ insertedTaskIds.push(message.id);
+ if (status === 'pending') {
+ queuedTasks += 1;
+ acceptedTaskIds.add(message.id);
+ continue;
+ }
+
+ rejectedTaskIds.push(message.id);
+ if (!message.overloadReply) {
+ throw invalidArgs(`messages.${index}.overloadReply is required when queue is full`);
+ }
+ insertOutboxChunk(
+ insertOutbox,
+ bindingEpoch,
+ message.id,
+ {
+ id: message.overloadReply.outboxId,
+ clientId: message.overloadReply.clientId,
+ kind: 'overload',
+ chunkIndex: 0,
+ text: message.overloadReply.text,
+ },
+ now,
+ );
+ }
+
+ commitMediaBlobs(db, mediaBlobs, mediaRefs, acceptedTaskIds);
+ commitMediaRefs(db, mediaRefs, acceptedTaskIds);
+ commitFileAttachments(db, fileAttachments, acceptedTaskIds, bindingEpoch);
+
+ const cursorResult = db
+ .prepare(
+ `UPDATE wechat_sync_state
+ SET sync_cursor = ?, last_poll_at = ?, last_error_code = NULL, updated_at = ?
+ WHERE binding_epoch = ? AND is_active = 1 AND sync_cursor = ?`,
+ )
+ .run(nextCursor, now, now, bindingEpoch, expectedCursor);
+ if (cursorResult.changes !== 1) {
+ throw invariantViolation('active WeChat cursor changed inside poll transaction');
+ }
+
+ return {
+ committed: true,
+ insertedTaskIds,
+ duplicateTaskIds,
+ rejectedTaskIds,
+ };
+ });
+ return transaction();
+}
+
+export function wechatLeaseNextTask(db: Database.Database, args: unknown): WechatLeasedTask | null {
+ const payload = asRecord(args, 'wechatLeaseNextTask args');
+ const bindingEpoch = expectId(payload.bindingEpoch, 'bindingEpoch');
+ const now = expectTimestamp(payload.now, 'now');
+ const leaseUntil = expectTimestamp(payload.leaseUntil, 'leaseUntil');
+ if (leaseUntil <= now) throw invalidArgs('leaseUntil must be later than now');
+
+ return db.transaction(() => {
+ if (readActiveEpoch(db)?.bindingEpoch !== bindingEpoch) return null;
+
+ expirePendingTasks(db, bindingEpoch, now);
+ db.prepare(
+ `UPDATE wechat_inbox
+ SET status = 'pending', lease_until = NULL
+ WHERE binding_epoch = ? AND status = 'dispatching'
+ AND lease_until IS NOT NULL AND lease_until <= ? AND expires_at > ?`,
+ ).run(bindingEpoch, now, now);
+
+ const row = db
+ .prepare(
+ `SELECT
+ i.id,
+ i.binding_epoch AS bindingEpoch,
+ i.peer_id AS peerId,
+ i.session_id AS sessionId,
+ i.conversation_epoch AS conversationEpoch,
+ i.payload_json AS payloadJson,
+ i.context_nonce AS contextNonce,
+ i.context_ciphertext AS contextCiphertext,
+ i.context_tag AS contextTag,
+ i.attempts,
+ i.received_at AS receivedAt,
+ i.expires_at AS expiresAt
+ FROM wechat_inbox i
+ WHERE i.binding_epoch = ? AND i.status = 'pending' AND i.expires_at > ?
+ AND i.session_id IS NOT NULL
+ AND NOT EXISTS (
+ SELECT 1 FROM wechat_inbox running
+ WHERE running.binding_epoch = i.binding_epoch
+ AND running.session_id = i.session_id
+ AND running.status IN (${sqlPlaceholders(RUNNING_STATUSES.length)})
+ )
+ ORDER BY
+ CASE
+ WHEN json_extract(i.payload_json, '$.text') IN ('/stop', '/stop all') THEN 0
+ ELSE 1
+ END,
+ i.received_at ASC,
+ i.id ASC
+ LIMIT 1`,
+ )
+ .get(bindingEpoch, now, ...RUNNING_STATUSES) as
+ | {
+ id: string;
+ bindingEpoch: string;
+ peerId: string;
+ sessionId: string;
+ conversationEpoch: number;
+ payloadJson: string;
+ contextNonce: string;
+ contextCiphertext: string;
+ contextTag: string;
+ attempts: number;
+ receivedAt: number;
+ expiresAt: number;
+ }
+ | undefined;
+ if (!row) return null;
+
+ const leased = db
+ .prepare(
+ `UPDATE wechat_inbox
+ SET status = 'dispatching', lease_until = ?, attempts = attempts + 1
+ WHERE id = ? AND binding_epoch = ? AND status = 'pending'`,
+ )
+ .run(leaseUntil, row.id, bindingEpoch);
+ if (leased.changes !== 1) return null;
+
+ return {
+ id: row.id,
+ bindingEpoch: row.bindingEpoch,
+ peerId: row.peerId,
+ sessionId: row.sessionId,
+ conversationEpoch: row.conversationEpoch,
+ payloadJson: row.payloadJson,
+ context: {
+ nonce: row.contextNonce,
+ ciphertext: row.contextCiphertext,
+ tag: row.contextTag,
+ },
+ attempts: row.attempts + 1,
+ receivedAt: row.receivedAt,
+ expiresAt: row.expiresAt,
+ };
+ })();
+}
+
+export function wechatMarkAccepted(db: Database.Database, args: unknown): boolean {
+ const payload = asRecord(args, 'wechatMarkAccepted args');
+ const bindingEpoch = expectId(payload.bindingEpoch, 'bindingEpoch');
+ const taskId = expectId(payload.taskId, 'taskId');
+ return db.transaction(() => {
+ if (readActiveEpoch(db)?.bindingEpoch !== bindingEpoch) return false;
+ const result = db
+ .prepare(
+ `UPDATE wechat_inbox
+ SET status = 'accepted_running', lease_until = NULL
+ WHERE id = ? AND binding_epoch = ? AND status = 'dispatching'`,
+ )
+ .run(taskId, bindingEpoch);
+ return result.changes === 1;
+ })();
+}
+
+export function wechatReleaseDispatch(db: Database.Database, args: unknown): boolean {
+ const payload = asRecord(args, 'wechatReleaseDispatch args');
+ const bindingEpoch = expectId(payload.bindingEpoch, 'bindingEpoch');
+ const taskId = expectId(payload.taskId, 'taskId');
+ return db.transaction(() => {
+ if (readActiveEpoch(db)?.bindingEpoch !== bindingEpoch) return false;
+ const result = db
+ .prepare(
+ `UPDATE wechat_inbox
+ SET status = 'pending', lease_until = NULL
+ WHERE id = ? AND binding_epoch = ? AND status = 'dispatching'`,
+ )
+ .run(taskId, bindingEpoch);
+ return result.changes === 1;
+ })();
+}
+
+export function wechatSetWaitingDesktop(db: Database.Database, args: unknown): boolean {
+ const payload = asRecord(args, 'wechatSetWaitingDesktop args');
+ const bindingEpoch = expectId(payload.bindingEpoch, 'bindingEpoch');
+ const taskId = expectId(payload.taskId, 'taskId');
+ const waiting = expectBoolean(payload.waiting, 'waiting');
+ const from = waiting ? 'accepted_running' : 'waiting_desktop';
+ const to = waiting ? 'waiting_desktop' : 'accepted_running';
+ return db.transaction(() => {
+ if (readActiveEpoch(db)?.bindingEpoch !== bindingEpoch) return false;
+ const result = db
+ .prepare(
+ `UPDATE wechat_inbox
+ SET status = ?
+ WHERE id = ? AND binding_epoch = ? AND status = ?`,
+ )
+ .run(to, taskId, bindingEpoch, from);
+ return result.changes === 1;
+ })();
+}
+
+export function wechatCommitInterrupted(db: Database.Database, args: unknown): boolean {
+ const payload = asRecord(args, 'wechatCommitInterrupted args');
+ const bindingEpoch = expectId(payload.bindingEpoch, 'bindingEpoch');
+ const taskId = expectId(payload.taskId, 'taskId');
+ const now = expectTimestamp(payload.now, 'now');
+ const errorCode = expectMachineCode(payload.errorCode, 'errorCode');
+ const outbox = payload.outbox === undefined ? [] : parseOutbox(payload.outbox, 'outbox');
+ const context =
+ payload.context === undefined ? null : parseEncryptedContext(payload.context, 'context');
+
+ return db.transaction(() => {
+ if (readActiveEpoch(db)?.bindingEpoch !== bindingEpoch) return false;
+ const row = db
+ .prepare('SELECT status FROM wechat_inbox WHERE id = ? AND binding_epoch = ?')
+ .get(taskId, bindingEpoch) as InboxStatusRow | undefined;
+ const canInterrupt = row && ['accepted_running', 'waiting_desktop'].includes(row.status);
+ const canAttachRecoveredNotice = row?.status === 'interrupted' && outbox.length > 0;
+ if (!canInterrupt && !canAttachRecoveredNotice) return false;
+ if (canAttachRecoveredNotice && !context) {
+ throw invalidArgs('context is required for a recovered interruption notice');
+ }
+
+ if (outbox.length > 0) {
+ const insertOutbox = prepareOutboxInsert(db);
+ for (const chunk of outbox) {
+ insertOutboxChunk(insertOutbox, bindingEpoch, taskId, chunk, now);
+ }
+ db.prepare(
+ `UPDATE wechat_inbox
+ SET status = 'delivery_pending', lease_until = NULL, last_error_code = ?,
+ context_nonce = COALESCE(?, context_nonce),
+ context_ciphertext = COALESCE(?, context_ciphertext),
+ context_tag = COALESCE(?, context_tag)
+ WHERE id = ? AND binding_epoch = ?`,
+ ).run(
+ errorCode,
+ context?.nonce ?? null,
+ context?.ciphertext ?? null,
+ context?.tag ?? null,
+ taskId,
+ bindingEpoch,
+ );
+ } else {
+ db.prepare(
+ `UPDATE wechat_inbox
+ SET status = 'interrupted', lease_until = NULL, last_error_code = ?
+ WHERE id = ? AND binding_epoch = ?`,
+ ).run(errorCode, taskId, bindingEpoch);
+ releaseTaskMediaRefs(db, taskId);
+ }
+ return true;
+ })();
+}
+
+export function wechatCommitPreDispatchFailure(db: Database.Database, args: unknown): boolean {
+ const payload = asRecord(args, 'wechatCommitPreDispatchFailure args');
+ const bindingEpoch = expectId(payload.bindingEpoch, 'bindingEpoch');
+ const taskId = expectId(payload.taskId, 'taskId');
+ const now = expectTimestamp(payload.now, 'now');
+ const errorCode = expectMachineCode(payload.errorCode, 'errorCode');
+ const outbox = parseOutbox(payload.outbox, 'outbox');
+ if (outbox.length === 0) throw invalidArgs('outbox must contain at least one chunk');
+
+ return db.transaction(() => {
+ if (readActiveEpoch(db)?.bindingEpoch !== bindingEpoch) return false;
+ const row = db
+ .prepare('SELECT status FROM wechat_inbox WHERE id = ? AND binding_epoch = ?')
+ .get(taskId, bindingEpoch) as InboxStatusRow | undefined;
+ if (row?.status !== 'dispatching') return false;
+ const insertOutbox = prepareOutboxInsert(db);
+ for (const chunk of outbox) {
+ insertOutboxChunk(insertOutbox, bindingEpoch, taskId, chunk, now);
+ }
+ const updated = db
+ .prepare(
+ `UPDATE wechat_inbox
+ SET status = 'delivery_pending', lease_until = NULL, last_error_code = ?
+ WHERE id = ? AND binding_epoch = ? AND status = 'dispatching'`,
+ )
+ .run(errorCode, taskId, bindingEpoch);
+ if (updated.changes !== 1) {
+ throw invariantViolation('pre-dispatch outbox was inserted without task transition');
+ }
+ return true;
+ })();
+}
+
+export function wechatCancelForCommand(
+ db: Database.Database,
+ args: unknown,
+): WechatCancelForCommandResult {
+ const payload = asRecord(args, 'wechatCancelForCommand args');
+ const bindingEpoch = expectId(payload.bindingEpoch, 'bindingEpoch');
+ const commandTaskId = expectId(payload.commandTaskId, 'commandTaskId');
+ const peerId = payload.peerId === undefined ? null : expectString(payload.peerId, 'peerId', 512);
+ const now = expectTimestamp(payload.now, 'now');
+
+ return db.transaction(() => {
+ if (readActiveEpoch(db)?.bindingEpoch !== bindingEpoch) {
+ return { cancelled: 0, interrupted: 0 };
+ }
+ const command = db
+ .prepare(
+ `SELECT peer_id AS peerId, status
+ FROM wechat_inbox
+ WHERE binding_epoch = ? AND id = ?`,
+ )
+ .get(bindingEpoch, commandTaskId) as
+ { peerId: string; status: WechatInboxStatus } | undefined;
+ if (!command || command.status !== 'pending') {
+ return { cancelled: 0, interrupted: 0 };
+ }
+ if (peerId !== null && command.peerId !== peerId) {
+ throw invalidArgs('command task peer does not match peerId');
+ }
+
+ const peerClause = peerId === null ? '' : ' AND peer_id = ?';
+ const peerParams = peerId === null ? [] : [peerId];
+ const cancellable = db
+ .prepare(
+ `SELECT id FROM wechat_inbox
+ WHERE binding_epoch = ? AND id != ?
+ AND status IN ('pending', 'dispatching')${peerClause}`,
+ )
+ .all(bindingEpoch, commandTaskId, ...peerParams) as Array<{ id: string }>;
+ const cancelled = db
+ .prepare(
+ `UPDATE wechat_inbox
+ SET status = 'cancelled', lease_until = NULL, last_error_code = 'STOPPED_BY_USER'
+ WHERE binding_epoch = ? AND id != ?
+ AND status IN ('pending', 'dispatching')${peerClause}`,
+ )
+ .run(bindingEpoch, commandTaskId, ...peerParams).changes;
+ for (const row of cancellable) releaseTaskMediaRefs(db, row.id);
+
+ const interrupted = db
+ .prepare(
+ `UPDATE wechat_inbox
+ SET status = 'interrupted', lease_until = NULL, last_error_code = 'STOPPED_BY_USER'
+ WHERE binding_epoch = ? AND id != ?
+ AND status IN ('accepted_running', 'waiting_desktop')${peerClause}`,
+ )
+ .run(bindingEpoch, commandTaskId, ...peerParams).changes;
+
+ db.prepare(
+ `UPDATE wechat_sync_state
+ SET updated_at = ?
+ WHERE binding_epoch = ? AND is_active = 1`,
+ ).run(now, bindingEpoch);
+ return { cancelled, interrupted };
+ })();
+}
+
+export function wechatCommitTerminal(
+ db: Database.Database,
+ args: unknown,
+): WechatCommitTerminalResult {
+ const payload = asRecord(args, 'wechatCommitTerminal args');
+ const bindingEpoch = expectId(payload.bindingEpoch, 'bindingEpoch');
+ const taskId = expectId(payload.taskId, 'taskId');
+ const now = expectTimestamp(payload.now, 'now');
+ const outbox = parseOutbox(payload.outbox, 'outbox');
+ if (outbox.length === 0) throw invalidArgs('outbox must contain at least one chunk');
+
+ return db.transaction(() => {
+ if (readActiveEpoch(db)?.bindingEpoch !== bindingEpoch) {
+ return { committed: false, alreadyCommitted: false };
+ }
+ const row = db
+ .prepare('SELECT status FROM wechat_inbox WHERE id = ? AND binding_epoch = ?')
+ .get(taskId, bindingEpoch) as InboxStatusRow | undefined;
+ if (!row) return { committed: false, alreadyCommitted: false };
+ if (row.status === 'delivery_pending' || row.status === 'completed') {
+ const count = Number(
+ db
+ .prepare('SELECT COUNT(*) FROM wechat_outbox WHERE binding_epoch = ? AND task_id = ?')
+ .pluck()
+ .get(bindingEpoch, taskId),
+ );
+ return { committed: count > 0, alreadyCommitted: count > 0 };
+ }
+ if (!['accepted_running', 'waiting_desktop'].includes(row.status)) {
+ return { committed: false, alreadyCommitted: false };
+ }
+
+ const insertOutbox = prepareOutboxInsert(db);
+ for (const chunk of outbox) {
+ insertOutboxChunk(insertOutbox, bindingEpoch, taskId, chunk, now);
+ }
+ const updated = db
+ .prepare(
+ `UPDATE wechat_inbox
+ SET status = 'delivery_pending', lease_until = NULL, last_error_code = NULL
+ WHERE id = ? AND binding_epoch = ?
+ AND status IN ('accepted_running', 'waiting_desktop')`,
+ )
+ .run(taskId, bindingEpoch);
+ if (updated.changes !== 1) {
+ throw invariantViolation('terminal outbox was inserted without task transition');
+ }
+ return { committed: true, alreadyCommitted: false };
+ })();
+}
+
+export function wechatMarkOutboxDelivered(
+ db: Database.Database,
+ args: unknown,
+): WechatMarkOutboxDeliveredResult {
+ const payload = asRecord(args, 'wechatMarkOutboxDelivered args');
+ const bindingEpoch = expectId(payload.bindingEpoch, 'bindingEpoch');
+ const outboxId = expectId(payload.outboxId, 'outboxId');
+ const deliveredAt = expectTimestamp(payload.deliveredAt, 'deliveredAt');
+
+ return db.transaction(() => {
+ const row = db
+ .prepare(
+ 'SELECT task_id AS taskId, status FROM wechat_outbox WHERE id = ? AND binding_epoch = ?',
+ )
+ .get(outboxId, bindingEpoch) as OutboxTaskRow | undefined;
+ if (!row) return { changed: false, taskId: null, taskCompleted: false };
+ const changed =
+ db
+ .prepare(
+ `UPDATE wechat_outbox
+ SET status = 'delivered', delivered_at = ?
+ WHERE id = ? AND binding_epoch = ? AND status IN ('pending', 'sending')`,
+ )
+ .run(deliveredAt, outboxId, bindingEpoch).changes === 1;
+ const remaining = Number(
+ db
+ .prepare(
+ `SELECT COUNT(*) FROM wechat_outbox
+ WHERE binding_epoch = ? AND task_id = ? AND status != 'delivered'`,
+ )
+ .pluck()
+ .get(bindingEpoch, row.taskId),
+ );
+ let taskCompleted = false;
+ if (remaining === 0) {
+ taskCompleted =
+ db
+ .prepare(
+ `UPDATE wechat_inbox
+ SET status = 'completed', lease_until = NULL
+ WHERE id = ? AND binding_epoch = ? AND status = 'delivery_pending'`,
+ )
+ .run(row.taskId, bindingEpoch).changes === 1;
+ if (taskCompleted) releaseTaskMediaRefs(db, row.taskId);
+ }
+ return { changed, taskId: row.taskId, taskCompleted };
+ })();
+}
+
+export function wechatRecordOutboxFailure(
+ db: Database.Database,
+ args: unknown,
+): WechatRecordOutboxFailureResult {
+ const payload = asRecord(args, 'wechatRecordOutboxFailure args');
+ const bindingEpoch = expectId(payload.bindingEpoch, 'bindingEpoch');
+ const outboxId = expectId(payload.outboxId, 'outboxId');
+ const nextRetryAt = expectTimestamp(payload.nextRetryAt, 'nextRetryAt');
+ const terminal = expectBoolean(payload.terminal, 'terminal');
+ const errorCode = expectMachineCode(payload.errorCode, 'errorCode');
+
+ return db.transaction(() => {
+ const row = db
+ .prepare(
+ 'SELECT task_id AS taskId, status FROM wechat_outbox WHERE id = ? AND binding_epoch = ?',
+ )
+ .get(outboxId, bindingEpoch) as OutboxTaskRow | undefined;
+ if (!row) return { changed: false, taskId: null, taskFailed: false };
+ const changed =
+ db
+ .prepare(
+ `UPDATE wechat_outbox
+ SET status = ?, next_retry_at = ?
+ WHERE id = ? AND binding_epoch = ? AND status = 'sending'`,
+ )
+ .run(terminal ? 'failed_terminal' : 'pending', nextRetryAt, outboxId, bindingEpoch)
+ .changes === 1;
+ if (!changed) return { changed: false, taskId: row.taskId, taskFailed: false };
+
+ if (!terminal) {
+ db.prepare(
+ `UPDATE wechat_inbox SET last_error_code = ?
+ WHERE id = ? AND binding_epoch = ? AND status = 'delivery_pending'`,
+ ).run(errorCode, row.taskId, bindingEpoch);
+ return { changed: true, taskId: row.taskId, taskFailed: false };
+ }
+
+ db.prepare(
+ `UPDATE wechat_outbox
+ SET status = 'failed_terminal'
+ WHERE task_id = ? AND binding_epoch = ? AND status != 'delivered'`,
+ ).run(row.taskId, bindingEpoch);
+ const taskFailed =
+ db
+ .prepare(
+ `UPDATE wechat_inbox
+ SET status = 'failed_terminal', lease_until = NULL, last_error_code = ?
+ WHERE id = ? AND binding_epoch = ? AND status = 'delivery_pending'`,
+ )
+ .run(errorCode, row.taskId, bindingEpoch).changes === 1;
+ if (taskFailed) releaseTaskMediaRefs(db, row.taskId);
+ return { changed: true, taskId: row.taskId, taskFailed };
+ })();
+}
+
+export function wechatStopAll(db: Database.Database, args: unknown): WechatStopAllResult {
+ const payload = asRecord(args, 'wechatStopAll args');
+ const bindingEpoch = expectId(payload.bindingEpoch, 'bindingEpoch');
+ const now = expectTimestamp(payload.now, 'now');
+ const errorCode = expectMachineCode(payload.errorCode, 'errorCode');
+
+ return db.transaction(() => {
+ db.prepare(
+ `UPDATE wechat_outbox
+ SET status = 'pending', next_retry_at = ?
+ WHERE binding_epoch = ? AND status = 'sending'`,
+ ).run(now, bindingEpoch);
+ repairAcceptedTaskAttachments(db, bindingEpoch, now);
+ const expired = expirePendingTasks(db, bindingEpoch, now);
+ const requeued = db
+ .prepare(
+ `UPDATE wechat_inbox
+ SET status = 'pending', lease_until = NULL, last_error_code = ?
+ WHERE binding_epoch = ? AND status = 'dispatching' AND expires_at > ?`,
+ )
+ .run(errorCode, bindingEpoch, now).changes;
+ const interrupted = db
+ .prepare(
+ `UPDATE wechat_inbox
+ SET status = 'interrupted', lease_until = NULL, last_error_code = ?
+ WHERE binding_epoch = ? AND status IN ('accepted_running', 'waiting_desktop')`,
+ )
+ .run(errorCode, bindingEpoch).changes;
+ const repaired = db
+ .prepare(
+ `UPDATE wechat_inbox
+ SET status = 'interrupted', lease_until = NULL,
+ last_error_code = 'OUTBOX_INVARIANT_VIOLATION'
+ WHERE binding_epoch = ? AND status = 'delivery_pending'
+ AND NOT EXISTS (
+ SELECT 1 FROM wechat_outbox o
+ WHERE o.binding_epoch = wechat_inbox.binding_epoch
+ AND o.task_id = wechat_inbox.id
+ )`,
+ )
+ .run(bindingEpoch).changes;
+ releaseTerminalMediaRefs(db, bindingEpoch);
+ return { requeued, interrupted, expired, repaired };
+ })();
+}
+
+export function wechatCloseBindingEpoch(db: Database.Database, args: unknown): { closed: boolean } {
+ const payload = asRecord(args, 'wechatCloseBindingEpoch args');
+ const bindingEpoch = expectId(payload.bindingEpoch, 'bindingEpoch');
+ const now = expectTimestamp(payload.now, 'now');
+
+ return db.transaction(() => {
+ const exists =
+ db.prepare('SELECT 1 FROM wechat_sync_state WHERE binding_epoch = ?').get(bindingEpoch) !==
+ undefined;
+ if (!exists) return { closed: false };
+ repairAcceptedTaskAttachments(db, bindingEpoch, now);
+ db.prepare(
+ `UPDATE wechat_sync_state
+ SET is_active = 0, updated_at = ?
+ WHERE binding_epoch = ?`,
+ ).run(now, bindingEpoch);
+ db.prepare(
+ `UPDATE wechat_inbox
+ SET status = 'cancelled', lease_until = NULL, last_error_code = 'BINDING_CLOSED'
+ WHERE binding_epoch = ? AND status IN ('pending', 'dispatching')`,
+ ).run(bindingEpoch);
+ db.prepare(
+ `UPDATE wechat_inbox
+ SET status = 'interrupted', lease_until = NULL, last_error_code = 'BINDING_CLOSED'
+ WHERE binding_epoch = ? AND status IN ('accepted_running', 'waiting_desktop')`,
+ ).run(bindingEpoch);
+ releaseTerminalMediaRefs(db, bindingEpoch);
+ return { closed: true };
+ })();
+}
+
+export function wechatPromoteTaskAttachments(
+ db: Database.Database,
+ args: unknown,
+): WechatPromoteTaskAttachmentsResult {
+ const payload = asRecord(args, 'wechatPromoteTaskAttachments args');
+ const bindingEpoch = expectId(payload.bindingEpoch, 'bindingEpoch');
+ const taskId = expectId(payload.taskId, 'taskId');
+ const sessionId = expectId(payload.sessionId, 'sessionId');
+ const now = expectTimestamp(payload.now, 'now');
+
+ return db.transaction(() => {
+ const task = db
+ .prepare(
+ `SELECT session_id AS sessionId, status
+ FROM wechat_inbox
+ WHERE binding_epoch = ? AND id = ?`,
+ )
+ .get(bindingEpoch, taskId) as { sessionId: string; status: string } | undefined;
+ if (
+ !task ||
+ task.sessionId !== sessionId ||
+ !['accepted_running', 'waiting_desktop', 'delivery_pending', 'completed'].includes(
+ task.status,
+ )
+ ) {
+ return { eligible: false, promotedMediaRefs: 0, promotedFiles: 0 };
+ }
+
+ const promotedMediaRefs = db
+ .prepare(
+ `INSERT OR IGNORE INTO media_refs
+ (id, hash, ref_kind, ref_id, origin_session_id, origin_kind, origin_id, label, created_at)
+ SELECT
+ lower(hex(randomblob(16))),
+ hash,
+ 'session-attachment',
+ ?,
+ ?,
+ 'integration',
+ 'wechat',
+ label,
+ ?
+ FROM media_refs
+ WHERE ref_kind IN ('im-inbox', 'wechat-inbox') AND ref_id = ?`,
+ )
+ .run(sessionId, sessionId, now, taskId).changes;
+ db.prepare(
+ `DELETE FROM media_refs
+ WHERE ref_kind IN ('im-inbox', 'wechat-inbox') AND ref_id = ?`,
+ ).run(taskId);
+ const promotedFiles = db
+ .prepare(
+ `UPDATE wechat_file_attachments
+ SET status = 'promoted', promoted_at = ?
+ WHERE binding_epoch = ? AND task_id = ? AND session_id = ? AND status = 'staged'`,
+ )
+ .run(now, bindingEpoch, taskId, sessionId).changes;
+ return { eligible: true, promotedMediaRefs, promotedFiles };
+ })();
+}
+
+export function wechatRefreshOutboxContexts(
+ db: Database.Database,
+ args: unknown,
+): WechatRefreshOutboxContextsResult {
+ const payload = asRecord(args, 'wechatRefreshOutboxContexts args');
+ const bindingEpoch = expectId(payload.bindingEpoch, 'bindingEpoch');
+ const peerId = expectString(payload.peerId, 'peerId', 512);
+ const now = expectTimestamp(payload.now, 'now');
+ const contexts = expectArray(payload.contexts, 'contexts');
+ enforceArrayLimit(contexts, 'contexts', 100);
+
+ return db.transaction(() => {
+ const updateContext = db.prepare(
+ `UPDATE wechat_inbox
+ SET context_nonce = ?, context_ciphertext = ?, context_tag = ?
+ WHERE binding_epoch = ? AND id = ? AND peer_id = ? AND status = 'delivery_pending'
+ AND EXISTS (
+ SELECT 1 FROM wechat_outbox
+ WHERE binding_epoch = ? AND task_id = ? AND status = 'pending'
+ )`,
+ );
+ let refreshedTasks = 0;
+ const refreshedIds: string[] = [];
+ for (let index = 0; index < contexts.length; index += 1) {
+ const item = asRecord(contexts[index], `contexts.${index}`);
+ const taskId = expectId(item.taskId, `contexts.${index}.taskId`);
+ const context = parseEncryptedContext(item.context, `contexts.${index}.context`);
+ const changed = updateContext.run(
+ context.nonce,
+ context.ciphertext,
+ context.tag,
+ bindingEpoch,
+ taskId,
+ peerId,
+ bindingEpoch,
+ taskId,
+ ).changes;
+ if (changed > 0) {
+ refreshedTasks += changed;
+ refreshedIds.push(taskId);
+ }
+ }
+ if (refreshedIds.length === 0) return { refreshedTasks: 0, outboxWoken: 0 };
+ const outboxWoken = db
+ .prepare(
+ `UPDATE wechat_outbox
+ SET next_retry_at = ?
+ WHERE binding_epoch = ? AND status = 'pending'
+ AND task_id IN (${sqlPlaceholders(refreshedIds.length)})`,
+ )
+ .run(now, bindingEpoch, ...refreshedIds).changes;
+ return { refreshedTasks, outboxWoken };
+ })();
+}
+
+export function wechatUnbindCleanup(
+ db: Database.Database,
+ args: unknown,
+): WechatUnbindCleanupResult {
+ const payload = asRecord(args, 'wechatUnbindCleanup args');
+ const bindingEpoch = expectId(payload.bindingEpoch, 'bindingEpoch');
+
+ return db.transaction(() => {
+ const active = db
+ .prepare('SELECT is_active AS isActive FROM wechat_sync_state WHERE binding_epoch = ?')
+ .get(bindingEpoch) as { isActive: number } | undefined;
+ if (active?.isActive === 1) throw invalidArgs('active binding epoch must be closed first');
+ const deletedTasks = Number(
+ db
+ .prepare('SELECT COUNT(*) FROM wechat_inbox WHERE binding_epoch = ?')
+ .pluck()
+ .get(bindingEpoch),
+ );
+ const filePaths = (
+ db
+ .prepare(
+ `SELECT abs_path AS absPath
+ FROM wechat_file_attachments
+ WHERE binding_epoch = ? AND status != 'promoted'`,
+ )
+ .all(bindingEpoch) as Array<{ absPath: string }>
+ ).map(({ absPath }) => absPath);
+ const deletedMediaRefs = db
+ .prepare(
+ `DELETE FROM media_refs
+ WHERE ref_kind IN ('im-inbox', 'wechat-inbox')
+ AND ref_id IN (SELECT id FROM wechat_inbox WHERE binding_epoch = ?)`,
+ )
+ .run(bindingEpoch).changes;
+ db.prepare('DELETE FROM wechat_sync_state WHERE binding_epoch = ?').run(bindingEpoch);
+ return { deletedTasks, deletedMediaRefs, filePaths };
+ })();
+}
+
+function readActiveEpoch(db: Database.Database): ActiveEpochRow | undefined {
+ return db
+ .prepare(
+ `SELECT binding_epoch AS bindingEpoch, sync_cursor AS syncCursor
+ FROM wechat_sync_state WHERE is_active = 1 LIMIT 1`,
+ )
+ .get() as ActiveEpochRow | undefined;
+}
+
+function parsePollMessage(value: unknown, index: number) {
+ const label = `messages.${index}`;
+ const item = asRecord(value, label);
+ const context = parseEncryptedContext(item.context, `${label}.context`);
+ const overloadRaw =
+ item.overloadReply === undefined
+ ? undefined
+ : asRecord(item.overloadReply, `${label}.overloadReply`);
+ const receivedAt = expectTimestamp(item.receivedAt, `${label}.receivedAt`);
+ const expiresAt = expectTimestamp(item.expiresAt, `${label}.expiresAt`);
+ if (expiresAt < receivedAt) {
+ throw invalidArgs(`${label}.expiresAt must not be earlier than receivedAt`);
+ }
+ return {
+ id: expectId(item.id, `${label}.id`),
+ platformMessageId: expectString(item.platformMessageId, `${label}.platformMessageId`, 512),
+ platformSeq: expectInteger(item.platformSeq, `${label}.platformSeq`, 0),
+ peerId: expectString(item.peerId, `${label}.peerId`, 512),
+ receivedAt,
+ platformCreatedAt: expectTimestamp(item.platformCreatedAt, `${label}.platformCreatedAt`),
+ expiresAt,
+ sessionId: expectId(item.sessionId, `${label}.sessionId`),
+ conversationEpoch: expectInteger(item.conversationEpoch, `${label}.conversationEpoch`, 0),
+ payloadJson: expectString(item.payloadJson, `${label}.payloadJson`, 4 * 1024 * 1024),
+ context,
+ overloadReply: overloadRaw
+ ? {
+ outboxId: expectId(overloadRaw.outboxId, `${label}.overloadReply.outboxId`),
+ clientId: expectId(overloadRaw.clientId, `${label}.overloadReply.clientId`),
+ text: expectString(overloadRaw.text, `${label}.overloadReply.text`, 16_384),
+ }
+ : undefined,
+ };
+}
+
+function isWechatControlCommand(payloadJson: string): boolean {
+ try {
+ const payload: unknown = JSON.parse(payloadJson);
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) return false;
+ const text = (payload as { text?: unknown }).text;
+ return typeof text === 'string' && CONTROL_COMMANDS.has(text.trim());
+ } catch {
+ return false;
+ }
+}
+
+function parseEncryptedContext(value: unknown, label: string) {
+ const context = asRecord(value, label);
+ return {
+ nonce: expectBase64(context.nonce, `${label}.nonce`, 64),
+ ciphertext: expectBase64(context.ciphertext, `${label}.ciphertext`, 64 * 1024),
+ tag: expectBase64(context.tag, `${label}.tag`, 64),
+ };
+}
+
+function commitMediaBlobs(
+ db: Database.Database,
+ mediaBlobs: unknown[],
+ mediaRefs: unknown[],
+ acceptedTaskIds: ReadonlySet<string>,
+): void {
+ const referencedHashes = new Set<string>();
+ for (let index = 0; index < mediaRefs.length; index += 1) {
+ const item = asRecord(mediaRefs[index], `mediaRefs.${index}`);
+ const taskId = expectId(item.taskId, `mediaRefs.${index}.taskId`);
+ if (acceptedTaskIds.has(taskId)) {
+ referencedHashes.add(expectHash(item.hash, `mediaRefs.${index}.hash`));
+ }
+ }
+ const suppliedHashes = new Set<string>();
+ const findBlob = db.prepare(
+ 'SELECT ext, mime_type AS mimeType, bytes FROM media_blobs WHERE hash = ?',
+ );
+ const upsertBlob = db.prepare(
+ `INSERT INTO media_blobs
+ (hash, ext, mime_type, bytes, is_cache, created_at, last_access_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?)
+ ON CONFLICT(hash) DO UPDATE SET
+ is_cache = CASE
+ WHEN media_blobs.is_cache = 0 OR excluded.is_cache = 0 THEN 0
+ ELSE 1
+ END,
+ last_access_at = MAX(media_blobs.last_access_at, excluded.last_access_at)`,
+ );
+ for (let index = 0; index < mediaBlobs.length; index += 1) {
+ const item = asRecord(mediaBlobs[index], `mediaBlobs.${index}`);
+ const hash = expectHash(item.hash, `mediaBlobs.${index}.hash`);
+ if (!referencedHashes.has(hash)) continue;
+ const ext = expectExtension(item.ext, `mediaBlobs.${index}.ext`);
+ const mimeType = expectString(item.mimeType, `mediaBlobs.${index}.mimeType`, 255);
+ const bytes = expectInteger(item.bytes, `mediaBlobs.${index}.bytes`, 0);
+ const isCache = expectBoolean(item.isCache, `mediaBlobs.${index}.isCache`);
+ const createdAt = expectTimestamp(item.createdAt, `mediaBlobs.${index}.createdAt`);
+ const lastAccessAt = expectTimestamp(item.lastAccessAt, `mediaBlobs.${index}.lastAccessAt`);
+ const existing = findBlob.get(hash) as
+ { ext: string; mimeType: string; bytes: number } | undefined;
+ if (
+ existing &&
+ (existing.ext !== ext || existing.mimeType !== mimeType || existing.bytes !== bytes)
+ ) {
+ throw invariantViolation(`media metadata mismatch for hash ${hash}`);
+ }
+ upsertBlob.run(hash, ext, mimeType, bytes, isCache ? 1 : 0, createdAt, lastAccessAt);
+ suppliedHashes.add(hash);
+ }
+ for (const hash of referencedHashes) {
+ if (!suppliedHashes.has(hash) && !findBlob.get(hash)) {
+ throw invalidArgs(`mediaRefs references unknown hash ${hash}`);
+ }
+ }
+}
+
+function commitMediaRefs(
+ db: Database.Database,
+ mediaRefs: unknown[],
+ acceptedTaskIds: ReadonlySet<string>,
+): void {
+ const insertRef = db.prepare(
+ `INSERT OR IGNORE INTO media_refs
+ (id, hash, ref_kind, ref_id, origin_session_id, origin_kind, origin_id, label, created_at)
+ VALUES (?, ?, 'im-inbox', ?, NULL, 'integration', 'wechat', ?, ?)`,
+ );
+ for (let index = 0; index < mediaRefs.length; index += 1) {
+ const item = asRecord(mediaRefs[index], `mediaRefs.${index}`);
+ const taskId = expectId(item.taskId, `mediaRefs.${index}.taskId`);
+ if (!acceptedTaskIds.has(taskId)) continue;
+ insertRef.run(
+ expectId(item.id, `mediaRefs.${index}.id`),
+ expectHash(item.hash, `mediaRefs.${index}.hash`),
+ taskId,
+ nullableString(item.label, `mediaRefs.${index}.label`, 1_024),
+ expectTimestamp(item.createdAt, `mediaRefs.${index}.createdAt`),
+ );
+ }
+}
+
+function commitFileAttachments(
+ db: Database.Database,
+ fileAttachments: unknown[],
+ acceptedTaskIds: ReadonlySet<string>,
+ bindingEpoch: string,
+): void {
+ const insertFile = db.prepare(
+ `INSERT INTO wechat_file_attachments
+ (id, binding_epoch, task_id, session_id, abs_path, original_name,
+ mime_type, bytes, status, promoted_at, created_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'staged', NULL, ?)`,
+ );
+ for (let index = 0; index < fileAttachments.length; index += 1) {
+ const item = asRecord(fileAttachments[index], `fileAttachments.${index}`);
+ const taskId = expectId(item.taskId, `fileAttachments.${index}.taskId`);
+ if (!acceptedTaskIds.has(taskId)) continue;
+ insertFile.run(
+ expectId(item.id, `fileAttachments.${index}.id`),
+ bindingEpoch,
+ taskId,
+ expectId(item.sessionId, `fileAttachments.${index}.sessionId`),
+ expectString(item.absPath, `fileAttachments.${index}.absPath`, 32_768),
+ expectString(item.originalName, `fileAttachments.${index}.originalName`, 1_024),
+ expectString(item.mimeType, `fileAttachments.${index}.mimeType`, 255),
+ expectInteger(item.bytes, `fileAttachments.${index}.bytes`, 0),
+ expectTimestamp(item.createdAt, `fileAttachments.${index}.createdAt`),
+ );
+ }
+}
+
+function prepareOutboxInsert(db: Database.Database): Database.Statement {
+ return db.prepare(
+ `INSERT INTO wechat_outbox
+ (id, binding_epoch, task_id, client_id, kind, chunk_index, text,
+ media_json, status, attempts, next_retry_at, created_at, delivered_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending', 0, ?, ?, NULL)`,
+ );
+}
+
+function insertOutboxChunk(
+ statement: Database.Statement,
+ bindingEpoch: string,
+ taskId: string,
+ chunk: WechatOutboxChunkInput,
+ now: number,
+): void {
+ statement.run(
+ chunk.id,
+ bindingEpoch,
+ taskId,
+ chunk.clientId,
+ chunk.kind,
+ chunk.chunkIndex,
+ chunk.text,
+ chunk.mediaJson ?? '[]',
+ now,
+ now,
+ );
+}
+
+function parseOutbox(value: unknown, label: string): WechatOutboxChunkInput[] {
+ const rows = expectArray(value, label);
+ enforceArrayLimit(rows, label, MAX_OUTBOX_CHUNKS);
+ const seenChunks = new Set<number>();
+ return rows.map((raw, index) => {
+ const itemLabel = `${label}.${index}`;
+ const item = asRecord(raw, itemLabel);
+ const chunkIndex = expectInteger(item.chunkIndex, `${itemLabel}.chunkIndex`, 0);
+ if (seenChunks.has(chunkIndex)) throw invalidArgs(`${label} contains duplicate chunkIndex`);
+ seenChunks.add(chunkIndex);
+ const kind = expectEnum(item.kind, `${itemLabel}.kind`, [
+ 'final',
+ 'error',
+ 'interrupted',
+ 'overload',
+ ] as const);
+ const mediaJson =
+ item.mediaJson === undefined
+ ? undefined
+ : expectString(item.mediaJson, `${itemLabel}.mediaJson`, 256 * 1024);
+ return {
+ id: expectId(item.id, `${itemLabel}.id`),
+ clientId: expectId(item.clientId, `${itemLabel}.clientId`),
+ kind,
+ chunkIndex,
+ text: expectString(item.text, `${itemLabel}.text`, 16_384),
+ mediaJson,
+ };
+ });
+}
+
+function expirePendingTasks(db: Database.Database, bindingEpoch: string, now: number): number {
+ const changed = db
+ .prepare(
+ `UPDATE wechat_inbox
+ SET status = 'expired', lease_until = NULL, last_error_code = 'TASK_EXPIRED'
+ WHERE binding_epoch = ? AND status IN ('pending', 'dispatching') AND expires_at <= ?`,
+ )
+ .run(bindingEpoch, now).changes;
+ if (changed > 0) releaseTerminalMediaRefs(db, bindingEpoch);
+ return changed;
+}
+
+function releaseTaskMediaRefs(db: Database.Database, taskId: string): void {
+ db.prepare(
+ "DELETE FROM media_refs WHERE ref_kind IN ('im-inbox', 'wechat-inbox') AND ref_id = ?",
+ ).run(taskId);
+ db.prepare(
+ `UPDATE wechat_file_attachments
+ SET status = 'released'
+ WHERE task_id = ? AND status = 'staged'`,
+ ).run(taskId);
+}
+
+function repairAcceptedTaskAttachments(
+ db: Database.Database,
+ bindingEpoch: string,
+ now: number,
+): void {
+ const acceptedStatuses = [
+ 'accepted_running',
+ 'waiting_desktop',
+ 'delivery_pending',
+ 'completed',
+ ] as const;
+ const placeholders = sqlPlaceholders(acceptedStatuses.length);
+ db.prepare(
+ `INSERT OR IGNORE INTO media_refs
+ (id, hash, ref_kind, ref_id, origin_session_id, origin_kind, origin_id, label, created_at)
+ SELECT
+ lower(hex(randomblob(16))),
+ r.hash,
+ 'session-attachment',
+ i.session_id,
+ i.session_id,
+ 'integration',
+ 'wechat',
+ r.label,
+ ?
+ FROM media_refs r
+ INNER JOIN wechat_inbox i ON i.id = r.ref_id
+ WHERE i.binding_epoch = ?
+ AND i.status IN (${placeholders})
+ AND r.ref_kind IN ('im-inbox', 'wechat-inbox')`,
+ ).run(now, bindingEpoch, ...acceptedStatuses);
+ db.prepare(
+ `DELETE FROM media_refs
+ WHERE ref_kind IN ('im-inbox', 'wechat-inbox')
+ AND ref_id IN (
+ SELECT id FROM wechat_inbox
+ WHERE binding_epoch = ? AND status IN (${placeholders})
+ )`,
+ ).run(bindingEpoch, ...acceptedStatuses);
+ db.prepare(
+ `UPDATE wechat_file_attachments
+ SET status = 'promoted', promoted_at = COALESCE(promoted_at, ?)
+ WHERE binding_epoch = ? AND status = 'staged'
+ AND task_id IN (
+ SELECT id FROM wechat_inbox
+ WHERE binding_epoch = ? AND status IN (${placeholders})
+ )`,
+ ).run(now, bindingEpoch, bindingEpoch, ...acceptedStatuses);
+}
+
+function releaseTerminalMediaRefs(db: Database.Database, bindingEpoch: string): void {
+ db.prepare(
+ `DELETE FROM media_refs
+ WHERE ref_kind IN ('im-inbox', 'wechat-inbox')
+ AND ref_id IN (
+ SELECT id FROM wechat_inbox
+ WHERE binding_epoch = ?
+ AND status IN ('completed', 'interrupted', 'cancelled', 'expired', 'failed_terminal')
+ )`,
+ ).run(bindingEpoch);
+ db.prepare(
+ `UPDATE wechat_file_attachments
+ SET status = 'released'
+ WHERE binding_epoch = ? AND status = 'staged'
+ AND task_id IN (
+ SELECT id FROM wechat_inbox
+ WHERE binding_epoch = ?
+ AND status IN ('completed', 'interrupted', 'cancelled', 'expired', 'failed_terminal')
+ )`,
+ ).run(bindingEpoch, bindingEpoch);
+}
+
+function sqlPlaceholders(count: number): string {
+ return Array.from({ length: count }, () => '?').join(', ');
+}
+
+function enforceArrayLimit(value: unknown[], label: string, max: number): void {
+ if (value.length > max) throw invalidArgs(`${label} exceeds ${max} items`);
+}
+
+function asRecord(value: unknown, label: string): Record<string, unknown> {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
+ throw invalidArgs(`${label} must be an object`);
+ }
+ return value as Record<string, unknown>;
+}
+
+function expectArray(value: unknown, label: string): unknown[] {
+ if (!Array.isArray(value)) throw invalidArgs(`${label} must be an array`);
+ return value;
+}
+
+function expectString(value: unknown, label: string, max = 4_096): string {
+ if (typeof value !== 'string') throw invalidArgs(`${label} must be a string`);
+ if (value.length > max) throw invalidArgs(`${label} exceeds ${max} characters`);
+ return value;
+}
+
+function expectId(value: unknown, label: string): string {
+ const id = expectString(value, label, 512);
+ if (id.length === 0) throw invalidArgs(`${label} must not be empty`);
+ return id;
+}
+
+function nullableId(value: unknown, label: string): string | null {
+ if (value === null) return null;
+ return expectId(value, label);
+}
+
+function nullableString(value: unknown, label: string, max: number): string | null {
+ if (value === null || value === undefined) return null;
+ return expectString(value, label, max);
+}
+
+function expectInteger(
+ value: unknown,
+ label: string,
+ min: number,
+ max = Number.MAX_SAFE_INTEGER,
+): number {
+ if (!Number.isSafeInteger(value) || (value as number) < min || (value as number) > max) {
+ throw invalidArgs(`${label} must be an integer between ${min} and ${max}`);
+ }
+ return value as number;
+}
+
+function expectTimestamp(value: unknown, label: string): number {
+ return expectInteger(value, label, 0);
+}
+
+function expectBoolean(value: unknown, label: string): boolean {
+ if (typeof value !== 'boolean') throw invalidArgs(`${label} must be a boolean`);
+ return value;
+}
+
+function expectMachineCode(value: unknown, label: string): string {
+ const code = expectString(value, label, 128);
+ if (!/^[A-Z][A-Z0-9_]*$/.test(code)) {
+ throw invalidArgs(`${label} must be an uppercase machine code`);
+ }
+ return code;
+}
+
+function expectHash(value: unknown, label: string): string {
+ const hash = expectString(value, label, 64);
+ if (!/^[a-f0-9]{64}$/.test(hash)) throw invalidArgs(`${label} must be a SHA-256 hex hash`);
+ return hash;
+}
+
+function expectExtension(value: unknown, label: string): string {
+ const ext = expectString(value, label, 16);
+ if (!/^\.[a-z0-9]{1,15}$/.test(ext)) throw invalidArgs(`${label} is invalid`);
+ return ext;
+}
+
+function expectBase64(value: unknown, label: string, max: number): string {
+ const encoded = expectString(value, label, max);
+ if (encoded.length === 0 || !/^[A-Za-z0-9+/]+={0,2}$/.test(encoded)) {
+ throw invalidArgs(`${label} must be base64`);
+ }
+ return encoded;
+}
+
+function expectEnum<const T extends readonly string[]>(
+ value: unknown,
+ label: string,
+ values: T,
+): T[number] {
+ if (typeof value !== 'string' || !values.includes(value)) {
+ throw invalidArgs(`${label} is invalid`);
+ }
+ return value as T[number];
+}
+
+function invalidArgs(message: string): Error {
+ return Object.assign(new Error(message), { code: 'INVALID_ARGS' });
+}
+
+function invariantViolation(message: string): Error {
+ return Object.assign(new Error(message), { code: 'DB_INVARIANT_VIOLATION' });
+}
diff --git a/apps/desktop/src/main/maker-host/plugins/__tests__/plugin-registry.test.ts b/apps/desktop/src/main/maker-host/plugins/__tests__/plugin-registry.test.ts
index 2d22969ec5..700b31fea8 100644
--- a/apps/desktop/src/main/maker-host/plugins/__tests__/plugin-registry.test.ts
+++ b/apps/desktop/src/main/maker-host/plugins/__tests__/plugin-registry.test.ts
@@ -63,6 +63,7 @@ function realBuiltinProviderNames(): KnownProviderName[] {
browser: {} as never,
computer: {} as never,
feishuBot: {} as never,
+ wechatBot: {} as never,
slackHook: {} as never,
scheduler: {} as never,
ssh: {} as never,
diff --git a/apps/desktop/src/main/maker-host/plugins/builtin-plugins.ts b/apps/desktop/src/main/maker-host/plugins/builtin-plugins.ts
index b7033965ad..24f99d8fc9 100644
--- a/apps/desktop/src/main/maker-host/plugins/builtin-plugins.ts
+++ b/apps/desktop/src/main/maker-host/plugins/builtin-plugins.ts
@@ -6,7 +6,7 @@
* - 项目设置:.claude/settings.json → xdtMaker.builtinTools.{id}
*
* 所有 ID 都使用短且一致的名字,不带 `cindy_` 前缀:
- * android | browser | computer | feishu_bot |
+ * android | browser | computer | feishu_bot | wechat |
* scheduler | ssh | memory | contacts | xdt_helper | collab(→ cindy_orca) | lsp
*
* @cindy/mcps/providers.ts 里的现役 MCP provider `name` 使用 `cindy_` 前缀;
@@ -33,6 +33,7 @@ const BUILTIN_META: BuiltinPluginMeta[] = [
{ id: 'browser', name: 'Browser', description: 'Browser automation — isolated browsing, snapshots, screenshots, and page actions' },
{ id: 'computer', name: 'Computer Use', description: 'Local desktop automation — apps, windows, UI inspection, clicks, and typing via an installed driver' },
{ id: 'feishu_bot', name: 'Feishu Bot', description: 'Send files and notifications to Feishu users via bot messages' },
+ { id: 'wechat', name: 'Personal WeChat', description: 'Send proactive messages to known personal WeChat contacts' },
{ id: 'slack', name: 'Slack', description: 'Slack tools via the bound Slack connection — search, read history, and post through Slack\'s hosted MCP as the bound user' },
{ id: 'scheduler', name: 'Scheduler', description: 'Task scheduling — cron-based recurring jobs and one-shot reminders' },
{ id: 'ssh', name: 'SSH Remote', description: 'Run commands on configured SSH hosts via the built-in connection pool (aliases, ssh-agent/keys) — nothing installed remotely' },
@@ -71,6 +72,7 @@ export type KnownProviderName =
| 'cindy_browser'
| 'cindy_computer'
| 'cindy_feishu_bot'
+ | 'cindy_wechat'
| 'cindy_slack'
| 'cindy_scheduler'
| 'cindy_ssh'
@@ -99,6 +101,7 @@ export const PROVIDER_NAME_TO_PLUGIN_ID: Record<KnownProviderName, PluginId> = {
cindy_browser: 'browser',
cindy_computer: 'computer',
cindy_feishu_bot: 'feishu_bot',
+ cindy_wechat: 'wechat',
cindy_slack: 'slack',
cindy_scheduler: 'scheduler',
cindy_ssh: 'ssh',
@@ -154,6 +157,7 @@ const PLUGIN_ID_TO_MCP_ID: Record<PluginId, LiziMcpId | undefined> = {
browser: 'browser',
computer: 'computer',
feishu_bot: 'cindy_feishu_bot',
+ wechat: 'cindy_wechat',
slack: 'cindy_slack',
scheduler: 'cindy_scheduler',
ssh: 'cindy_ssh',
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/interactionRouter.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/interactionRouter.test.ts
new file mode 100644
index 0000000000..983cdcb605
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/interactionRouter.test.ts
@@ -0,0 +1,227 @@
+import { describe, expect, it, vi } from 'vitest';
+import type { InteractionDecision, InteractionRequest } from '@cindy/maker-core';
+
+import {
+ beginInteractionRoute,
+ installDesktopInteractionHandler,
+ type InteractionHandler,
+} from '../interactionRouter';
+
+function permission(requestId: string): InteractionRequest {
+ return {
+ kind: 'permission',
+ requestId,
+ toolName: 'Read',
+ input: {},
+ } as InteractionRequest;
+}
+
+function ask(requestId: string): InteractionRequest {
+ return {
+ kind: 'ask_user_question',
+ requestId,
+ questions: [{ question: 'Which?', options: [] }],
+ } as InteractionRequest;
+}
+
+function makeSession() {
+ let listener: InteractionHandler | null = null;
+ const setInteractionListener = vi.fn((next: InteractionHandler | null) => {
+ listener = next;
+ });
+ return {
+ session: { id: 'session-1', setInteractionListener },
+ setInteractionListener,
+ dispatch: (request: InteractionRequest) => {
+ if (!listener) throw new Error('listener not installed');
+ return listener(request);
+ },
+ };
+}
+
+describe('session interaction router', () => {
+ it('owns one listener and falls back to the Desktop handler', async () => {
+ const harness = makeSession();
+ const desktop = vi.fn(async (): Promise<InteractionDecision> => ({
+ kind: 'permission',
+ behavior: 'allow',
+ }));
+
+ installDesktopInteractionHandler(harness.session, desktop);
+ installDesktopInteractionHandler(harness.session, desktop);
+
+ await expect(harness.dispatch(permission('desktop-1'))).resolves.toMatchObject({
+ behavior: 'allow',
+ });
+ expect(harness.setInteractionListener).toHaveBeenCalledTimes(1);
+ expect(desktop).toHaveBeenCalledTimes(1);
+ });
+
+ it('routes only the admitted turn to its channel surface', async () => {
+ const harness = makeSession();
+ const desktop = vi.fn(async (): Promise<InteractionDecision> => ({
+ kind: 'permission',
+ behavior: 'deny',
+ reason: 'desktop',
+ }));
+ const channel = vi.fn(async (): Promise<InteractionDecision> => ({
+ kind: 'permission',
+ behavior: 'allow',
+ }));
+ installDesktopInteractionHandler(harness.session, desktop);
+
+ const lease = beginInteractionRoute(harness.session, {
+ route: {
+ sessionId: 'session-1',
+ turnId: 'feishu-turn-1',
+ origin: { kind: 'im', channel: 'feishu' },
+ interactionSurface: 'channel-card',
+ },
+ handle: channel,
+ });
+
+ await expect(harness.dispatch(permission('channel-1'))).resolves.toMatchObject({
+ behavior: 'allow',
+ });
+ lease.release();
+ await expect(harness.dispatch(permission('desktop-2'))).resolves.toMatchObject({
+ reason: 'desktop',
+ });
+ expect(channel).toHaveBeenCalledTimes(1);
+ expect(desktop).toHaveBeenCalledTimes(1);
+ expect(harness.setInteractionListener).toHaveBeenCalledTimes(1);
+ });
+
+ it('routes an admitted personal WeChat turn to Desktop without a channel handler', async () => {
+ const harness = makeSession();
+ const desktop = vi.fn(async (): Promise<InteractionDecision> => ({
+ kind: 'permission',
+ behavior: 'allow',
+ }));
+ installDesktopInteractionHandler(harness.session, desktop);
+
+ const lease = beginInteractionRoute(harness.session, {
+ route: {
+ sessionId: 'session-1',
+ turnId: 'wechat-task-1',
+ origin: { kind: 'im', channel: 'wechat', taskId: 'wechat-task-1' },
+ interactionSurface: 'desktop',
+ },
+ });
+
+ await expect(harness.dispatch(permission('wechat-1'))).resolves.toMatchObject({
+ behavior: 'allow',
+ });
+ expect(desktop).toHaveBeenCalledOnce();
+ lease.release();
+ });
+
+ it('fails a Desktop-routed confirmation closed when its turn timeout expires', async () => {
+ vi.useFakeTimers();
+ try {
+ const harness = makeSession();
+ installDesktopInteractionHandler(
+ harness.session,
+ async () => new Promise<InteractionDecision>(() => {}),
+ );
+ const states: string[] = [];
+ const lease = beginInteractionRoute(harness.session, {
+ route: {
+ sessionId: 'session-1',
+ turnId: 'wechat-task-timeout',
+ origin: {
+ kind: 'im',
+ channel: 'wechat',
+ taskId: 'wechat-task-timeout',
+ },
+ interactionSurface: 'desktop',
+ timeoutMs: 100,
+ onStateChange: (state) => states.push(state),
+ },
+ });
+
+ const decision = harness.dispatch(permission('wechat-timeout'));
+ await vi.advanceTimersByTimeAsync(100);
+
+ await expect(decision).resolves.toMatchObject({
+ kind: 'permission',
+ behavior: 'deny',
+ reason: 'interaction_timeout',
+ });
+ expect(states).toEqual(['waiting', 'cancelled']);
+ lease.release();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('cancels pending requests with a kind-correct safe decision on release', async () => {
+ const harness = makeSession();
+ let keepPending!: () => void;
+ const never = new Promise<void>((resolve) => {
+ keepPending = resolve;
+ });
+ const onCancel = vi.fn();
+ const states: string[] = [];
+ const lease = beginInteractionRoute(harness.session, {
+ route: {
+ sessionId: 'session-1',
+ turnId: 'slack-turn-1',
+ origin: { kind: 'im', channel: 'slack' },
+ interactionSurface: 'channel-card',
+ onStateChange: (state) => states.push(state),
+ },
+ handle: async () => {
+ await never;
+ return { kind: 'ask_user_question', answers: { Which: 'late' } };
+ },
+ onCancel,
+ });
+
+ const decision = harness.dispatch(ask('ask-1'));
+ await vi.waitFor(() => expect(states).toEqual(['waiting']));
+ lease.release('turn_terminal');
+
+ await expect(decision).resolves.toEqual({
+ kind: 'ask_user_question',
+ answers: {},
+ });
+ expect(onCancel).toHaveBeenCalledWith('ask-1', {
+ kind: 'ask_user_question',
+ answers: {},
+ });
+ expect(states).toEqual(['waiting', 'cancelled']);
+ keepPending();
+ });
+
+ it('rejects overlapping routes before provider dispatch', () => {
+ const harness = makeSession();
+ const handle = vi.fn(async (): Promise<InteractionDecision> => ({
+ kind: 'permission',
+ behavior: 'allow',
+ }));
+ const first = beginInteractionRoute(harness.session, {
+ route: {
+ sessionId: 'session-1',
+ turnId: 'turn-1',
+ origin: { kind: 'hook', source: 'slack' },
+ interactionSurface: 'channel-card',
+ },
+ handle,
+ });
+
+ expect(() =>
+ beginInteractionRoute(harness.session, {
+ route: {
+ sessionId: 'session-1',
+ turnId: 'turn-2',
+ origin: { kind: 'im', channel: 'discord' },
+ interactionSurface: 'channel-card',
+ },
+ handle,
+ }),
+ ).toThrow(/already active/);
+
+ first.release();
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/interactionRouter.ts b/apps/desktop/src/main/maker-ipc/interactionRouter.ts
new file mode 100644
index 0000000000..b379300783
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/interactionRouter.ts
@@ -0,0 +1,216 @@
+/**
+ * Session-scoped interaction routing.
+ *
+ * Maker Session exposes a single replaceable interaction listener. Desktop,
+ * direct IM and hook-control used to overwrite that listener for each turn and
+ * later "restore" the previous surface. The router owns the listener for the
+ * lifetime of a Session instance; turn producers only register an active route.
+ */
+
+import type {
+ InteractionDecision,
+ InteractionRequest,
+ TurnPermissionOrigin,
+} from '@cindy/maker-core';
+
+export type TurnOrigin = TurnPermissionOrigin;
+
+export type InteractionSurface = 'desktop' | 'channel-card' | 'headless';
+export type InteractionRouteState = 'waiting' | 'resolved' | 'cancelled';
+
+export interface InteractionRoute {
+ sessionId: string;
+ turnId: string;
+ origin: TurnOrigin;
+ interactionSurface: InteractionSurface;
+ timeoutMs?: number;
+ onStateChange?(state: InteractionRouteState): void;
+}
+
+export type InteractionHandler = (request: InteractionRequest) => Promise<InteractionDecision>;
+
+export interface InteractionSession {
+ readonly id: string;
+ setInteractionListener(listener: InteractionHandler | null): void;
+}
+
+type RouteRegistration =
+ | {
+ route: InteractionRoute & { interactionSurface: 'desktop' };
+ handle?: never;
+ onCancel?: (requestId: string, decision: InteractionDecision) => boolean | void;
+ }
+ | {
+ route: InteractionRoute & { interactionSurface: 'channel-card' | 'headless' };
+ handle: InteractionHandler;
+ /**
+ * Return true when the routed surface resolved its own handler promise.
+ * Otherwise the router resolves the request with its kind-correct fallback.
+ */
+ onCancel?: (requestId: string, decision: InteractionDecision) => boolean | void;
+ };
+
+type ActiveRoute = RouteRegistration & { token: symbol };
+
+interface PendingRequest {
+ routeToken: symbol | null;
+ request: InteractionRequest;
+ cancel(decision: InteractionDecision): void;
+}
+
+export interface InteractionRouteLease {
+ readonly route: InteractionRoute;
+ release(reason?: string): void;
+}
+
+function safeDecision(
+ request: InteractionRequest,
+ reason: string,
+): InteractionDecision {
+ if (request.kind === 'ask_user_question') {
+ return { kind: 'ask_user_question', answers: {} };
+ }
+ if (request.kind === 'plan_review') {
+ return {
+ kind: 'plan_review',
+ behavior: 'deny',
+ reason,
+ dismissed: true,
+ };
+ }
+ return { kind: 'permission', behavior: 'deny', reason };
+}
+
+class SessionInteractionRouter {
+ private desktopHandler: InteractionHandler | null = null;
+ private activeRoute: ActiveRoute | null = null;
+ private readonly pending = new Map<string, PendingRequest>();
+
+ constructor(private readonly session: InteractionSession) {
+ session.setInteractionListener((request) => this.dispatch(request));
+ }
+
+ setDesktopHandler(handler: InteractionHandler): void {
+ this.desktopHandler = handler;
+ }
+
+ begin(registration: RouteRegistration): InteractionRouteLease {
+ if (registration.route.sessionId !== this.session.id) {
+ throw new Error(
+ `interaction route session mismatch: expected=${this.session.id} actual=${registration.route.sessionId}`,
+ );
+ }
+ if (this.activeRoute) {
+ throw new Error(
+ `interaction route already active for session=${this.session.id} turn=${this.activeRoute.route.turnId}`,
+ );
+ }
+ const active: ActiveRoute = {
+ ...registration,
+ token: Symbol(registration.route.turnId),
+ };
+ this.activeRoute = active;
+ let released = false;
+ return {
+ route: registration.route,
+ release: (reason = 'interaction_route_released') => {
+ if (released) return;
+ released = true;
+ if (this.activeRoute?.token !== active.token) return;
+ this.activeRoute = null;
+ for (const [requestId, pending] of this.pending) {
+ if (pending.routeToken !== active.token) continue;
+ const decision = safeDecision(pending.request, reason);
+ const handledBySurface = active.onCancel?.(requestId, decision) === true;
+ if (!handledBySurface) pending.cancel(decision);
+ }
+ },
+ };
+ }
+
+ private async dispatch(request: InteractionRequest): Promise<InteractionDecision> {
+ if (this.pending.has(request.requestId)) {
+ return safeDecision(request, 'duplicate_request_id');
+ }
+
+ const active = this.activeRoute;
+ const handler =
+ active?.route.interactionSurface === 'desktop'
+ ? this.desktopHandler
+ : active?.handle ?? this.desktopHandler;
+ if (!handler) return safeDecision(request, 'no_interaction_route');
+
+ let cancel!: (decision: InteractionDecision) => void;
+ let cancelledByRouter = false;
+ const cancelled = new Promise<InteractionDecision>((resolve) => {
+ cancel = (decision) => {
+ cancelledByRouter = true;
+ resolve(decision);
+ };
+ });
+ this.pending.set(request.requestId, {
+ routeToken: active?.token ?? null,
+ request,
+ cancel,
+ });
+ active?.route.onStateChange?.('waiting');
+ const timeoutMs = active?.route.timeoutMs;
+ const timeout =
+ timeoutMs && timeoutMs > 0
+ ? setTimeout(() => {
+ const decision = safeDecision(request, 'interaction_timeout');
+ const handledBySurface =
+ active?.onCancel?.(request.requestId, decision) === true;
+ if (!handledBySurface) cancel(decision);
+ }, timeoutMs)
+ : null;
+
+ try {
+ const decision = await Promise.race([handler(request), cancelled]);
+ active?.route.onStateChange?.(
+ !cancelledByRouter && this.activeRoute?.token === active?.token
+ ? 'resolved'
+ : 'cancelled',
+ );
+ return decision;
+ } catch {
+ active?.route.onStateChange?.('cancelled');
+ return safeDecision(request, 'interaction_handler_failed');
+ } finally {
+ if (timeout) clearTimeout(timeout);
+ this.pending.delete(request.requestId);
+ }
+ }
+}
+
+const routers = new WeakMap<object, SessionInteractionRouter>();
+
+function routerFor(session: InteractionSession): SessionInteractionRouter {
+ const key = session as object;
+ let router = routers.get(key);
+ if (!router) {
+ router = new SessionInteractionRouter(session);
+ routers.set(key, router);
+ }
+ return router;
+}
+
+/** Register/update the Desktop fallback without replacing Session's listener. */
+export function installDesktopInteractionHandler(
+ session: InteractionSession,
+ handler: InteractionHandler,
+): void {
+ routerFor(session).setDesktopHandler(handler);
+}
+
+/**
+ * Activate a non-Desktop route after Session's busy guard has admitted the
+ * turn. A second live route is rejected so the provider cannot start with an
+ * ambiguous interaction destination.
+ */
+export function beginInteractionRoute(
+ session: InteractionSession,
+ registration: RouteRegistration,
+): InteractionRouteLease {
+ return routerFor(session).begin(registration);
+}
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 14e6c3b80d..1b2bb446ff 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -324,6 +324,7 @@ import {
readOrcaWorkerOutputReadOnly,
} from './orcaDiagnostics.js';
import { createMakerSendTransaction } from './makerSendTransaction.js';
+import { installDesktopInteractionHandler } from './interactionRouter.js';
import { registerMakerMessageDeleteHandler } from './messageDeleteHandler.js';
import { normalizeUserMessage, materializeQueuedOssAttachments } from './normalizeAttachments.js';
import { AGENT_ISLAND_DISPLAY_CONFIG } from '../agent-island/displayConfig.js';
@@ -1491,13 +1492,21 @@ export function takePendingInteractionsForSession(
return taken;
}
+type WiredSession = NonNullable<ReturnType<Maker['getSession']>>;
+
+interface WiredSessionRegistration {
+ session: WiredSession;
+ disposers: Array<() => void>;
+}
+
/**
- * 标记已经 wire 过 IPC 转发的 session, 避免 lazy-create 路径或多个调用方
+ * 记录已经 wire 过 IPC 转发的 session 实例,避免 lazy-create 路径或多个调用方
* (renderer IPC handler / scheduler runner / feishu 接管 / future MCP server) 重复挂 listener。
*
- * 进程级单例 —— register.ts 模块只 load 一次, 此 Set 在 closeSession 时按 id 清理。
+ * deferred agent switch 会保留业务 id 但替换 Session 实例;此时必须解绑旧实例并完整
+ * wire 新实例,不能只按 id 去重。
*/
-const wiredSessionIds = new Set<string>();
+const wiredSessionsById = new Map<string, WiredSessionRegistration>();
/**
* SDK result 事件的 total_cost_usd 是 session 累计 (不是 per-turn) ——
@@ -2144,22 +2153,19 @@ export function setGoalAskAnswerObserver(
}
/**
- * 把 desktop 版的 interaction listener 装到一个 session 上 — 行为: broadcast
+ * 把 Desktop fallback handler 登记到 session 级中央 InteractionRouter — 行为:broadcast
* INTERACTION_REQUEST 给所有 window, 等 renderer 通过 RESOLVE_INTERACTION IPC
* 回 decision。permission 10 分钟超时兜底为 deny; ask/plan 不超时,必须等
* 用户提交、停止任务或关闭 session。
*
- * 抽出来 export 是为了 feishu /ctr 接管流程的 detach 路径能"还原" desktop
- * listener: 接管期间 setInteractionListener 是 single-listener 语义, 被 feishu
- * 版覆盖了, detach 后必须主动调一次 install... 把 desktop 版重新挂回去,
- * 否则 desktop renderer 永远收不到 permission 弹窗。
- *
- * 幂等: setInteractionListener 是覆盖式写, 重复调安全。
+ * Router 在 Session 实例生命周期内只安装一次 listener。Feishu/Discord/Slack
+ * turn 通过 beforeProviderStart 登记临时 route,终态只释放自己的 lease,
+ * 不再覆盖或“还原” Desktop listener。重复调用只更新 Desktop fallback。
*/
export function installDesktopInteractionListener(
session: { id: string; setInteractionListener: (l: ((req: InteractionRequest) => Promise<InteractionDecision>) | null) => void },
): void {
- session.setInteractionListener(async (req: InteractionRequest) => {
+ installDesktopInteractionHandler(session, async (req: InteractionRequest) => {
const agentIslandInteractionEpoch = shouldNotifyAgentIslandForSession(session.id)
? getAgentIslandService()?.captureInteractionEpoch(session.id) ?? null
: null;
@@ -2370,8 +2376,17 @@ async function handleSilentStopTurnEnd(
export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void {
if (!session) return;
- if (wiredSessionIds.has(session.id)) return;
- wiredSessionIds.add(session.id);
+ const existing = wiredSessionsById.get(session.id);
+ if (existing?.session === session) {
+ installDesktopInteractionListener(session);
+ return;
+ }
+ if (existing) {
+ for (const dispose of existing.disposers) dispose();
+ existing.session.setInteractionListener(null);
+ }
+ const registration: WiredSessionRegistration = { session, disposers: [] };
+ wiredSessionsById.set(session.id, registration);
// session-agent-switch:登记本会话当前引擎,broadcaster / user 行落库据此逐行
// stamp messages.agent_kind(切换后历史行的 agent_meta 必须按写入时引擎解析)。
@@ -2380,15 +2395,15 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
// 订阅槽①旁听 tap(独立监听,叠加在主转发之外互不干扰):AgentEvent →
// did-turn-*。资格(用户主会话)与自动化轮次过滤都在 tap 内部,这里零逻辑。
const ghostSessionTap = createGhostSessionTap(session.id);
- session.onEvent((event: AgentEvent) => {
+ registration.disposers.push(session.onEvent((event: AgentEvent) => {
ghostSessionTap.handleEvent(
event as { type: string; data?: unknown; source?: string; turnOrigin?: { kind?: string } },
);
- });
+ }));
// 转发事件到所有 window。interaction_dismissed 单独走专用 channel,
// 让 renderer chat store 不必扫所有 vendor-raw 找它。
- session.onEvent((event: AgentEvent) => {
+ registration.disposers.push(session.onEvent((event: AgentEvent) => {
const broadcastEvent = redactEventForRenderer(event);
if (event.type === 'interaction_dismissed') {
const data = event.data as { requestId?: unknown; reason?: unknown };
@@ -3154,8 +3169,9 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
});
}
}
- });
- session.onStatusChange((status) => {
+ }));
+ registration.disposers.push(session.onStatusChange((status) => {
+ if (wiredSessionsById.get(session.id)?.session !== session) return;
broadcastToAllWindows(MAKER_PUSH.STATUS_CHANGED, { sessionId: session.id, status });
if (status === 'closed') {
cleanupPendingInteractionsForSession(session.id, 'session_closed');
@@ -3165,7 +3181,9 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
deferredCodexRestartHolder?.onSessionSettled();
agentInputCoordinatorHolder?.onExternalTurnSettled(session.id);
gitSnapshotCoordinator?.onSessionClosed(session.id);
- wiredSessionIds.delete(session.id);
+ wiredSessionsById.delete(session.id);
+ for (const dispose of registration.disposers) dispose();
+ session.setInteractionListener(null);
clearOrcaMcpHydrated(session.id);
knownNonOrcaSessionIds.delete(session.id);
lastReportedCostUsdBySession.delete(session.id);
@@ -3178,7 +3196,7 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
clearSessionPersistState(session.id);
handleAgentIslandSessionClosedAfterCleanup(session.id);
}
- });
+ }));
// 注入 interaction listener (permission/ask/plan 三合一,renderer 按 kind 弹不同 UI)
installDesktopInteractionListener(session);
@@ -3827,7 +3845,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
});
// ── Session 生命周期 ────────────────────────────────────────────────────
- // wiredSessionIds + lastReportedCostUsdBySession + sessionTurnActivityTracker 都在模块顶层,
+ // wiredSessionsById + lastReportedCostUsdBySession + sessionTurnActivityTracker 都在模块顶层,
// 让 scheduler runner / feishu 接管 / future MCP 等绕过 IPC 的调用方也能复用同一份 wire 逻辑。
type CreateOpts = MakerSessionCreateOpts;
diff --git a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
index cf5144ed59..c8c2d2c7c2 100644
--- a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
+++ b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
@@ -13,7 +13,7 @@ import { getCindyGhostsMcpDeps } from './ghost.js';
import { getAndroidMcpDeps } from './android.js';
import { getBrowserMcpDeps } from './browser.js';
import { getComputerMcpDeps } from './computer.js';
-import { feishuIm } from '../im';
+import { feishuIm, wechatIm } from '../im';
import { getSlackToolBridge } from '../hook-control/slackToolBridge.js';
import { createLogger } from '../logger.js';
import { getScheduler } from '../scheduler-host/index.js';
@@ -142,6 +142,36 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMc
},
logger: createLogger('mcp/cindy_feishu_bot'),
},
+ wechatBot: {
+ getActivePeerIdForSession: (sessionId) =>
+ wechatIm.getActivePeerIdForSession(sessionId),
+ getMostRecentPeerId: () => wechatIm.getMostRecentPeerId(),
+ sendMessage: async (peerId, text) => {
+ try {
+ const { messageId } = await wechatIm.sendText(peerId, text);
+ return { ok: true, messageId };
+ } catch (error) {
+ createLogger('mcp/cindy_wechat').warn(
+ 'sendMessage failed target=...%s detail=%s',
+ peerId.slice(-8),
+ error instanceof Error ? error.message : String(error),
+ );
+ return { ok: false, reason: 'SEND_FAIL' };
+ }
+ },
+ sendFile: async (peerId, absPath, displayName) => {
+ const result = await wechatIm.sendFile(peerId, absPath, displayName);
+ if (!result.ok) {
+ createLogger('mcp/cindy_wechat').warn(
+ 'sendFile failed target=...%s reason=%s',
+ peerId.slice(-8),
+ result.reason ?? 'unknown',
+ );
+ }
+ return result;
+ },
+ logger: createLogger('mcp/cindy_wechat'),
+ },
// cindy_slack(2026-07-19): Slack 网关工具。桥经 hook-control 的零依赖
// 注册表取用(静态 import ipc.ts 会与 maker-host 闭环, 见 slackToolBridge
// 模块头); 未注册 = null, provider isEnabled fail-closed。
diff --git a/apps/desktop/src/main/scheduler-host/runner.ts b/apps/desktop/src/main/scheduler-host/runner.ts
index d162fc8207..61545322d8 100644
--- a/apps/desktop/src/main/scheduler-host/runner.ts
+++ b/apps/desktop/src/main/scheduler-host/runner.ts
@@ -766,7 +766,7 @@ export class MakerScheduleRunner implements ScheduleRunner {
// assistant text / tool_use / tool_result 等落库到 messages 表。
// 不 wire → renderer 收不到事件 → messages 永远空(修复 Phase 6 之前 bug:
// 调度跑出来的 session 在 UI 里一片空白,msg_count=0,但 schedule_runs.status=success)。
- // wireSessionToIpc 内部按 session.id 幂等,并发 fire 同 session 不会重复挂。
+ // wireSessionToIpc 内部按 Session 实例幂等;同 id 换实例时会先解绑旧实例。
wireSessionToIpc(session);
// 4.5.0 abort listener:scheduler 在 user delete/pause 时会 abort ctx.signal,
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index f6713b79e9..6ad6f7c805 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -374,6 +374,8 @@ const fanOutFeishuBotConflict = createIpcFanOut('feishuBot:conflict');
const fanOutFeishuBotRegistrationStatus = createIpcFanOut('feishuBot:registration-status');
// Discord Bot:本机凭证模式;这里只暴露 @cindy/im DiscordIM 的 transport 状态。
const fanOutDiscordBotStatusChange = createIpcFanOut('discordBot:status-change');
+// Personal WeChat: main owns auth/polling and broadcasts a credential-free state snapshot.
+const fanOutWechatBotStateChange = createIpcFanOut('wechatBot:state-changed');
const fanOutVoiceInputEvent = createIpcFanOut('voice-input:event');
const fanOutVoiceInputGlobalShortcutTrigger = createIpcFanOut('voice-input:global-shortcut-trigger');
const fanOutVoiceInputGlobalOverlayCommand = createIpcFanOut('voice-input:global-overlay-command');
@@ -1464,6 +1466,47 @@ contextBridge.exposeInMainWorld('electronAPI', {
onStatusChange: fanOutDiscordBotStatusChange,
},
+ // ── Personal WeChat (Settings → IM Bot → Personal) ──
+ // Renderer receives state only. Authorization URLs and credentials never
+ // cross preload; main opens the Tencent page in the system browser.
+ wechatBot: {
+ getState: (): Promise<{
+ phase:
+ | 'disconnected'
+ | 'authorizing'
+ | 'waiting_confirmation'
+ | 'connected'
+ | 'reconnecting'
+ | 'needs_reauth'
+ | 'disabled_by_policy'
+ | 'error';
+ bound: boolean;
+ connectedAt?: number;
+ lastInboundAt?: number;
+ queuedTasks: number;
+ errorCode?: string;
+ }> => ipcRenderer.invoke('wechatBot:get-state'),
+ authorize: (): Promise<{ started: true }> => ipcRenderer.invoke('wechatBot:authorize'),
+ cancelAuthorization: (): Promise<{ ok: true }> =>
+ ipcRenderer.invoke('wechatBot:cancel-authorization'),
+ unbind: (): Promise<{ ok: true }> => ipcRenderer.invoke('wechatBot:unbind'),
+ getChannelSettings: (): Promise<{
+ version: 1;
+ workingDir: string | null;
+ workingDirAvailable: boolean;
+ }> => ipcRenderer.invoke('wechatBot:get-channel-settings'),
+ chooseWorkingDirectory: (): Promise<{
+ canceled: boolean;
+ state: { version: 1; workingDir: string | null; workingDirAvailable: boolean };
+ }> => ipcRenderer.invoke('wechatBot:choose-working-directory'),
+ resetWorkingDirectory: (): Promise<{
+ version: 1;
+ workingDir: string | null;
+ workingDirAvailable: boolean;
+ }> => ipcRenderer.invoke('wechatBot:reset-working-directory'),
+ onStateChange: fanOutWechatBotStateChange,
+ },
+
// Renderer → main 的 "用户已登录 + localDb 已就绪" 信号。LocalDbGate 在
// ensureReady 成功之后 fire-and-forget 调一次。main 收到后才启动 FeishuBot
// 的 WS 长连接 —— 在此之前 bot 不上线,避免"bot 已上线但 db/auth 未就绪,
diff --git a/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts b/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts
index f291a398d0..b96a41cdef 100644
--- a/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts
+++ b/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts
@@ -109,6 +109,7 @@ describe('automation-generated sessions', () => {
'slack',
'telegram',
'discord',
+ 'wechat',
'scheduler',
'learn',
'shared',
@@ -968,7 +969,9 @@ describe('automation-generated sessions', () => {
expect(zh.scheduler.runs.sessionValue).toBe('对话价值 {{value}}');
expect(zh.scheduler.runs.runCost).toBe('本次开销 {{cost}}');
expect(zh.scheduler.runs.legacyCostUnavailable).toBe('历史费用无法拆分');
- expect(zh.scheduler.runs.persistentSessionGroup).toBe('持续对话 {{session}} · {{count}} 次运行');
+ expect(zh.scheduler.runs.persistentSessionGroup).toBe(
+ '持续对话 {{session}} · {{count}} 次运行',
+ );
expect(zh.scheduler.runs.expandRemainingRuns).toBe('展开另外 {{count}} 次');
});
diff --git a/apps/desktop/src/renderer/__tests__/imageRefParseUserContent.test.ts b/apps/desktop/src/renderer/__tests__/imageRefParseUserContent.test.ts
index 1f62a64805..d4d4fef698 100644
--- a/apps/desktop/src/renderer/__tests__/imageRefParseUserContent.test.ts
+++ b/apps/desktop/src/renderer/__tests__/imageRefParseUserContent.test.ts
@@ -189,6 +189,23 @@ describe('parseUserContent — array input (SDK content blocks)', () => {
expect(parseUserContent([])).toEqual({ text: '', images: [], files: [] });
});
+ it('restores persisted IM image blocks from cindy-media URLs', () => {
+ const url = `cindy-media://blobs/${ATTACHMENT_SHA256}.png`;
+ const blocks = [
+ {
+ type: 'image',
+ path: 'C:\\Users\\User\\wechat-image.png',
+ mimeType: 'image/png',
+ url,
+ },
+ ];
+ expect(parseUserContent(blocks)).toEqual({
+ text: '',
+ images: [{ url, mimeType: 'image/png', originalName: 'wechat-image.png' }],
+ files: [],
+ });
+ });
+
it('returns empty text for array of only image blocks', () => {
const blocks = [{ type: 'image', source: {} }];
expect(parseUserContent(blocks)).toEqual({ text: '', images: [], files: [] });
@@ -210,9 +227,7 @@ describe('parseUserContent — array input (SDK content blocks)', () => {
});
});
- it('SDK array content always yields empty files (no SDK file block exists)', () => {
- // Even if a malicious / future block claims to be a file, we ignore it —
- // file attachments only round-trip via the {text, images, files} shape.
+ it('restores legacy IM file blocks', () => {
const blocks = [
{ type: 'text', text: 'hi' },
{ type: 'document', source: { type: 'base64', data: '...' } },
@@ -221,7 +236,7 @@ describe('parseUserContent — array input (SDK content blocks)', () => {
expect(parseUserContent(blocks)).toEqual({
text: 'hi',
images: [],
- files: [],
+ files: [{ name: 'x.txt', path: '/x' }],
});
});
});
diff --git a/apps/desktop/src/renderer/__tests__/permissionSelectorMorph.test.tsx b/apps/desktop/src/renderer/__tests__/permissionSelectorMorph.test.tsx
index 521d019056..e3852f40cf 100644
--- a/apps/desktop/src/renderer/__tests__/permissionSelectorMorph.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/permissionSelectorMorph.test.tsx
@@ -271,6 +271,41 @@ describe('PermissionSelector triggerVariant', () => {
await waitFor(() => expect(document.activeElement).toBe(selectedOption));
});
+ it('field 形态可原生禁用渠道不支持的权限档', async () => {
+ const { onChange } = renderSelector({
+ triggerVariant: 'field',
+ disabledModes: { bypassPermissions: '个人微信暂不支持' },
+ });
+ fireEvent.click(getTrigger());
+ await screen.findByRole('listbox');
+
+ const fullAccess = screen.getByRole('option', { name: '完全访问' });
+ expect((fullAccess as HTMLButtonElement).disabled).toBe(true);
+ fireEvent.click(fullAccess);
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it('keeps the selected disabled mode focusable for keyboard navigation', async () => {
+ const { onChange } = renderSelector({
+ triggerVariant: 'field',
+ permissionMode: 'bypassPermissions',
+ disabledModes: { bypassPermissions: 'Personal WeChat is not supported' },
+ });
+ fireEvent.click(getTrigger());
+ const listbox = await screen.findByRole('listbox');
+
+ const selectedOption = screen.getByRole('option', { name: '完全访问' });
+ const defaultOption = screen.getByRole('option', { name: '默认权限' });
+ await waitFor(() => expect(document.activeElement).toBe(selectedOption));
+ expect((selectedOption as HTMLButtonElement).disabled).toBe(false);
+ expect(selectedOption.getAttribute('aria-disabled')).toBe('true');
+
+ fireEvent.keyDown(listbox, { key: 'ArrowDown' });
+ expect(document.activeElement).toBe(defaultOption);
+ fireEvent.click(selectedOption);
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
it('ariaContext 前置到 trigger 可及名(多实例同屏读屏区分,不传则原样)', () => {
renderSelector({ triggerVariant: 'field', ariaContext: '权限模式 · chat' });
expect(screen.getByRole('button', { name: '权限模式 · chat:默认权限' })).toBeTruthy();
diff --git a/apps/desktop/src/renderer/components/new-chat/PermissionSelector.tsx b/apps/desktop/src/renderer/components/new-chat/PermissionSelector.tsx
index 18560ddfa5..e5b99b95bc 100644
--- a/apps/desktop/src/renderer/components/new-chat/PermissionSelector.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/PermissionSelector.tsx
@@ -47,6 +47,8 @@ interface PermissionSelectorProps {
* VendorSegmentedSwitcher.ariaLabel 同一动机;单实例的 composer 不传,行为不变。
*/
ariaContext?: string;
+ /** Disable individual modes without forking the shared permission picker. */
+ disabledModes?: Partial<Record<PermissionMode, string>>;
}
/**
@@ -103,6 +105,7 @@ export function PermissionSelector({
visualVariant = 'default',
triggerVariant = 'chip',
ariaContext,
+ disabledModes,
}: PermissionSelectorProps) {
const { t } = useTranslation();
const [open, setOpen] = useState(false);
@@ -291,10 +294,11 @@ export function PermissionSelector({
const selectedTone = isSelected ? getModeTone(option.id) : null;
const label = labelOf(option, option.id);
const description = descriptionOf(option, option.id);
+ const disabledReason = disabledModes?.[option.id];
return (
<Tip
key={option.id}
- text={description}
+ text={disabledReason ?? description}
side="right"
contentClassName="max-w-[280px] whitespace-normal break-words text-left"
>
@@ -304,7 +308,10 @@ export function PermissionSelector({
// MorphPopover 打开后优先聚焦当前选中项;否则会聚焦列表首项,
// 触发“默认权限”的 focus tooltip,造成介绍与当前权限不一致。
data-morph-autofocus={isSelected ? '' : undefined}
+ aria-disabled={Boolean(disabledReason)}
+ disabled={Boolean(disabledReason) && !isSelected}
onClick={() => {
+ if (disabledReason) return;
onPermissionModeChange(option.id);
setOpen(false);
}}
@@ -322,6 +329,7 @@ export function PermissionSelector({
selectedTone === 'auto' && 'text-[var(--perm-auto-selected-text)]',
selectedTone === 'bypassPermissions' &&
'text-[var(--perm-bypass-selected-text)]',
+ disabledReason && 'cursor-not-allowed opacity-45 hover:bg-transparent',
)}
>
<Icon
diff --git a/apps/desktop/src/renderer/components/settings/ImBotSection.tsx b/apps/desktop/src/renderer/components/settings/ImBotSection.tsx
index 340eef8b26..1c4469a9cc 100644
--- a/apps/desktop/src/renderer/components/settings/ImBotSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/ImBotSection.tsx
@@ -28,6 +28,7 @@ import { CURRENT_CINDY_REGION } from '../../../shared/brandRegion';
import { DiscordBotSection } from './DiscordBotSection';
import { FeishuBotSection } from './FeishuBotSection';
import { HookConnectionsSection } from './HookConnectionsSection';
+import { WechatBotSection } from './WechatBotSection';
import { showCindyGroup, showDiscordBot, type ImBotIdentity } from './imBotVisibility';
/** 「IM 机器人」页内分栏 id(tab 与 ?imGroup= 参数共用)。 */
@@ -55,14 +56,17 @@ export function isImBotSettingsGroup(value: string | null): value is ImBotSettin
/** 个人栏内容 —— 用户自配凭证的机器人(国区个人账号无 Discord)。 */
function PersonalGroupContent({ showDiscord }: { showDiscord: boolean }) {
- const [expandedChannel, setExpandedChannel] = useState<'feishu' | 'discord' | null>(null);
+ const [expandedChannel, setExpandedChannel] = useState<'wechat' | 'feishu' | 'discord' | null>(
+ null,
+ );
- const toggle = (channel: 'feishu' | 'discord') => {
+ const toggle = (channel: 'wechat' | 'feishu' | 'discord') => {
setExpandedChannel((current) => (current === channel ? null : channel));
};
return (
<div className="flex flex-col gap-3">
+ <WechatBotSection expanded={expandedChannel === 'wechat'} onToggle={() => toggle('wechat')} />
<FeishuBotSection expanded={expandedChannel === 'feishu'} onToggle={() => toggle('feishu')} />
{showDiscord && (
<DiscordBotSection
diff --git a/apps/desktop/src/renderer/components/settings/ImDefaultSettingsSection.tsx b/apps/desktop/src/renderer/components/settings/ImDefaultSettingsSection.tsx
index d46e1bc7d6..102becc9a8 100644
--- a/apps/desktop/src/renderer/components/settings/ImDefaultSettingsSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/ImDefaultSettingsSection.tsx
@@ -13,6 +13,7 @@ import { useTranslation } from 'react-i18next';
import { ClaudeMark } from '@/components/icons/ClaudeMark';
import { CodexMark } from '@/components/icons/CodexMark';
import { ModelSelector } from '@/components/new-chat/ModelSelector';
+import { PermissionSelector } from '@/components/new-chat/PermissionSelector';
import { type ModelDescriptor, useAgentCapabilities } from '@/hooks/useAgentCapabilities';
import { useProviders } from '@/hooks/useProviders';
import { deriveModelsFromProviders } from '@/lib/providerModels';
@@ -28,6 +29,8 @@ import {
type ImDefaultSettingsPatch,
type ImDefaultSettingsState,
isImDefaultEffort,
+ isImDefaultPermissionMode,
+ isWechatUnsupportedPermissionMode,
} from '../../../shared/imDefaultSettings';
import { DefaultOverrideControls } from './DefaultOverrideControls';
import { buildAgentSettingsPatch, mergeSettingsPatch } from './imDefaultSettingsLogic';
@@ -212,6 +215,17 @@ export function ImDefaultSettingsSection({
);
};
+ const changePermissionMode = (permissionMode: string) => {
+ if (
+ !isImDefaultPermissionMode(permissionMode) ||
+ isWechatUnsupportedPermissionMode(permissionMode) ||
+ permissionMode === settings.permissionMode
+ ) {
+ return;
+ }
+ void persist({ permissionMode });
+ };
+
return (
<section
className={cn(
@@ -304,6 +318,29 @@ export function ImDefaultSettingsSection({
/>
</div>
</div>
+
+ {channel === 'wechat' && (
+ <div className="flex flex-col gap-2">
+ <span className="text-[12px] font-medium text-[var(--text-secondary)]">
+ {t('settings.wechatBot.permission.label')}
+ </span>
+ <PermissionSelector
+ permissionMode={settings.permissionMode}
+ onPermissionModeChange={changePermissionMode}
+ vendorKey={vendorKeyFor(settings.agentKind)}
+ disabled={pending}
+ triggerVariant="field"
+ ariaContext={t('settings.wechatBot.permission.label')}
+ disabledModes={{
+ bypassPermissions: t('settings.wechatBot.permission.fullAccessDisabled'),
+ acceptEdits: t('settings.wechatBot.permission.permissionModeDisabled'),
+ }}
+ />
+ <p className="text-[12px] leading-[1.5] text-[var(--settings-section-desc)]">
+ {t('settings.wechatBot.permission.hint')}
+ </p>
+ </div>
+ )}
</section>
);
}
diff --git a/apps/desktop/src/renderer/components/settings/WechatBotSection.tsx b/apps/desktop/src/renderer/components/settings/WechatBotSection.tsx
new file mode 100644
index 0000000000..3412ac91bf
--- /dev/null
+++ b/apps/desktop/src/renderer/components/settings/WechatBotSection.tsx
@@ -0,0 +1,335 @@
+import { Check, FolderOpen, Loader2, RotateCw, Trash2, Unplug } from 'lucide-react';
+import { useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';
+import { useWechatBot } from '@/hooks/useWechatBot';
+import { cn } from '@/lib/utils';
+import { ImChannelSettingsCard, useImChannelSettingsSummary } from './ImChannelSettingsCard';
+import { ImDefaultSettingsSection } from './ImDefaultSettingsSection';
+
+const STATUS_KEYS: Record<WechatBotPhase, string> = {
+ disconnected: 'settings.wechatBot.status.disconnected',
+ authorizing: 'settings.wechatBot.status.authorizing',
+ waiting_confirmation: 'settings.wechatBot.status.waitingConfirmation',
+ connected: 'settings.wechatBot.status.connected',
+ reconnecting: 'settings.wechatBot.status.reconnecting',
+ needs_reauth: 'settings.wechatBot.status.needsReauth',
+ disabled_by_policy: 'settings.wechatBot.status.disabled',
+ error: 'settings.wechatBot.status.error',
+};
+
+function statusColor(phase: WechatBotPhase): string {
+ switch (phase) {
+ case 'connected':
+ return 'var(--settings-badge-connected)';
+ case 'authorizing':
+ case 'waiting_confirmation':
+ case 'reconnecting':
+ case 'needs_reauth':
+ return 'var(--settings-badge-saved)';
+ case 'error':
+ case 'disabled_by_policy':
+ return 'var(--settings-badge-error)';
+ case 'disconnected':
+ return 'var(--settings-badge-needs-config)';
+ }
+}
+
+function statusTextColor(phase: WechatBotPhase): string {
+ return phase === 'connected' ? 'var(--settings-badge-connected-text)' : statusColor(phase);
+}
+
+export function WechatBotSection({
+ expanded,
+ onToggle,
+}: {
+ expanded: boolean;
+ onToggle: () => void;
+}) {
+ const { t } = useTranslation();
+ const { confirm } = useConfirmDialog();
+ const {
+ state,
+ channelSettings,
+ isAuthorizing,
+ isUnbinding,
+ isUpdatingWorkingDir,
+ authorize,
+ cancelAuthorization,
+ unbind,
+ chooseWorkingDirectory,
+ resetWorkingDirectory,
+ } = useWechatBot();
+ const [routeSummary, setRouteSummary] = useImChannelSettingsSummary('wechat');
+
+ const authorizationSteps = (
+ <ol className="mt-1 grid gap-2 rounded-xl border border-[var(--border-default)] bg-[var(--surface-chip)] px-4 py-3 text-[12px] leading-[1.55] text-[var(--text-secondary)]">
+ {[1, 2, 3, 4].map((step) => (
+ <li key={step} className="flex gap-2">
+ <span className="shrink-0 text-[var(--text-tertiary)]">{step}.</span>
+ <span>{t(`settings.wechatBot.authorization.steps.${step}`)}</span>
+ </li>
+ ))}
+ </ol>
+ );
+
+ const handleAuthorize = useCallback(async () => {
+ const replacing = state.bound;
+ const accepted = await confirm({
+ title: t(
+ replacing
+ ? 'settings.wechatBot.authorization.rebindTitle'
+ : 'settings.wechatBot.authorization.title',
+ ),
+ description: t(
+ replacing
+ ? 'settings.wechatBot.authorization.rebindDescription'
+ : 'settings.wechatBot.authorization.description',
+ ),
+ content: authorizationSteps,
+ confirmText: t('settings.wechatBot.authorization.confirm'),
+ cancelText: t('settings.wechatBot.authorization.cancel'),
+ maxWidth: 440,
+ autoFocusConfirm: true,
+ });
+ if (accepted) await authorize();
+ }, [authorizationSteps, authorize, confirm, state.bound, t]);
+
+ const handleUnbind = useCallback(async () => {
+ const accepted = await confirm({
+ title: t('settings.wechatBot.unbind.title'),
+ description: t('settings.wechatBot.unbind.description'),
+ confirmText: t('settings.wechatBot.unbind.confirm'),
+ cancelText: t('settings.wechatBot.unbind.cancel'),
+ });
+ if (accepted) await unbind();
+ }, [confirm, t, unbind]);
+
+ const authorizationPending =
+ state.phase === 'authorizing' || state.phase === 'waiting_confirmation';
+ const disabledByPolicy = state.phase === 'disabled_by_policy';
+
+ return (
+ <ImChannelSettingsCard
+ id="personal-im-wechat"
+ title={t('settings.wechatBot.title')}
+ description={t('settings.wechatBot.description')}
+ routeSummary={
+ routeSummary
+ ? `${t(`settings.imBot.defaults.agents.${routeSummary.agentKind}`)} · ${routeSummary.model}`
+ : null
+ }
+ expanded={expanded}
+ onToggle={onToggle}
+ status={
+ <span
+ className={cn(
+ 'inline-flex items-center gap-1.5 rounded-full',
+ 'border border-[var(--settings-badge-border)] bg-[var(--settings-badge-bg)]',
+ 'px-2.5 py-1 text-11 font-medium tracking-[0.12px]',
+ )}
+ style={{ color: statusTextColor(state.phase) }}
+ role="status"
+ aria-live="polite"
+ aria-label={t('settings.wechatBot.statusAria', {
+ status: t(STATUS_KEYS[state.phase]),
+ })}
+ >
+ <span
+ className="h-1.5 w-1.5 rounded-full"
+ style={{ backgroundColor: statusColor(state.phase) }}
+ aria-hidden
+ />
+ {t(STATUS_KEYS[state.phase])}
+ </span>
+ }
+ >
+ <ImDefaultSettingsSection channel="wechat" embedded onSummaryChange={setRouteSummary} />
+
+ <div className="h-px w-full bg-[var(--border-default)]" />
+
+ <WechatWorkingDirectory
+ settings={channelSettings}
+ pending={isUpdatingWorkingDir}
+ onChoose={() => void chooseWorkingDirectory()}
+ onReset={() => void resetWorkingDirectory()}
+ />
+
+ <div className="h-px w-full bg-[var(--border-default)]" />
+
+ {authorizationPending ? (
+ <div className="flex flex-col items-center gap-3 rounded-xl border border-[var(--settings-theme-card-border)] bg-[var(--settings-theme-card-bg)] px-5 py-6 text-center">
+ <span className="inline-flex animate-spin text-[var(--text-secondary)] motion-reduce:animate-none">
+ <Loader2 size={22} />
+ </span>
+ <div>
+ <h3 className="text-13 font-medium text-[var(--settings-section-title)]">
+ {t('settings.wechatBot.waiting.heading')}
+ </h3>
+ <p className="mt-1 max-w-[460px] text-12 leading-[1.6] text-[var(--settings-section-desc)]">
+ {t('settings.wechatBot.waiting.note')}
+ </p>
+ </div>
+ <button
+ type="button"
+ onClick={() => void cancelAuthorization()}
+ className="h-9 rounded-full border border-[var(--settings-btn-secondary-border)] bg-[var(--settings-btn-secondary-bg)] px-5 text-12 font-medium text-[var(--settings-btn-secondary-text)]"
+ >
+ {t('settings.wechatBot.waiting.cancel')}
+ </button>
+ </div>
+ ) : state.bound ? (
+ <div className="flex flex-col gap-4 rounded-xl border border-[var(--settings-theme-card-border)] bg-[var(--settings-theme-card-bg)] p-5">
+ <div className="flex items-start gap-3">
+ <div className="mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-full border border-[var(--settings-badge-border)] bg-[var(--settings-badge-bg)] text-[var(--settings-badge-connected)]">
+ {state.phase === 'connected' ? <Check size={16} /> : <Unplug size={16} />}
+ </div>
+ <div className="min-w-0">
+ <h3 className="text-13 font-medium text-[var(--settings-section-title)]">
+ {t(
+ state.phase === 'connected'
+ ? 'settings.wechatBot.bound.heading'
+ : 'settings.wechatBot.bound.attentionHeading',
+ )}
+ </h3>
+ <p className="mt-1 text-12 leading-[1.6] text-[var(--settings-section-desc)]">
+ {t(`settings.wechatBot.bound.notes.${state.phase}`)}
+ </p>
+ </div>
+ </div>
+ <div className="flex flex-wrap gap-2">
+ <button
+ type="button"
+ onClick={() => void handleAuthorize()}
+ disabled={isAuthorizing || disabledByPolicy}
+ className={cn(
+ 'flex h-9 flex-1 items-center justify-center gap-1.5 rounded-full',
+ 'border border-[var(--settings-btn-secondary-border)] bg-[var(--settings-btn-secondary-bg)]',
+ 'px-4 text-12 font-medium text-[var(--settings-btn-secondary-text)]',
+ (isAuthorizing || disabledByPolicy) && 'cursor-not-allowed opacity-40',
+ )}
+ >
+ {isAuthorizing ? (
+ <Loader2 size={13} className="animate-spin motion-reduce:animate-none" />
+ ) : (
+ <RotateCw size={13} />
+ )}
+ {t('settings.wechatBot.actions.rebind')}
+ </button>
+ <button
+ type="button"
+ onClick={() => void handleUnbind()}
+ disabled={isUnbinding}
+ className={cn(
+ 'flex h-9 flex-1 items-center justify-center gap-1.5 rounded-full',
+ 'border border-[var(--settings-btn-secondary-border)] bg-[var(--settings-btn-secondary-bg)]',
+ 'px-4 text-12 font-medium text-[var(--settings-btn-secondary-text)]',
+ isUnbinding && 'cursor-not-allowed opacity-40',
+ )}
+ >
+ {isUnbinding ? (
+ <Loader2 size={13} className="animate-spin motion-reduce:animate-none" />
+ ) : (
+ <Trash2 size={13} />
+ )}
+ {t('settings.wechatBot.actions.unbind')}
+ </button>
+ </div>
+ </div>
+ ) : (
+ <div className="flex flex-col gap-3">
+ <div className="rounded-xl border border-[var(--settings-theme-card-border)] bg-[var(--settings-theme-card-bg)] px-4 py-3">
+ <p className="text-12 leading-[1.6] text-[var(--settings-section-desc)]">
+ {t(
+ disabledByPolicy
+ ? 'settings.wechatBot.disabledNote'
+ : state.phase === 'error'
+ ? 'settings.wechatBot.errorNote'
+ : 'settings.wechatBot.intro',
+ )}
+ </p>
+ </div>
+ <button
+ type="button"
+ onClick={() => void handleAuthorize()}
+ disabled={isAuthorizing || disabledByPolicy}
+ className={cn(
+ 'flex h-[42px] w-full items-center justify-center gap-1.5 rounded-full',
+ 'border border-[var(--settings-btn-primary-border)] bg-[var(--settings-btn-primary-bg)]',
+ 'text-13 font-medium text-[var(--settings-btn-primary-text)]',
+ 'transition-colors hover:bg-[var(--settings-btn-primary-hover-bg)]',
+ (isAuthorizing || disabledByPolicy) && 'cursor-not-allowed opacity-40',
+ )}
+ >
+ {isAuthorizing && (
+ <Loader2 size={14} className="animate-spin motion-reduce:animate-none" />
+ )}
+ {t('settings.wechatBot.actions.connect')}
+ </button>
+ </div>
+ )}
+ </ImChannelSettingsCard>
+ );
+}
+
+function WechatWorkingDirectory({
+ settings,
+ pending,
+ onChoose,
+ onReset,
+}: {
+ settings: WechatChannelSettingsState | null;
+ pending: boolean;
+ onChoose: () => void;
+ onReset: () => void;
+}) {
+ const { t } = useTranslation();
+ const configured = settings?.workingDir ?? null;
+
+ return (
+ <section className="flex flex-col gap-3" aria-label={t('settings.wechatBot.workingDir.title')}>
+ <div>
+ <h3 className="text-13 font-medium text-[var(--settings-section-title)]">
+ {t('settings.wechatBot.workingDir.title')}
+ </h3>
+ <p className="mt-1 text-12 leading-[1.55] text-[var(--settings-section-desc)]">
+ {t('settings.wechatBot.workingDir.hint')}
+ </p>
+ </div>
+ <div className="flex min-w-0 items-center gap-2">
+ <button
+ type="button"
+ onClick={onChoose}
+ disabled={pending}
+ className={cn(
+ 'flex h-10 min-w-0 flex-1 items-center gap-2 rounded-full px-3 text-left',
+ 'border border-[var(--settings-input-border)] bg-[var(--settings-input-bg)]',
+ 'text-12 text-[var(--settings-input-text)]',
+ pending && 'cursor-not-allowed opacity-50',
+ )}
+ >
+ <FolderOpen size={15} className="shrink-0 text-[var(--text-tertiary)]" />
+ <span className="truncate" title={configured ?? undefined} dir="auto">
+ {configured ?? t('settings.wechatBot.workingDir.managed')}
+ </span>
+ </button>
+ {configured && (
+ <button
+ type="button"
+ onClick={onReset}
+ disabled={pending}
+ className="h-10 shrink-0 rounded-full border border-[var(--settings-btn-secondary-border)] bg-[var(--settings-btn-secondary-bg)] px-4 text-12 font-medium text-[var(--settings-btn-secondary-text)] disabled:cursor-not-allowed disabled:opacity-50"
+ >
+ {t('settings.wechatBot.workingDir.reset')}
+ </button>
+ )}
+ </div>
+ {settings && !settings.workingDirAvailable && (
+ <p className="text-12 text-[var(--settings-error-text)]" role="alert">
+ {t('settings.wechatBot.workingDir.unavailable')}
+ </p>
+ )}
+ </section>
+ );
+}
diff --git a/apps/desktop/src/renderer/components/settings/__tests__/WechatBotSection.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/WechatBotSection.test.tsx
new file mode 100644
index 0000000000..110bd325dd
--- /dev/null
+++ b/apps/desktop/src/renderer/components/settings/__tests__/WechatBotSection.test.tsx
@@ -0,0 +1,147 @@
+// @vitest-environment jsdom
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { WechatBotSection } from '../WechatBotSection';
+
+const mocks = vi.hoisted(() => ({
+ confirm: vi.fn(),
+ authorize: vi.fn(),
+ cancelAuthorization: vi.fn(),
+ unbind: vi.fn(),
+ chooseWorkingDirectory: vi.fn(),
+ resetWorkingDirectory: vi.fn(),
+ state: {
+ phase: 'disconnected',
+ bound: false,
+ queuedTasks: 0,
+ } as WechatBotState,
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}));
+
+vi.mock('@/components/ui/confirm-dialog-provider', () => ({
+ useConfirmDialog: () => ({ confirm: mocks.confirm }),
+}));
+
+vi.mock('@/hooks/useWechatBot', () => ({
+ useWechatBot: () => ({
+ state: mocks.state,
+ channelSettings: {
+ version: 1,
+ workingDir: null,
+ workingDirAvailable: true,
+ },
+ isAuthorizing: false,
+ isUnbinding: false,
+ isUpdatingWorkingDir: false,
+ authorize: mocks.authorize,
+ cancelAuthorization: mocks.cancelAuthorization,
+ unbind: mocks.unbind,
+ chooseWorkingDirectory: mocks.chooseWorkingDirectory,
+ resetWorkingDirectory: mocks.resetWorkingDirectory,
+ }),
+}));
+
+vi.mock('../ImDefaultSettingsSection', () => ({
+ ImDefaultSettingsSection: () => <div data-testid="defaults" />,
+}));
+
+vi.mock('../ImChannelSettingsCard', () => ({
+ useImChannelSettingsSummary: () => [null, vi.fn()],
+ ImChannelSettingsCard: ({
+ title,
+ status,
+ children,
+ }: {
+ title: string;
+ status: React.ReactNode;
+ children: React.ReactNode;
+ }) => (
+ <section>
+ <h2>{title}</h2>
+ {status}
+ {children}
+ </section>
+ ),
+}));
+
+describe('WechatBotSection', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.state = {
+ phase: 'disconnected',
+ bound: false,
+ queuedTasks: 0,
+ };
+ mocks.confirm.mockResolvedValue(true);
+ mocks.authorize.mockResolvedValue(true);
+ mocks.unbind.mockResolvedValue(true);
+ });
+
+ it('explains the external Tencent authorization flow before starting it', async () => {
+ render(<WechatBotSection expanded onToggle={vi.fn()} />);
+
+ fireEvent.click(screen.getByRole('button', { name: 'settings.wechatBot.actions.connect' }));
+
+ await waitFor(() => expect(mocks.confirm).toHaveBeenCalledTimes(1));
+ expect(mocks.confirm.mock.calls[0]?.[0]).toMatchObject({
+ title: 'settings.wechatBot.authorization.title',
+ confirmText: 'settings.wechatBot.authorization.confirm',
+ autoFocusConfirm: true,
+ });
+ expect(mocks.authorize).toHaveBeenCalledTimes(1);
+ });
+
+ it('uses the replacement warning for an existing binding', async () => {
+ mocks.state = {
+ phase: 'connected',
+ bound: true,
+ queuedTasks: 0,
+ };
+ render(<WechatBotSection expanded onToggle={vi.fn()} />);
+
+ fireEvent.click(screen.getByRole('button', { name: 'settings.wechatBot.actions.rebind' }));
+
+ await waitFor(() => expect(mocks.confirm).toHaveBeenCalledTimes(1));
+ expect(mocks.confirm.mock.calls[0]?.[0]).toMatchObject({
+ title: 'settings.wechatBot.authorization.rebindTitle',
+ description: 'settings.wechatBot.authorization.rebindDescription',
+ });
+ });
+
+ it('allows an in-flight scan to be cancelled', () => {
+ mocks.state = {
+ phase: 'waiting_confirmation',
+ bound: false,
+ queuedTasks: 0,
+ };
+ render(<WechatBotSection expanded onToggle={vi.fn()} />);
+
+ fireEvent.click(screen.getByRole('button', { name: 'settings.wechatBot.waiting.cancel' }));
+
+ expect(mocks.cancelAuthorization).toHaveBeenCalledTimes(1);
+ });
+
+ it('confirms unbind while retaining existing Cindy history', async () => {
+ mocks.state = {
+ phase: 'needs_reauth',
+ bound: true,
+ queuedTasks: 0,
+ };
+ render(<WechatBotSection expanded onToggle={vi.fn()} />);
+
+ fireEvent.click(screen.getByRole('button', { name: 'settings.wechatBot.actions.unbind' }));
+
+ await waitFor(() => expect(mocks.confirm).toHaveBeenCalledTimes(1));
+ expect(mocks.confirm.mock.calls[0]?.[0]).toMatchObject({
+ title: 'settings.wechatBot.unbind.title',
+ description: 'settings.wechatBot.unbind.description',
+ });
+ expect(mocks.unbind).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/desktop/src/renderer/hooks/__tests__/useWechatBot.test.ts b/apps/desktop/src/renderer/hooks/__tests__/useWechatBot.test.ts
new file mode 100644
index 0000000000..704132fafd
--- /dev/null
+++ b/apps/desktop/src/renderer/hooks/__tests__/useWechatBot.test.ts
@@ -0,0 +1,169 @@
+// @vitest-environment jsdom
+import { act, renderHook, waitFor } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { __testing, useWechatBot } from '../useWechatBot';
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string, vars?: Record<string, string>) =>
+ vars?.message ? `${key}:${vars.message}` : key,
+ }),
+}));
+
+vi.mock('@/lib/toast', () => ({
+ toast: {
+ success: vi.fn(),
+ error: vi.fn(),
+ },
+}));
+
+vi.mock('@/lib/logger', () => ({
+ createLogger: () => ({
+ error: vi.fn(),
+ warn: vi.fn(),
+ info: vi.fn(),
+ debug: vi.fn(),
+ }),
+}));
+
+function installWechatApi(initial: WechatBotState = disconnectedState()) {
+ const listeners = new Set<(state: WechatBotState) => void>();
+ const channelState: WechatChannelSettingsState = {
+ version: 1,
+ workingDir: null,
+ workingDirAvailable: true,
+ };
+ const api = {
+ getState: vi.fn(async () => initial),
+ authorize: vi.fn(async () => ({ started: true as const })),
+ cancelAuthorization: vi.fn(async () => ({ ok: true as const })),
+ unbind: vi.fn(async () => ({ ok: true as const })),
+ getChannelSettings: vi.fn(async () => channelState),
+ chooseWorkingDirectory: vi.fn(async () => ({
+ canceled: false,
+ state: { ...channelState, workingDir: 'D:/project' },
+ })),
+ resetWorkingDirectory: vi.fn(async () => channelState),
+ onStateChange: vi.fn((callback: (state: WechatBotState) => void) => {
+ listeners.add(callback);
+ return () => listeners.delete(callback);
+ }),
+ };
+ (
+ window as unknown as {
+ electronAPI: { wechatBot: typeof api };
+ }
+ ).electronAPI = { wechatBot: api };
+ return {
+ api,
+ push(state: WechatBotState) {
+ for (const listener of listeners) listener(state);
+ },
+ };
+}
+
+describe('useWechatBot', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ __testing.resetCache();
+ delete (window as unknown as { electronAPI?: unknown }).electronAPI;
+ });
+
+ it('subscribes before loading and does not overwrite a newer pushed state', async () => {
+ let resolveInitial!: (state: WechatBotState) => void;
+ const harness = installWechatApi();
+ harness.api.getState.mockReturnValueOnce(
+ new Promise<WechatBotState>((resolve) => {
+ resolveInitial = resolve;
+ }),
+ );
+ const { result } = renderHook(() => useWechatBot());
+
+ const connected: WechatBotState = {
+ phase: 'connected',
+ bound: true,
+ queuedTasks: 2,
+ };
+ act(() => harness.push(connected));
+ resolveInitial(disconnectedState());
+
+ await waitFor(() => expect(result.current.state).toEqual(connected));
+ });
+
+ it('ignores the initial load after unmounting', async () => {
+ let resolveState!: (state: WechatBotState) => void;
+ let resolveChannelSettings!: (state: WechatChannelSettingsState) => void;
+ const harness = installWechatApi();
+ harness.api.getState.mockReturnValueOnce(
+ new Promise<WechatBotState>((resolve) => {
+ resolveState = resolve;
+ }),
+ );
+ harness.api.getChannelSettings.mockReturnValueOnce(
+ new Promise<WechatChannelSettingsState>((resolve) => {
+ resolveChannelSettings = resolve;
+ }),
+ );
+ const { unmount } = renderHook(() => useWechatBot());
+
+ unmount();
+ await act(async () => {
+ resolveState({
+ phase: 'connected',
+ bound: true,
+ queuedTasks: 1,
+ });
+ resolveChannelSettings({
+ version: 1,
+ workingDir: 'D:/late-result',
+ workingDirAvailable: true,
+ });
+ await Promise.resolve();
+ });
+
+ expect(__testing.getCache()).toEqual({
+ state: null,
+ channelSettings: null,
+ });
+ });
+
+ it('starts and cancels authorization through the credential-free bridge', async () => {
+ const { api } = installWechatApi();
+ const { result } = renderHook(() => useWechatBot());
+ await waitFor(() => expect(api.getState).toHaveBeenCalled());
+
+ await act(async () => {
+ expect(await result.current.authorize()).toBe(true);
+ await result.current.cancelAuthorization();
+ });
+
+ expect(api.authorize).toHaveBeenCalledTimes(1);
+ expect(api.cancelAuthorization).toHaveBeenCalledTimes(1);
+ });
+
+ it('updates and resets the user-picked working directory', async () => {
+ const { api } = installWechatApi();
+ const { result } = renderHook(() => useWechatBot());
+ await waitFor(() => expect(result.current.channelSettings).not.toBeNull());
+
+ await act(async () => {
+ await result.current.chooseWorkingDirectory();
+ });
+ expect(result.current.channelSettings?.workingDir).toBe('D:/project');
+
+ await act(async () => {
+ await result.current.resetWorkingDirectory();
+ });
+ expect(result.current.channelSettings?.workingDir).toBeNull();
+ expect(api.resetWorkingDirectory).toHaveBeenCalledTimes(1);
+ });
+});
+
+function disconnectedState(): WechatBotState {
+ return {
+ phase: 'disconnected',
+ bound: false,
+ queuedTasks: 0,
+ };
+}
diff --git a/apps/desktop/src/renderer/hooks/useWechatBot.ts b/apps/desktop/src/renderer/hooks/useWechatBot.ts
new file mode 100644
index 0000000000..6b64191c38
--- /dev/null
+++ b/apps/desktop/src/renderer/hooks/useWechatBot.ts
@@ -0,0 +1,174 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { createLogger } from '@/lib/logger';
+import { toast } from '@/lib/toast';
+
+const log = createLogger('useWechatBot');
+
+const EMPTY_STATE: WechatBotState = {
+ phase: 'disconnected',
+ bound: false,
+ queuedTasks: 0,
+};
+
+let cachedState: WechatBotState | null = null;
+let cachedChannelSettings: WechatChannelSettingsState | null = null;
+
+export interface UseWechatBotReturn {
+ state: WechatBotState;
+ channelSettings: WechatChannelSettingsState | null;
+ isAuthorizing: boolean;
+ isUnbinding: boolean;
+ isUpdatingWorkingDir: boolean;
+ authorize: () => Promise<boolean>;
+ cancelAuthorization: () => Promise<void>;
+ unbind: () => Promise<boolean>;
+ chooseWorkingDirectory: () => Promise<void>;
+ resetWorkingDirectory: () => Promise<void>;
+}
+
+export function useWechatBot(): UseWechatBotReturn {
+ const { t } = useTranslation();
+ const [state, setState] = useState<WechatBotState>(() => cachedState ?? EMPTY_STATE);
+ const [channelSettings, setChannelSettings] = useState<WechatChannelSettingsState | null>(
+ () => cachedChannelSettings,
+ );
+ const [isAuthorizing, setIsAuthorizing] = useState(false);
+ const [isUnbinding, setIsUnbinding] = useState(false);
+ const [isUpdatingWorkingDir, setIsUpdatingWorkingDir] = useState(false);
+ const pushVersionRef = useRef(0);
+
+ useEffect(() => {
+ let cancelled = false;
+ const unsubscribe = window.electronAPI.wechatBot.onStateChange((next) => {
+ if (cancelled) return;
+ pushVersionRef.current += 1;
+ cachedState = next;
+ setState(next);
+ });
+ const initialPushVersion = pushVersionRef.current;
+ void Promise.all([
+ window.electronAPI.wechatBot.getState(),
+ window.electronAPI.wechatBot.getChannelSettings(),
+ ])
+ .then(([nextState, nextChannelSettings]) => {
+ if (cancelled) return;
+ if (pushVersionRef.current === initialPushVersion) {
+ cachedState = nextState;
+ setState(nextState);
+ }
+ cachedChannelSettings = nextChannelSettings;
+ setChannelSettings(nextChannelSettings);
+ })
+ .catch(() => {
+ if (cancelled) return;
+ log.error('failed to load personal WeChat state');
+ });
+ return () => {
+ cancelled = true;
+ unsubscribe();
+ };
+ }, []);
+
+ const authorize = useCallback(async (): Promise<boolean> => {
+ if (isAuthorizing) return false;
+ setIsAuthorizing(true);
+ try {
+ await window.electronAPI.wechatBot.authorize();
+ return true;
+ } catch {
+ log.error('failed to start personal WeChat authorization');
+ toast.error(t('settings.wechatBot.toasts.authorizeFailed'));
+ return false;
+ } finally {
+ setIsAuthorizing(false);
+ }
+ }, [isAuthorizing, t]);
+
+ const cancelAuthorization = useCallback(async (): Promise<void> => {
+ try {
+ await window.electronAPI.wechatBot.cancelAuthorization();
+ } catch {
+ log.error('failed to cancel personal WeChat authorization');
+ toast.error(t('settings.wechatBot.toasts.cancelFailed'));
+ }
+ }, [t]);
+
+ const unbind = useCallback(async (): Promise<boolean> => {
+ if (isUnbinding) return false;
+ setIsUnbinding(true);
+ try {
+ await window.electronAPI.wechatBot.unbind();
+ toast.success(t('settings.wechatBot.toasts.unbound'));
+ return true;
+ } catch {
+ log.error('failed to unbind personal WeChat');
+ toast.error(t('settings.wechatBot.toasts.unbindFailed'));
+ return false;
+ } finally {
+ setIsUnbinding(false);
+ }
+ }, [isUnbinding, t]);
+
+ const chooseWorkingDirectory = useCallback(async (): Promise<void> => {
+ if (isUpdatingWorkingDir) return;
+ setIsUpdatingWorkingDir(true);
+ try {
+ const result = await window.electronAPI.wechatBot.chooseWorkingDirectory();
+ cachedChannelSettings = result.state;
+ setChannelSettings(result.state);
+ if (!result.canceled) toast.success(t('settings.wechatBot.toasts.workingDirSaved'));
+ } catch {
+ log.error('failed to choose personal WeChat working directory');
+ toast.error(t('settings.wechatBot.toasts.workingDirFailed'));
+ } finally {
+ setIsUpdatingWorkingDir(false);
+ }
+ }, [isUpdatingWorkingDir, t]);
+
+ const resetWorkingDirectory = useCallback(async (): Promise<void> => {
+ if (isUpdatingWorkingDir) return;
+ setIsUpdatingWorkingDir(true);
+ try {
+ const next = await window.electronAPI.wechatBot.resetWorkingDirectory();
+ cachedChannelSettings = next;
+ setChannelSettings(next);
+ toast.success(t('settings.wechatBot.toasts.workingDirReset'));
+ } catch {
+ log.error('failed to reset personal WeChat working directory');
+ toast.error(t('settings.wechatBot.toasts.workingDirFailed'));
+ } finally {
+ setIsUpdatingWorkingDir(false);
+ }
+ }, [isUpdatingWorkingDir, t]);
+
+ return {
+ state,
+ channelSettings,
+ isAuthorizing,
+ isUnbinding,
+ isUpdatingWorkingDir,
+ authorize,
+ cancelAuthorization,
+ unbind,
+ chooseWorkingDirectory,
+ resetWorkingDirectory,
+ };
+}
+
+export const __testing = {
+ resetCache(): void {
+ cachedState = null;
+ cachedChannelSettings = null;
+ },
+ getCache(): {
+ state: WechatBotState | null;
+ channelSettings: WechatChannelSettingsState | null;
+ } {
+ return {
+ state: cachedState,
+ channelSettings: cachedChannelSettings,
+ };
+ },
+};
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index c2f6cd6a25..f40b10c6b9 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -1557,6 +1557,90 @@
},
"bind": "Bind"
},
+ "wechatBot": {
+ "title": "Personal WeChat",
+ "description": "Scan to connect personal WeChat and work with {{appName}} from a private chat.",
+ "statusAria": "Personal WeChat status: {{status}}",
+ "status": {
+ "disconnected": "Not connected",
+ "authorizing": "Preparing authorization…",
+ "waitingConfirmation": "Waiting for WeChat…",
+ "connected": "Connected",
+ "reconnecting": "Reconnecting…",
+ "needsReauth": "Authorization required",
+ "disabled": "Unavailable",
+ "error": "Connection failed"
+ },
+ "intro": "After connecting, private messages sent to this WeChat connection enter Cindy on this computer. Tencent provides the authorization page, which may display OpenClaw.",
+ "errorNote": "The connection was not completed. Check your network and scan again. Cindy never stores plaintext credentials after a failed connection.",
+ "disabledNote": "Personal WeChat is paused in this version by the compatibility policy. Saved conversations and settings are not removed.",
+ "permission": {
+ "label": "Permission mode",
+ "hint": "Applies to new context after /new. Risky actions still require confirmation in Cindy Desktop.",
+ "fullAccessDisabled": "Personal WeChat does not support Full Access yet because actions that cannot be confirmed in WeChat must not run directly.",
+ "permissionModeDisabled": "Personal WeChat always uses Cindy Desktop's confirmation policy, so this permission mode is unavailable."
+ },
+ "authorization": {
+ "title": "Authorize WeChat",
+ "rebindTitle": "Connect a new Cindy to WeChat",
+ "description": "Tencent's webpage will open for authorization. After scanning, you can talk to Cindy from WeChat.",
+ "rebindDescription": "This WeChat account already has a connection. Continuing may replace its existing Cindy or OpenClaw connection.",
+ "confirm": "Authorize",
+ "cancel": "Cancel",
+ "steps": {
+ "1": "Select Authorize to open the WeChat binding page in your system browser.",
+ "2": "Scan with the WeChat app and confirm the connection in WeChat.",
+ "3": "Return to Cindy after binding; the connection status updates automatically.",
+ "4": "Tencent provides the authorization page, which may display OpenClaw."
+ }
+ },
+ "waiting": {
+ "heading": "Waiting for confirmation in WeChat",
+ "note": "Finish scanning and confirmation in your system browser. Cindy updates automatically when it succeeds, or you can cancel this attempt.",
+ "cancel": "Cancel authorization"
+ },
+ "bound": {
+ "heading": "Personal WeChat connected",
+ "attentionHeading": "Personal WeChat needs attention",
+ "notes": {
+ "disconnected": "The connection is saved but is not currently running.",
+ "authorizing": "Preparing a new WeChat authorization.",
+ "waiting_confirmation": "Waiting for scan confirmation in WeChat.",
+ "connected": "WeChat private messages go directly to Cindy on this computer and are not relayed through Cindy servers.",
+ "reconnecting": "This computer is restoring the WeChat connection. No new scan is needed.",
+ "needs_reauth": "The WeChat authorization expired or was replaced by another connection. Scan again.",
+ "disabled_by_policy": "The connection is paused by this version's compatibility policy; credentials and conversations remain saved.",
+ "error": "The connection is temporarily unavailable. Scan again or unbind and retry later."
+ }
+ },
+ "actions": {
+ "connect": "Connect WeChat",
+ "rebind": "Reconnect",
+ "unbind": "Unbind"
+ },
+ "workingDir": {
+ "title": "Working directory for new conversations",
+ "hint": "Used for the first WeChat conversation and after /new. Changing it does not move the current context.",
+ "managed": "Use a Cindy-managed directory",
+ "reset": "Restore default",
+ "unavailable": "The selected directory is unavailable. New conversations temporarily use a Cindy-managed directory."
+ },
+ "unbind": {
+ "title": "Unbind personal WeChat?",
+ "description": "Unbinding stops messaging, removes local WeChat credentials, and clears unfinished tasks. Existing Cindy conversations, history, and saved attachments remain.",
+ "confirm": "Unbind",
+ "cancel": "Cancel"
+ },
+ "toasts": {
+ "authorizeFailed": "Could not start WeChat authorization. Try again later.",
+ "cancelFailed": "Could not cancel WeChat authorization",
+ "unbound": "Personal WeChat unbound",
+ "unbindFailed": "Unbind failed. Try again later.",
+ "workingDirSaved": "Working directory for new WeChat conversations updated",
+ "workingDirReset": "New WeChat conversations now use the default directory",
+ "workingDirFailed": "Could not update the working directory. Select it again."
+ }
+ },
"discordBot": {
"title": "Discord Bot",
"description": "Connect your own Discord bot so {{appName}} can work from Discord DMs.",
@@ -2278,15 +2362,16 @@
},
"tips": {
"cindy": "Cindy is the official shared bot — no credentials needed. Connect Slack and just @Cindy to hand off tasks.",
- "personal": "Personal bots connect to Feishu / Discord with your own credentials — the bot is fully yours, but you create the app and fill in its config yourself.",
- "personalFeishuOnly": "Personal bots connect to Feishu with your own credentials — the bot is fully yours, but you create the app and fill in its config yourself."
+ "personal": "Personal connections include WeChat scan authorization and your own Feishu / Discord credentials. Each channel keeps independent new-conversation settings.",
+ "personalFeishuOnly": "Personal connections include WeChat scan authorization and your own Feishu credentials. Each channel keeps independent new-conversation settings."
},
"defaults": {
"title": "New Conversation Configuration",
"channelDescriptions": {
"feishu": "New Feishu conversations use this Agent and model. Send /new in an existing DM to apply it.",
"slack": "New Slack threads use this Agent and model.",
- "discord": "New Discord conversations use this Agent and model. Send /new in an existing DM to apply it."
+ "discord": "New Discord conversations use this Agent and model. Send /new in an existing DM to apply it.",
+ "wechat": "New WeChat conversations use this Agent, model, and permission mode. Send /new in an existing chat to apply them."
},
"agentLabel": "Agent",
"modelLabel": "Model Configuration",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 232b866a3a..0a2124ef7e 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -1556,6 +1556,90 @@
},
"bind": "連携"
},
+ "wechatBot": {
+ "title": "個人 WeChat",
+ "description": "QR コードで個人 WeChat を接続し、プライベートチャットから {{appName}} を利用します。",
+ "statusAria": "個人 WeChat の状態: {{status}}",
+ "status": {
+ "disconnected": "未接続",
+ "authorizing": "認証を準備中…",
+ "waitingConfirmation": "WeChat の確認待ち…",
+ "connected": "接続済み",
+ "reconnecting": "再接続中…",
+ "needsReauth": "再認証が必要",
+ "disabled": "利用不可",
+ "error": "接続失敗"
+ },
+ "intro": "接続後、この WeChat 接続へのプライベートメッセージは、このコンピューターの Cindy に届きます。認証ページは Tencent が提供し、OpenClaw と表示される場合があります。",
+ "errorNote": "接続を完了できませんでした。ネットワークを確認してもう一度スキャンしてください。失敗時に Cindy が認証情報を平文で保存することはありません。",
+ "disabledNote": "互換性ポリシーにより、このバージョンでは個人 WeChat 接続が一時停止されています。保存済みの会話と設定は削除されません。",
+ "permission": {
+ "label": "権限モード",
+ "hint": "/new 後の新しいコンテキストに適用されます。高リスク操作は引き続き Cindy Desktop での確認が必要です。",
+ "fullAccessDisabled": "WeChat 内で確認できない操作が直接実行されないよう、個人 WeChat では Full Access をまだ利用できません。",
+ "permissionModeDisabled": "個人 WeChat では常に Cindy Desktop の確認ポリシーを使用するため、この権限モードは利用できません。"
+ },
+ "authorization": {
+ "title": "WeChat を認証",
+ "rebindTitle": "新しい Cindy を WeChat に接続",
+ "description": "Tencent の認証ページをシステムブラウザで開きます。スキャン後、WeChat から Cindy と会話できます。",
+ "rebindDescription": "この WeChat には既に接続があります。続行すると、既存の Cindy または OpenClaw 接続が置き換わる場合があります。",
+ "confirm": "認証へ",
+ "cancel": "キャンセル",
+ "steps": {
+ "1": "「認証へ」を選択し、システムブラウザで WeChat の連携ページを開きます。",
+ "2": "WeChat アプリでスキャンし、WeChat 画面で接続を確認します。",
+ "3": "連携後に Cindy へ戻ると、接続状態が自動更新されます。",
+ "4": "認証ページは Tencent が提供し、OpenClaw と表示される場合があります。"
+ }
+ },
+ "waiting": {
+ "heading": "WeChat での確認を待っています",
+ "note": "システムブラウザでスキャンと確認を完了してください。成功すると自動更新されます。続けない場合はキャンセルできます。",
+ "cancel": "認証をキャンセル"
+ },
+ "bound": {
+ "heading": "個人 WeChat 接続済み",
+ "attentionHeading": "個人 WeChat の確認が必要です",
+ "notes": {
+ "disconnected": "接続は保存されていますが、現在は動作していません。",
+ "authorizing": "新しい WeChat 認証を準備しています。",
+ "waiting_confirmation": "WeChat のスキャン確認を待っています。",
+ "connected": "WeChat のプライベートメッセージはこのコンピューターの Cindy に直接届き、Cindy サーバーを経由しません。",
+ "reconnecting": "WeChat 接続を復旧しています。再スキャンは不要です。",
+ "needs_reauth": "WeChat 認証が期限切れか、別の接続に置き換えられました。もう一度スキャンしてください。",
+ "disabled_by_policy": "互換性ポリシーにより接続は一時停止中です。認証情報と会話は保持されています。",
+ "error": "接続を一時的に利用できません。再スキャンするか、連携解除後にもう一度お試しください。"
+ }
+ },
+ "actions": {
+ "connect": "WeChat を接続",
+ "rebind": "再接続",
+ "unbind": "連携解除"
+ },
+ "workingDir": {
+ "title": "新しい会話の作業ディレクトリ",
+ "hint": "WeChat の初回会話と /new の後に使用します。変更しても現在のコンテキストは移動しません。",
+ "managed": "Cindy 管理の専用ディレクトリを使用",
+ "reset": "デフォルトに戻す",
+ "unavailable": "選択したディレクトリにアクセスできません。新しい会話では一時的に Cindy 管理のディレクトリを使用します。"
+ },
+ "unbind": {
+ "title": "個人 WeChat の連携を解除しますか?",
+ "description": "連携を解除するとメッセージ送受信を停止し、ローカルの WeChat 認証情報と未完了タスクを削除します。既存の Cindy 会話、履歴、保存済み添付ファイルは残ります。",
+ "confirm": "連携解除",
+ "cancel": "キャンセル"
+ },
+ "toasts": {
+ "authorizeFailed": "WeChat 認証を開始できませんでした。しばらくしてからもう一度お試しください。",
+ "cancelFailed": "WeChat 認証をキャンセルできませんでした",
+ "unbound": "個人 WeChat の連携を解除しました",
+ "unbindFailed": "連携解除に失敗しました。しばらくしてからもう一度お試しください。",
+ "workingDirSaved": "WeChat の新しい会話の作業ディレクトリを更新しました",
+ "workingDirReset": "WeChat の新しい会話はデフォルトディレクトリを使用します",
+ "workingDirFailed": "作業ディレクトリを更新できませんでした。もう一度選択してください。"
+ }
+ },
"discordBot": {
"title": "Discord ボット",
"description": "自分で作成した Discord ボットを連携し、Discord の DM から {{appName}} を使えるようにします。",
@@ -2277,15 +2361,16 @@
},
"tips": {
"cindy": "Cindy は公式提供の共有ボットです。認証情報の申請は不要で、Slack を連携して @Cindy にメンションするだけでタスクを任せられます。",
- "personal": "個人ボットは自分で申請した認証情報で Feishu / Discord に接続します。ボットは完全に自分専用ですが、アプリの作成と設定の入力が必要です。",
- "personalFeishuOnly": "個人ボットは自分で申請した認証情報で Feishu に接続します。ボットは完全に自分専用ですが、アプリの作成と設定の入力が必要です。"
+ "personal": "個人接続には WeChat のスキャン認証と、自分の Feishu / Discord 認証情報を使用する接続があります。新規会話設定はチャネルごとに保存されます。",
+ "personalFeishuOnly": "個人接続には WeChat のスキャン認証と、自分の Feishu 認証情報を使用する接続があります。新規会話設定はチャネルごとに保存されます。"
},
"defaults": {
"title": "新規会話設定",
"channelDescriptions": {
"feishu": "Feishu の新規会話では、この Agent とモデルを使用します。既存の DM には /new で適用します。",
"slack": "Slack の新しいスレッドでは、この Agent とモデルを使用します。",
- "discord": "Discord の新規会話では、この Agent とモデルを使用します。既存の DM には /new で適用します。"
+ "discord": "Discord の新規会話では、この Agent とモデルを使用します。既存の DM には /new で適用します。",
+ "wechat": "WeChat の新規会話では、この Agent・モデル・権限モードを使用します。既存のチャットには /new で適用します。"
},
"agentLabel": "Agent",
"modelLabel": "モデル設定",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index f6ad930898..2dfe5a2746 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -1556,6 +1556,90 @@
},
"bind": "연동"
},
+ "wechatBot": {
+ "title": "개인 WeChat",
+ "description": "QR 코드로 개인 WeChat을 연결하고 개인 채팅에서 {{appName}}로 작업하세요.",
+ "statusAria": "개인 WeChat 상태: {{status}}",
+ "status": {
+ "disconnected": "연결 안 됨",
+ "authorizing": "인증 준비 중…",
+ "waitingConfirmation": "WeChat 확인 대기 중…",
+ "connected": "연결됨",
+ "reconnecting": "재연결 중…",
+ "needsReauth": "재인증 필요",
+ "disabled": "사용할 수 없음",
+ "error": "연결 실패"
+ },
+ "intro": "연결하면 이 WeChat 연결로 보낸 개인 메시지가 이 컴퓨터의 Cindy로 전달됩니다. 인증 페이지는 Tencent가 제공하며 OpenClaw로 표시될 수 있습니다.",
+ "errorNote": "연결이 완료되지 않았습니다. 네트워크를 확인하고 다시 스캔하세요. 연결 실패 시 Cindy는 인증 정보를 평문으로 저장하지 않습니다.",
+ "disabledNote": "호환성 정책에 따라 이 버전에서는 개인 WeChat 연결이 일시 중지되었습니다. 저장된 대화와 설정은 삭제되지 않습니다.",
+ "permission": {
+ "label": "권한 모드",
+ "hint": "/new 이후의 새 컨텍스트에 적용됩니다. 위험한 작업은 계속 Cindy Desktop에서 확인해야 합니다.",
+ "fullAccessDisabled": "WeChat에서 확인할 수 없는 작업이 바로 실행되지 않도록 개인 WeChat에서는 아직 Full Access를 지원하지 않습니다.",
+ "permissionModeDisabled": "개인 WeChat은 항상 Cindy Desktop의 확인 정책을 사용하므로 이 권한 모드는 사용할 수 없습니다."
+ },
+ "authorization": {
+ "title": "WeChat 인증",
+ "rebindTitle": "새 Cindy를 WeChat에 연결",
+ "description": "Tencent 인증 페이지가 시스템 브라우저에서 열립니다. 스캔 후 WeChat에서 Cindy와 대화할 수 있습니다.",
+ "rebindDescription": "이 WeChat에는 이미 연결이 있습니다. 계속하면 기존 Cindy 또는 OpenClaw 연결이 대체될 수 있습니다.",
+ "confirm": "인증하기",
+ "cancel": "취소",
+ "steps": {
+ "1": "「인증하기」를 선택해 시스템 브라우저에서 WeChat 연결 페이지를 엽니다.",
+ "2": "WeChat 앱으로 스캔하고 WeChat 화면에서 연결을 확인합니다.",
+ "3": "연결 후 Cindy로 돌아오면 상태가 자동으로 업데이트됩니다.",
+ "4": "인증 페이지는 Tencent가 제공하며 OpenClaw로 표시될 수 있습니다."
+ }
+ },
+ "waiting": {
+ "heading": "WeChat 확인 대기 중",
+ "note": "시스템 브라우저에서 스캔과 확인을 완료하세요. 성공하면 자동으로 업데이트됩니다. 계속하지 않으려면 취소할 수 있습니다.",
+ "cancel": "인증 취소"
+ },
+ "bound": {
+ "heading": "개인 WeChat 연결됨",
+ "attentionHeading": "개인 WeChat 확인 필요",
+ "notes": {
+ "disconnected": "연결은 저장되어 있지만 현재 실행 중이 아닙니다.",
+ "authorizing": "새 WeChat 인증을 준비하고 있습니다.",
+ "waiting_confirmation": "WeChat 스캔 확인을 기다리고 있습니다.",
+ "connected": "WeChat 개인 메시지는 이 컴퓨터의 Cindy로 직접 전달되며 Cindy 서버를 경유하지 않습니다.",
+ "reconnecting": "WeChat 연결을 복구하고 있습니다. 다시 스캔할 필요가 없습니다.",
+ "needs_reauth": "WeChat 인증이 만료되었거나 다른 연결로 교체되었습니다. 다시 스캔하세요.",
+ "disabled_by_policy": "호환성 정책으로 연결이 일시 중지되었습니다. 인증 정보와 대화는 유지됩니다.",
+ "error": "연결을 일시적으로 사용할 수 없습니다. 다시 스캔하거나 연동 해제 후 나중에 다시 시도하세요."
+ }
+ },
+ "actions": {
+ "connect": "WeChat 연결",
+ "rebind": "다시 연결",
+ "unbind": "연동 해제"
+ },
+ "workingDir": {
+ "title": "새 대화 작업 디렉터리",
+ "hint": "WeChat 첫 대화와 /new 이후에 사용합니다. 변경해도 현재 컨텍스트는 이동하지 않습니다.",
+ "managed": "Cindy 관리 전용 디렉터리 사용",
+ "reset": "기본값 복원",
+ "unavailable": "선택한 디렉터리에 접근할 수 없습니다. 새 대화는 임시로 Cindy 관리 디렉터리를 사용합니다."
+ },
+ "unbind": {
+ "title": "개인 WeChat 연동을 해제하시겠습니까?",
+ "description": "연동을 해제하면 메시지 송수신을 중지하고 로컬 WeChat 인증 정보와 미완료 작업을 삭제합니다. 기존 Cindy 대화, 기록, 저장된 첨부 파일은 유지됩니다.",
+ "confirm": "연동 해제",
+ "cancel": "취소"
+ },
+ "toasts": {
+ "authorizeFailed": "WeChat 인증을 시작할 수 없습니다. 잠시 후 다시 시도하세요.",
+ "cancelFailed": "WeChat 인증을 취소하지 못했습니다",
+ "unbound": "개인 WeChat 연동이 해제되었습니다",
+ "unbindFailed": "연동 해제에 실패했습니다. 잠시 후 다시 시도하세요.",
+ "workingDirSaved": "WeChat 새 대화 작업 디렉터리가 업데이트되었습니다",
+ "workingDirReset": "WeChat 새 대화가 기본 디렉터리를 사용합니다",
+ "workingDirFailed": "작업 디렉터리를 업데이트하지 못했습니다. 다시 선택하세요."
+ }
+ },
"discordBot": {
"title": "Discord 봇",
"description": "직접 만든 Discord 봇을 연결하여 Discord DM에서 {{appName}}로 작업하세요.",
@@ -2277,15 +2361,16 @@
},
"tips": {
"cindy": "Cindy는 공식 제공 공유 봇입니다. 자격 증명을 신청할 필요 없이 Slack을 연결하고 @Cindy를 멘션하면 바로 작업을 맡길 수 있습니다.",
- "personal": "개인 봇은 직접 발급한 자격 증명으로 Feishu / Discord에 연결합니다. 봇은 온전히 내 전용이지만, 앱 생성과 설정 입력은 직접 해야 합니다.",
- "personalFeishuOnly": "개인 봇은 직접 발급한 자격 증명으로 Feishu에 연결합니다. 봇은 온전히 내 전용이지만, 앱 생성과 설정 입력은 직접 해야 합니다."
+ "personal": "개인 연결에는 WeChat 스캔 인증과 직접 발급한 Feishu / Discord 인증 정보 연결이 포함됩니다. 새 대화 설정은 채널별로 저장됩니다.",
+ "personalFeishuOnly": "개인 연결에는 WeChat 스캔 인증과 직접 발급한 Feishu 인증 정보 연결이 포함됩니다. 새 대화 설정은 채널별로 저장됩니다."
},
"defaults": {
"title": "새 대화 설정",
"channelDescriptions": {
"feishu": "새 Feishu 대화는 이 Agent와 모델을 사용합니다. 기존 DM에는 /new를 보내 적용하세요.",
"slack": "새 Slack 스레드는 이 Agent와 모델을 사용합니다.",
- "discord": "새 Discord 대화는 이 Agent와 모델을 사용합니다. 기존 DM에는 /new를 보내 적용하세요."
+ "discord": "새 Discord 대화는 이 Agent와 모델을 사용합니다. 기존 DM에는 /new를 보내 적용하세요.",
+ "wechat": "새 WeChat 대화는 이 Agent, 모델, 권한 모드를 사용합니다. 기존 채팅에는 /new를 보내 적용하세요."
},
"agentLabel": "Agent",
"modelLabel": "모델 설정",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 5a59b6fcd4..7e177e2e77 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -1556,6 +1556,90 @@
},
"bind": "绑定"
},
+ "wechatBot": {
+ "title": "个人微信",
+ "description": "扫码连接个人微信,在微信私聊中与 {{appName}} 工作。",
+ "statusAria": "个人微信状态:{{status}}",
+ "status": {
+ "disconnected": "未连接",
+ "authorizing": "准备授权…",
+ "waitingConfirmation": "等待微信确认…",
+ "connected": "已连接",
+ "reconnecting": "重新连接中…",
+ "needsReauth": "需要重新授权",
+ "disabled": "暂不可用",
+ "error": "连接失败"
+ },
+ "intro": "连接后,你发给该微信连接的私聊消息会进入本机 Cindy。授权网页由腾讯提供,页面中可能显示 OpenClaw。",
+ "errorNote": "本次连接未完成。请确认网络正常后重新扫码;Cindy 不会在连接失败时保存明文凭证。",
+ "disabledNote": "此版本的个人微信连接已因兼容性策略暂停。已保存的对话和设置不会被删除。",
+ "permission": {
+ "label": "权限模式",
+ "hint": "仅影响 /new 后的新上下文。高风险操作仍会要求你回到 Cindy 桌面端确认。",
+ "fullAccessDisabled": "个人微信首版不支持 Full Access,避免无法在微信内确认的操作被直接执行。",
+ "permissionModeDisabled": "个人微信始终使用 Cindy 桌面端的确认策略,因此该权限模式不可用。"
+ },
+ "authorization": {
+ "title": "微信授权",
+ "rebindTitle": "将新的 Cindy 连接到微信",
+ "description": "即将跳转到腾讯提供的网页完成授权。扫码绑定后,即可在微信中与 Cindy 对话。",
+ "rebindDescription": "当前微信已有连接。继续扫码可能解除该微信原有的 Cindy 或 OpenClaw 连接。",
+ "confirm": "去授权",
+ "cancel": "取消",
+ "steps": {
+ "1": "点击「去授权」,在系统浏览器打开微信绑定页。",
+ "2": "使用微信 App 扫码,并在微信页面确认连接。",
+ "3": "绑定成功后回到 Cindy,连接状态会自动更新。",
+ "4": "授权页由腾讯提供,页面中可能显示 OpenClaw。"
+ }
+ },
+ "waiting": {
+ "heading": "等待你在微信中确认",
+ "note": "请在系统浏览器完成扫码和确认。成功后无需手动刷新;如果不想继续,可以取消本次授权。",
+ "cancel": "取消授权"
+ },
+ "bound": {
+ "heading": "个人微信已连接",
+ "attentionHeading": "个人微信需要处理",
+ "notes": {
+ "disconnected": "连接已保存,当前尚未启动。",
+ "authorizing": "正在准备新的微信授权。",
+ "waiting_confirmation": "正在等待微信扫码确认。",
+ "connected": "微信私聊消息会直接进入本机 Cindy,消息不经过 Cindy 服务端转发。",
+ "reconnecting": "本机正在恢复与微信的连接,无需重新扫码。",
+ "needs_reauth": "微信授权已失效或被新的连接替换,请重新扫码。",
+ "disabled_by_policy": "连接因当前版本的兼容性策略暂停;凭证和对话仍保留。",
+ "error": "连接暂时失败。可以重新扫码,或解绑后稍后再试。"
+ }
+ },
+ "actions": {
+ "connect": "连接微信",
+ "rebind": "重新连接",
+ "unbind": "解绑"
+ },
+ "workingDir": {
+ "title": "新对话工作目录",
+ "hint": "微信首次对话或发送 /new 后使用。更改不会移动当前上下文。",
+ "managed": "使用 Cindy 管理的专用目录",
+ "reset": "恢复默认",
+ "unavailable": "已选目录当前不可访问;新对话将暂时使用 Cindy 管理的专用目录。"
+ },
+ "unbind": {
+ "title": "解绑个人微信?",
+ "description": "解绑会停止收发、删除本机微信凭证并清理未完成任务。已创建的 Cindy 对话、历史消息和已保存附件会保留。",
+ "confirm": "解绑",
+ "cancel": "取消"
+ },
+ "toasts": {
+ "authorizeFailed": "无法开始微信授权,请稍后重试",
+ "cancelFailed": "取消微信授权失败",
+ "unbound": "个人微信已解绑",
+ "unbindFailed": "解绑失败,请稍后重试",
+ "workingDirSaved": "微信新对话工作目录已更新",
+ "workingDirReset": "微信新对话已恢复使用默认目录",
+ "workingDirFailed": "更新工作目录失败,请重新选择"
+ }
+ },
"discordBot": {
"title": "Discord 机器人",
"description": "绑定你自建的 Discord Bot,在 Discord 私聊里连接 {{appName}}。",
@@ -2277,15 +2361,16 @@
},
"tips": {
"cindy": "Cindy 是官方提供的共享机器人:无需申请任何凭证,连接 Slack 后 @Cindy 即可直接派活。",
- "personal": "个人机器人用你自己申请的凭证接入飞书 / Discord:机器人完全归你,需要自行创建应用并填写配置。",
- "personalFeishuOnly": "个人机器人用你自己申请的凭证接入飞书:机器人完全归你,需要自行创建应用并填写配置。"
+ "personal": "个人连接包括微信扫码,以及使用自有凭证接入飞书 / Discord;各渠道独立保存新对话配置。",
+ "personalFeishuOnly": "个人连接包括微信扫码,以及使用自有凭证接入飞书;各渠道独立保存新对话配置。"
},
"defaults": {
"title": "新对话配置",
"channelDescriptions": {
"feishu": "飞书新对话会使用这组 Agent 和模型;已有私聊发送 /new 后应用。",
"slack": "Slack 新 thread 会使用这组 Agent 和模型。",
- "discord": "Discord 新对话会使用这组 Agent 和模型;已有私聊发送 /new 后应用。"
+ "discord": "Discord 新对话会使用这组 Agent 和模型;已有私聊发送 /new 后应用。",
+ "wechat": "微信新对话会使用这组 Agent、模型和权限模式;已有私聊发送 /new 后应用。"
},
"agentLabel": "Agent",
"modelLabel": "模型配置",
diff --git a/apps/desktop/src/renderer/lib/imageRef.ts b/apps/desktop/src/renderer/lib/imageRef.ts
index 50effeda8f..d2a9c49757 100644
--- a/apps/desktop/src/renderer/lib/imageRef.ts
+++ b/apps/desktop/src/renderer/lib/imageRef.ts
@@ -97,6 +97,12 @@ export interface UserMessageContent {
agentReferences?: AgentInputReference[];
}
+function basenameForAttachment(value: string): string {
+ const normalized = value.replace(/\\/g, '/');
+ const name = normalized.slice(normalized.lastIndexOf('/') + 1);
+ return name || 'attachment';
+}
+
/**
* Parse a `Message.content` value into { text, images, files }.
*
@@ -109,10 +115,9 @@ export interface UserMessageContent {
* Strings that look like JSON ('{' / '[' lead) are parsed
* and recursed into the relevant branch.
* 2. array — SDK-native content blocks: `[{type:'text',text},
- * {type:'image',...}]`. Text blocks are concatenated;
- * image blocks are dropped (user attachments flow through
- * the independent `images` field, not via inline content).
- * The SDK has no standard "file" block, so files is always [].
+ * {type:'image',...}]`. Text blocks are concatenated and
+ * attachment blocks are projected into `{images, files}` so
+ * legacy IM messages remain renderable after a restart.
* 3. object — `{text, images, files}` shape produced by stringifyUserContent
* AFTER messageToCamel has parsed it back into an object.
*
@@ -139,19 +144,42 @@ export function parseUserContent(content: unknown): UserMessageContent {
// ── Branch 2: array — SDK-native content blocks ──────────────────────────
if (Array.isArray(content)) {
const textParts: string[] = [];
+ const images: ImageRef[] = [];
+ const files: FileRef[] = [];
for (const block of content) {
if (block && typeof block === 'object') {
const b = block as Record<string, unknown>;
if (b.type === 'text' && typeof b.text === 'string') {
textParts.push(b.text);
}
- // image blocks are intentionally ignored — user-message attachments
- // live in the independent `images` field on the parent shape.
- // SDK has no "file" / "document" block we want to surface here either;
- // historical SDK-array payloads never carried desktop file attachments.
+ if (b.type === 'image') {
+ const image = coerceImageRef({
+ url: b.url,
+ mimeType: b.mimeType,
+ originalName:
+ typeof b.originalName === 'string'
+ ? b.originalName
+ : typeof b.path === 'string'
+ ? basenameForAttachment(b.path)
+ : undefined,
+ });
+ if (image) images.push(image);
+ }
+ if (b.type === 'file' && typeof b.path === 'string') {
+ files.push({
+ name:
+ typeof b.name === 'string'
+ ? b.name
+ : typeof b.originalName === 'string'
+ ? b.originalName
+ : basenameForAttachment(b.path),
+ path: b.path,
+ });
+ }
+ // Unknown block types remain intentionally ignored.
}
}
- return { text: textParts.join(''), images: [], files: [] };
+ return { text: textParts.join(''), images, files };
}
// ── Branch 3: object — already-parsed {text, images, files} shape ────────
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 0ad91a7f68..ace10eb86f 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -380,6 +380,31 @@ type DiscordBotTransportStatus =
| { kind: 'conflict'; appId: string }
| { kind: 'error'; reason: string };
+type WechatBotPhase =
+ | 'disconnected'
+ | 'authorizing'
+ | 'waiting_confirmation'
+ | 'connected'
+ | 'reconnecting'
+ | 'needs_reauth'
+ | 'disabled_by_policy'
+ | 'error';
+
+interface WechatBotState {
+ phase: WechatBotPhase;
+ bound: boolean;
+ connectedAt?: number;
+ lastInboundAt?: number;
+ queuedTasks: number;
+ errorCode?: string;
+}
+
+interface WechatChannelSettingsState {
+ version: 1;
+ workingDir: string | null;
+ workingDirAvailable: boolean;
+}
+
type DiscordBotSessionAuthCheckResult = {
ok: boolean;
missing: 'gateway-key' | 'agent-oauth' | 'provider-key' | 'provider-disconnected' | null;
@@ -1643,6 +1668,21 @@ interface ElectronAPI {
) => () => void;
};
+ // ── Personal WeChat (Settings → IM Bot → Personal) ──
+ wechatBot: {
+ getState: () => Promise<WechatBotState>;
+ authorize: () => Promise<{ started: true }>;
+ cancelAuthorization: () => Promise<{ ok: true }>;
+ unbind: () => Promise<{ ok: true }>;
+ getChannelSettings: () => Promise<WechatChannelSettingsState>;
+ chooseWorkingDirectory: () => Promise<{
+ canceled: boolean;
+ state: WechatChannelSettingsState;
+ }>;
+ resetWorkingDirectory: () => Promise<WechatChannelSettingsState>;
+ onStateChange: (callback: (state: WechatBotState) => void) => () => void;
+ };
+
/**
* Renderer → main signal that the user is logged in and localDb is open.
* Triggers FeishuBot WS connection (gated; otherwise the bot would come
diff --git a/apps/desktop/src/shared/imDefaultSettings.ts b/apps/desktop/src/shared/imDefaultSettings.ts
index 526600cf31..98db89f1de 100644
--- a/apps/desktop/src/shared/imDefaultSettings.ts
+++ b/apps/desktop/src/shared/imDefaultSettings.ts
@@ -1,7 +1,9 @@
export type ImDefaultAgentKind = 'claude-code' | 'codex';
+export type ImDefaultPermissionMode =
+ 'ask' | 'default' | 'acceptEdits' | 'plan' | 'auto' | 'bypassPermissions';
export type ImDefaultEffort = 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max' | 'ultra';
/** IM channel scopes that keep independent new-conversation routing preferences. */
-export type ImDefaultSettingsChannel = 'feishu' | 'slack' | 'discord';
+export type ImDefaultSettingsChannel = 'feishu' | 'slack' | 'discord' | 'wechat';
export interface ImDefaultAgentSettings {
providerId: string | null;
@@ -13,6 +15,7 @@ export type ImDefaultAgentSettingsMap = Record<ImDefaultAgentKind, ImDefaultAgen
export interface ImDefaultSettings {
agentKind: ImDefaultAgentKind;
+ permissionMode: ImDefaultPermissionMode;
agents: ImDefaultAgentSettingsMap;
}
@@ -28,6 +31,7 @@ export interface ImDefaultSettingsState extends ImDefaultSettings {
export const IM_DEFAULT_SETTINGS: ImDefaultSettings = {
agentKind: 'claude-code',
+ permissionMode: 'auto',
agents: {
'claude-code': {
providerId: null,
@@ -46,6 +50,7 @@ export const IM_DEFAULT_SETTINGS_CHANNELS: readonly ImDefaultSettingsChannel[] =
'feishu',
'slack',
'discord',
+ 'wechat',
];
export const IM_DEFAULT_EFFORT_OVERRIDES: Readonly<Partial<Record<string, ImDefaultEffort>>> = {
@@ -63,6 +68,19 @@ const EFFORTS = new Set<ImDefaultEffort>([
'max',
'ultra',
]);
+const PERMISSION_MODES = new Set<ImDefaultPermissionMode>([
+ 'ask',
+ 'default',
+ 'acceptEdits',
+ 'plan',
+ 'auto',
+ 'bypassPermissions',
+]);
+
+export const WECHAT_UNSUPPORTED_PERMISSION_MODES: readonly ImDefaultPermissionMode[] = [
+ 'acceptEdits',
+ 'bypassPermissions',
+];
export function isImDefaultAgentKind(value: unknown): value is ImDefaultAgentKind {
return typeof value === 'string' && AGENT_KINDS.has(value as ImDefaultAgentKind);
@@ -72,6 +90,16 @@ export function isImDefaultEffort(value: unknown): value is ImDefaultEffort {
return typeof value === 'string' && EFFORTS.has(value as ImDefaultEffort);
}
+export function isImDefaultPermissionMode(value: unknown): value is ImDefaultPermissionMode {
+ return typeof value === 'string' && PERMISSION_MODES.has(value as ImDefaultPermissionMode);
+}
+
+export function isWechatUnsupportedPermissionMode(
+ value: unknown,
+): value is ImDefaultPermissionMode {
+ return isImDefaultPermissionMode(value) && WECHAT_UNSUPPORTED_PERMISSION_MODES.includes(value);
+}
+
export function isImDefaultSettingsChannel(value: unknown): value is ImDefaultSettingsChannel {
return (
typeof value === 'string' &&
diff --git a/apps/desktop/src/shared/sessionSource.ts b/apps/desktop/src/shared/sessionSource.ts
index fbbe788834..166ab0a9cb 100644
--- a/apps/desktop/src/shared/sessionSource.ts
+++ b/apps/desktop/src/shared/sessionSource.ts
@@ -4,6 +4,7 @@ export const SESSION_SOURCES = [
'slack',
'telegram',
'discord',
+ 'wechat',
'scheduler',
'learn',
'shared',
@@ -29,6 +30,7 @@ export const DESKTOP_VISIBLE_SESSION_SOURCES: SessionSource[] = [
'slack',
'telegram',
'discord',
+ 'wechat',
'scheduler',
'learn',
'shared',
@@ -40,6 +42,7 @@ export function normalizeSessionSource(source: unknown): SessionSource {
source === 'slack' ||
source === 'telegram' ||
source === 'discord' ||
+ source === 'wechat' ||
source === 'scheduler' ||
source === 'learn' ||
source === 'shared' ||
diff --git a/apps/desktop/vite.silk-worker.config.ts b/apps/desktop/vite.silk-worker.config.ts
new file mode 100644
index 0000000000..d523dc5717
--- /dev/null
+++ b/apps/desktop/vite.silk-worker.config.ts
@@ -0,0 +1,18 @@
+import { defineConfig } from 'vite';
+
+export default defineConfig({
+ ssr: {
+ noExternal: ['silk-wasm'],
+ },
+ resolve: {
+ conditions: ['node'],
+ mainFields: ['module', 'jsnext:main', 'jsnext'],
+ },
+ build: {
+ rollupOptions: {
+ output: {
+ inlineDynamicImports: true,
+ },
+ },
+ },
+});
diff --git a/docs/legal/README.md b/docs/legal/README.md
index c8b47faea0..98403de22c 100644
--- a/docs/legal/README.md
+++ b/docs/legal/README.md
@@ -18,6 +18,8 @@
- [微信 Open SDK 合规记录](./wechat-open-sdk-compliance.md):版本、隐私披露、用户
同意和发布前复核记录。
+- [个人微信 IM 合规与发布记录](./wechat-personal-im-compliance.md):iLink 协议来源、
+ 数据处理、腾讯接入授权与 GA 门禁。
### 第三方许可、受限组件与 SBOM
diff --git a/docs/legal/notices/THIRD-PARTY-NOTICES.txt b/docs/legal/notices/THIRD-PARTY-NOTICES.txt
index 3d2dbdc26c..199f62d3ff 100644
--- a/docs/legal/notices/THIRD-PARTY-NOTICES.txt
+++ b/docs/legal/notices/THIRD-PARTY-NOTICES.txt
@@ -3947,7 +3947,7 @@ Apache License
Copyright (c) OpenAI
------------------------------------------------------------------------------
-openclaw fs-safe sources (vendored) vendored
+openclaw fs-safe sources (vendored)
License: MIT
Source: https://github.com/openclaw/openclaw
------------------------------------------------------------------------------
@@ -4035,7 +4035,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-TapDB SDK (vendored) vendored
+TapDB SDK (vendored)
License: Apache-2.0
Source: https://www.taptap.cn/developer
------------------------------------------------------------------------------
@@ -4266,8 +4266,40 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
+------------------------------------------------------------------------------
+Tencent openclaw-weixin protocol sources (adapted) 2.4.6
+License: MIT
+Source: https://github.com/Tencent/openclaw-weixin/tree/v2.4.6
+------------------------------------------------------------------------------
+Tencent is pleased to support the open source community by making openclaw-weixin available.
+
+Copyright (C) 2026 Tencent. All rights reserved.
+
+openclaw-weixin is licensed under the MIT.
+
+Terms of the MIT:
+--------------------------------------------------------------------
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
==============================================================================
-SECTION 2: npm packages (1310 packages)
+SECTION 2: npm packages (1311 packages)
==============================================================================
- @adobe/[email protected] — MIT — https://github.com/adobe/css-tools
@@ -5434,6 +5466,7 @@ SECTION 2: npm packages (1310 packages)
- [email protected] — MIT — https://github.com/ljharb/side-channel-weakmap
- [email protected] — ISC — https://github.com/tapjs/signal-exit
- [email protected] — ISC — https://github.com/tapjs/signal-exit
+- [email protected] — MIT — https://github.com/idranme/silk-wasm
- [email protected] — MIT — https://github.com/feross/simple-concat
- [email protected] — MIT — https://github.com/feross/simple-get
- [email protected] — MIT — https://github.com/steveukx/git-js
@@ -43671,7 +43704,32 @@ WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
------------------------------------------------------------------------------
-[564] Applies to: npm:[email protected], npm:[email protected]
+[564] Applies to: npm:[email protected]
+------------------------------------------------------------------------------
+MIT License
+
+Copyright (c) 2024 idranme
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+------------------------------------------------------------------------------
+[565] Applies to: npm:[email protected], npm:[email protected]
------------------------------------------------------------------------------
The MIT License (MIT)
@@ -43695,7 +43753,7 @@ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[565] Applies to: npm:[email protected]
+[566] Applies to: npm:[email protected]
------------------------------------------------------------------------------
The MIT License (MIT)
@@ -43719,7 +43777,7 @@ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[566] Applies to: npm:[email protected]
+[567] Applies to: npm:[email protected]
------------------------------------------------------------------------------
The MIT License (MIT)
@@ -43744,7 +43802,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
------------------------------------------------------------------------------
-[567] Applies to: npm:[email protected]
+[568] Applies to: npm:[email protected]
------------------------------------------------------------------------------
The MIT License (MIT)
@@ -43769,7 +43827,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[568] Applies to: npm:[email protected]
+[569] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Copyright (c) Squirrel Chat et al., All rights reserved.
@@ -43797,7 +43855,7 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
------------------------------------------------------------------------------
-[569] Applies to: npm:[email protected]
+[570] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -43822,7 +43880,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Copyright (c) 2009-2011, Mozilla Foundation and contributors
All rights reserved.
@@ -43853,7 +43911,7 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
------------------------------------------------------------------------------
-[571] Applies to: npm:[email protected]
+[572] Applies to: npm:[email protected]
------------------------------------------------------------------------------
The MIT License (MIT)
@@ -43878,7 +43936,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[572] Applies to: npm:[email protected]
+[573] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Copyright (c) 2007-2014, Alexandru Marasteanu <hello [at) alexei (dot] ro>
All rights reserved.
@@ -43906,7 +43964,7 @@ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
------------------------------------------------------------------------------
-[573] Applies to: npm:[email protected]
+[574] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -43931,7 +43989,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[574] Applies to: npm:[email protected]
+[575] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -43956,7 +44014,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[575] Applies to: npm:[email protected], npm:[email protected]
+[576] Applies to: npm:[email protected], npm:[email protected]
------------------------------------------------------------------------------
The MIT License (MIT)
@@ -43982,7 +44040,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
------------------------------------------------------------------------------
-[576] Applies to: npm:[email protected]
+[577] Applies to: npm:[email protected]
------------------------------------------------------------------------------
This is free and unencumbered software released into the public domain.
@@ -44010,7 +44068,7 @@ OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org/>
------------------------------------------------------------------------------
-[577] Applies to: npm:[email protected]
+[578] Applies to: npm:[email protected]
------------------------------------------------------------------------------
The MIT License (MIT)
@@ -44035,7 +44093,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
------------------------------------------------------------------------------
-[578] Applies to: npm:[email protected]
+[579] Applies to: npm:[email protected]
------------------------------------------------------------------------------
The MIT License (MIT)
@@ -44060,7 +44118,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
------------------------------------------------------------------------------
-[579] Applies to: npm:[email protected]
+[580] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Copyright (C) 2018 by Marijn Haverbeke <[email protected]> and others
@@ -44083,7 +44141,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
------------------------------------------------------------------------------
-[580] Applies to: npm:[email protected]
+[581] Applies to: npm:[email protected]
------------------------------------------------------------------------------
The MIT License (MIT)
@@ -44109,7 +44167,7 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[581] Applies to: npm:[email protected]
+[582] Applies to: npm:[email protected]
------------------------------------------------------------------------------
The MIT License (MIT)
@@ -44135,7 +44193,7 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[582] Applies to: npm:[email protected]
+[583] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -44160,7 +44218,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[583] Applies to: npm:[email protected]
+[584] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -44185,7 +44243,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[584] Applies to: npm:[email protected]
+[585] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -44198,7 +44256,7 @@ The above copyright notice and this permission notice shall be included in all c
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[585] Applies to: npm:[email protected]
+[586] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -44223,7 +44281,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[586] Applies to: npm:[email protected]
+[587] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -44248,7 +44306,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[587] Applies to: npm:[email protected]
+[588] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Copyright 2012-2018 (c) Mihai Bazon <[email protected]>
@@ -44279,7 +44337,7 @@ THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
------------------------------------------------------------------------------
-[588] Applies to: npm:[email protected]
+[589] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Copyright (c) 2013 Forbes Lindesay
@@ -44302,7 +44360,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
------------------------------------------------------------------------------
-[589] Applies to: npm:[email protected]
+[590] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -44327,7 +44385,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[590] Applies to: npm:[email protected]
+[591] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -44352,7 +44410,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[591] Applies to: npm:[email protected]
+[592] Applies to: npm:[email protected]
------------------------------------------------------------------------------
The MIT License (MIT)
@@ -44377,7 +44435,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
------------------------------------------------------------------------------
-[592] Applies to: npm:[email protected]
+[593] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -44402,7 +44460,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[593] Applies to: npm:[email protected]
+[594] Applies to: npm:[email protected]
------------------------------------------------------------------------------
(The MIT License)
@@ -44427,7 +44485,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
------------------------------------------------------------------------------
-[594] Applies to: npm:[email protected]
+[595] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -44452,7 +44510,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[595] Applies to: npm:[email protected]
+[596] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -44477,7 +44535,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[596] Applies to: npm:[email protected]
+[597] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Copyright (c) Microsoft Corporation.
@@ -44493,7 +44551,7 @@ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
------------------------------------------------------------------------------
-[597] Applies to: npm:[email protected]
+[598] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -44518,7 +44576,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[598] Applies to: npm:[email protected]
+[599] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Apache License
@@ -44577,7 +44635,7 @@ If the Work includes a "NOTICE" text file as part of its distribution, then any
END OF TERMS AND CONDITIONS
------------------------------------------------------------------------------
-[599] Applies to: npm:[email protected], npm:[email protected]
+[600] Applies to: npm:[email protected], npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -44590,7 +44648,7 @@ The above copyright notice and this permission notice shall be included in all c
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[600] Applies to: npm:[email protected]
+[601] Applies to: npm:[email protected]
------------------------------------------------------------------------------
TypeBox
@@ -44617,7 +44675,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
------------------------------------------------------------------------------
-[601] Applies to: npm:[email protected]
+[602] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -44642,7 +44700,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
------------------------------------------------------------------------------
MIT License
@@ -44667,7 +44725,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[603] Applies to: npm:[email protected], npm:[email protected]
+[604] Applies to: npm:[email protected], npm:[email protected]
------------------------------------------------------------------------------
(The MIT License)
@@ -44692,7 +44750,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
------------------------------------------------------------------------------
-[604] Applies to: npm:[email protected]
+[605] Applies to: npm:[email protected]
------------------------------------------------------------------------------
(The MIT license)
@@ -44718,7 +44776,7 @@ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[605] Applies to: npm:[email protected]
+[606] Applies to: npm:[email protected]
------------------------------------------------------------------------------
(The MIT License)
@@ -44742,7 +44800,7 @@ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[606] Applies to: npm:[email protected]
+[607] Applies to: npm:[email protected]
------------------------------------------------------------------------------
(The MIT License)
@@ -44768,7 +44826,7 @@ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[607] Applies to: npm:[email protected]
+[608] Applies to: npm:[email protected]
------------------------------------------------------------------------------
The MIT License (MIT)
@@ -44792,7 +44850,7 @@ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[608] Applies to: npm:[email protected]
+[609] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Copyright 2011 Gary Court. All rights reserved.
@@ -44807,7 +44865,7 @@ THIS SOFTWARE IS PROVIDED BY GARY COURT "AS IS" AND ANY EXPRESS OR IMPLIED WARRA
The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of Gary Court.
------------------------------------------------------------------------------
-[609] Applies to: npm:[email protected]
+[610] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Copyright (c) 2012-2014, Bram Stein
All rights reserved.
@@ -44836,7 +44894,7 @@ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
------------------------------------------------------------------------------
-[610] Applies to: npm:[email protected]
+[611] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -44861,7 +44919,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[611] Applies to: npm:[email protected]
+[612] Applies to: npm:[email protected]
------------------------------------------------------------------------------
(The MIT License)
@@ -44889,7 +44947,7 @@ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[612] Applies to: npm:[email protected]
+[613] Applies to: npm:[email protected]
------------------------------------------------------------------------------
The MIT License (MIT)
@@ -44913,7 +44971,7 @@ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[613] Applies to: npm:[email protected]
+[614] Applies to: npm:[email protected]
------------------------------------------------------------------------------
The MIT License (MIT)
@@ -44926,7 +44984,7 @@ The above copyright notice and this permission notice shall be included in all c
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[614] Applies to: npm:[email protected]
+[615] Applies to: npm:[email protected]
------------------------------------------------------------------------------
The MIT License (MIT)
@@ -44951,7 +45009,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[615] Applies to: npm:[email protected]
+[616] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Copyright (c) 2015, npm, Inc
@@ -44961,7 +45019,7 @@ Permission to use, copy, modify, and/or distribute this software for any purpose
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
------------------------------------------------------------------------------
-[616] Applies to: npm:[email protected]
+[617] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -44974,7 +45032,7 @@ The above copyright notice and this permission notice shall be included in all c
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[617] Applies to: npm:[email protected]
+[618] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Copyright (c) 2017 [these people](https://github.com/Rich-Harris/vlq/graphs/contributors)
@@ -44985,7 +45043,7 @@ The above copyright notice and this permission notice shall be included in all c
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[618] Applies to: npm:[email protected]
+[619] Applies to: npm:[email protected]
------------------------------------------------------------------------------
(The MIT License)
@@ -45011,7 +45069,7 @@ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[619] Applies to: npm:[email protected]
+[620] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Copyright 2013 Naitik Shah
@@ -45028,7 +45086,7 @@ See the License for the specific language governing permissions and
limitations under the License.
------------------------------------------------------------------------------
-[620] Applies to: npm:[email protected]
+[621] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -45053,7 +45111,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[621] Applies to: npm:[email protected]
+[622] Applies to: npm:[email protected]
------------------------------------------------------------------------------
wcwidth.js: JavaScript Portng of Markus Kuhn's wcwidth() Implementation
=======================================================================
@@ -45086,7 +45144,7 @@ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
------------------------------------------------------------------------------
-[622] Applies to: npm:[email protected]
+[623] Applies to: npm:[email protected]
------------------------------------------------------------------------------
The MIT License (MIT)
@@ -45112,7 +45170,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[623] Applies to: npm:[email protected]
+[624] Applies to: npm:[email protected]
------------------------------------------------------------------------------
# The BSD 2-Clause License
@@ -45128,7 +45186,7 @@ Redistribution and use in source and binary forms, with or without modification,
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
------------------------------------------------------------------------------
-[624] Applies to: npm:[email protected]
+[625] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Copyright (c) 2014-2023 GitHub, Inc.
@@ -45152,7 +45210,7 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[625] Applies to: npm:[email protected]
+[626] Applies to: npm:[email protected]
------------------------------------------------------------------------------
The MIT License (MIT)
@@ -45177,7 +45235,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
------------------------------------------------------------------------------
-[626] Applies to: npm:[email protected]
+[627] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -45204,7 +45262,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[627] Applies to: npm:[email protected]
+[628] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Copyright (c) 2016, Contributors
@@ -45221,7 +45279,7 @@ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
THIS SOFTWARE.
------------------------------------------------------------------------------
-[628] Applies to: npm:[email protected]
+[629] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Apache License
Version 2.0, January 2004
@@ -45426,7 +45484,7 @@ Apache License
limitations under the License.
------------------------------------------------------------------------------
-[629] Applies to: npm:[email protected]
+[630] Applies to: npm:[email protected]
------------------------------------------------------------------------------
The MIT License (MIT)
@@ -45451,7 +45509,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[630] Applies to: npm:[email protected]
+[631] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Copyright (c) 2011 Einar Otto Stangvik <[email protected]>
Copyright (c) 2013 Arnout Kazemier and contributors
@@ -45475,7 +45533,7 @@ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[631] Applies to: npm:[email protected] (NOTICE)
+[632] Applies to: npm:[email protected] (NOTICE)
------------------------------------------------------------------------------
NOTICE for npm:[email protected]:
@@ -45486,7 +45544,7 @@ This product includes software developed at
The Apache Software Foundation (http://www.apache.org/).
------------------------------------------------------------------------------
-[632] Applies to: npm:[email protected]
+[633] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Copyright 2010, 2011, 2012, 2013. All rights reserved.
@@ -45509,7 +45567,7 @@ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
------------------------------------------------------------------------------
-[633] Applies to: npm:[email protected], npm:[email protected]
+[634] Applies to: npm:[email protected], npm:[email protected]
------------------------------------------------------------------------------
The MIT License (MIT)
@@ -45534,7 +45592,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
------------------------------------------------------------------------------
-[634] Applies to: npm:[email protected], npm:[email protected]
+[635] Applies to: npm:[email protected], npm:[email protected]
------------------------------------------------------------------------------
Copyright (c) 2015, Contributors
@@ -45551,7 +45609,7 @@ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
THIS SOFTWARE.
------------------------------------------------------------------------------
-[635] Applies to: npm:[email protected]
+[636] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Copyright Eemeli Aro <[email protected]>
@@ -45568,7 +45626,7 @@ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
THIS SOFTWARE.
------------------------------------------------------------------------------
-[636] Applies to: npm:[email protected], npm:[email protected]
+[637] Applies to: npm:[email protected], npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -45593,7 +45651,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
------------------------------------------------------------------------------
-[637] Applies to: npm:[email protected]
+[638] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -45618,7 +45676,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[638] Applies to: npm:[email protected]
+[639] Applies to: npm:[email protected]
------------------------------------------------------------------------------
ISC License
diff --git a/docs/legal/notices/desktop-linux.txt b/docs/legal/notices/desktop-linux.txt
index 881dcc82af..ae3374975c 100644
--- a/docs/legal/notices/desktop-linux.txt
+++ b/docs/legal/notices/desktop-linux.txt
@@ -289,7 +289,7 @@ Electron 自身捆绑了 Chromium、Node.js、V8 等组件,其完整许可证集
(LICENSES.chromium.html)由 Electron 打包流程自动包含在应用安装目录中。
------------------------------------------------------------------------------
-TapDB SDK (vendored) vendored
+TapDB SDK (vendored)
License: Apache-2.0
Source: https://www.taptap.cn/developer
------------------------------------------------------------------------------
@@ -912,7 +912,7 @@ Source: https://sqlite.org
SQLite is in the public domain. See https://sqlite.org/copyright.html
------------------------------------------------------------------------------
-openclaw fs-safe sources (vendored) vendored
+openclaw fs-safe sources (vendored)
License: MIT
Source: https://github.com/openclaw/openclaw
------------------------------------------------------------------------------
@@ -939,13 +939,45 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-Lobe Icons SVG paths (vendored) 5.14.0
+Tencent openclaw-weixin protocol sources (adapted) 2.4.6
License: MIT
-Source: https://github.com/lobehub/lobe-icons/tree/v5.14.0
+Source: https://github.com/Tencent/openclaw-weixin/tree/v2.4.6
+------------------------------------------------------------------------------
+Tencent is pleased to support the open source community by making openclaw-weixin available.
+
+Copyright (C) 2026 Tencent. All rights reserved.
+
+openclaw-weixin is licensed under the MIT.
+
+Terms of the MIT:
+--------------------------------------------------------------------
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+------------------------------------------------------------------------------
+LiteLLM mascot SVG path (adapted)
+License: MIT
+Source: https://github.com/BerriAI/litellm-docs/blob/main/static/img/logo.svg
------------------------------------------------------------------------------
MIT License
-Copyright (c) 2023 LobeHub
+Copyright (c) 2026 Berri AI
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
@@ -966,13 +998,13 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
------------------------------------------------------------------------------
-LiteLLM mascot SVG path (adapted)
+Lobe Icons SVG paths (vendored) 5.14.0
License: MIT
-Source: https://github.com/BerriAI/litellm-docs/blob/main/static/img/logo.svg
+Source: https://github.com/lobehub/lobe-icons/tree/v5.14.0
------------------------------------------------------------------------------
MIT License
-Copyright (c) 2026 Berri AI
+Copyright (c) 2023 LobeHub
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
@@ -993,7 +1025,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
==============================================================================
-SECTION 2: npm packages (781 packages)
+SECTION 2: npm packages (782 packages)
==============================================================================
- @antfu/[email protected] — MIT — https://github.com/antfu/install-pkg
@@ -1695,6 +1727,7 @@ SECTION 2: npm packages (781 packages)
- [email protected] — MIT — https://github.com/ljharb/side-channel-weakmap
- [email protected] — ISC — https://github.com/tapjs/signal-exit
- [email protected] — ISC — https://github.com/tapjs/signal-exit
+- [email protected] — MIT — https://github.com/idranme/silk-wasm
- [email protected] — MIT — https://github.com/feross/simple-concat
- [email protected] — MIT — https://github.com/feross/simple-get
- [email protected] — BSD-3-Clause — https://github.com/squirrelchat/smol-toml
@@ -14030,7 +14063,32 @@ WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
------------------------------------------------------------------------------
-[314] Applies to: npm:[email protected], npm:[email protected]
+[314] Applies to: npm:[email protected]
+------------------------------------------------------------------------------
+MIT License
+
+Copyright (c) 2024 idranme
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+------------------------------------------------------------------------------
+[315] Applies to: npm:[email protected], npm:[email protected]
------------------------------------------------------------------------------
The MIT License (MIT)
@@ -14054,7 +14112,7 @@ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[315] Applies to: npm:[email protected]
+[316] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Copyright (c) Squirrel Chat et al., All rights reserved.
@@ -14082,7 +14140,7 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
------------------------------------------------------------------------------
-[316] Applies to: npm:[email protected]
+[317] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -14107,7 +14165,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[317] Applies to: npm:[email protected]
+[318] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Copyright (c) 2007-2014, Alexandru Marasteanu <hello [at) alexei (dot] ro>
All rights reserved.
@@ -14135,7 +14193,7 @@ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
------------------------------------------------------------------------------
-[318] Applies to: npm:[email protected]
+[319] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -14160,7 +14218,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[319] Applies to: npm:[email protected]
+[320] Applies to: npm:[email protected]
------------------------------------------------------------------------------
The MIT License (MIT)
@@ -14186,7 +14244,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
------------------------------------------------------------------------------
-[320] Applies to: npm:[email protected]
+[321] Applies to: npm:[email protected]
------------------------------------------------------------------------------
The MIT License (MIT)
@@ -14211,7 +14269,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
------------------------------------------------------------------------------
-[321] Applies to: npm:[email protected]
+[322] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Copyright (C) 2018 by Marijn Haverbeke <[email protected]> and others
@@ -14234,7 +14292,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
------------------------------------------------------------------------------
-[322] Applies to: npm:[email protected]
+[323] Applies to: npm:[email protected]
------------------------------------------------------------------------------
The MIT License (MIT)
@@ -14260,7 +14318,7 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[323] Applies to: npm:[email protected]
+[324] Applies to: npm:[email protected]
------------------------------------------------------------------------------
The MIT License (MIT)
@@ -14286,7 +14344,7 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[324] Applies to: npm:[email protected]
+[325] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -14311,7 +14369,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[325] Applies to: npm:[email protected]
+[326] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -14336,7 +14394,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[326] Applies to: npm:[email protected]
+[327] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -14361,7 +14419,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[327] Applies to: npm:[email protected]
+[328] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -14386,7 +14444,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[328] Applies to: npm:[email protected]
+[329] Applies to: npm:[email protected]
------------------------------------------------------------------------------
(The MIT License)
@@ -14411,7 +14469,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
------------------------------------------------------------------------------
-[329] Applies to: npm:[email protected]
+[330] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -14436,7 +14494,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[330] Applies to: npm:[email protected]
+[331] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -14461,7 +14519,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[331] Applies to: npm:[email protected]
+[332] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Copyright (c) Microsoft Corporation.
@@ -14477,7 +14535,7 @@ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
------------------------------------------------------------------------------
-[332] Applies to: npm:[email protected]
+[333] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -14502,7 +14560,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[333] Applies to: npm:[email protected]
+[334] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Apache License
@@ -14561,7 +14619,7 @@ If the Work includes a "NOTICE" text file as part of its distribution, then any
END OF TERMS AND CONDITIONS
------------------------------------------------------------------------------
-[334] Applies to: npm:[email protected]
+[335] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -14574,7 +14632,7 @@ The above copyright notice and this permission notice shall be included in all c
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[335] Applies to: npm:[email protected]
+[336] Applies to: npm:[email protected]
------------------------------------------------------------------------------
TypeBox
@@ -14601,7 +14659,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
------------------------------------------------------------------------------
------------------------------------------------------------------------------
MIT License
@@ -14626,7 +14684,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[337] Applies to: npm:[email protected], npm:[email protected]
+[338] Applies to: npm:[email protected], npm:[email protected]
------------------------------------------------------------------------------
(The MIT License)
@@ -14651,7 +14709,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
------------------------------------------------------------------------------
-[338] Applies to: npm:[email protected]
+[339] Applies to: npm:[email protected]
------------------------------------------------------------------------------
(The MIT license)
@@ -14677,7 +14735,7 @@ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[339] Applies to: npm:[email protected]
+[340] Applies to: npm:[email protected]
------------------------------------------------------------------------------
(The MIT License)
@@ -14701,7 +14759,7 @@ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[340] Applies to: npm:[email protected]
+[341] Applies to: npm:[email protected]
------------------------------------------------------------------------------
(The MIT License)
@@ -14727,7 +14785,7 @@ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[341] Applies to: npm:[email protected]
+[342] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Copyright 2011 Gary Court. All rights reserved.
@@ -14742,7 +14800,7 @@ THIS SOFTWARE IS PROVIDED BY GARY COURT "AS IS" AND ANY EXPRESS OR IMPLIED WARRA
The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of Gary Court.
------------------------------------------------------------------------------
-[342] Applies to: npm:[email protected]
+[343] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Copyright (c) 2012-2014, Bram Stein
All rights reserved.
@@ -14771,7 +14829,7 @@ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
------------------------------------------------------------------------------
-[343] Applies to: npm:[email protected]
+[344] Applies to: npm:[email protected]
------------------------------------------------------------------------------
(The MIT License)
@@ -14799,7 +14857,7 @@ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[344] Applies to: npm:[email protected]
+[345] Applies to: npm:[email protected]
------------------------------------------------------------------------------
The MIT License (MIT)
@@ -14812,7 +14870,7 @@ The above copyright notice and this permission notice shall be included in all c
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[345] Applies to: npm:[email protected]
+[346] Applies to: npm:[email protected]
------------------------------------------------------------------------------
(The MIT License)
@@ -14838,7 +14896,7 @@ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[346] Applies to: npm:[email protected]
+[347] Applies to: npm:[email protected]
------------------------------------------------------------------------------
The MIT License (MIT)
@@ -14864,7 +14922,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[347] Applies to: npm:[email protected]
+[348] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Copyright (c) 2016, Contributors
@@ -14881,7 +14939,7 @@ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
THIS SOFTWARE.
------------------------------------------------------------------------------
-[348] Applies to: npm:[email protected]
+[349] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Apache License
Version 2.0, January 2004
@@ -15086,7 +15144,7 @@ Apache License
limitations under the License.
------------------------------------------------------------------------------
-[349] Applies to: npm:[email protected]
+[350] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Copyright (c) 2011 Einar Otto Stangvik <[email protected]>
Copyright (c) 2013 Arnout Kazemier and contributors
@@ -15110,7 +15168,7 @@ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[350] Applies to: npm:[email protected]
+[351] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Copyright (c) 2015, Contributors
@@ -15127,7 +15185,7 @@ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
THIS SOFTWARE.
------------------------------------------------------------------------------
-[351] Applies to: npm:[email protected]
+[352] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -15152,7 +15210,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
------------------------------------------------------------------------------
-[352] Applies to: npm:[email protected]
+[353] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -15177,7 +15235,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[353] Applies to: npm:[email protected]
+[354] Applies to: npm:[email protected]
------------------------------------------------------------------------------
ISC License
diff --git a/docs/legal/notices/desktop-macos.txt b/docs/legal/notices/desktop-macos.txt
index 290ff9bacd..a719d09116 100644
--- a/docs/legal/notices/desktop-macos.txt
+++ b/docs/legal/notices/desktop-macos.txt
@@ -289,7 +289,7 @@ Electron 自身捆绑了 Chromium、Node.js、V8 等组件,其完整许可证集
(LICENSES.chromium.html)由 Electron 打包流程自动包含在应用安装目录中。
------------------------------------------------------------------------------
-TapDB SDK (vendored) vendored
+TapDB SDK (vendored)
License: Apache-2.0
Source: https://www.taptap.cn/developer
------------------------------------------------------------------------------
@@ -912,7 +912,7 @@ Source: https://sqlite.org
SQLite is in the public domain. See https://sqlite.org/copyright.html
------------------------------------------------------------------------------
-openclaw fs-safe sources (vendored) vendored
+openclaw fs-safe sources (vendored)
License: MIT
Source: https://github.com/openclaw/openclaw
------------------------------------------------------------------------------
@@ -939,13 +939,45 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-Lobe Icons SVG paths (vendored) 5.14.0
+Tencent openclaw-weixin protocol sources (adapted) 2.4.6
License: MIT
-Source: https://github.com/lobehub/lobe-icons/tree/v5.14.0
+Source: https://github.com/Tencent/openclaw-weixin/tree/v2.4.6
+------------------------------------------------------------------------------
+Tencent is pleased to support the open source community by making openclaw-weixin available.
+
+Copyright (C) 2026 Tencent. All rights reserved.
+
+openclaw-weixin is licensed under the MIT.
+
+Terms of the MIT:
+--------------------------------------------------------------------
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+------------------------------------------------------------------------------
+LiteLLM mascot SVG path (adapted)
+License: MIT
+Source: https://github.com/BerriAI/litellm-docs/blob/main/static/img/logo.svg
------------------------------------------------------------------------------
MIT License
-Copyright (c) 2023 LobeHub
+Copyright (c) 2026 Berri AI
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
@@ -966,13 +998,13 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
------------------------------------------------------------------------------
-LiteLLM mascot SVG path (adapted)
+Lobe Icons SVG paths (vendored) 5.14.0
License: MIT
-Source: https://github.com/BerriAI/litellm-docs/blob/main/static/img/logo.svg
+Source: https://github.com/lobehub/lobe-icons/tree/v5.14.0
------------------------------------------------------------------------------
MIT License
-Copyright (c) 2026 Berri AI
+Copyright (c) 2023 LobeHub
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
@@ -1020,7 +1052,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
==============================================================================
-SECTION 2: npm packages (781 packages)
+SECTION 2: npm packages (782 packages)
==============================================================================
- @antfu/[email protected] — MIT — https://github.com/antfu/install-pkg
@@ -1722,6 +1754,7 @@ SECTION 2: npm packages (781 packages)
- [email protected] — MIT — https://github.com/ljharb/side-channel-weakmap
- [email protected] — ISC — https://github.com/tapjs/signal-exit
- [email protected] — ISC — https://github.com/tapjs/signal-exit
+- [email protected] — MIT — https://github.com/idranme/silk-wasm
- [email protected] — MIT — https://github.com/feross/simple-concat
- [email protected] — MIT — https://github.com/feross/simple-get
- [email protected] — BSD-3-Clause — https://github.com/squirrelchat/smol-toml
@@ -14057,7 +14090,32 @@ WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
------------------------------------------------------------------------------
-[314] Applies to: npm:[email protected], npm:[email protected]
+[314] Applies to: npm:[email protected]
+------------------------------------------------------------------------------
+MIT License
+
+Copyright (c) 2024 idranme
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+------------------------------------------------------------------------------
+[315] Applies to: npm:[email protected], npm:[email protected]
------------------------------------------------------------------------------
The MIT License (MIT)
@@ -14081,7 +14139,7 @@ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[315] Applies to: npm:[email protected]
+[316] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Copyright (c) Squirrel Chat et al., All rights reserved.
@@ -14109,7 +14167,7 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
------------------------------------------------------------------------------
-[316] Applies to: npm:[email protected]
+[317] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -14134,7 +14192,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[317] Applies to: npm:[email protected]
+[318] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Copyright (c) 2007-2014, Alexandru Marasteanu <hello [at) alexei (dot] ro>
All rights reserved.
@@ -14162,7 +14220,7 @@ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
------------------------------------------------------------------------------
-[318] Applies to: npm:[email protected]
+[319] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -14187,7 +14245,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[319] Applies to: npm:[email protected]
+[320] Applies to: npm:[email protected]
------------------------------------------------------------------------------
The MIT License (MIT)
@@ -14213,7 +14271,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
------------------------------------------------------------------------------
-[320] Applies to: npm:[email protected]
+[321] Applies to: npm:[email protected]
------------------------------------------------------------------------------
The MIT License (MIT)
@@ -14238,7 +14296,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
------------------------------------------------------------------------------
-[321] Applies to: npm:[email protected]
+[322] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Copyright (C) 2018 by Marijn Haverbeke <[email protected]> and others
@@ -14261,7 +14319,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
------------------------------------------------------------------------------
-[322] Applies to: npm:[email protected]
+[323] Applies to: npm:[email protected]
------------------------------------------------------------------------------
The MIT License (MIT)
@@ -14287,7 +14345,7 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[323] Applies to: npm:[email protected]
+[324] Applies to: npm:[email protected]
------------------------------------------------------------------------------
The MIT License (MIT)
@@ -14313,7 +14371,7 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[324] Applies to: npm:[email protected]
+[325] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -14338,7 +14396,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[325] Applies to: npm:[email protected]
+[326] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -14363,7 +14421,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[326] Applies to: npm:[email protected]
+[327] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -14388,7 +14446,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[327] Applies to: npm:[email protected]
+[328] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -14413,7 +14471,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[328] Applies to: npm:[email protected]
+[329] Applies to: npm:[email protected]
------------------------------------------------------------------------------
(The MIT License)
@@ -14438,7 +14496,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
------------------------------------------------------------------------------
-[329] Applies to: npm:[email protected]
+[330] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -14463,7 +14521,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[330] Applies to: npm:[email protected]
+[331] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -14488,7 +14546,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[331] Applies to: npm:[email protected]
+[332] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Copyright (c) Microsoft Corporation.
@@ -14504,7 +14562,7 @@ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
------------------------------------------------------------------------------
-[332] Applies to: npm:[email protected]
+[333] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -14529,7 +14587,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[333] Applies to: npm:[email protected]
+[334] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Apache License
@@ -14588,7 +14646,7 @@ If the Work includes a "NOTICE" text file as part of its distribution, then any
END OF TERMS AND CONDITIONS
------------------------------------------------------------------------------
-[334] Applies to: npm:[email protected]
+[335] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -14601,7 +14659,7 @@ The above copyright notice and this permission notice shall be included in all c
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[335] Applies to: npm:[email protected]
+[336] Applies to: npm:[email protected]
------------------------------------------------------------------------------
TypeBox
@@ -14628,7 +14686,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
------------------------------------------------------------------------------
------------------------------------------------------------------------------
MIT License
@@ -14653,7 +14711,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[337] Applies to: npm:[email protected], npm:[email protected]
+[338] Applies to: npm:[email protected], npm:[email protected]
------------------------------------------------------------------------------
(The MIT License)
@@ -14678,7 +14736,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
------------------------------------------------------------------------------
-[338] Applies to: npm:[email protected]
+[339] Applies to: npm:[email protected]
------------------------------------------------------------------------------
(The MIT license)
@@ -14704,7 +14762,7 @@ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[339] Applies to: npm:[email protected]
+[340] Applies to: npm:[email protected]
------------------------------------------------------------------------------
(The MIT License)
@@ -14728,7 +14786,7 @@ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[340] Applies to: npm:[email protected]
+[341] Applies to: npm:[email protected]
------------------------------------------------------------------------------
(The MIT License)
@@ -14754,7 +14812,7 @@ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[341] Applies to: npm:[email protected]
+[342] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Copyright 2011 Gary Court. All rights reserved.
@@ -14769,7 +14827,7 @@ THIS SOFTWARE IS PROVIDED BY GARY COURT "AS IS" AND ANY EXPRESS OR IMPLIED WARRA
The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of Gary Court.
------------------------------------------------------------------------------
-[342] Applies to: npm:[email protected]
+[343] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Copyright (c) 2012-2014, Bram Stein
All rights reserved.
@@ -14798,7 +14856,7 @@ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
------------------------------------------------------------------------------
-[343] Applies to: npm:[email protected]
+[344] Applies to: npm:[email protected]
------------------------------------------------------------------------------
(The MIT License)
@@ -14826,7 +14884,7 @@ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[344] Applies to: npm:[email protected]
+[345] Applies to: npm:[email protected]
------------------------------------------------------------------------------
The MIT License (MIT)
@@ -14839,7 +14897,7 @@ The above copyright notice and this permission notice shall be included in all c
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[345] Applies to: npm:[email protected]
+[346] Applies to: npm:[email protected]
------------------------------------------------------------------------------
(The MIT License)
@@ -14865,7 +14923,7 @@ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[346] Applies to: npm:[email protected]
+[347] Applies to: npm:[email protected]
------------------------------------------------------------------------------
The MIT License (MIT)
@@ -14891,7 +14949,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[347] Applies to: npm:[email protected]
+[348] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Copyright (c) 2016, Contributors
@@ -14908,7 +14966,7 @@ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
THIS SOFTWARE.
------------------------------------------------------------------------------
-[348] Applies to: npm:[email protected]
+[349] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Apache License
Version 2.0, January 2004
@@ -15113,7 +15171,7 @@ Apache License
limitations under the License.
------------------------------------------------------------------------------
-[349] Applies to: npm:[email protected]
+[350] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Copyright (c) 2011 Einar Otto Stangvik <[email protected]>
Copyright (c) 2013 Arnout Kazemier and contributors
@@ -15137,7 +15195,7 @@ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[350] Applies to: npm:[email protected]
+[351] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Copyright (c) 2015, Contributors
@@ -15154,7 +15212,7 @@ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
THIS SOFTWARE.
------------------------------------------------------------------------------
-[351] Applies to: npm:[email protected]
+[352] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -15179,7 +15237,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
------------------------------------------------------------------------------
-[352] Applies to: npm:[email protected]
+[353] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -15204,7 +15262,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[353] Applies to: npm:[email protected]
+[354] Applies to: npm:[email protected]
------------------------------------------------------------------------------
ISC License
diff --git a/docs/legal/notices/desktop-win.txt b/docs/legal/notices/desktop-win.txt
index c84da2ebcd..ec59e861a2 100644
--- a/docs/legal/notices/desktop-win.txt
+++ b/docs/legal/notices/desktop-win.txt
@@ -289,7 +289,7 @@ Electron 自身捆绑了 Chromium、Node.js、V8 等组件,其完整许可证集
(LICENSES.chromium.html)由 Electron 打包流程自动包含在应用安装目录中。
------------------------------------------------------------------------------
-TapDB SDK (vendored) vendored
+TapDB SDK (vendored)
License: Apache-2.0
Source: https://www.taptap.cn/developer
------------------------------------------------------------------------------
@@ -839,7 +839,7 @@ Source: https://sqlite.org
SQLite is in the public domain. See https://sqlite.org/copyright.html
------------------------------------------------------------------------------
-openclaw fs-safe sources (vendored) vendored
+openclaw fs-safe sources (vendored)
License: MIT
Source: https://github.com/openclaw/openclaw
------------------------------------------------------------------------------
@@ -866,13 +866,45 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-Lobe Icons SVG paths (vendored) 5.14.0
+Tencent openclaw-weixin protocol sources (adapted) 2.4.6
License: MIT
-Source: https://github.com/lobehub/lobe-icons/tree/v5.14.0
+Source: https://github.com/Tencent/openclaw-weixin/tree/v2.4.6
+------------------------------------------------------------------------------
+Tencent is pleased to support the open source community by making openclaw-weixin available.
+
+Copyright (C) 2026 Tencent. All rights reserved.
+
+openclaw-weixin is licensed under the MIT.
+
+Terms of the MIT:
+--------------------------------------------------------------------
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+------------------------------------------------------------------------------
+LiteLLM mascot SVG path (adapted)
+License: MIT
+Source: https://github.com/BerriAI/litellm-docs/blob/main/static/img/logo.svg
------------------------------------------------------------------------------
MIT License
-Copyright (c) 2023 LobeHub
+Copyright (c) 2026 Berri AI
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
@@ -893,13 +925,13 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
------------------------------------------------------------------------------
-LiteLLM mascot SVG path (adapted)
+Lobe Icons SVG paths (vendored) 5.14.0
License: MIT
-Source: https://github.com/BerriAI/litellm-docs/blob/main/static/img/logo.svg
+Source: https://github.com/lobehub/lobe-icons/tree/v5.14.0
------------------------------------------------------------------------------
MIT License
-Copyright (c) 2026 Berri AI
+Copyright (c) 2023 LobeHub
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
@@ -3565,7 +3597,7 @@ necessary. Here is a sample; alter the names:
That's all there is to it!
==============================================================================
-SECTION 2: npm packages (772 packages)
+SECTION 2: npm packages (773 packages)
==============================================================================
- @antfu/[email protected] — MIT — https://github.com/antfu/install-pkg
@@ -4258,6 +4290,7 @@ SECTION 2: npm packages (772 packages)
- [email protected] — MIT — https://github.com/ljharb/side-channel-weakmap
- [email protected] — ISC — https://github.com/tapjs/signal-exit
- [email protected] — ISC — https://github.com/tapjs/signal-exit
+- [email protected] — MIT — https://github.com/idranme/silk-wasm
- [email protected] — MIT — https://github.com/feross/simple-concat
- [email protected] — MIT — https://github.com/feross/simple-get
- [email protected] — BSD-3-Clause — https://github.com/squirrelchat/smol-toml
@@ -37427,7 +37460,32 @@ WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
------------------------------------------------------------------------------
-[432] Applies to: npm:[email protected], npm:[email protected]
+[432] Applies to: npm:[email protected]
+------------------------------------------------------------------------------
+MIT License
+
+Copyright (c) 2024 idranme
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+------------------------------------------------------------------------------
+[433] Applies to: npm:[email protected], npm:[email protected]
------------------------------------------------------------------------------
The MIT License (MIT)
@@ -37451,7 +37509,7 @@ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[433] Applies to: npm:[email protected]
+[434] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Copyright (c) Squirrel Chat et al., All rights reserved.
@@ -37479,7 +37537,7 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
------------------------------------------------------------------------------
-[434] Applies to: npm:[email protected]
+[435] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -37504,7 +37562,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[435] Applies to: npm:[email protected]
+[436] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Copyright (c) 2007-2014, Alexandru Marasteanu <hello [at) alexei (dot] ro>
All rights reserved.
@@ -37532,7 +37590,7 @@ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
------------------------------------------------------------------------------
-[436] Applies to: npm:[email protected]
+[437] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -37557,7 +37615,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[437] Applies to: npm:[email protected]
+[438] Applies to: npm:[email protected]
------------------------------------------------------------------------------
The MIT License (MIT)
@@ -37583,7 +37641,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
------------------------------------------------------------------------------
-[438] Applies to: npm:[email protected]
+[439] Applies to: npm:[email protected]
------------------------------------------------------------------------------
The MIT License (MIT)
@@ -37608,7 +37666,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
------------------------------------------------------------------------------
-[439] Applies to: npm:[email protected]
+[440] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Copyright (C) 2018 by Marijn Haverbeke <[email protected]> and others
@@ -37631,7 +37689,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
------------------------------------------------------------------------------
-[440] Applies to: npm:[email protected]
+[441] Applies to: npm:[email protected]
------------------------------------------------------------------------------
The MIT License (MIT)
@@ -37657,7 +37715,7 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[441] Applies to: npm:[email protected]
+[442] Applies to: npm:[email protected]
------------------------------------------------------------------------------
The MIT License (MIT)
@@ -37683,7 +37741,7 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[442] Applies to: npm:[email protected]
+[443] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -37708,7 +37766,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[443] Applies to: npm:[email protected]
+[444] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -37733,7 +37791,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[444] Applies to: npm:[email protected]
+[445] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -37758,7 +37816,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[445] Applies to: npm:[email protected]
+[446] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -37783,7 +37841,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[446] Applies to: npm:[email protected]
+[447] Applies to: npm:[email protected]
------------------------------------------------------------------------------
(The MIT License)
@@ -37808,7 +37866,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
------------------------------------------------------------------------------
-[447] Applies to: npm:[email protected]
+[448] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -37833,7 +37891,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[448] Applies to: npm:[email protected]
+[449] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -37858,7 +37916,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[449] Applies to: npm:[email protected]
+[450] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Copyright (c) Microsoft Corporation.
@@ -37874,7 +37932,7 @@ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
------------------------------------------------------------------------------
-[450] Applies to: npm:[email protected]
+[451] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -37899,7 +37957,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[451] Applies to: npm:[email protected]
+[452] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Apache License
@@ -37958,7 +38016,7 @@ If the Work includes a "NOTICE" text file as part of its distribution, then any
END OF TERMS AND CONDITIONS
------------------------------------------------------------------------------
-[452] Applies to: npm:[email protected]
+[453] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -37971,7 +38029,7 @@ The above copyright notice and this permission notice shall be included in all c
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[453] Applies to: npm:[email protected]
+[454] Applies to: npm:[email protected]
------------------------------------------------------------------------------
TypeBox
@@ -37998,7 +38056,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
------------------------------------------------------------------------------
------------------------------------------------------------------------------
MIT License
@@ -38023,7 +38081,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[455] Applies to: npm:[email protected], npm:[email protected]
+[456] Applies to: npm:[email protected], npm:[email protected]
------------------------------------------------------------------------------
(The MIT License)
@@ -38048,7 +38106,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
------------------------------------------------------------------------------
-[456] Applies to: npm:[email protected]
+[457] Applies to: npm:[email protected]
------------------------------------------------------------------------------
(The MIT license)
@@ -38074,7 +38132,7 @@ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[457] Applies to: npm:[email protected]
+[458] Applies to: npm:[email protected]
------------------------------------------------------------------------------
(The MIT License)
@@ -38098,7 +38156,7 @@ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[458] Applies to: npm:[email protected]
+[459] Applies to: npm:[email protected]
------------------------------------------------------------------------------
(The MIT License)
@@ -38124,7 +38182,7 @@ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[459] Applies to: npm:[email protected]
+[460] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Copyright 2011 Gary Court. All rights reserved.
@@ -38139,7 +38197,7 @@ THIS SOFTWARE IS PROVIDED BY GARY COURT "AS IS" AND ANY EXPRESS OR IMPLIED WARRA
The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of Gary Court.
------------------------------------------------------------------------------
-[460] Applies to: npm:[email protected]
+[461] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Copyright (c) 2012-2014, Bram Stein
All rights reserved.
@@ -38168,7 +38226,7 @@ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
------------------------------------------------------------------------------
-[461] Applies to: npm:[email protected]
+[462] Applies to: npm:[email protected]
------------------------------------------------------------------------------
(The MIT License)
@@ -38196,7 +38254,7 @@ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[462] Applies to: npm:[email protected]
+[463] Applies to: npm:[email protected]
------------------------------------------------------------------------------
The MIT License (MIT)
@@ -38209,7 +38267,7 @@ The above copyright notice and this permission notice shall be included in all c
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[463] Applies to: npm:[email protected]
+[464] Applies to: npm:[email protected]
------------------------------------------------------------------------------
(The MIT License)
@@ -38235,7 +38293,7 @@ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[464] Applies to: npm:[email protected]
+[465] Applies to: npm:[email protected]
------------------------------------------------------------------------------
The MIT License (MIT)
@@ -38261,7 +38319,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[465] Applies to: npm:[email protected]
+[466] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Copyright (c) 2016, Contributors
@@ -38278,7 +38336,7 @@ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
THIS SOFTWARE.
------------------------------------------------------------------------------
-[466] Applies to: npm:[email protected]
+[467] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Apache License
Version 2.0, January 2004
@@ -38483,7 +38541,7 @@ Apache License
limitations under the License.
------------------------------------------------------------------------------
-[467] Applies to: npm:[email protected]
+[468] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Copyright (c) 2011 Einar Otto Stangvik <[email protected]>
Copyright (c) 2013 Arnout Kazemier and contributors
@@ -38507,7 +38565,7 @@ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
-[468] Applies to: npm:[email protected]
+[469] Applies to: npm:[email protected]
------------------------------------------------------------------------------
Copyright (c) 2015, Contributors
@@ -38524,7 +38582,7 @@ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
THIS SOFTWARE.
------------------------------------------------------------------------------
-[469] Applies to: npm:[email protected]
+[470] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -38549,7 +38607,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
------------------------------------------------------------------------------
-[470] Applies to: npm:[email protected]
+[471] Applies to: npm:[email protected]
------------------------------------------------------------------------------
MIT License
@@ -38574,7 +38632,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
-[471] Applies to: npm:[email protected]
+[472] Applies to: npm:[email protected]
------------------------------------------------------------------------------
ISC License
diff --git a/docs/legal/notices/sbom/desktop-linux.spdx.json b/docs/legal/notices/sbom/desktop-linux.spdx.json
index cf979f5033..e3488cb32e 100644
--- a/docs/legal/notices/sbom/desktop-linux.spdx.json
+++ b/docs/legal/notices/sbom/desktop-linux.spdx.json
@@ -3,9 +3,9 @@
"dataLicense": "CC0-1.0",
"SPDXID": "SPDXRef-DOCUMENT",
"name": "cindy-desktop-linux",
- "documentNamespace": "https://cindy.app/spdx/desktop-linux/a2a52b563135833de6f30063b0ebe53d9da3b35b98cf4547b31f5257258b127a",
+ "documentNamespace": "https://cindy.app/spdx/desktop-linux/464bff7eabf005aa01e25a654671aa5dede2568cb57ada4e9a58a912d0b71fbf",
"creationInfo": {
- "created": "2026-07-26T02:38:39Z",
+ "created": "2026-07-27T21:02:23Z",
"creators": [
"Tool: scripts/generate-third-party-notices.mjs"
]
@@ -131,6 +131,16 @@
"licenseDeclared": "Apache-2.0",
"copyrightText": "NOASSERTION"
},
+ {
+ "name": "Tencent openclaw-weixin protocol sources (adapted)",
+ "SPDXID": "SPDXRef-Package-c675a4f80195e3e9",
+ "versionInfo": "2.4.6",
+ "downloadLocation": "https://github.com/Tencent/openclaw-weixin/tree/v2.4.6",
+ "filesAnalyzed": false,
+ "licenseConcluded": "MIT",
+ "licenseDeclared": "MIT",
+ "copyrightText": "NOASSERTION"
+ },
{
"name": "@antfu/install-pkg",
"SPDXID": "SPDXRef-Package-90a75350ac517909",
@@ -12014,6 +12024,23 @@
}
]
},
+ {
+ "name": "silk-wasm",
+ "SPDXID": "SPDXRef-Package-1f5626585935f113",
+ "versionInfo": "3.7.1",
+ "downloadLocation": "https://github.com/idranme/silk-wasm",
+ "filesAnalyzed": false,
+ "licenseConcluded": "MIT",
+ "licenseDeclared": "MIT",
+ "copyrightText": "NOASSERTION",
+ "externalRefs": [
+ {
+ "referenceCategory": "PACKAGE-MANAGER",
+ "referenceType": "purl",
+ "referenceLocator": "pkg:npm/[email protected]"
+ }
+ ]
+ },
{
"name": "simple-concat",
"SPDXID": "SPDXRef-Package-21d7a09ca81c30af",
@@ -13470,6 +13497,11 @@
"relationshipType": "DESCRIBES",
"relatedSpdxElement": "SPDXRef-Package-5db1c86634c06028"
},
+ {
+ "spdxElementId": "SPDXRef-DOCUMENT",
+ "relationshipType": "DESCRIBES",
+ "relatedSpdxElement": "SPDXRef-Package-c675a4f80195e3e9"
+ },
{
"spdxElementId": "SPDXRef-DOCUMENT",
"relationshipType": "DESCRIBES",
@@ -16965,6 +16997,11 @@
"relationshipType": "DESCRIBES",
"relatedSpdxElement": "SPDXRef-Package-0540e3a65d43c022"
},
+ {
+ "spdxElementId": "SPDXRef-DOCUMENT",
+ "relationshipType": "DESCRIBES",
+ "relatedSpdxElement": "SPDXRef-Package-1f5626585935f113"
+ },
{
"spdxElementId": "SPDXRef-DOCUMENT",
"relationshipType": "DESCRIBES",
diff --git a/docs/legal/notices/sbom/desktop-macos.spdx.json b/docs/legal/notices/sbom/desktop-macos.spdx.json
index 256238747c..94af0bbd6f 100644
--- a/docs/legal/notices/sbom/desktop-macos.spdx.json
+++ b/docs/legal/notices/sbom/desktop-macos.spdx.json
@@ -3,9 +3,9 @@
"dataLicense": "CC0-1.0",
"SPDXID": "SPDXRef-DOCUMENT",
"name": "cindy-desktop-macos",
- "documentNamespace": "https://cindy.app/spdx/desktop-macos/45cd364c70333e33334a8a1dbe4e21a65e4620dbde2a8ac4e377b37c6ab72744",
+ "documentNamespace": "https://cindy.app/spdx/desktop-macos/432b125431404c6ce264d111cde2d5409419e399c9da0fa3969567775906926a",
"creationInfo": {
- "created": "2026-07-26T02:38:39Z",
+ "created": "2026-07-27T21:02:23Z",
"creators": [
"Tool: scripts/generate-third-party-notices.mjs"
]
@@ -141,6 +141,16 @@
"licenseDeclared": "Apache-2.0",
"copyrightText": "NOASSERTION"
},
+ {
+ "name": "Tencent openclaw-weixin protocol sources (adapted)",
+ "SPDXID": "SPDXRef-Package-c675a4f80195e3e9",
+ "versionInfo": "2.4.6",
+ "downloadLocation": "https://github.com/Tencent/openclaw-weixin/tree/v2.4.6",
+ "filesAnalyzed": false,
+ "licenseConcluded": "MIT",
+ "licenseDeclared": "MIT",
+ "copyrightText": "NOASSERTION"
+ },
{
"name": "@antfu/install-pkg",
"SPDXID": "SPDXRef-Package-90a75350ac517909",
@@ -12024,6 +12034,23 @@
}
]
},
+ {
+ "name": "silk-wasm",
+ "SPDXID": "SPDXRef-Package-1f5626585935f113",
+ "versionInfo": "3.7.1",
+ "downloadLocation": "https://github.com/idranme/silk-wasm",
+ "filesAnalyzed": false,
+ "licenseConcluded": "MIT",
+ "licenseDeclared": "MIT",
+ "copyrightText": "NOASSERTION",
+ "externalRefs": [
+ {
+ "referenceCategory": "PACKAGE-MANAGER",
+ "referenceType": "purl",
+ "referenceLocator": "pkg:npm/[email protected]"
+ }
+ ]
+ },
{
"name": "simple-concat",
"SPDXID": "SPDXRef-Package-21d7a09ca81c30af",
@@ -13485,6 +13512,11 @@
"relationshipType": "DESCRIBES",
"relatedSpdxElement": "SPDXRef-Package-5db1c86634c06028"
},
+ {
+ "spdxElementId": "SPDXRef-DOCUMENT",
+ "relationshipType": "DESCRIBES",
+ "relatedSpdxElement": "SPDXRef-Package-c675a4f80195e3e9"
+ },
{
"spdxElementId": "SPDXRef-DOCUMENT",
"relationshipType": "DESCRIBES",
@@ -16980,6 +17012,11 @@
"relationshipType": "DESCRIBES",
"relatedSpdxElement": "SPDXRef-Package-0540e3a65d43c022"
},
+ {
+ "spdxElementId": "SPDXRef-DOCUMENT",
+ "relationshipType": "DESCRIBES",
+ "relatedSpdxElement": "SPDXRef-Package-1f5626585935f113"
+ },
{
"spdxElementId": "SPDXRef-DOCUMENT",
"relationshipType": "DESCRIBES",
diff --git a/docs/legal/notices/sbom/desktop-win.spdx.json b/docs/legal/notices/sbom/desktop-win.spdx.json
index b09a45eb25..a2152b7f8c 100644
--- a/docs/legal/notices/sbom/desktop-win.spdx.json
+++ b/docs/legal/notices/sbom/desktop-win.spdx.json
@@ -3,9 +3,9 @@
"dataLicense": "CC0-1.0",
"SPDXID": "SPDXRef-DOCUMENT",
"name": "cindy-desktop-win",
- "documentNamespace": "https://cindy.app/spdx/desktop-win/6a5a11919e34e4b8636b7faa8671adc012e09400bcbc5d6a25ef4d7f4ca0533f",
+ "documentNamespace": "https://cindy.app/spdx/desktop-win/ce1be7eb8491943fe65d6e6cde3b22c6b5cba437a6692a63582e116ce015fe07",
"creationInfo": {
- "created": "2026-07-26T02:38:39Z",
+ "created": "2026-07-27T21:02:23Z",
"creators": [
"Tool: scripts/generate-third-party-notices.mjs"
]
@@ -131,6 +131,16 @@
"licenseDeclared": "Apache-2.0",
"copyrightText": "NOASSERTION"
},
+ {
+ "name": "Tencent openclaw-weixin protocol sources (adapted)",
+ "SPDXID": "SPDXRef-Package-c675a4f80195e3e9",
+ "versionInfo": "2.4.6",
+ "downloadLocation": "https://github.com/Tencent/openclaw-weixin/tree/v2.4.6",
+ "filesAnalyzed": false,
+ "licenseConcluded": "MIT",
+ "licenseDeclared": "MIT",
+ "copyrightText": "NOASSERTION"
+ },
{
"name": "adler2",
"SPDXID": "SPDXRef-Package-1a8f76385143cfaa",
@@ -16383,6 +16393,23 @@
}
]
},
+ {
+ "name": "silk-wasm",
+ "SPDXID": "SPDXRef-Package-1f5626585935f113",
+ "versionInfo": "3.7.1",
+ "downloadLocation": "https://github.com/idranme/silk-wasm",
+ "filesAnalyzed": false,
+ "licenseConcluded": "MIT",
+ "licenseDeclared": "MIT",
+ "copyrightText": "NOASSERTION",
+ "externalRefs": [
+ {
+ "referenceCategory": "PACKAGE-MANAGER",
+ "referenceType": "purl",
+ "referenceLocator": "pkg:npm/[email protected]"
+ }
+ ]
+ },
{
"name": "simple-concat",
"SPDXID": "SPDXRef-Package-21d7a09ca81c30af",
@@ -17839,6 +17866,11 @@
"relationshipType": "DESCRIBES",
"relatedSpdxElement": "SPDXRef-Package-5db1c86634c06028"
},
+ {
+ "spdxElementId": "SPDXRef-DOCUMENT",
+ "relationshipType": "DESCRIBES",
+ "relatedSpdxElement": "SPDXRef-Package-c675a4f80195e3e9"
+ },
{
"spdxElementId": "SPDXRef-DOCUMENT",
"relationshipType": "DESCRIBES",
@@ -22619,6 +22651,11 @@
"relationshipType": "DESCRIBES",
"relatedSpdxElement": "SPDXRef-Package-0540e3a65d43c022"
},
+ {
+ "spdxElementId": "SPDXRef-DOCUMENT",
+ "relationshipType": "DESCRIBES",
+ "relatedSpdxElement": "SPDXRef-Package-1f5626585935f113"
+ },
{
"spdxElementId": "SPDXRef-DOCUMENT",
"relationshipType": "DESCRIBES",
diff --git a/docs/legal/notices/sbom/mobile-android.spdx.json b/docs/legal/notices/sbom/mobile-android.spdx.json
index 838208aca4..2674b7cea2 100644
--- a/docs/legal/notices/sbom/mobile-android.spdx.json
+++ b/docs/legal/notices/sbom/mobile-android.spdx.json
@@ -5,7 +5,7 @@
"name": "cindy-mobile-android",
"documentNamespace": "https://cindy.app/spdx/mobile-android/05efd357f74ac207a075699dbbd457afe65ed99fd574ee594be1d4bb651dc49a",
"creationInfo": {
- "created": "2026-07-26T02:38:39Z",
+ "created": "2026-07-27T21:02:23Z",
"creators": [
"Tool: scripts/generate-third-party-notices.mjs"
]
diff --git a/docs/legal/notices/sbom/mobile-ios.spdx.json b/docs/legal/notices/sbom/mobile-ios.spdx.json
index 2e287dec0f..f9701ae676 100644
--- a/docs/legal/notices/sbom/mobile-ios.spdx.json
+++ b/docs/legal/notices/sbom/mobile-ios.spdx.json
@@ -5,7 +5,7 @@
"name": "cindy-mobile-ios",
"documentNamespace": "https://cindy.app/spdx/mobile-ios/9cae3d29bee1df233432e6dd0978265ea2d61b380b2e50bf92a64c3516a1cccf",
"creationInfo": {
- "created": "2026-07-26T02:38:39Z",
+ "created": "2026-07-27T21:02:23Z",
"creators": [
"Tool: scripts/generate-third-party-notices.mjs"
]
diff --git a/docs/legal/wechat-personal-im-compliance.md b/docs/legal/wechat-personal-im-compliance.md
new file mode 100644
index 0000000000..7f627eedd7
--- /dev/null
+++ b/docs/legal/wechat-personal-im-compliance.md
@@ -0,0 +1,67 @@
+# 个人微信 IM 合规与发布记录
+
+> 状态:`release-blocked`。本文记录个人微信 IM 的协议来源、数据处理和发布门禁,
+> 不代表腾讯已允许 Cindy 商业分发,也不代表产品、法务或隐私审核已经完成。
+
+## 接入边界
+
+Cindy Desktop 通过腾讯 iLink 协议连接用户主动绑定的个人微信账号,仅支持私聊。
+协议行为和少量纯工具逻辑独立改写自腾讯开源项目
+[`openclaw-weixin`](https://github.com/Tencent/openclaw-weixin):
+
+- 固定版本:`v2.4.6`
+- 固定 commit:`cef0bfc390393f716903e16d50408118047f87e0`
+- 获取日期:2026-07-27
+- 源码许可:MIT
+- 仓库内来源与派生文件清单:
+ [`packages/wechat-ilink/UPSTREAM.md`](../../packages/wechat-ilink/UPSTREAM.md)
+- 上游许可原文:
+ [`packages/wechat-ilink/LICENSE.tencent-openclaw-weixin`](../../packages/wechat-ilink/LICENSE.tencent-openclaw-weixin)
+
+MIT 源码许可只覆盖相应源码,不自动授予 iLink 服务、微信品牌、绑定页面或商业分发权。
+正式发布必须取得腾讯对第三方接入方式、应用标识、品牌展示、目标地区和分发渠道的明确确认。
+
+本功能与 Mobile 使用的微信 Open SDK 登录是两条独立链路。Open SDK 的合规记录见
+[`wechat-open-sdk-compliance.md`](./wechat-open-sdk-compliance.md),不得互相替代签核。
+
+## 数据处理
+
+用户完成绑定后,Cindy Desktop 会处理:
+
+- 微信私聊文本、引用上下文和平台消息标识;
+- 用户主动发送的图片、语音、文件和视频;
+- 回复所需的 `context_token`、轮询 cursor、收件箱和发件箱状态;
+- 绑定凭证、绑定 epoch、错误诊断码和连接时间。
+
+处理边界:
+
+- 绑定凭证只进入 Desktop Main 的系统安全存储,不进入 Renderer、日志或仓库;
+- 消息任务和可靠队列保存在当前 Cindy 账号的本地数据库中,敏感 payload 使用独立数据密钥;
+- 入站媒体只落在 Cindy 受管附件目录;用户通过系统目录选择器指定的是 Agent 工作目录,
+ 不改变媒体存储边界;
+- 用户选择的 Agent/provider 可能把消息和附件发送给对应模型服务,隐私政策必须按真实
+ provider 行为披露;
+- Cindy 服务端不承担首版微信消息中转;
+- 解绑会先关闭绑定 epoch,再停止传输、清理队列与受管媒体,最后删除凭证和数据密钥。
+
+## 用户可见行为
+
+- 绑定前明确说明将打开腾讯控制的外部页面,页面可能显示 OpenClaw 品牌;
+- 重绑前明确说明新的 Cindy/OpenClaw 连接可能替换已有连接;
+- 个人微信不允许 Full Access,高风险确认只在 Desktop 完成;
+- 有效的签名兼容策略只允许停用功能,不能远程改 endpoint、协议参数或下载代码;
+- 远程 `reason` 只作为受限诊断码,不能作为 HTML/Markdown 或任意 UI 文案渲染。
+
+## 发布前签核清单
+
+- [ ] 腾讯确认 Cindy 可按目标地区、版本和渠道使用 iLink 并商业分发。
+- [ ] 腾讯确认应用标识、绑定页 OpenClaw 品牌展示和重绑排他行为可接受。
+- [ ] 产品/法务确认用户协议、隐私政策和帮助文档已覆盖上述数据处理。
+- [ ] 安全团队生成独立 Ed25519 密钥;私钥不进入本仓、构建机日志或更新器密钥系统。
+- [ ] 发布负责人填入内置 manifest URL、公钥和帮助链接固定前缀,并完成签名停用演练。
+- [ ] Windows 与 macOS 完成首次绑定、重绑、解绑、断网恢复、五种媒体和熔断回归。
+- [ ] `pnpm licenses:generate` 后生成产物无意外差异,`pnpm test:runner` 通过,安装包内
+ NOTICE/SBOM 已核对。
+- [ ] 记录签核日期、签核人、目标版本、目标地区和发行渠道。
+
+未全部完成前,个人微信入口不得作为 GA 能力发布。
diff --git a/docs/wechat-personal-im-release-checklist.md b/docs/wechat-personal-im-release-checklist.md
new file mode 100644
index 0000000000..6d162223d8
--- /dev/null
+++ b/docs/wechat-personal-im-release-checklist.md
@@ -0,0 +1,84 @@
+# 个人微信 IM 发布与熔断操作清单
+
+本文供 release、安全和 on-call 使用。技术实现完成不代表已满足外部授权;法务发布门禁见
+[`docs/legal/wechat-personal-im-compliance.md`](./legal/wechat-personal-im-compliance.md)。
+
+## 1. 生产配置
+
+生产配置位于:
+
+`apps/desktop/src/main/im/wechat/compatibilityPolicy.ts`
+
+只允许通过 code review 修改以下内置值:
+
+- `manifestUrl`:固定 HTTPS JSON 地址,不允许 query、fragment、用户信息或运行时覆盖;
+- `publicKeySpkiBase64`:独立 Ed25519 公钥的 DER/SPKI Base64;
+- `trustedHelpUrlPrefixes`:固定 HTTPS origin 与 path 前缀。
+
+当前三个值为空,因此兼容策略不会联网并保持 fail-open。这是有意的发布阻塞状态。
+不得使用环境变量、endpoint manifest、更新器密钥或服务端动态配置替代这些内置值。
+
+私钥必须由安全团队离线保管,不能进入:
+
+- Git、CI 变量导出、构建产物或日志;
+- Cindy 更新器签名系统;
+- Desktop 用户数据目录;
+- manifest 托管服务。
+
+## 2. Manifest 契约
+
+- 最大响应:32 KiB;
+- Content-Type:`application/json`;
+- 请求:`GET`、`no-store`、禁止重定向、10 秒超时;
+- 时间字段:Unix epoch 毫秒;
+- `sequence`:正整数,必须单调递增;
+- `action`:只允许 `disable`;
+- 版本范围:闭区间 SemVer;
+- `reason`:最长 64 字符的稳定小写诊断码;
+- `helpUrl`:只能命中内置 HTTPS origin/path 前缀;
+- `signature`:标准 Base64 Ed25519 签名。
+
+签名 payload 是移除 `signature` 后的对象,使用递归 key 字典序、无空白的 canonical JSON。
+实现导出的 `canonicalizeWechatCompatibilityManifestPayload` 是唯一签名基线。发布脚本在进入
+生产前必须用与该函数相同的测试向量做互操作验证。
+
+Manifest 只能停用授权、轮询和发送。它不能:
+
+- 修改腾讯或 Cindy endpoint;
+- 修改 header、协议字段、消息或权限策略;
+- 下发代码、脚本、证书或新的公钥;
+- 删除凭证、会话、设置或用户文件。
+
+## 3. 停用演练
+
+1. 在隔离环境生成测试 Ed25519 key pair,只把公钥写入测试构建。
+2. 发布不命中当前版本的 sequence N manifest,确认功能保持可用。
+3. 发布命中当前版本的 sequence N+1 manifest,确认:
+ - UI 进入“已被兼容策略停用”;
+ - 正在进行的授权取消;
+ - poll/send 停止;
+ - 凭证、设置、会话和工作目录仍保留;
+ - 解绑仍可执行。
+4. 发布篡改签名、未知字段、恶意 help URL、超大 body 和低 sequence 样本,确认全部拒绝且
+ 最后一个有效策略不被覆盖。
+5. 断网重启,确认未过期缓存继续生效。
+6. 等缓存过期或用更高 sequence 的不命中 manifest 恢复,确认功能重新连接。
+7. 核对日志只有稳定错误码和脱敏缓存路径,没有 URL、response body、token 或签名材料。
+
+## 4. 跨平台发布矩阵
+
+- [ ] Windows:绑定、扫码确认、重绑、解绑。
+- [ ] macOS:绑定、扫码确认、重绑、解绑。
+- [ ] Light 与 Dark 设置页目检。
+- [ ] 文本、图片、语音、文件、视频。
+- [ ] 断网、网络恢复、stale token、30 分钟 backlog。
+- [ ] 应用重启后的 inbox/outbox 恢复。
+- [ ] permission 确认窗口关闭/重开。
+- [ ] manifest disable、缓存、过期、恢复与 sequence rollback。
+- [ ] 安装包 NOTICE/SBOM。
+
+## 5. 回滚
+
+协议异常时只发布更高 sequence 的 `disable` manifest,不远程热修协议。代码修复仍走正常
+PR、签名构建和发布流程。若 manifest 服务不可用,客户端 fail-open;严重事件必须同时通过
+正常版本发布修复,不把熔断服务当作更新器。
diff --git a/docs/wechat-personal-im-technical-design.md b/docs/wechat-personal-im-technical-design.md
new file mode 100644
index 0000000000..562405a532
--- /dev/null
+++ b/docs/wechat-personal-im-technical-design.md
@@ -0,0 +1,1479 @@
+# 个人微信 IM Connector 技术设计
+
+> 状态:`reviewed-approved`
+>
+> 目标交付:一个 PR、多个按层次可 review 的 commit。开发期间可以创建本地 commit,
+> 但 push 和创建 PR 的时机由维护者决定。
+>
+> 平台范围:Desktop Windows / macOS。首版不修改 Mobile,不修改 Cindy 服务端。
+>
+> 合规边界:本文讨论的是腾讯 iLink 个人微信消息 Connector,不是 Cindy Mobile
+> 已有的微信 Open SDK 登录。后者的合规记录见
+> [`legal/wechat-open-sdk-compliance.md`](./legal/wechat-open-sdk-compliance.md)。
+
+## 1. 目标与最终结论
+
+Cindy 在「设置 → IM 机器人 → 个人」中增加个人微信连接。用户在系统浏览器完成
+微信扫码授权后,可以从个人微信与本机 Cindy Agent 对话。
+
+最终架构:
+
+> 架构决策(2026-07-27):实现形态采用更接近 FeishuBot 的 Desktop Main
+> 进程内直连通道,复用共享 IM turn runner;微信模块自行负责授权、长轮询、
+> durable inbox/outbox 与媒体生命周期。SlackBot 的 hook-control/WebSocket
+> 控制面不进入本功能范围。
+
+```mermaid
+flowchart LR
+ WX["个人微信"]
+ IL["腾讯 iLink"]
+ TP["packages/wechat-ilink<br/>可替换 Transport"]
+ IM["@cindy/im<br/>WechatIM"]
+ RQ["Desktop 可靠层<br/>SQLite inbox/outbox"]
+ OR["现有 IM Orchestrator"]
+ MK["现有 Maker Session"]
+ UI["Desktop 设置与确认 UI"]
+
+ WX <--> IL
+ IL <--> TP
+ TP <--> IM
+ IM <--> RQ
+ RQ <--> OR
+ OR <--> MK
+ UI <--> IM
+ UI <--> OR
+```
+
+实施原则:
+
+1. **原生客户端连接**:微信消息只在腾讯 iLink 与本机 Cindy 之间传输,不经
+ Cindy 服务端,不引入 `wechat-hook-server`。
+2. **不嵌入完整 OpenClaw**:只复用腾讯 MIT 仓库中与 iLink 协议直接相关的
+ 类型、鉴权、媒体、Markdown 规则,并保留许可证要求。
+3. **Transport 可替换**:业务层不依赖腾讯当前 endpoint 细节。若未来腾讯要求
+ 通过 OpenClaw Host,只替换 Transport,不改 UI、队列、会话和权限层。
+4. **复用现有 Agent 编排**:微信不是一套新 Agent runtime,而是 Cindy 现有
+ Maker Session 的一个入站/出站渠道。
+5. **可靠边界在本地 SQLite**:cursor、去重、待执行任务和待发送结果必须跨重启
+ 恢复,不能只依赖现有内存 `sendQueue`。
+6. **高风险确认只在 Desktop**:微信不模拟交互卡片。permission、结构化 Ask、
+ Plan Review 进入 Desktop;微信只显示等待提示。
+7. **直接 GA 但带前置门禁**:完成技术实现不等于已获商业分发授权。腾讯/iLink
+ 的第三方接入、应用标识、品牌展示和分发条件未确认前不得 GA。
+8. **Core 例外有明确退出条件**:当前插件沙箱不能持有后台长轮询、系统浏览器授权、
+ safeStorage、owner DB 和 Maker Session ingress,因此首版进入 Desktop Core;
+ vendor 协议仍隔离在独立 package。未来出现通用 IM Connector capability slot 后,
+ 官方微信实现应迁回插件。
+
+## 2. 产品范围
+
+### 2.1 首版包含
+
+- 个人微信扫码绑定、重绑、解绑;
+- Cindy Local 模式和 Cloud 模式,数据按当前 data owner 隔离;
+- 每个 data owner 同时绑定一个微信;
+- Windows、macOS;
+- 私聊收发;
+- 文本、图片、语音、文件、视频入站;
+- 引用消息作为当前 turn 的补充上下文;
+- typing、接收确认、长任务心跳、最终答案;
+- `/new`、`/stop`、`/stop all`、`/status`、`/help`;
+- 默认复用同一 Cindy 会话,`/new` 开启新上下文;
+- Desktop 设置新会话默认 Agent、模型、effort、permission 和工作区;
+- 本地持久队列、去重、过期、重试和重启恢复;
+- 有效签名的远程兼容禁用清单。
+
+### 2.2 首版不包含
+
+- 群聊;
+- Mobile Connector;
+- Cindy 服务端消息转发;
+- 主动消息、定时推送、scheduler 通知;
+- 在微信中审批高风险操作;
+- `/model`、`/permission`、`/ctr`、`/exctr`;
+- 多微信账号;
+- 完整 OpenClaw sidecar;
+- 运行时下载代码或通过远程清单改变协议行为;
+- 语音形式的 Agent 出站回复。
+
+## 3. 外部依据与 Coze 对照
+
+### 3.1 Coze 1.1.21
+
+Coze 的 Desktop 端实现以下云端接口:
+
+- `POST /api/coze_claw/channel/wechat/bind_start`
+- `POST /api/coze_claw/channel/wechat/bind_wait`
+- `POST /api/coze_claw/wechat/webhook`
+- `POST /api/coze_claw/channel/wechat/unbind`
+
+源码位置(独立 `agent-src` 归档仓,不属于本仓):
+
+- `coze-desktop/1.1.21/beautified/main/main.js`
+ 的微信 API client;
+- `coze-desktop/1.1.21/beautified/renderer/static/js/index.b7a3954b13.js`
+ 的外部授权弹窗和等待状态。
+
+可复用的是产品流程:
+
+1. 先解释会跳转外部网页;
+2. 系统浏览器扫码;
+3. Desktop 显示等待中;
+4. 成功后显示连接状态;
+5. 重绑时明确会断开旧连接。
+
+不能复用的是云端 webhook 拓扑。Cindy 首版没有服务端消息处理面。
+
+### 3.2 腾讯 iLink
+
+官方仓库:
+
+- <https://github.com/Tencent/openclaw-weixin>
+- <https://github.com/Tencent/openclaw-weixin/blob/v2.4.6/LICENSE>
+
+首个实现固定的协议核对基线(获取于 2026-07-27):
+
+- tag:`v2.4.6`;
+- commit:`cef0bfc390393f716903e16d50408118047f87e0`;
+- 许可:MIT;
+- 派生文件:Commit 2 按实际复制或改写的文件逐项登记;Commit 1 只有设计和协议核对
+ 记录,没有复制上游源码。
+
+当前公开协议包括:
+
+- 扫码授权;
+- `getupdates` 长轮询和 `get_updates_buf` cursor;
+- `sendmessage`;
+- `getuploadurl`;
+- `getconfig` / `sendtyping`;
+- TEXT / IMAGE / VOICE / FILE / VIDEO;
+- `context_token`;
+- AES-128-ECB CDN 媒体。
+
+官方插件仍带 OpenClaw Host 版本兼容约束,因此 Cindy 不依赖它的 plugin runtime,
+只把稳定协议实现放进独立包。`bot_agent=Cindy/<version>` 只做观测归因,不作为
+鉴权或路由依据。
+
+实现开始前必须记录复用依据的**精确 tag/commit SHA**、获取日期和派生文件清单;
+许可与行为基线不得长期指向可变的 `main`。如果实现仅依据协议重写而没有复制源码,
+同样记录协议核对 commit,便于后续兼容审计。
+
+## 4. 仓库落点
+
+### 4.1 新增纯协议包 `packages/wechat-ilink`
+
+建议结构:
+
+```text
+packages/wechat-ilink/
+ package.json
+ tsconfig.json
+ src/
+ types.ts
+ transport.ts
+ tencentIlinkTransport.ts
+ auth.ts
+ apiClient.ts
+ poller.ts
+ codec.ts
+ mediaCrypto.ts
+ mediaDownload.ts
+ mediaUpload.ts
+ markdown.ts
+ chunk.ts
+ errors.ts
+ index.ts
+ __tests__/
+```
+
+约束:
+
+- 不依赖 Electron、Drizzle、Maker;
+- 不读写 Cindy 路径;
+- 不自行持久化 cursor/token;
+- 网络和文件写入全部由 host 注入或明确返回字节;
+- 使用 `AbortSignal` 取消授权、长轮询、上传和下载;
+- 错误输出稳定 machine code,不向上层透出 token 或完整响应体。
+
+核心接口:
+
+```ts
+export interface WechatTransport {
+ beginAuthorization(signal: AbortSignal): Promise<WechatAuthChallenge>;
+ waitAuthorization(
+ challenge: WechatAuthChallenge,
+ signal: AbortSignal,
+ ): Promise<WechatCredentials>;
+
+ poll(cursor: string, signal: AbortSignal): Promise<WechatPollResult>;
+ sendMessage(request: WechatSendRequest): Promise<WechatSendResult>;
+
+ getTypingTicket(peerId: string, contextToken: string): Promise<string>;
+ setTyping(peerId: string, ticket: string, active: boolean): Promise<void>;
+
+ downloadMedia(ref: WechatMediaRef, signal: AbortSignal): Promise<Uint8Array>;
+ uploadMedia(request: WechatUploadRequest): Promise<WechatMediaRef>;
+}
+```
+
+默认实现为 `TencentIlinkTransport`。
+
+### 4.2 扩展 `packages/lizi-im`
+
+新增:
+
+```text
+packages/lizi-im/src/wechat/
+ index.ts
+ ipc.ts
+ inbound.ts
+ outbound.ts
+ status.ts
+```
+
+现有 `ChannelIM` 默认假定渠道支持交互卡片和 streaming edit,微信不支持。不能把
+现有方法简单改成 optional:现有编排层会立即失去类型安全,并造成中间 commit 无法
+编译。改为 discriminated output driver:
+
+```ts
+export type ImOutputDriver =
+ | {
+ kind: 'rich-card';
+ im: RichChannelIM;
+ }
+ | {
+ kind: 'chunked-text';
+ im: TextChannelIM;
+ commitFinal(args: ImFinalOutput): Promise<void>;
+ };
+```
+
+`TextChannelIM` 只包含订阅、文本、文件和状态基础能力;`RichChannelIM` 在其上增加
+卡片、patch 和 streaming。Feishu/Discord adapter 使用 `kind: 'rich-card'`,微信使用
+`kind: 'chunked-text'`。`turnRunner` 必须按 `kind` 完成穷尽分支,不能通过 boolean
+capability 后继续无条件调用卡片 API。
+
+该 OutputDriver 只负责 Desktop 直连 IM 的输出差异。生产 Slack 仍走
+`main/hook-control` + 外部 hook server,不迁入 `@cindy/im`;Slack 与直连 IM
+共享的是 session 级 InteractionRouter、发送前安全屏障和 accepted/terminal 契约,
+不是 transport 或消息队列实现。
+
+该类型改造与 `turnRunner` output 分流放在**同一个 commit**,确保每个 commit 独立
+typecheck。微信输出能力:
+
+```ts
+{
+ kind: 'chunked-text',
+ im: wechatIm,
+ commitFinal,
+}
+```
+
+类型变更:
+
+- `IMMessageEvent` 增加结构化 `quote`;
+- 新增 `WechatBotState`,不把微信详细状态硬塞进通用 `IMStatus`。
+
+`IMAttachment.kind` 首版继续保持 `image | file`;音频和视频按 `kind: 'file'` +
+真实 MIME 进入 model-facing/落库路径,避免无必要扩大公共契约。
+
+### 4.3 Desktop Main
+
+新增:
+
+```text
+apps/desktop/src/main/im/wechat/
+ index.ts
+ adapter.ts
+ sessions.ts
+ uiText.ts
+ lifecycle.ts
+ taskStore.ts
+ taskPump.ts
+ mediaStore.ts
+ credentialStore.ts
+ compatibilityManifest.ts
+```
+
+修改:
+
+- `apps/desktop/src/main/im/host.ts`:创建 `wechatIm` 并加入 `createIM`;
+- `apps/desktop/src/main/im/index.ts`:创建 WeChat orchestrator;
+- `apps/desktop/src/main/im/shared/types.ts`:增加 `wechat` 和渠道策略;
+- `apps/desktop/src/main/im/shared/turnRunner.ts`:output driver、可观测的 accepted/terminal
+ 执行契约和 external queue 模式;
+- `apps/desktop/src/main/maker-ipc/interactionRouter.ts`:session 级中央 interaction 路由;
+- `apps/desktop/src/main/im/shared/messageHandler.ts`:渠道命令策略;
+- `apps/desktop/src/shared/sessionSource.ts`:增加微信 session source;
+- `apps/desktop/src/shared/imDefaultSettings.ts`:增加微信默认设置;
+- `apps/desktop/src/main/localDb/schema.ts`:可靠层 schema;
+- 下一条正式 Drizzle migration:当前 migration 线在 `0081` 之后继续生成,
+ 不手工选择名称或弱化 migration 校验。
+
+运行期多表原子操作不能在 Main 中拼接多个 awaited Drizzle 调用。必须通过 DbClient
+命名 worker transaction 实现:
+
+```text
+wechatActivateBindingEpoch
+wechatCommitPollBatch
+wechatLeaseNextTask
+wechatMarkAccepted
+wechatCommitInterrupted
+wechatCommitTerminal
+wechatMarkOutboxDelivered
+wechatRecordOutboxFailure
+wechatStopAll
+wechatCloseBindingEpoch
+wechatUnbindCleanup
+```
+
+### 4.4 Renderer / preload
+
+新增:
+
+```text
+apps/desktop/src/renderer/components/settings/WechatBotSection.tsx
+apps/desktop/src/renderer/hooks/useWechatBot.ts
+```
+
+修改:
+
+- `apps/desktop/src/renderer/components/settings/ImBotSection.tsx`;
+- `apps/desktop/src/renderer/components/settings/ImDefaultSettingsSection.tsx`;
+- `apps/desktop/src/preload/preload.ts`;
+- `apps/desktop/src/renderer/vite-env.d.ts`;
+- i18n 文案与 `i18n/GLOSSARY.md` / `i18n/glossary.json`。
+
+所有 UI 同时实现 Light/Dark,颜色只能使用语义 token。
+
+## 5. 授权、连接与生命周期
+
+### 5.1 状态机
+
+```text
+disconnected
+ -> authorizing
+ -> waiting_confirmation
+ -> connected
+ <-> reconnecting
+
+异常:
+ needs_reauth
+ disabled_by_policy
+ error
+```
+
+```ts
+export interface WechatBotState {
+ phase:
+ | 'disconnected'
+ | 'authorizing'
+ | 'waiting_confirmation'
+ | 'connected'
+ | 'reconnecting'
+ | 'needs_reauth'
+ | 'disabled_by_policy'
+ | 'error';
+ connectedAt?: number;
+ lastInboundAt?: number;
+ queuedTasks: number;
+ errorCode?: string;
+}
+```
+
+### 5.2 授权流程
+
+1. 用户点击「连接微信」;
+2. Main 获取授权 challenge;
+3. Main 校验授权 URL,仅允许 HTTPS 和明确允许的腾讯域名;
+4. Main 直接调用 `shell.openExternal`,Renderer 不取得 URL;
+5. Main 等待扫码确认,最长 5 分钟,可取消;
+6. 校验返回的 `baseUrl`、bot id、token;
+7. 先写新凭证,再切换 binding generation;
+8. 启动长轮询并广播 `connected`。
+
+微信授权页可能显示 OpenClaw,这是腾讯授权页行为。Cindy 设置页在打开前说明该事实,
+不修改、不套壳、不伪装授权页。
+
+### 5.3 后台生命周期
+
+- Window 隐藏或进入托盘不停止长轮询;
+- App 退出时 abort in-flight poll;
+- 网络恢复后按 `1s/2s/5s/10s/30s + jitter` 重连;
+- stale token 进入 `needs_reauth`,不持续撞接口;
+- data owner generation 关闭后,旧 generation 的回调不能再写凭证、DB 或发消息;
+- 每次绑定生成独立随机 `bindingEpoch` UUID,不复用 owner generation;
+- 所有 sync/inbox/outbox 行和命名事务都带 `bindingEpoch`;
+- 每次 DB 写、凭证切换和出站发送同时校验 owner generation 与 active binding epoch;
+- 新凭证先写 `wechat_credentials_<epoch>` staging key,再初始化该 epoch 的 DB state;
+- `wechatActivateBindingEpoch` 以 CAS 切换 active epoch;
+- CAS 成功后关闭旧 epoch,abort 并 await auth/poll/pump/outbox drain,再删除旧 secret;
+- 旧 poll 即使迟到,也因 epoch CAS 失败而不能写进新绑定。
+
+## 6. 凭证和本地数据
+
+### 6.1 safeStorage
+
+复用 owner-scoped IM secrets。若 `safeStorage.isAvailable() === false`,绑定入口必须
+fail-closed,不允许降级成明文:
+
+- `wechat_credentials_<bindingEpoch>`;
+- `wechat_data_key_v1`。
+
+凭证形状:
+
+```ts
+interface StoredWechatCredentials {
+ botToken: string;
+ ilinkBotId: string;
+ baseUrl: string;
+ boundAt: number;
+ bindingEpoch: string;
+}
+```
+
+`wechat_data_key_v1` 是随机 256-bit key,用于本地 SQLite 中敏感上下文字段的
+AES-256-GCM 加密。
+
+### 6.2 不写明文的字段
+
+- bot token;
+- context token;
+- CDN AES key;
+- 登录 challenge;
+- 完整原始响应。
+
+CDN AES key 只在下载/解密过程内存中存在。`context_token` 需要跨重启补发结果,
+因此以 `nonce + ciphertext + tag` 写 SQLite,密钥只在 safeStorage。
+
+### 6.3 可写本地 DB 的数据
+
+- sync cursor;
+- platform message id/seq;
+- peer id;
+- 消息正文和附件元数据;
+- 队列状态、时间戳、重试次数;
+- 脱敏错误码;
+- outbox 文本。
+
+这些数据与 Cindy 会话历史同属当前 data owner 的本地业务数据,不进入日志或云端。
+
+## 7. SQLite 可靠层
+
+### 7.1 `wechat_sync_state`
+
+```text
+binding_epoch PRIMARY KEY
+is_active
+sync_cursor
+last_poll_at
+last_error_code
+updated_at
+```
+
+### 7.2 `wechat_inbox`
+
+```text
+id
+binding_epoch
+platform_message_id
+platform_seq
+peer_id
+received_at
+platform_created_at
+expires_at
+status
+lease_until
+session_id
+conversation_epoch
+payload_json
+context_nonce
+context_ciphertext
+context_tag
+attempts
+last_error_code
+```
+
+状态:
+
+```text
+pending
+dispatching
+accepted_running
+waiting_desktop
+delivery_pending
+completed
+interrupted
+cancelled
+expired
+failed_terminal
+rejected_overload
+```
+
+唯一键和索引:
+
+```text
+UNIQUE(binding_epoch, platform_message_id)
+INDEX(binding_epoch, status, received_at)
+INDEX(binding_epoch, lease_until)
+INDEX(binding_epoch, peer_id, conversation_epoch)
+```
+
+### 7.3 `wechat_outbox`
+
+```text
+id
+binding_epoch
+task_id
+client_id
+kind
+chunk_index
+text
+media_json
+status
+attempts
+next_retry_at
+created_at
+delivered_at
+```
+
+durable outbox 只保存 Agent 已生成且不能丢的 final/error/interrupted notice。ack、typing
+和 heartbeat 是 best-effort 临时状态,不写 durable outbox,避免 final 已送达后恢复出
+过期心跳。`client_id` 的实际唯一范围是 binding epoch,schema 使用
+`UNIQUE(binding_epoch, client_id)`。
+
+### 7.4 `wechat_file_attachments`
+
+```text
+id
+binding_epoch
+task_id
+session_id
+abs_path
+original_name
+mime_type
+bytes
+status
+promoted_at
+created_at
+```
+
+普通文档不进入 Cindy media blob store。它们写在 data-owner-scoped
+`im-attachments/wechat/`,文件名由 task id 和随机 id 生成,原始文件名只作为展示元数据。
+
+### 7.5 Cursor 原子边界
+
+每个 poll batch:
+
+1. 校验 message 类型、owner、id 和大小;
+2. 去重并准备附件;
+3. 使用 `blobStore.writeBlob()` 先原子发布媒体字节,但不在 Main 调
+ `ingestMedia()` 拼接多次 DB 写;
+4. 把 hash/ext/mime/bytes 交给 `wechatCommitPollBatch` 命名事务;
+5. 该 worker transaction 中:
+ - 写/触碰 `media_blobs`;
+ - 插入 inbox;
+ - 写媒体临时引用;
+ - 写普通文件 metadata;
+ - 更新 cursor;
+6. commit 成功后才开始下一次 poll。
+
+ack 不进入 durable outbox;transaction commit 返回后 Main best-effort 发送。
+
+故障语义:
+
+- DB transaction 失败:保留旧 cursor,下一次重拉,依赖 message id 去重;
+- 媒体字节已写、transaction 失败:成为无账 blob,符合 cindy-media
+ 「先字节后记账」语义,由既有对账/回收策略处理;
+- transaction 成功、进程在 Agent 前崩溃:启动后从 inbox 恢复;
+- 不允许先推进 cursor、后异步落 inbox。
+
+### 7.6 Queue 与 lease
+
+- 同一 session 只允许一个 `dispatching | accepted_running | waiting_desktop |
+ delivery_pending`;
+- 可执行 `pending + dispatching + accepted_running + waiting_desktop` 最大 20;
+- 达到上限的新消息落 `rejected_overload`,生成忙碌回复并推进 cursor;
+- 每条任务 `expires_at = received_at + 30min`;
+- 30 分钟 TTL 只约束尚未跨过 `beforeProviderStart` accepted 屏障的任务;
+- `dispatching` 过期 lease 若确认尚未 accepted,可以回退 pending;
+- `accepted_running` 在进程崩溃后必须改为 `interrupted`,**绝不自动重放**;
+- `waiting_desktop` 在重启后取消 interaction,并标 `interrupted`;
+- `delivery_pending` 只恢复 outbox 发送,绝不重跑 Agent;
+- interrupted notice 在取得新的可用 context token 后发送;
+- 只有用户明确要求重试时,才从原 payload 创建**新的 task id**;
+- 一个任务失败不能卡死后续任务;
+- 完成、取消、过期后释放 inbox 临时媒体引用。
+
+Agent task 状态机:
+
+```text
+pending
+ -> dispatching
+ -> accepted_running
+ -> waiting_desktop -> accepted_running
+ -> delivery_pending
+ -> completed
+
+crash before accepted:
+ dispatching -> pending
+
+crash after accepted:
+ accepted_running/waiting_desktop -> interrupted
+
+crash after final outbox commit:
+ delivery_pending -> resume outbox only
+```
+
+`finalizing` 只允许是进程内瞬时概念,不能写成 DB 状态。`wechatCommitTerminal` 必须在
+同一个命名事务内完成:
+
+```text
+accepted_running
+ + insert all final outbox chunks
+ -> delivery_pending
+```
+
+事务前崩溃仍是 `accepted_running`,启动后改 interrupted;事务中崩溃整体回滚;事务后
+崩溃一定已有完整 outbox。发现 `delivery_pending` 但没有 outbox 属于 DB invariant
+violation,启动 repair 将其改为 `interrupted` 并记录安全 machine code,不能重跑 Agent。
+
+### 7.7 Turn 执行契约与唯一队列所有权
+
+现有 `runAgentTurn(): Promise<void>` 可能只把消息加入内存 `sendQueue` 就返回,不能作为
+durable task 终态。增加不依赖回调时序的执行契约:
+
+```ts
+export type ImTurnDispatch =
+ | {
+ kind: 'accepted';
+ sessionId: string;
+ acceptedAt: number;
+ terminal: Promise<ImTurnTerminal>;
+ }
+ | {
+ kind: 'busy' | 'rejected';
+ reason: string;
+ };
+
+export interface ImTurnTerminal {
+ kind: 'done' | 'aborted' | 'error';
+ finalText: string;
+ completedAt: number;
+ errorCode?: string;
+}
+```
+
+约束:
+
+- Feishu/Discord 可继续使用现有内存排队 wrapper;
+- WeChat 使用 `queueMode: 'external'`,`turnRunner` 遇到 busy 只返回 `busy`,不得加入
+ `sendQueue`;
+- WeChat durable task pump 是微信任务的唯一排队者;
+- task pump 同一 session 每次只把一条任务交给 `turnRunner`;
+- Maker send path 增加 awaited `beforeProviderStart` hook。它位于 session busy guard
+ 通过之后、任何 provider/model/tool 执行之前;
+- WeChat 的 `beforeProviderStart` 调用 `wechatMarkAccepted`,CAS 成功后任务才进入
+ `accepted_running`;
+- hook/CAS 失败必须让 send 返回 `rejected`,provider、model、MCP 和 tool 均不得启动;
+- 现有 `onAccepted` 继续承担 user message 持久化等既有语义,不能充当安全屏障;
+- DB accepted 早于 provider 真正启动会产生“保守中断”窗口:若此刻崩溃,任务仍按
+ interrupted 处理而不自动重放,这是有意的副作用安全取舍;
+- task pump 必须等待 `terminal`;
+- `terminal` 不能复用现有早于最终输出收集的 `onTurnComplete`;
+- `wechatCommitTerminal` 在一个命名事务内写全部 final outbox,并把 inbox 改为
+ `delivery_pending`;
+- 该事务提交后才能考虑下一条任务;
+- 同 peer 存在 `delivery_pending` 时,先完成 outbox;没有新 context token 时保持阻塞,
+ 不重新运行 Agent;
+- 所有 final chunk 送达后,`wechatMarkOutboxDelivered` 才把任务改为 `completed`。
+
+## 8. 会话路由与命令
+
+### 8.1 会话
+
+- `sessions.source = 'wechat'`;
+- 默认 `workspaceKind = 'dialogue'`;
+- 默认工作目录是 Cindy 托管的 IM dialogue 目录;
+- 用户可在 Desktop 选择一个已登记项目,选择只影响之后的新上下文;
+- session id 按 `botContextId + peerId` 确定性生成;
+- `/new` 不新建无限 session row,而是重置 SDK 上下文并增加
+ `conversation_epoch`;
+- 现有历史继续保留在 Cindy 会话中。
+
+### 8.2 新会话默认
+
+`im-default-settings.json` 从 v2 升到 v3:
+
+- channel 增加 `wechat`;
+- `ImDefaultSettings` 增加 `permissionMode`,默认 `auto`;
+- 旧文件缺字段时 normalize 为 `auto`;
+- Feishu/Discord/Slack 行为不变;
+- full access 设置只作用于新上下文。
+
+微信独有的项目选择放在 owner-scoped `wechat-channel.json`,不扩散到其它 IM。
+
+### 8.3 命令
+
+微信命令采用显式 allowlist:
+
+- `/new`;
+- `/stop`;
+- `/stop all`;
+- `/status`;
+- `/help`。
+
+命令不作为普通 Agent 消息:
+
+- `/stop` 立即 abort 当前 task,保留后续 pending;
+- `/stop all` abort 当前 task,并原子取消全部 pending;
+- `/status`、`/help` 立即回复;
+- `/new` 作为 FIFO 会话边界,边界后的任务使用新 epoch;
+- 其它 `/xxx` 回复 unknown command,不进入 Agent。
+
+## 9. Interaction 与权限
+
+### 9.1 中央 InteractionRouter
+
+Maker Session 的 interaction listener 是覆盖式单 listener,不能继续让 Desktop、
+Feishu、Discord 和 WeChat 互相安装/还原 listener。新增 session 级中央
+`InteractionRouter`:
+
+```ts
+type TurnOrigin =
+ | { kind: 'desktop' }
+ | { kind: 'im'; channel: 'feishu' | 'discord' | 'slack' | 'wechat'; taskId?: string }
+ | { kind: 'scheduler' }
+ | { kind: 'hook'; source: string };
+
+interface InteractionRoute {
+ sessionId: string;
+ turnId: string;
+ origin: TurnOrigin;
+ interactionSurface: 'desktop' | 'channel-card' | 'headless';
+ onStateChange?(state: 'waiting' | 'resolved' | 'cancelled'): void;
+}
+```
+
+规则:
+
+- 每个 Maker Session 只安装一次 Router listener;
+- Desktop、IM、scheduler、hook 在 turn dispatch 时登记 origin;
+- Desktop turn → Desktop UI;
+- WeChat turn → Desktop UI,同时通知对应 durable task observer;
+- Feishu/Discord turn → 对应渠道卡片;
+- 无法识别/已过期 turn → 安全拒绝;
+- request id 到 route 一次性绑定;
+- abort、timeout、解绑、owner/binding epoch 关闭统一经 Router resolve 一次;
+- 渠道不得再直接 `setInteractionListener()` 抢占;
+- 现有 detach 流程不再负责“恢复 Desktop listener”。
+
+微信行为:
+
+1. permission、结构化 Ask、Plan Review 使用 Desktop interaction listener;
+2. 微信发送「任务正在等待你在 Cindy 中确认」;
+3. inbox 状态改为 `waiting_desktop`;
+4. 最长等待 30 分钟;
+5. `/stop` 可以取消等待;
+6. 超时后 permission/plan 拒绝,Ask 以取消结束,不无限占住队列;
+7. turn 收口后继续派发下一条。
+
+### 9.2 高风险工具策略前移
+
+只在 `turnRunner.handleInteractionFor()` 检查 destructive 不足以兑现安全承诺:
+Claude MCP auto-approve 和 Full Access 可能根本不产生 interaction。新增按 turn origin
+注入的 Maker 权限策略:
+
+```ts
+interface TurnPermissionPolicy {
+ origin: TurnOrigin;
+ forceConfirmToolCall(toolName: string, input: unknown): boolean;
+ confirmationSurface: 'desktop' | 'channel';
+}
+```
+
+执行边界:
+
+- policy 随 `session.send()` 的本次 turn 传入,不写进 system prompt;
+- Claude Code 在 `canUseTool` 与 MCP auto-approve **之前**执行
+ `forceConfirmToolCall`;
+- Codex policy turn 使用可被 host 观察的 `untrusted + read-only` turn 配置,并在
+ approval 自动放行之前执行同一策略;
+- 微信 origin 命中 destructive classifier 时强制生成 Router permission request;
+- session permission mode 为 `auto` 时,微信 origin 的高风险命中不能绕过 Desktop
+ 确认;
+- 非微信 turn 保持现有权限行为;
+- provider 若无法提供强制确认前置钩子,该 provider 的微信 Full Access 不可选,
+ 不能静默降级;
+- 这项改动进入 `maker-core` Agent 行为边界,实施时必须按
+ `docs/dev-rules/maker-core-and-agent-behavior.md` 验证 Claude/Codex 两条路径。
+
+现有 destructive guard 对其它渠道继续直接 deny。微信的旧 guard 仅作为 defense in
+depth,真正保证来自 Maker/Agent 权限入口。
+
+Full Access:
+
+1. 当前 Claude/Codex adapter 都无法证明 Full Access 下每一种文件删除会在执行前回调
+ host,因此个人微信首版明确禁用 Full Access;
+2. capability 对外声明不支持的 permission mode,dispatch preflight 在任何 durable
+ accepted/CAS/消息落库之前拒绝,不静默降级成 Auto;
+3. 将来只有 provider 提供覆盖所有工具执行的前置 hook 并完成回归后,才能重新开放;
+4. 届时仍需 Desktop 二次风险确认、只写新会话默认且 `/new` 后生效。
+
+## 10. 文本与回复
+
+### 10.1 输出策略
+
+微信不尝试模拟卡片 streaming edit:
+
+1. inbox commit 后发 ack;
+2. 获取 typing ticket 并开启 typing;
+3. Agent 运行;
+4. 60 秒未完成时发第一条可见心跳;
+5. 之后最多每 2 分钟一条;
+6. structured interaction 时发等待 Desktop 提示;
+7. turn 结束,关闭 typing;
+8. Markdown filter;
+9. 代码块感知地切成不超过 3500 字符;
+10. 写 durable outbox 并发送 final。
+
+ack、typing、heartbeat 都是进程内 best-effort 状态;进程重启后不恢复它们。只有
+final/error/interrupted notice 写 durable outbox。
+
+### 10.2 重试与新 token 补发
+
+- 每个 outbox chunk 固定一个 `client_id`;
+- 同一 chunk 最多即时重试 3 次;
+- 失败后保持 pending,不重复生成 Agent 回答;
+- 下一条同 peer 入站带来新 `context_token` 后,先补发旧 final;
+- 补发结束后才执行新任务;
+- Agent terminal 到 final outbox 的写入与 inbox `delivery_pending` 状态更新必须在
+ `wechatCommitTerminal` 同一命名事务;
+- retry 复用原 `client_id`;
+- ack/heartbeat 失败不阻塞 Agent,final 失败必须进入 outbox。
+
+### 10.3 Markdown
+
+- 复用/移植腾讯官方 Markdown filter 的协议相关规则;
+- 不直接复制 OpenClaw runtime glue;
+- 3500 是 Cindy 上限,低于官方插件当前 4000;
+- chunker 必须保持 fenced code block 成对;
+- 无法保持时在 chunk 边界补 fence,并在下一 chunk 重开;
+- 不切断 surrogate pair、组合字符和 Markdown 链接目标。
+
+## 11. 入站媒体与引用
+
+### 11.1 限制
+
+- 每条最多 4 个附件;
+- 单个明文最大 5 MB;
+- 读取流执行硬上限,不信任 Content-Length;
+- 总上限自然为 20 MB;
+- 超出部分写 `unsupported`,其它文本/附件继续执行;
+- 下载失败不能阻塞整个 poll batch;
+- URL 必须 HTTPS 且命中允许域;
+- AES key 长度、padding、MD5/size 均验证。
+
+### 11.2 Cindy media 边界
+
+进入 cindy-media:
+
+- image;
+- audio;
+- video。
+
+不进入 cindy-media:
+
+- PDF、Office、压缩包和其它普通文件。
+
+媒体入仓时挂 `im-inbox` 临时引用。Maker 接受 user message 后,现有
+`persistUserMessage()` 仍可能吞掉落库失败,因此不能仅凭 Agent accepted 删除临时引用。
+
+晋升协议:
+
+1. user message 落库返回成功;
+2. 确认对应 cindy-media hash 已有目标 session 的 `session-attachment` ref;
+3. 命名事务/repair 操作把附件标记 promoted;
+4. 最后删除 `im-inbox` ref;
+5. 任一步失败都保留 `im-inbox` ref 和 `repair_required` 状态;
+6. 启动 repair 重试晋升,不删除用户附件。
+
+为此给 `MediaRefKind` 增加 `im-inbox`,不改变底层 SQLite 列类型。
+
+普通文件:
+
+- 入站时状态 `staged`;
+- user message 成功落库后改为 `promoted` 并写 `promoted_at/session_id`;
+- Agent 使用受控 `xdt-file` URL 或同等级 root grant,不把任意裸绝对路径暴露给
+ Renderer;
+- session 删除时清理对应 promoted 文件;
+- 解绑只删除 staged 文件,不能删除已进入 session history 的文件;
+- DB cleanup transaction 返回待删路径,Main 做 root containment、symlink 和 epoch
+ 校验后再删除字节。
+
+### 11.3 语音
+
+- 微信提供 transcript 时,把 transcript 放入当前 turn;
+- 原始 SILK 在 Worker 内转 WAV,不能阻塞 Electron Main;
+- WAV 进入 cindy-media;
+- 转码失败时保留 transcript,并将音频标成 unsupported;
+- 没有 transcript 且转码失败时,不调用 Agent,直接提示暂不能处理。
+
+### 11.4 引用消息
+
+```ts
+interface IMQuote {
+ authorLabel?: string;
+ text?: string;
+ attachments?: IMAttachment[];
+}
+```
+
+quote 只注入本次 model-facing `UserMessage`,不伪造成上一条历史消息。用户消息落库
+可保存 quote metadata 供 UI 展示,但 session transcript 的顺序不改变。
+
+## 12. 网络与 Electron 安全
+
+所有网络请求在 Main:
+
+- Renderer 不收 token、context token、AES key、base URL 或原始事件;
+- 协议包只使用 Main 注入的 HTTP client,Desktop 实现使用 Electron `net.fetch`,
+ 包内不直接使用全局 fetch;
+- 授权 URL 由 Main 校验后直接 `shell.openExternal`;
+- 登录返回的 base URL 不能直接信任;
+- API host 与 CDN host 使用独立 allowlist;
+- auth/API 请求禁用自动重定向;
+- 媒体若协议确需重定向,逐跳手工处理并重新校验 scheme、host、端口和跳数;
+- 禁止 localhost、私网 IP、`file:`、自定义协议;
+- auth、poll 和错误响应设置严格字节上限;
+- 单个 poll batch 设置最大消息数和最大 item 数,超过时以协议错误处理,不能无界
+ `JSON.parse` 后继续分配;
+- `payload_json` 只保存字段 allowlist 后的 normalized payload,禁止放原始 response
+ 或 `raw`;
+- 日志只记录 endpoint 类别、状态码、错误码、长度和脱敏 id 后缀;
+- 不记录 query、Authorization、context token、完整 message body;
+- error 类型只能携带稳定 machine code 和安全参数,禁止直接 `String(err)` 记录可能包含
+ URL、header 或 body 的底层网络错误;
+- 媒体文件名不使用平台提供的原始路径;
+- 普通文件落盘前做 root containment、symlink 和最终绝对路径校验。
+
+`X-WECHAT-UIN` 每次请求重新生成。`bot_agent` 固定从构建版本生成,不接受远程或用户
+输入。
+
+## 13. 兼容禁用 Manifest
+
+Manifest 只允许停用,不允许修改 endpoint、协议参数或下载代码:
+
+```json
+{
+ "schemaVersion": 1,
+ "sequence": 1,
+ "generatedAt": 0,
+ "expiresAt": 0,
+ "rules": [
+ {
+ "minVersion": "1.0.0",
+ "maxVersion": "1.2.0",
+ "action": "disable",
+ "reason": "Tencent protocol incompatible",
+ "helpUrl": "https://..."
+ }
+ ],
+ "signature": "..."
+}
+```
+
+规则:
+
+- 使用独立 Ed25519 key,不能复用更新器签名 key;
+- 只接受内置 manifest URL;
+- 文件最大 32 KiB,Content-Type 和最终字节数都验证;
+- 使用仓库固定的 canonical JSON 规则签名,`signature` 字段不参与 payload;
+- 签名覆盖 schemaVersion、sequence、生成/过期时间和全部 rules;
+- 增加单调递增 `sequence`,拒绝低于最近有效 sequence 的回滚 manifest;
+- 网络失败 fail-open;
+- 有效签名、未过期、版本命中时才 disable;
+- 缓存放 owner 无关的受控配置目录,原子写;最后一个有效 manifest 过期后不再生效;
+- disable 只停止 auth/poll/send,保留凭证、设置和会话;
+- UI 显示稳定本地文案,远程 `reason` 只作为诊断码,不直接渲染任意 HTML/Markdown。
+- `helpUrl` 只能从内置可信域和固定 path 前缀中选择,远程值不能任意打开。
+
+## 14. 解绑语义
+
+解绑顺序:
+
+1. `wechatCloseBindingEpoch` CAS 把 active epoch 改为 closed,之后所有旧写入失败;
+2. abort auth、poll、typing、task pump、outbox sender;
+3. await 这些 epoch-scoped operation 的 drain promise,不能只发 abort 不等待;
+4. best-effort 调用腾讯支持的 stop/revoke;
+5. `wechatUnbindCleanup` 命名事务删除 sync、inbox、outbox、未晋升 file metadata 和
+ `im-inbox` refs,并返回待删普通文件路径;
+6. Main 对返回路径做 root containment 后删除 staged 文件;
+7. 删除 `wechat_credentials_<epoch>`;
+8. 只有当前 owner 不再有任何 WeChat epoch/context 密文时,才删除
+ `wechat_data_key_v1`;
+9. 广播 disconnected。
+
+保留:
+
+- 已创建 Cindy session;
+- 已落入 session 历史的消息;
+- 已挂 `session-attachment` 的媒体;
+- 非敏感默认 Agent/模型/项目设置。
+
+删除:
+
+- token;
+- context token 密文和本地 data key;
+- cursor;
+- pending/running queue;
+- pending outbox;
+- 未提交附件;
+- 登录 challenge。
+
+## 15. 可观测性
+
+只使用本地脱敏日志:
+
+- auth phase;
+- poll latency、消息数量;
+- cursor 长度,不记 cursor;
+- queue depth;
+- task 状态迁移;
+- outbox retry 次数;
+- media 类型、明文大小、处理耗时;
+- error machine code;
+- peer/message/task id 只显示短 hash。
+
+首版不增加云端 analytics,不上报微信绑定状态、消息量、内容或错误响应体。
+
+## 16. 测试策略
+
+### 16.1 `packages/wechat-ilink`
+
+- QR challenge 和状态轮询;
+- headers 与 `X-WECHAT-UIN`;
+- abort;
+- API error 分类;
+- stale token;
+- getupdates cursor;
+- 五种 MessageItem;
+- AES 解密/加密 fixture;
+- Markdown filter;
+- 3500 chunk 和 code fence;
+- media size cap;
+- URL allowlist。
+
+### 16.2 Desktop Main
+
+- 使用 fake iLink server,不访问真实腾讯;
+- inbox + cursor 原子提交;
+- duplicate batch;
+- transaction fail;
+- crash injection;
+- crash before accepted 可恢复;
+- crash after accepted 只标 interrupted、绝不重放工具;
+- crash after final outbox commit 只恢复发送;
+- lease recovery;
+- 30 分钟 TTL;
+- queue 20 上限;
+- `/stop` / `/stop all`;
+- outbox 三次重试;
+- 新 context token 补发;
+- owner generation 切换;
+- binding epoch staging/CAS/drain;
+- 旧 poll/outbox 回调在 rebind 后写入失败;
+- Local/Cloud 数据隔离;
+- token/context 不出现在日志和 IPC;
+- media 临时引用晋升;
+- unbind 清理;
+- migration replay 和 compatibility。
+
+### 16.3 Orchestrator
+
+- 微信不调用 card API;
+- rich-card/chunked-text discriminated union 穷尽;
+- session 只安装一个 InteractionRouter listener;
+- Desktop/Feishu/Discord/WeChat origin 路由互不抢占;
+- Desktop interaction 正常 resolve;
+- 30 分钟超时;
+- destructive 强制 Desktop 确认;
+- Claude MCP auto-approve 前强制确认;
+- Claude/Codex Full Access 微信 turn 在 durable accept 前明确拒绝;
+- 当前 task 与 pending 串行;
+- `/new` epoch 边界;
+- final outbox 只生成一次。
+
+### 16.4 Renderer
+
+- 授权状态;
+- 取消、超时、重试、重绑、解绑;
+- needs reauth;
+- disabled by policy;
+- Local 和 Cloud 可见性;
+- Full Access 不可选原因文案;
+- i18n;
+- Light/Dark。
+
+### 16.5 手工矩阵
+
+- Windows/macOS;
+- 前台、隐藏窗口、托盘;
+- 睡眠唤醒;
+- 断网/恢复;
+- 首次绑定、同微信重绑、不同微信顶替;
+- stale token;
+- 五种媒体;
+- 超大文件;
+- 30 分钟 backlog;
+- Desktop permission 打开/关闭窗口;
+- 解绑后重启;
+- manifest disable。
+
+## 17. 单 PR、多 commit 计划
+
+一个 commit 只承担一个可独立 review 的职责。不得把后续层的占位实现混进前一层。
+每个 commit 都带 DCO sign-off,并在创建前跑仓库规定的完整提交门禁。
+
+### Commit 1:设计文档与协议/合规基线
+
+建议标题:
+
+```text
+docs: design personal WeChat IM connector
+```
+
+内容:
+
+- 本设计文档;
+- 固定上游 tag、commit SHA、获取日期、许可和派生登记规则;
+- 本 commit 没有引入第三方代码或依赖,因此不生成新的第三方 NOTICE;Commit 2 按实际
+ 复制/改写清单更新 NOTICE 和 SBOM;
+- 不含运行时代码。
+
+验证:
+
+- 文档链接;
+- Markdown/Mermaid 目检;
+- 若只改 docs,提交前仍按仓库硬门禁跑完整 `pnpm test:unit`。
+
+### Commit 2:iLink 纯协议包
+
+建议标题:
+
+```text
+feat(wechat): add isolated iLink protocol package
+```
+
+内容:
+
+- `packages/wechat-ilink`;
+- auth/API/types/codec/crypto/markdown/chunk;
+- fake server/fixture 单测;
+- MIT NOTICE。
+
+不包含:
+
+- Electron;
+- SQLite;
+- UI;
+- Cindy session。
+
+### Commit 3:可靠存储与 migration
+
+建议标题:
+
+```text
+feat(desktop): persist WeChat inbox and outbox
+```
+
+内容:
+
+- schema/migration;
+- task store 和全部 named worker transaction;
+- binding epoch schema/index;
+- cursor + inbox + media ledger transaction;
+- context token 本地加密;
+- accepted/interrupted/delivery_pending 状态机;
+- lease/TTL/recovery;
+- migration 与 crash 测试。
+
+不包含:
+
+- 设置 UI;
+- Maker turn;
+- 媒体完整支持。
+
+### Commit 4:OutputDriver 与中央 InteractionRouter
+
+建议标题:
+
+```text
+refactor(im): centralize output and interaction routing
+```
+
+内容:
+
+- `TextChannelIM` / `RichChannelIM` 与 discriminated `ImOutputDriver`;
+- `turnRunner` rich-card/chunked-text 穷尽分流;
+- accepted/terminal execution contract;
+- awaited `beforeProviderStart` 安全屏障;
+- external queue 模式;
+- session 级中央 `InteractionRouter`;
+- Desktop/Feishu/Discord 与 Slack `hook-control` origin 路由迁移;
+- 现有渠道全量回归。
+
+该 commit 不接微信真实网络,但必须独立编译,且现有渠道行为不变。
+
+### Commit 5:按 turn origin 的权限策略与 Desktop 确认
+
+建议标题:
+
+```text
+feat(maker): enforce IM-origin desktop confirmations
+```
+
+内容:
+
+- Claude/Codex `TurnPermissionPolicy`;
+- MCP auto-approve 前置拦截;
+- Auto destructive 强制确认,Full Access 在 durable accept 前明确拒绝;
+- WeChat origin → Desktop InteractionRouter 路由能力,但尚不接真实微信网络;
+- waiting/timeout/abort/epoch close;
+- provider capability gate;
+- maker-core 和 Desktop 回归测试。
+
+该 commit 完成前不得接通微信 Agent turn,避免存在默认 `auto` 但高风险策略尚未生效的
+中间提交。
+
+### Commit 6:WechatIM、binding epoch 与文本 task pump
+
+建议标题:
+
+```text
+feat(im): add personal WeChat text channel lifecycle
+```
+
+内容:
+
+- WechatIM;
+- owner-scoped epoch credentials;
+- auth IPC;
+- binding staging/CAS/drain;
+- poll lifecycle;
+- `createIM` 接线;
+- `wechat` source/namespace;
+- durable task pump;
+- task pump 作为唯一微信队列;
+- command allowlist;
+- `/new`、stop/status/help;
+- default permission migration;
+- 启用 Commit 5 已存在的微信 origin 权限策略。
+
+首版在该 commit 只要求纯文本任务进入 Agent;媒体保持 unsupported,不放未完成占位。
+
+### Commit 7:媒体与出站可靠性
+
+建议标题:
+
+```text
+feat(wechat): support media and reliable replies
+```
+
+内容:
+
+- 图片/音频/视频 cindy-media;
+- 普通文件受控存储;
+- SILK Worker;
+- quote;
+- typing/heartbeat;
+- outbox retry/new-token recovery;
+- media/file promotion 与 repair;
+- session 文件清理;
+- cleanup tests。
+
+### Commit 8:设置 UI 与 i18n
+
+建议标题:
+
+```text
+feat(settings): add personal WeChat connector controls
+```
+
+内容:
+
+- WechatBotSection/useWechatBot;
+- preload/renderer types;
+- Agent/模型/项目/permission;
+- Full Access 禁用与不可选原因文案;
+- Light/Dark;
+- 中英文/i18n glossary;
+- UI tests。
+
+### Commit 9:兼容熔断与 GA hardening
+
+建议标题:
+
+```text
+feat(wechat): add signed compatibility disable policy
+```
+
+内容:
+
+- signed manifest;
+- security/adversarial tests;
+- release docs;
+- final NOTICE/compliance checklist;
+- cross-platform fixes。
+
+## 18. 每个 commit 的执行门禁
+
+仓库硬门禁:
+
+```text
+pnpm test:unit
+pnpm --filter <本次涉及的每个 package> run --if-present typecheck
+```
+
+典型 package:
+
+```text
+pnpm --filter desktop run --if-present typecheck
+pnpm --filter @cindy/im run --if-present typecheck
+pnpm --filter @cindy/wechat-ilink run --if-present typecheck
+```
+
+UI/i18n commit 追加:
+
+```text
+pnpm check:i18n-glossary
+```
+
+schema/migration commit 追加:
+
+```text
+pnpm --filter desktop db:validate
+pnpm --filter desktop test:migration-replay
+```
+
+提交:
+
+```text
+git commit -s
+```
+
+执行约束:
+
+- 测试失败不得创建正常 commit;
+- 不跳过、不删除、不弱化测试;
+- 每个 commit 创建前 review staged diff;
+- 不在本计划中 push;
+- 不创建 PR;
+- 最终 PR 使用 `.github/PULL_REQUEST_TEMPLATE.md`;
+- PR 时机和最终 push 由维护者决定。
+
+## 19. 阶段退出条件
+
+### Phase 0:协议与合规 Spike
+
+- 腾讯允许的第三方接入边界已确认;
+- Windows/macOS 至少完成文本收发 PoC;
+- 授权页 OpenClaw 展示已被产品接受;
+- 若必须使用 OpenClaw Host,Transport 替换结论已记录。
+
+### Phase 1:协议核心
+
+- fake server 下 auth/poll/send/media 单测通过;
+- 没有 Electron/DB 依赖;
+- MIT NOTICE 完成。
+
+### Phase 2:可靠收发
+
+- crash/restart 不丢消息;
+- cursor 不先于 inbox;
+- 同消息不会执行两次;
+- accepted 后崩溃只产生 interrupted,不自动重跑 Agent/工具;
+- final outbox 已提交后只恢复发送;
+- 30 分钟 TTL 和 queue 20 生效;
+- final 可在新 context token 到达后补发。
+
+### Phase 3:Cindy Agent
+
+- 微信消息进入现有 Maker Session;
+- session history 正常;
+- 微信不调用 card API;
+- durable pump 与 `turnRunner.sendQueue` 不形成双重队列;
+- InteractionRouter 单 listener 正确路由所有 origin;
+- Auto 下微信高风险工具仍进 Desktop;
+- Full Access 在 provider capability gate 被明确拒绝;
+- Desktop interaction 可完成和超时;
+- `/new` 和 stop 语义稳定。
+
+### Phase 4:产品完成
+
+- 五种入站类型;
+- 设置页完整;
+- Light/Dark 与 i18n;
+- 解绑完整清理;
+- Windows/macOS 回归。
+
+### Phase 5:GA
+
+- 腾讯/iLink 接入条件和发行地区已签核;
+- signed disable policy 演练完成;
+- 隐私、NOTICE、用户帮助文档完成;
+- 最终 PR 无 P0/P1 review 问题。
+
+## 20. 已知风险与发布阻塞项
+
+1. **腾讯接入授权**:MIT 代码许可不自动等于 iLink 商业服务授权;不得预设一定存在
+ 某种独立 App ID,以腾讯确认的第三方接入、应用标识、品牌展示和分发条件为准。
+2. **OpenClaw 品牌展示**:绑定页由腾讯控制,Cindy 只能提前解释。
+3. **服务端 cursor 保留期未知**:本地 cursor 能解决客户端崩溃,不能承诺超过腾讯
+ 服务端保留窗口后补齐全部历史。
+4. **context token 时效**:首版限制为 reply-only,并用新入站 token 补发旧 final。
+5. **重绑排他性**:新连接可能解除旧 OpenClaw/Cindy 连接,UI 必须明确告知。
+6. **协议变化**:只允许签名 disable,不允许远程热修协议。
+7. **普通文件生命周期**:必须有 session 归属和删除清理,不能复制后永久遗留。
+8. **Main 性能**:SILK、AES、大文件 hash 必须在 Worker 或流式路径,不能阻塞 Electron。
+9. **工具副作用不可自动重放**:accepted 后崩溃只能中断并让用户显式重试。
+10. **上游漂移**:实现和 NOTICE 必须固定到精确 tag/commit,升级单独 review。
+
+## 21. Review 清单
+
+Subagent review 至少检查:
+
+- 是否违反仓库产品原则或客户端/服务端边界;
+- 是否误用 cindy-media 存普通文件;
+- cursor/inbox/outbox 崩溃边界是否闭合;
+- accepted 后是否存在任何自动重放路径;
+- context token 是否可能明文落盘或进入日志;
+- InteractionRouter 是否真正消除了 listener 抢占;
+- durable queue 是否会和现有 turnRunner 内存队列形成双重乱序;
+- owner generation、解绑、重绑是否存在陈旧回调;
+- `TextChannelIM/RichChannelIM + ImOutputDriver` 改造是否破坏 Feishu/Discord;
+- migration 是否可 replay、可从旧库升级;
+- commit 切分是否存在不可编译的中间 commit;
+- named worker transaction 是否覆盖全部跨表原子边界;
+- Claude/Codex Auto、MCP auto-approve 是否都经过 origin policy,Full Access 是否在
+ accepted 前被 capability gate 拒绝;
+- GA gate 是否把技术完成误写为外部授权完成。
+
+## 22. 独立 Review 记录
+
+2026-07-27 由独立 subagent 对照当前仓库代码和规则完成两轮对抗性 review。
+
+第一轮发现并要求修复:
+
+- accepted 后崩溃自动重放工具副作用;
+- durable queue 与 `turnRunner.sendQueue` 双重所有权;
+- Maker Session 单 interaction listener 抢占;
+- Auto/MCP auto-approve/Full Access 绕过高风险确认;
+- binding epoch、命名事务、媒体晋升和中间 commit 编译边界。
+
+第二轮确认:
+
+- `beforeProviderStart` 已成为 provider/tool 前 awaited accepted 屏障;
+- 持久 `finalizing` 已删除,terminal outbox 与 `delivery_pending` 同事务;
+- origin 权限策略先于真实 WeChat Agent 接线落地;
+- 无剩余 P0/P1,可以进入实现。
diff --git a/i18n/GLOSSARY.md b/i18n/GLOSSARY.md
index 8b5c7faf3f..d150227319 100644
--- a/i18n/GLOSSARY.md
+++ b/i18n/GLOSSARY.md
@@ -152,6 +152,14 @@ OAuth 2.0 Device Authorization Grant 中由用户在另一设备验证页输入
灵动岛角色皮肤名(设置页「图标皮肤」列表)。角色专名,四语统一保留拉丁原词,不做音译(避免「艾莉卡 / エリカ / 에리카」多套写法)。
+### OpenClaw
+
+腾讯授权页可能展示的外部产品名称,客户端仅按原品牌名展示;先登记为 proposed,待产品术语评审后再决定是否固化。
+
+### Personal WeChat
+
+个人微信连接在设置页中的产品名称;先登记为 proposed,待产品术语评审后再决定是否固化。
+
### Region badge
桌面登录页标题旁的品牌红胶囊(DESIGN.md §16.3),指徽标这个 UI 元素本身。徽标上的标签值另立条目(region-code-cn / region-code-dev)——本条 en 为 Region badge、各语言译文均非英文原词,caseStandardFor 天然返回 null,所以本条约束不到标签值,也无需写 checkCase。作为待产品裁决术语登记:尚未拍板是否改为可译文案(如「中国大陆版 / Mainland China」),先登记以免后续界面自造“国内版/中国版/开发版”等多套说法。
@@ -172,6 +180,10 @@ dev 版登录页区域徽标上的标签值(DESIGN.md §16.3),四语同值
语音输入的用户自定义术语表(人名、产品名、代号与其常见误识别写法),在同账号的电脑之间自动同步、手机只读查看。当前先采用四语直译并登记为待讨论术语,避免与「自定义词典」「术语表」「用户词库」等说法混用。
+### WeChat
+
+个人微信连接的产品名称,沿用微信官方品牌写法;先登记为 proposed,待产品术语评审后再决定是否固化。
+
## 怎么加一条术语
1. 在 `i18n/glossary.json` 的 `terms` 里加条目,`note` 必填——写清楚**为什么**这么定,
diff --git a/i18n/glossary.json b/i18n/glossary.json
index 116606c4fd..6528a56826 100644
--- a/i18n/glossary.json
+++ b/i18n/glossary.json
@@ -54,6 +54,39 @@
},
"note": "远端主机上由 Cindy 管理的 Codex 凭证目录(~/.xdt-server/v1/codex-home/),与用户本机 ~/.codex 相区分。四语统一保留英文原词(home 小写),避免各语言自造「Codex 主目录」等不同说法;syncAuth 与 codexAuthMissing 等远端登录态文案使用。"
},
+ {
+ "id": "wechat",
+ "status": "proposed",
+ "en": "WeChat",
+ "translations": {
+ "zh-CN": "微信",
+ "ja": "WeChat",
+ "ko": "WeChat"
+ },
+ "note": "个人微信连接的产品名称,沿用微信官方品牌写法;先登记为 proposed,待产品术语评审后再决定是否固化。"
+ },
+ {
+ "id": "personal-wechat",
+ "status": "proposed",
+ "en": "Personal WeChat",
+ "translations": {
+ "zh-CN": "个人微信",
+ "ja": "個人 WeChat",
+ "ko": "개인 WeChat"
+ },
+ "note": "个人微信连接在设置页中的产品名称;先登记为 proposed,待产品术语评审后再决定是否固化。"
+ },
+ {
+ "id": "openclaw",
+ "status": "proposed",
+ "en": "OpenClaw",
+ "translations": {
+ "zh-CN": "OpenClaw",
+ "ja": "OpenClaw",
+ "ko": "OpenClaw"
+ },
+ "note": "腾讯授权页可能展示的外部产品名称,客户端仅按原品牌名展示;先登记为 proposed,待产品术语评审后再决定是否固化。"
+ },
{
"id": "region-badge",
"status": "proposed",
diff --git a/packages/lizi-im/src/channelIM.ts b/packages/lizi-im/src/channelIM.ts
index 1b5a4d9cf2..5025410daf 100644
--- a/packages/lizi-im/src/channelIM.ts
+++ b/packages/lizi-im/src/channelIM.ts
@@ -25,14 +25,13 @@ import type {
StreamingTextHandle,
} from './types.js';
-export interface ChannelIM {
+export interface TextChannelIM {
/** 渠道名 ('feishu' / 'slack') — 与 IdentityKey.channel 同值域。 */
readonly name: string;
// ── inbound subscriptions ──────────────────────────────────────────────────
onMessage(handler: (e: IMMessageEvent) => void): () => void;
- onCardAction(handler: (e: IMCardActionEvent) => void): () => void;
onStatusChange(handler: (s: IMStatus) => void): () => void;
// ── outbound ───────────────────────────────────────────────────────────────
@@ -54,6 +53,34 @@ export interface ChannelIM {
opts?: { threadTs?: string },
): Promise<{ messageId: string }>;
+ /** 发送本地文件;失败原因见 SendFileResult.reason。 */
+ sendFile(
+ userId: string,
+ absPath: string,
+ displayName?: string,
+ opts?: { threadTs?: string },
+ ): Promise<SendFileResult>;
+
+ // ── optional capabilities ──────────────────────────────────────────────────
+
+ /**
+ * 给某条消息加 emoji 回应("已收到" ack)。返回撤销用的 token
+ * (feishu: reaction_id; slack: emoji 名), 失败返回 null。
+ */
+ reactToMessage?(messageId: string, emoji: string): Promise<string | null>;
+
+ /** 撤销 reactToMessage 加的回应;失败吞掉(清理是尽力而为)。 */
+ removeMessageReaction?(messageId: string, reactionToken: string): Promise<void>;
+
+ // ── status ─────────────────────────────────────────────────────────────────
+
+ getStatus(): IMStatus;
+}
+
+/** Channels that can render and mutate interactive/streaming cards. */
+export interface RichChannelIM extends TextChannelIM {
+ onCardAction(handler: (e: IMCardActionEvent) => void): () => void;
+
/** 带按钮的交互卡片;按钮按压经 onCardAction 回流。 */
sendInteractiveCard(
userId: string,
@@ -74,33 +101,38 @@ export interface ChannelIM {
opts?: { threadTs?: string },
): Promise<StreamingTextHandle>;
- /** 发送本地文件;失败原因见 SendFileResult.reason。 */
- sendFile(
- userId: string,
- absPath: string,
- displayName?: string,
- opts?: { threadTs?: string },
- ): Promise<SendFileResult>;
-
- // ── optional capabilities ──────────────────────────────────────────────────
-
- /**
- * 给某条消息加 emoji 回应("已收到" ack)。返回撤销用的 token
- * (feishu: reaction_id; slack: emoji 名), 失败返回 null。
- */
- reactToMessage?(messageId: string, emoji: string): Promise<string | null>;
-
- /** 撤销 reactToMessage 加的回应;失败吞掉(清理是尽力而为)。 */
- removeMessageReaction?(messageId: string, reactionToken: string): Promise<void>;
-
/**
* 从出站消息的 messageId 提取 thread 维度键(= 该消息作为 thread root 时的
* thread_ts)。thread 能力渠道(slack)实现;编排层用它把"刚发出的接管卡"
* 变成 thread root 的 scopeKey, 而不泄漏渠道 messageId 编码格式。
*/
threadKeyForMessage?(messageId: string): string;
+}
- // ── status ─────────────────────────────────────────────────────────────────
-
- getStatus(): IMStatus;
+/** Backward-compatible name for the existing rich-card channel contract. */
+export type ChannelIM = RichChannelIM;
+
+export interface ImFinalOutput {
+ userId: string;
+ text: string;
+ terminal: 'done' | 'aborted' | 'error';
+ threadTs?: string;
+ errorCode?: string;
+ /** Managed local media discovered in the terminal assistant output. */
+ mediaAbsPaths?: string[];
}
+
+/**
+ * Output is deliberately discriminated: rich channels may stream/patch,
+ * while durable text channels atomically commit the complete terminal output.
+ */
+export type ImOutputDriver =
+ | {
+ kind: 'rich-card';
+ im: RichChannelIM;
+ }
+ | {
+ kind: 'chunked-text';
+ im: TextChannelIM;
+ commitFinal(output: ImFinalOutput): Promise<void>;
+ };
diff --git a/packages/lizi-im/src/index.ts b/packages/lizi-im/src/index.ts
index 3b76da761b..a1f099c852 100644
--- a/packages/lizi-im/src/index.ts
+++ b/packages/lizi-im/src/index.ts
@@ -11,7 +11,13 @@ export const VERSION = '0.0.0';
export { BaseIM } from './BaseIM.js';
export { createIM } from './createIM.js';
export type { IM } from './createIM.js';
-export type { ChannelIM } from './channelIM.js';
+export type {
+ ChannelIM,
+ TextChannelIM,
+ RichChannelIM,
+ ImFinalOutput,
+ ImOutputDriver,
+} from './channelIM.js';
export type { Logger } from './logger.js';
diff --git a/packages/lizi-mcps/src/__tests__/providersWechatRouting.test.ts b/packages/lizi-mcps/src/__tests__/providersWechatRouting.test.ts
new file mode 100644
index 0000000000..c20366cec3
--- /dev/null
+++ b/packages/lizi-mcps/src/__tests__/providersWechatRouting.test.ts
@@ -0,0 +1,55 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { createLiziMcpProviders } from '../providers.js';
+import { runWithLiziMcpSessionContext } from '../session-context.js';
+
+function tools(server: unknown) {
+ return (
+ server as {
+ _registeredTools: Record<string, { handler: (args: unknown) => Promise<unknown> }>;
+ }
+ )._registeredTools;
+}
+
+describe('cindy_wechat provider routing', () => {
+ it('pins an attached WeChat turn to the peer active in the current session', async () => {
+ const getActivePeerIdForSession = vi.fn((sessionId: string | undefined) =>
+ sessionId === 'desktop-session' ? 'peer-active' : null,
+ );
+ const getMostRecentPeerId = vi.fn(() => 'peer-recent');
+ const sendMessage = vi.fn(async () => ({ ok: true, messageId: 'message-1' }));
+ const provider = createLiziMcpProviders({
+ wechatBot: {
+ getActivePeerIdForSession,
+ getMostRecentPeerId,
+ sendMessage,
+ sendFile: vi.fn(),
+ },
+ }).find((candidate) => candidate.name === 'cindy_wechat');
+ if (!provider) throw new Error('cindy_wechat provider missing');
+
+ const config = provider.toClaudeSdkConfig({
+ agentKind: 'codex',
+ workingDir: '',
+ vendorOptions: {},
+ }) as { type: 'sdk'; instance: unknown };
+
+ await runWithLiziMcpSessionContext(
+ {
+ agentKind: 'codex',
+ workingDir: 'C:\\repo',
+ sessionId: 'desktop-session',
+ vendorOptions: {},
+ },
+ () =>
+ tools(config.instance).call_tool.handler({
+ name: 'send_message_to_user',
+ args: { text: 'hello' },
+ }),
+ );
+
+ expect(getActivePeerIdForSession).toHaveBeenCalledWith('desktop-session');
+ expect(getMostRecentPeerId).not.toHaveBeenCalled();
+ expect(sendMessage).toHaveBeenCalledWith('peer-active', 'hello');
+ });
+});
diff --git a/packages/lizi-mcps/src/__tests__/wechatMcpServer.test.ts b/packages/lizi-mcps/src/__tests__/wechatMcpServer.test.ts
new file mode 100644
index 0000000000..8c232260d6
--- /dev/null
+++ b/packages/lizi-mcps/src/__tests__/wechatMcpServer.test.ts
@@ -0,0 +1,128 @@
+import fs from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+
+import { Client } from '@modelcontextprotocol/sdk/client/index.js';
+import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
+import { describe, expect, it, vi } from 'vitest';
+
+import { createWechatMcpServer } from '../cindy_wechatMcpServer';
+
+describe('cindy_wechat proactive routing', () => {
+ it('sends only to the host-resolved known peer', async () => {
+ const sendMessage = vi.fn(async () => ({ ok: true, messageId: 'msg-1' }));
+ const server = createWechatMcpServer({
+ getActivePeerIdForSession: () => null,
+ getMostRecentPeerId: () => 'peer-history',
+ getPeerId: () => 'peer-session',
+ sendMessage,
+ sendFile: vi.fn(),
+ });
+ const [clientTx, serverTx] = InMemoryTransport.createLinkedPair();
+ const client = new Client({ name: 'wechat-test', version: '0.0.0' });
+ await Promise.all([server.connect(serverTx), client.connect(clientTx)]);
+ try {
+ const result = await client.callTool({
+ name: 'call_tool',
+ arguments: { name: 'send_message_to_user', args: { text: 'hello' } },
+ });
+ expect(sendMessage).toHaveBeenCalledWith('peer-session', 'hello');
+ expect(JSON.stringify(result)).toContain('msg-1');
+ } finally {
+ await client.close();
+ await server.close();
+ }
+ });
+
+ it('fails closed when no peer has ever been observed', async () => {
+ const sendMessage = vi.fn();
+ const server = createWechatMcpServer({
+ getActivePeerIdForSession: () => null,
+ getMostRecentPeerId: () => null,
+ getPeerId: () => null,
+ sendMessage,
+ sendFile: vi.fn(),
+ });
+ const [clientTx, serverTx] = InMemoryTransport.createLinkedPair();
+ const client = new Client({ name: 'wechat-test', version: '0.0.0' });
+ await Promise.all([server.connect(serverTx), client.connect(clientTx)]);
+ try {
+ const result = await client.callTool({
+ name: 'call_tool',
+ arguments: { name: 'send_message_to_user', args: { text: 'hello' } },
+ });
+ expect(JSON.stringify(result)).toContain('NO_PEER_CONTEXT');
+ expect(sendMessage).not.toHaveBeenCalled();
+ } finally {
+ await client.close();
+ await server.close();
+ }
+ });
+
+ it('sends a working-directory file only to the host-resolved peer', async () => {
+ const workingDir = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-wechat-mcp-'));
+ const absPath = path.join(workingDir, 'preview.png');
+ await fs.writeFile(absPath, 'png-bytes');
+ const sendFile = vi.fn(async () => ({ ok: true, messageId: 'media-1' }));
+ const server = createWechatMcpServer({
+ getActivePeerIdForSession: () => null,
+ getMostRecentPeerId: () => 'peer-history',
+ getPeerId: () => 'peer-session',
+ sendMessage: vi.fn(),
+ sendFile,
+ workingDir,
+ });
+ const [clientTx, serverTx] = InMemoryTransport.createLinkedPair();
+ const client = new Client({ name: 'wechat-test', version: '0.0.0' });
+ await Promise.all([server.connect(serverTx), client.connect(clientTx)]);
+ try {
+ const call = await client.callTool({
+ name: 'call_tool',
+ arguments: {
+ name: 'send_file_to_user',
+ args: { absPath, displayName: 'result.png' },
+ },
+ });
+ expect(sendFile).toHaveBeenCalledWith('peer-session', await fs.realpath(absPath), 'result.png');
+ expect(JSON.stringify(call)).toContain('media-1');
+ } finally {
+ await client.close();
+ await server.close();
+ await fs.rm(workingDir, { recursive: true, force: true });
+ }
+ });
+
+ it('rejects files outside the current working directory', async () => {
+ const workingDir = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-wechat-workdir-'));
+ const outsideDir = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-wechat-outside-'));
+ const outsidePath = path.join(outsideDir, 'secret.txt');
+ await fs.writeFile(outsidePath, 'not-for-wechat');
+ const sendFile = vi.fn();
+ const server = createWechatMcpServer({
+ getActivePeerIdForSession: () => null,
+ getMostRecentPeerId: () => 'peer-history',
+ getPeerId: () => 'peer-session',
+ sendMessage: vi.fn(),
+ sendFile,
+ workingDir,
+ });
+ const [clientTx, serverTx] = InMemoryTransport.createLinkedPair();
+ const client = new Client({ name: 'wechat-test', version: '0.0.0' });
+ await Promise.all([server.connect(serverTx), client.connect(clientTx)]);
+ try {
+ const call = await client.callTool({
+ name: 'call_tool',
+ arguments: { name: 'send_file_to_user', args: { absPath: outsidePath } },
+ });
+ expect(JSON.stringify(call)).toContain('PATH_OUT_OF_BOUNDS');
+ expect(sendFile).not.toHaveBeenCalled();
+ } finally {
+ await client.close();
+ await server.close();
+ await Promise.all([
+ fs.rm(workingDir, { recursive: true, force: true }),
+ fs.rm(outsideDir, { recursive: true, force: true }),
+ ]);
+ }
+ });
+});
diff --git a/packages/lizi-mcps/src/cindy_wechatMcpServer.ts b/packages/lizi-mcps/src/cindy_wechatMcpServer.ts
new file mode 100644
index 0000000000..96173e7ebf
--- /dev/null
+++ b/packages/lizi-mcps/src/cindy_wechatMcpServer.ts
@@ -0,0 +1,199 @@
+import fs from 'node:fs/promises';
+import path from 'node:path';
+
+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
+import { z } from 'zod';
+
+import type { WechatBotMcpHostDeps } from './types.js';
+
+const MAX_MESSAGE_CHARS = 30_000;
+const MAX_DISPLAY_NAME_CHARS = 180;
+
+type WechatMcpDeps = WechatBotMcpHostDeps & {
+ getPeerId: () => Promise<string | null> | string | null;
+ workingDir?: string;
+};
+
+/**
+ * In-process MCP bridge for proactive personal WeChat messages.
+ *
+ * The host resolves the receiver from the current WeChat session or the most
+ * recent peer seen by the active binding. The model never supplies an
+ * arbitrary peer id. File sends are additionally confined to the session
+ * working directory after resolving symlinks.
+ */
+export function createWechatMcpServer(deps: WechatMcpDeps): McpServer {
+ const server = new McpServer({ name: 'cindy_wechat', version: '1.0.0' });
+
+ server.tool(
+ 'list_tools',
+ '列出个人微信可用工具。使用 call_tool 调用具体工具。',
+ {},
+ async () => ({
+ content: [
+ {
+ type: 'text' as const,
+ text: JSON.stringify({
+ ok: true,
+ tools: [
+ {
+ name: 'send_message_to_user',
+ description: '向当前个人微信会话对应的已知联系人发送一条文本消息。',
+ },
+ {
+ name: 'send_file_to_user',
+ description:
+ '向当前个人微信联系人发送当前工作目录内不超过 5 MB 的图片或文件。参数:{ absPath: 绝对路径, displayName?: 展示文件名 }。',
+ },
+ ],
+ }),
+ },
+ ],
+ }),
+ );
+
+ server.tool(
+ 'call_tool',
+ '调用个人微信工具。先使用 list_tools 获取工具名。',
+ {
+ name: z.string(),
+ args: z.record(z.string(), z.unknown()).default({}),
+ },
+ async ({ name, args }) => {
+ if (name === 'send_message_to_user') return sendMessageToUser(deps, args);
+ if (name === 'send_file_to_user') return sendFileToUser(deps, args);
+ return result({ ok: false, errorCode: 'UNKNOWN_TOOL', error: name }, true);
+ },
+ );
+
+ return server;
+}
+
+async function sendMessageToUser(deps: WechatMcpDeps, args: Record<string, unknown>) {
+ const parsed = z
+ .object({ text: z.string().min(1).max(MAX_MESSAGE_CHARS) })
+ .safeParse(args);
+ if (!parsed.success || parsed.data.text.trim().length === 0) {
+ return result({ ok: false, errorCode: 'INVALID_ARGS', error: 'text 不能为空' }, true);
+ }
+ const peerId = await deps.getPeerId();
+ if (!peerId) return noPeerContextResult();
+ try {
+ const sent = await deps.sendMessage(peerId, parsed.data.text);
+ return sent.ok
+ ? result({ ok: true, messageId: sent.messageId })
+ : result({ ok: false, errorCode: 'SEND_FAILED', error: sent.reason ?? 'unknown' }, true);
+ } catch (error) {
+ deps.logger?.warn?.(
+ 'send_message_to_user failed peer=...%s detail=%s',
+ peerId.slice(-8),
+ error instanceof Error ? error.message : String(error),
+ );
+ return result({ ok: false, errorCode: 'SEND_FAILED', error: 'WeChat send failed' }, true);
+ }
+}
+
+async function sendFileToUser(deps: WechatMcpDeps, args: Record<string, unknown>) {
+ const parsed = z
+ .object({
+ absPath: z.string().min(1),
+ displayName: z.string().min(1).max(MAX_DISPLAY_NAME_CHARS).optional(),
+ })
+ .safeParse(args);
+ if (!parsed.success) {
+ return result({ ok: false, errorCode: 'INVALID_ARGS', error: '文件参数无效' }, true);
+ }
+ const peerId = await deps.getPeerId();
+ if (!peerId) return noPeerContextResult();
+
+ let safePath: string;
+ try {
+ safePath = await resolveFileWithinWorkingDir(parsed.data.absPath, deps.workingDir);
+ } catch (error) {
+ const errorCode =
+ error instanceof WechatFilePathError
+ ? error.code
+ : (error as NodeJS.ErrnoException).code === 'ENOENT'
+ ? 'FILE_NOT_FOUND'
+ : 'FILE_UNAVAILABLE';
+ return result({ ok: false, errorCode, error: '文件不可用于发送' }, true);
+ }
+
+ try {
+ const sent = await deps.sendFile(peerId, safePath, parsed.data.displayName);
+ if (sent.ok) {
+ return result({
+ ok: true,
+ messageId: sent.messageId,
+ sent: {
+ displayName: parsed.data.displayName ?? path.basename(safePath),
+ },
+ });
+ }
+ return result(
+ {
+ ok: false,
+ errorCode: mapFileSendError(sent.reason),
+ error: sent.reason ?? 'unknown',
+ },
+ true,
+ );
+ } catch (error) {
+ deps.logger?.warn?.(
+ 'send_file_to_user failed peer=...%s detail=%s',
+ peerId.slice(-8),
+ error instanceof Error ? error.message : String(error),
+ );
+ return result({ ok: false, errorCode: 'SEND_FAILED', error: 'WeChat send failed' }, true);
+ }
+}
+
+async function resolveFileWithinWorkingDir(
+ candidate: string,
+ workingDir: string | undefined,
+): Promise<string> {
+ if (!workingDir) throw new WechatFilePathError('WORKING_DIR_UNAVAILABLE');
+ if (!path.isAbsolute(candidate)) throw new WechatFilePathError('PATH_MUST_BE_ABSOLUTE');
+ const [root, file] = await Promise.all([fs.realpath(workingDir), fs.realpath(candidate)]);
+ const relative = path.relative(root, file);
+ if (relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
+ throw new WechatFilePathError('PATH_OUT_OF_BOUNDS');
+ }
+ return file;
+}
+
+class WechatFilePathError extends Error {
+ constructor(readonly code: string) {
+ super(code);
+ }
+}
+
+function mapFileSendError(reason: string | undefined): string {
+ return (
+ {
+ NOT_FOUND: 'FILE_NOT_FOUND',
+ EMPTY: 'FILE_EMPTY',
+ TOO_LARGE: 'FILE_TOO_LARGE',
+ UPLOAD_FAIL: 'UPLOAD_FAILED',
+ SEND_FAIL: 'SEND_FAILED',
+ }[reason ?? ''] ?? 'SEND_FAILED'
+ );
+}
+
+function noPeerContextResult() {
+ return result(
+ {
+ ok: false,
+ errorCode: 'NO_PEER_CONTEXT',
+ error: '当前绑定尚未收到过微信消息,无法确定安全的发送目标。',
+ },
+ true,
+ );
+}
+
+function result(payload: unknown, isError = false) {
+ return {
+ isError,
+ content: [{ type: 'text' as const, text: JSON.stringify(payload, null, 2) }],
+ };
+}
diff --git a/packages/lizi-mcps/src/index.ts b/packages/lizi-mcps/src/index.ts
index 991bb5e0ea..ab5a084e87 100644
--- a/packages/lizi-mcps/src/index.ts
+++ b/packages/lizi-mcps/src/index.ts
@@ -17,6 +17,7 @@ export * from './providers.js';
// + @cindy/@cindy/im,与本已删模块无关。
export * from './cindy_feishuBotMcpServer.js';
+export * from './cindy_wechatMcpServer.js';
export * from './cindy_feishuBotToolRegistry.js';
export * from './cindy_schedulerMcpServer.js';
diff --git a/packages/lizi-mcps/src/providers.ts b/packages/lizi-mcps/src/providers.ts
index 51e1f011a9..c4f2f3011f 100644
--- a/packages/lizi-mcps/src/providers.ts
+++ b/packages/lizi-mcps/src/providers.ts
@@ -3,6 +3,7 @@ import type {
BrowserMcpDeps,
ComputerMcpDeps,
FeishuBotMcpHostDeps,
+ WechatBotMcpHostDeps,
LiziMcpId,
LiziMcpProvider,
LiziMcpSessionContext,
@@ -14,6 +15,7 @@ import type {
LspMcpDeps,
} from './types.js';
import { createFeishuBotMcpServer } from './cindy_feishuBotMcpServer.js';
+import { createWechatMcpServer } from './cindy_wechatMcpServer.js';
import { createSlackMcpGatewayServer } from './cindy_slackMcpServer.js';
import { createSchedulerMcpServer } from './cindy_schedulerMcpServer.js';
import { createSshMcpServer } from './cindy_sshMcpServer.js';
@@ -38,6 +40,7 @@ export interface CreateLiziMcpProvidersOptions {
/** Local desktop computer-use tools backed by a host-managed external driver. */
computer?: ComputerMcpDeps;
feishuBot?: FeishuBotMcpHostDeps;
+ wechatBot?: WechatBotMcpHostDeps;
/**
* cindy_slack: Slack 网关工具(经 hook 通道由 slack-hook-server 以托管
* user token 调 Slack 官方 MCP, 接替退役的 cindy-slack 意识)。
@@ -95,6 +98,11 @@ function readFeishuChatId(ctx: LiziMcpSessionContext): string | null {
return typeof raw === 'string' && raw.length > 0 ? raw : null;
}
+function readWechatPeerId(ctx: LiziMcpSessionContext): string | null {
+ const raw = ctx.vendorOptions?.wechatPeerId;
+ return typeof raw === 'string' && raw.length > 0 ? raw : null;
+}
+
/** 会话来源(如 'slack-hook'),feishu bot 用它在构建期注入渠道路由提示。 */
function readSessionSource(ctx: LiziMcpSessionContext): string | undefined {
const raw = ctx.vendorOptions?.source;
@@ -243,6 +251,28 @@ export function createLiziMcpProviders(
});
}
+ if (opts.wechatBot && selected(enabled, 'cindy_wechat')) {
+ providers.push({
+ name: 'cindy_wechat',
+ toClaudeSdkConfig: (ctx) => ({
+ type: 'sdk',
+ name: 'cindy_wechat',
+ instance: createWechatMcpServer({
+ ...opts.wechatBot!,
+ getPeerId: async () => {
+ const current = resolveLiziMcpSessionContext(ctx);
+ return (
+ readWechatPeerId(current) ??
+ (await opts.wechatBot!.getActivePeerIdForSession(current.sessionId)) ??
+ (await opts.wechatBot!.getMostRecentPeerId())
+ );
+ },
+ workingDir: ctx.workingDir,
+ }),
+ }),
+ });
+ }
+
if (opts.slackHook && selected(enabled, 'cindy_slack')) {
providers.push({
name: 'cindy_slack',
diff --git a/packages/lizi-mcps/src/types.ts b/packages/lizi-mcps/src/types.ts
index b3477c64a5..c62179c3ea 100644
--- a/packages/lizi-mcps/src/types.ts
+++ b/packages/lizi-mcps/src/types.ts
@@ -125,6 +125,33 @@ export interface FeishuBotMcpHostDeps {
logger?: LiziMcpLogger;
}
+export interface WechatBotSendMessageResult {
+ ok: boolean;
+ messageId?: string;
+ reason?: string;
+}
+
+export interface WechatBotSendFileResult {
+ ok: boolean;
+ messageId?: string;
+ reason?: string;
+}
+
+/** Host bridge for the personal WeChat proactive-message MCP. */
+export interface WechatBotMcpHostDeps {
+ getActivePeerIdForSession(
+ sessionId: string | undefined,
+ ): Promise<string | null> | string | null;
+ getMostRecentPeerId(): Promise<string | null> | string | null;
+ sendMessage(peerId: string, text: string): Promise<WechatBotSendMessageResult>;
+ sendFile(
+ peerId: string,
+ absPath: string,
+ displayName?: string,
+ ): Promise<WechatBotSendFileResult>;
+ logger?: LiziMcpLogger;
+}
+
// ── cindy_slack(Slack 网关工具, 2026-07 并轨 hook 通道) ──────────────────────
/** Slack 网关工具的结构化错误(hook-control manager 定义的同构形状)。 */
@@ -418,6 +445,7 @@ export type LiziMcpId =
| 'browser'
| 'computer'
| 'cindy_feishu_bot'
+ | 'cindy_wechat'
| 'cindy_slack'
| 'cindy_scheduler'
| 'cindy_ssh'
diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.ts
index 6836540777..59ae33ec06 100644
--- a/packages/maker-core/src/agents/base-agent.ts
+++ b/packages/maker-core/src/agents/base-agent.ts
@@ -631,6 +631,42 @@ export interface SendOptions {
* 共享 session 下区分自动任务 turn 与用户 turn。agent 子类不消费,透传无害。
*/
origin?: SendOrigin;
+ /**
+ * Host-owned, per-turn permission policy. This is deliberately a callback
+ * rather than prompt text: providers must enforce it at their pre-execution
+ * approval boundary, before MCP auto-approval or permission-mode bypasses.
+ */
+ turnPermissionPolicy?: TurnPermissionPolicy;
+}
+
+export type TurnPermissionOrigin =
+ | { kind: 'desktop' }
+ | { kind: 'im'; channel: 'feishu' | 'discord' | 'slack' | 'wechat'; taskId?: string }
+ | { kind: 'scheduler' }
+ | { kind: 'hook'; source: string };
+
+export interface TurnPermissionPolicy {
+ readonly origin: TurnPermissionOrigin;
+ readonly confirmationSurface: 'desktop' | 'channel';
+ readonly confirmationTimeoutMs?: number;
+ readonly onInteractionStateChange?: (
+ state: 'waiting' | 'resolved' | 'cancelled',
+ ) => void;
+ forceConfirmToolCall(toolName: string, input: unknown): boolean;
+}
+
+export class TurnPermissionPolicyUnsupportedError extends Error {
+ readonly code = 'TURN_PERMISSION_POLICY_UNSUPPORTED';
+
+ constructor(
+ readonly agentKind: AgentKind,
+ readonly permissionMode: PermissionMode,
+ ) {
+ super(
+ `Turn permission policy is not supported by ${agentKind} in permission mode ${permissionMode}`,
+ );
+ this.name = 'TurnPermissionPolicyUnsupportedError';
+ }
}
/**
@@ -670,6 +706,13 @@ export interface AgentSessionHandle {
/** 推送一条用户消息(流式输入) */
send(message: UserMessage, opts?: SendOptions): Promise<void>;
+ /**
+ * Synchronous provider preflight called by Session after reserving the turn
+ * but before any product `beforeProviderStart` / `onAccepted` side effect.
+ * Direct handle callers are still validated again inside send().
+ */
+ validateSendOptions?(opts: SendOptions): void;
+
/**
* 把用户消息追加到当前 in-flight turn。
*
diff --git a/packages/maker-core/src/agents/claude-code/__tests__/mcp-approval-policy.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/mcp-approval-policy.test.ts
index eeb211c380..799accf15c 100644
--- a/packages/maker-core/src/agents/claude-code/__tests__/mcp-approval-policy.test.ts
+++ b/packages/maker-core/src/agents/claude-code/__tests__/mcp-approval-policy.test.ts
@@ -18,7 +18,13 @@ import path from 'node:path';
import { afterEach, describe, expect, it, vi } from 'vitest';
-import type { AgentDeps, McpToolApprovalContext, McpToolApprovalPolicy } from '../../base-agent.js';
+import type {
+ AgentDeps,
+ McpToolApprovalContext,
+ McpToolApprovalPolicy,
+ TurnPermissionPolicy,
+} from '../../base-agent.js';
+import type { PermissionMode } from '../../../types/common.js';
import type { AuthAdapter } from '../../../interfaces/auth-adapter.js';
import type { InteractionDecision, InteractionRequest } from '../../../types/events.js';
import type { Logger } from '../../../interfaces/logger.js';
@@ -139,6 +145,7 @@ async function startSession(
decide?: (req: InteractionRequest) => InteractionDecision | undefined;
/** true 时不注入 resolver,用于验证 fail-closed 分支。 */
bare?: boolean;
+ permissionMode?: PermissionMode;
},
) {
const configDir = await makeTempDir();
@@ -153,7 +160,7 @@ async function startSession(
sessionId: 'session-mcp-policy',
model: 'claude-opus-4-6',
workingDir,
- permissionMode: 'default',
+ permissionMode: options?.permissionMode ?? 'default',
});
const queryOptions = sdkMock.query.mock.calls.at(-1)?.[0]?.options as
| { canUseTool?: CanUseToolFn }
@@ -194,6 +201,63 @@ afterEach(async () => {
});
describe('ClaudeCodeAgent canUseTool honors the host MCP approval policy', () => {
+ it('runs the per-turn policy before MCP auto-approval and drops session grants', async () => {
+ const { handle, canUseTool, seen } = await startSession(
+ () => 'auto-approve',
+ {
+ decide: () => ({
+ kind: 'permission',
+ behavior: 'allow',
+ permissionUpdates: SESSION_SUGGESTION,
+ }),
+ },
+ );
+ const turnPermissionPolicy: TurnPermissionPolicy = {
+ origin: { kind: 'im', channel: 'wechat', taskId: 'task-claude' },
+ confirmationSurface: 'desktop',
+ forceConfirmToolCall: (toolName) => toolName.includes('contacts'),
+ };
+ await handle.send(
+ { type: 'user', content: 'delete the duplicate contact' },
+ { turnPermissionPolicy },
+ );
+
+ const result = await canUseTool(
+ 'mcp__cindy_contacts__call_tool',
+ { name: 'contacts_delete' },
+ { toolUseID: 't-policy', suggestions: SESSION_SUGGESTION },
+ );
+
+ expect(permissionRequests(seen)).toHaveLength(1);
+ expect(permissionRequests(seen)[0]?.suggestions).toBeUndefined();
+ expect(result.behavior).toBe('allow');
+ expect(result.updatedPermissions).toBeUndefined();
+ await handle.close();
+ });
+
+ it('rejects a per-turn policy in permission modes that can skip canUseTool', async () => {
+ const { handle } = await startSession(undefined, {
+ permissionMode: 'bypassPermissions',
+ });
+ const policy: TurnPermissionPolicy = {
+ origin: { kind: 'im', channel: 'wechat', taskId: 'task-full' },
+ confirmationSurface: 'desktop',
+ forceConfirmToolCall: () => true,
+ };
+
+ await expect(
+ handle.send(
+ { type: 'user', content: 'remove it' },
+ { turnPermissionPolicy: policy },
+ ),
+ ).rejects.toMatchObject({
+ name: 'TurnPermissionPolicyUnsupportedError',
+ code: 'TURN_PERMISSION_POLICY_UNSUPPORTED',
+ permissionMode: 'bypassPermissions',
+ });
+ await handle.close();
+ });
+
it('auto-approves trusted MCP tools without prompting the user', async () => {
const { handle, canUseTool, seen } = await startSession(() => 'auto-approve');
diff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.ts
index ef2e400f06..26d969d861 100644
--- a/packages/maker-core/src/agents/claude-code/index.ts
+++ b/packages/maker-core/src/agents/claude-code/index.ts
@@ -39,7 +39,18 @@ import {
} from './subagent-model-default.js';
import Anthropic, { APIError } from '@anthropic-ai/sdk';
-import { BaseAgent, OneShotError, AgentNotAuthenticatedError, type AgentSessionHandle, type AgentDeps, type StartSessionOptions, type OneShotOptions, type SendOptions } from '../base-agent.js';
+import {
+ BaseAgent,
+ OneShotError,
+ AgentNotAuthenticatedError,
+ TurnPermissionPolicyUnsupportedError,
+ type AgentSessionHandle,
+ type AgentDeps,
+ type StartSessionOptions,
+ type OneShotOptions,
+ type SendOptions,
+ type TurnPermissionPolicy,
+} from '../base-agent.js';
import { SYSTEM_PROMPT_APPEND as MAKER_SYSTEM_PROMPT_APPEND } from './system-prompt-append.js';
import { MAKER_MEMORY_RULES } from '../../memory/system-prompt.js';
import { MemoryFlushController } from '../../memory/flush-controller.js';
@@ -501,6 +512,12 @@ const CAPABILITIES: Capabilities = {
reasoningDisplay: ['off', 'summarized', 'full'],
permissionModes: CLAUDE_PERMISSION_MODES,
setPermissionModeMidSession: { supported: true },
+ turnPermissionPolicy: {
+ supported: { supported: true },
+ // Both modes can execute mutations without invoking canUseTool. Reject the
+ // combination instead of presenting a false forced-confirmation promise.
+ unsupportedPermissionModes: ['acceptEdits', 'bypassPermissions'],
+ },
// 计划模式一级开关: SDK plan mode + ExitPlanMode → plan_review 审批, 批准后自动退出
planMode: { supported: true },
multimodal: {
@@ -999,6 +1016,24 @@ export class ClaudeCodeAgent extends BaseAgent {
let inputQueue = createAsyncQueue<SdkUserInput>();
let abortController = new AbortController();
let interactionResolver: InteractionResolver | null = null;
+ // Keep the policy across Claude task_notification auto-continue turns,
+ // which do not call handle.send again. The next explicit send replaces it.
+ let activeTurnPermissionPolicy: TurnPermissionPolicy | null = null;
+ const forceTurnConfirmation = (toolName: string, input: unknown): boolean => {
+ const policy = activeTurnPermissionPolicy;
+ if (!policy) return false;
+ try {
+ return policy.forceConfirmToolCall(toolName, input) === true;
+ } catch (error) {
+ // A safety classifier failure cannot become an approval bypass.
+ log.error('turn permission policy threw -> force confirmation', {
+ toolName,
+ origin: policy.origin,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ return true;
+ }
+ };
// 事件队列预先声明 —— canUseTool 路径要 push interaction_dismissed 事件
const eventQueue = createAsyncQueue<AgentEvent>();
@@ -1265,11 +1300,13 @@ export class ClaudeCodeAgent extends BaseAgent {
}
// 3a. MCP 工具过 host 审批策略(本地与远端会话共用 classifyMcpApprovalPolicy)。
+ const turnPolicyForcePrompt = forceTurnConfirmation(toolName, input);
const mcpApprovalPolicy = classifyMcpApprovalPolicy(toolName, input);
- if (mcpApprovalPolicy === 'auto-approve') {
+ if (mcpApprovalPolicy === 'auto-approve' && !turnPolicyForcePrompt) {
return { behavior: 'allow', updatedInput: input };
}
- const forcePrompt = mcpApprovalPolicy === 'prompt-each-time';
+ const forcePrompt =
+ turnPolicyForcePrompt || mcpApprovalPolicy === 'prompt-each-time';
const decision = await dispatchInteraction({
kind: 'permission',
requestId: options.toolUseID,
@@ -1954,14 +1991,19 @@ export class ClaudeCodeAgent extends BaseAgent {
}
// 远端会话走同一份 host MCP 策略 —— 否则 SSH 会话里可信 server 又要逐次
// 弹窗, prompt-each-time 的"禁止持久化授权"保护也整套缺失。
+ const remoteTurnPolicyForcePrompt = forceTurnConfirmation(
+ params.toolName ?? 'unknown',
+ params.input ?? {},
+ );
const remoteMcpPolicy = classifyMcpApprovalPolicy(
params.toolName ?? '',
params.input ?? {},
);
- if (remoteMcpPolicy === 'auto-approve') {
+ if (remoteMcpPolicy === 'auto-approve' && !remoteTurnPolicyForcePrompt) {
return { kind: 'permission', behavior: 'allow' };
}
- const remoteForcePrompt = remoteMcpPolicy === 'prompt-each-time';
+ const remoteForcePrompt =
+ remoteTurnPolicyForcePrompt || remoteMcpPolicy === 'prompt-each-time';
const decision = await dispatchWithTimeout({
kind: 'permission',
requestId: params.requestId,
@@ -3111,6 +3153,19 @@ export class ClaudeCodeAgent extends BaseAgent {
agentKind: 'claude-code',
get model() { return mutableModel; },
+ validateSendOptions(sendOpts: SendOptions) {
+ if (
+ sendOpts.turnPermissionPolicy &&
+ (mutablePermissionMode === 'acceptEdits' ||
+ mutablePermissionMode === 'bypassPermissions')
+ ) {
+ throw new TurnPermissionPolicyUnsupportedError(
+ 'claude-code',
+ mutablePermissionMode,
+ );
+ }
+ },
+
async send(message: UserMessage, sendOpts?: SendOptions) {
// idle resume fallback 正在重建(亚秒窗):等它完成再走正常受理。重建成功时
// 消息透明跑在新会话上;重建失败/close 竞态时 push 撞上已 end 的队列,由下方
@@ -3121,6 +3176,8 @@ export class ClaudeCodeAgent extends BaseAgent {
if (sendOpts?.signal?.aborted) {
throw new Error('Claude send cancelled before acceptance');
}
+ if (sendOpts) handle.validateSendOptions?.(sendOpts);
+ activeTurnPermissionPolicy = sendOpts?.turnPermissionPolicy ?? null;
// 仅用于诊断日志: 调用方每次 send 都可以带 logTitle (取自 storage 的最新值);
// 缺省时保留上一次的值 (没传不等于"清空")。
if (sendOpts?.logTitle !== undefined) lastSendTitle = sendOpts.logTitle;
diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.ts
index 15d412f728..19caee383b 100644
--- a/packages/maker-core/src/agents/codex/index.test.ts
+++ b/packages/maker-core/src/agents/codex/index.test.ts
@@ -6,7 +6,7 @@ import { promises as fs } from 'node:fs';
import { CodexAgent } from './index.js';
import { Method } from './app-server/protocol.js';
import type { ThreadEventHandlers } from './app-server/host.js';
-import type { AgentDeps } from '../base-agent.js';
+import type { AgentDeps, TurnPermissionPolicy } from '../base-agent.js';
import type { AuthAdapter } from '../../interfaces/auth-adapter.js';
import type { AgentEvent, InteractionDecision, InteractionRequest } from '../../types/events.js';
import type { Logger } from '../../interfaces/logger.js';
@@ -407,6 +407,111 @@ describe('CodexAgent permissions', () => {
'bypassPermissions',
]);
expect(agent.capabilities.extraDirs).toEqual({ supported: true });
+ expect(agent.capabilities.turnPermissionPolicy).toEqual({
+ supported: { supported: true },
+ unsupportedPermissionModes: ['bypassPermissions'],
+ });
+ });
+
+ it('makes policy turns host-observable and only prompts for forced Auto actions', async () => {
+ const agent = new CodexAgent(createDeps());
+ const host = installFakeHost(agent, (method) => {
+ if (method === Method.TurnStart) {
+ return { turn: { id: 'turn-wechat-policy' } };
+ }
+ return undefined;
+ });
+ const handle = await agent.startSession({
+ sessionId: 'session-wechat-policy',
+ model: 'gpt-5.5',
+ workingDir: '/repo',
+ permissionMode: 'auto',
+ });
+ const policy: TurnPermissionPolicy = {
+ origin: { kind: 'im', channel: 'wechat', taskId: 'task-codex' },
+ confirmationSurface: 'desktop',
+ forceConfirmToolCall: (_toolName, input) =>
+ JSON.stringify(input).includes('rm -rf'),
+ };
+ const resolver = vi.fn(async () => ({
+ kind: 'permission' as const,
+ behavior: 'allow' as const,
+ }));
+ handle.setInteractionResolver(resolver);
+
+ await handle.send(
+ { type: 'user', content: 'clean old output if needed' },
+ { turnPermissionPolicy: policy },
+ );
+ const turnParams = host.request.mock.calls.find(
+ ([method]) => method === Method.TurnStart,
+ )?.[1] as Record<string, unknown>;
+ expect(turnParams).toMatchObject({
+ approvalPolicy: 'untrusted',
+ sandboxPolicy: { type: 'readOnly' },
+ });
+ expect(turnParams).not.toHaveProperty('approvalsReviewer');
+
+ const handlers = host.getThreadHandlers();
+ if (!handlers?.commandExecutionApproval) {
+ throw new Error('expected commandExecutionApproval handler');
+ }
+ await expect(
+ handlers.commandExecutionApproval({
+ threadId: 'start-thread-id',
+ turnId: 'turn-wechat-policy',
+ itemId: 'cmd-safe',
+ command: 'pwd',
+ cwd: '/repo',
+ }),
+ ).resolves.toEqual({ decision: 'accept' });
+ expect(resolver).not.toHaveBeenCalled();
+
+ await expect(
+ handlers.commandExecutionApproval({
+ threadId: 'start-thread-id',
+ turnId: 'turn-wechat-policy',
+ itemId: 'cmd-risky',
+ command: 'rm -rf build',
+ cwd: '/repo',
+ }),
+ ).resolves.toEqual({ decision: 'accept' });
+ expect(resolver).toHaveBeenCalledOnce();
+ expect(resolver.mock.calls[0]?.[0]).toMatchObject({
+ kind: 'permission',
+ toolName: 'exec',
+ input: { command: 'rm -rf build' },
+ suggestions: undefined,
+ });
+ await handle.close();
+ });
+
+ it('rejects Full Access policy turns instead of silently downgrading them', async () => {
+ const agent = new CodexAgent(createDeps());
+ installFakeHost(agent);
+ const handle = await agent.startSession({
+ sessionId: 'session-wechat-full-access',
+ model: 'gpt-5.5',
+ workingDir: '/repo',
+ permissionMode: 'bypassPermissions',
+ });
+ const policy: TurnPermissionPolicy = {
+ origin: { kind: 'im', channel: 'wechat', taskId: 'task-full' },
+ confirmationSurface: 'desktop',
+ forceConfirmToolCall: () => true,
+ };
+
+ await expect(
+ handle.send(
+ { type: 'user', content: 'remove old output' },
+ { turnPermissionPolicy: policy },
+ ),
+ ).rejects.toMatchObject({
+ name: 'TurnPermissionPolicyUnsupportedError',
+ code: 'TURN_PERMISSION_POLICY_UNSUPPORTED',
+ permissionMode: 'bypassPermissions',
+ });
+ await handle.close();
});
});
@@ -4164,6 +4269,70 @@ describe('CodexAgent MCP thread context hooks', () => {
await handle.close();
});
+ it('runs the turn policy before trusted MCP auto-approval', async () => {
+ const agent = new CodexAgent(createDeps({}, {
+ getMcpToolApprovalPolicy: () => 'auto-approve',
+ }));
+ const host = installFakeHost(agent, (method) => {
+ if (method === Method.TurnStart) {
+ return { turn: { id: 'turn-wechat-mcp' } };
+ }
+ return undefined;
+ });
+ const handle = await agent.startSession({
+ sessionId: 'session-wechat-mcp',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ permissionMode: 'auto',
+ });
+ const resolver = vi.fn(async () => ({
+ kind: 'permission' as const,
+ behavior: 'deny' as const,
+ }));
+ handle.setInteractionResolver(resolver);
+ await handle.send(
+ { type: 'user', content: 'delete duplicate contact' },
+ {
+ turnPermissionPolicy: {
+ origin: { kind: 'im', channel: 'wechat', taskId: 'task-mcp' },
+ confirmationSurface: 'desktop',
+ forceConfirmToolCall: (_toolName, input) =>
+ JSON.stringify(input).includes('contacts_delete'),
+ },
+ },
+ );
+
+ const handlers = host.getThreadHandlers();
+ if (!handlers?.mcpServerElicitation) {
+ throw new Error('expected mcpServerElicitation handler');
+ }
+ const result = await handlers.mcpServerElicitation({
+ threadId: 'start-thread-id',
+ turnId: 'turn-wechat-mcp',
+ serverName: 'cindy_contacts',
+ mode: 'form',
+ _meta: {
+ codex_approval_kind: 'mcp_tool_call',
+ persist: ['session'],
+ tool_params: {
+ name: 'contacts_delete',
+ args: { id: 'contact-1' },
+ },
+ },
+ message: 'Allow tool call',
+ requestedSchema: {},
+ });
+
+ expect(result).toEqual({ action: 'decline', content: null, _meta: null });
+ expect(resolver).toHaveBeenCalledOnce();
+ expect(resolver.mock.calls[0]?.[0]).toMatchObject({
+ kind: 'permission',
+ toolName: 'mcp:cindy_contacts',
+ suggestions: undefined,
+ });
+ await handle.close();
+ });
+
it('prompts every time for high-risk inner MCP calls and never persists approval', async () => {
const agent = new CodexAgent(createDeps({}, {
getMcpToolApprovalPolicy: () => 'prompt-each-time',
diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.ts
index f91cc843bc..c282d0f974 100644
--- a/packages/maker-core/src/agents/codex/index.ts
+++ b/packages/maker-core/src/agents/codex/index.ts
@@ -28,12 +28,14 @@ import {
BaseAgent,
OneShotError,
AgentNotAuthenticatedError,
+ TurnPermissionPolicyUnsupportedError,
type AgentSessionHandle,
type AgentDeps,
type StartSessionOptions,
type OneShotOptions,
type RefreshLocalModelsOptions,
type SendOptions,
+ type TurnPermissionPolicy,
} from '../base-agent.js';
import type { AgentCredentialMode } from '../../interfaces/auth-adapter.js';
import type {
@@ -719,6 +721,11 @@ const CAPABILITIES: Capabilities = {
reasoningDisplay: ['off', 'summarized'],
permissionModes: CODEX_PERMISSION_MODES,
setPermissionModeMidSession: { supported: true },
+ turnPermissionPolicy: {
+ supported: { supported: true },
+ // Full access can mutate workspace files without a host approval callback.
+ unsupportedPermissionModes: ['bypassPermissions'],
+ },
// 计划模式一级开关: app-server experimental collaborationMode ({ mode:'plan' }) +
// plan item 捕获 → plan_review 审批 → 批准后自动发起实施 turn (对齐官方 TUI 流程)。
planMode: { supported: true },
@@ -2124,6 +2131,23 @@ export class CodexAgent extends BaseAgent {
let subscriptionInvalidatedByTransport = false;
let subscription: ThreadSubscription | null = null;
let interactionResolver: InteractionResolver | null = null;
+ // Kept across the internal plan implementation/revision turns. A later
+ // explicit Session.send replaces it before turn/start.
+ let activeTurnPermissionPolicy: TurnPermissionPolicy | null = null;
+ const forceTurnConfirmation = (toolName: string, input: unknown): boolean => {
+ const policy = activeTurnPermissionPolicy;
+ if (!policy) return false;
+ try {
+ return policy.forceConfirmToolCall(toolName, input) === true;
+ } catch (error) {
+ log.error('turn permission policy threw -> force confirmation', {
+ toolName,
+ origin: policy.origin,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ return true;
+ }
+ };
let stopRolloutPlanFallback: (() => void) | null = null;
const seenRolloutPlanCallIds = new Set<string>();
const latestPlanByTurn = new Map<string, TurnPlanUpdatedNotification['params']['plan']>();
@@ -2423,7 +2447,16 @@ export class CodexAgent extends BaseAgent {
| 'sandboxPolicy'
| 'runtimeWorkspaceRoots'
> {
- const { approvalPolicy, approvalsReviewer, sandbox } = currentApprovalConfig();
+ // A policy turn must make execution observable to the host. Read-only +
+ // untrusted routes command/file escalations through the request handlers;
+ // those handlers auto-accept non-forced actions in Auto mode.
+ const turnApprovalConfig: CodexPermissionConfig = activeTurnPermissionPolicy
+ ? {
+ approvalPolicy: 'untrusted',
+ sandbox: 'read-only',
+ }
+ : currentApprovalConfig();
+ const { approvalPolicy, approvalsReviewer, sandbox } = turnApprovalConfig;
const shared = {
approvalPolicy,
...(approvalsReviewer ? { approvalsReviewer } : {}),
@@ -2431,7 +2464,10 @@ export class CodexAgent extends BaseAgent {
? { runtimeWorkspaceRoots: runtimeWorkspaceRoots() }
: {}),
};
- if (shouldUseReadonlyReferencesProfile()) {
+ if (
+ shouldUseReadonlyReferencesProfile() &&
+ !activeTurnPermissionPolicy
+ ) {
// The profile was selected on thread/start or thread/resume. Repeating
// the selector here makes Codex 0.145.0 reload its base config (which
// does not contain our per-thread definition) and reject turn/start
@@ -3077,7 +3113,12 @@ export class CodexAgent extends BaseAgent {
: PLAN_IMPLEMENTATION_MESSAGE;
log.debug('plan review ◀ approved — starting implementation turn', { turnId, edited: Boolean(edited && edited !== plan.trim()) });
try {
- await handle.send({ type: 'user', content: message });
+ await handle.send(
+ { type: 'user', content: message },
+ activeTurnPermissionPolicy
+ ? { turnPermissionPolicy: activeTurnPermissionPolicy }
+ : undefined,
+ );
} catch (e) {
emitPlanFollowUpStartFailure('implementation', e);
}
@@ -3099,7 +3140,12 @@ export class CodexAgent extends BaseAgent {
}
log.debug('plan review ◀ revision requested — starting plan revision turn', { turnId });
try {
- await handle.send({ type: 'user', content: feedback });
+ await handle.send(
+ { type: 'user', content: feedback },
+ activeTurnPermissionPolicy
+ ? { turnPermissionPolicy: activeTurnPermissionPolicy }
+ : undefined,
+ );
} catch (e) {
planCycleActive = false;
proposedPlanText = null;
@@ -3118,26 +3164,46 @@ export class CodexAgent extends BaseAgent {
req: InteractionRequest,
opts?: { forcePrompt?: boolean },
): Promise<ApprovalDecision> {
+ const forcePrompt =
+ opts?.forcePrompt === true ||
+ (req.kind === 'permission' &&
+ forceTurnConfirmation(req.toolName, req.input));
// Full access 的普通审批不应打断用户。Auto 在已验证路由上由 app-server
// auto_review 负责;降级路由则由 untrusted 把越界请求发回客户端。两条路径
// 只要收到请求都走 UI,不能绕过 reviewer / 降级审批直接放行。forcePrompt 高风险 MCP inner tool
// (如 contacts delete/merge/系统回写)在任何模式下都必须拿到用户的逐次确认。
if (
- !opts?.forcePrompt &&
+ !forcePrompt &&
mutablePermissionMode === 'bypassPermissions'
) {
return Promise.resolve('accept');
}
+ // Policy turns deliberately route otherwise-unattended Auto actions back
+ // through the host. Preserve Auto semantics by accepting non-forced
+ // callbacks without opening Desktop UI.
+ if (
+ !forcePrompt &&
+ activeTurnPermissionPolicy &&
+ mutablePermissionMode === 'auto'
+ ) {
+ return Promise.resolve('accept');
+ }
+ const routedRequest =
+ forcePrompt && req.kind === 'permission'
+ ? { ...req, suggestions: undefined }
+ : req;
return new Promise<ApprovalDecision>((resolve) => {
- const entry: PendingEntry = { resolve, kind, settled: false, forcePrompt: opts?.forcePrompt === true };
+ const entry: PendingEntry = { resolve, kind, settled: false, forcePrompt };
pendingApprovals.set(requestId, entry);
const finalize = (d: ApprovalDecision) => {
if (entry.settled) return;
entry.settled = true;
pendingApprovals.delete(requestId);
- resolve(d);
+ // A stale/custom UI may still return a session grant. Forced policy
+ // confirmation applies to this call only and must never persist.
+ resolve(forcePrompt && d === 'acceptForSession' ? 'accept' : d);
};
- dispatchInteraction(req)
+ dispatchInteraction(routedRequest)
.then((decision) => {
if (decision.kind !== 'permission') {
log.warn('unexpected non-permission decision → decline', { kind: decision.kind });
@@ -3446,7 +3512,12 @@ export class CodexAgent extends BaseAgent {
// Host policy 可在 outer call_tool 的 metadata 中识别渐进式 server 的
// inner action。查询继续静默,高风险 action 逐次确认且不得持久化授权。
const approvalPolicy = mcpToolApprovalPolicy(params);
- if (approvalPolicy === 'auto-approve') {
+ const policyPermissionInput = mcpElicitationPermissionInput(params);
+ const turnPolicyForcePrompt = forceTurnConfirmation(
+ `mcp:${params.serverName}`,
+ policyPermissionInput,
+ );
+ if (approvalPolicy === 'auto-approve' && !turnPolicyForcePrompt) {
log.debug('mcp elicitation auto-approved by host policy', {
serverName: params.serverName,
mode: params.mode,
@@ -3467,7 +3538,7 @@ export class CodexAgent extends BaseAgent {
kind: 'permission',
requestId,
toolName: `mcp:${params.serverName}`,
- input: mcpElicitationPermissionInput(params),
+ input: policyPermissionInput,
title: `Allow Codex to use ${innerToolName ?? toolTitle ?? params.serverName}?`,
description: params.message,
suggestions:
@@ -3477,7 +3548,10 @@ export class CodexAgent extends BaseAgent {
},
// prompt-each-time:Full access 也必须逐次弹 UI,否则高风险 inner tool
// (contacts delete/merge/系统回写)会被 awaitApprovalDecision 首分支静默放行。
- { forcePrompt: approvalPolicy === 'prompt-each-time' },
+ {
+ forcePrompt:
+ turnPolicyForcePrompt || approvalPolicy === 'prompt-each-time',
+ },
);
if (decision === 'accept') {
@@ -4722,10 +4796,24 @@ export class CodexAgent extends BaseAgent {
get codexProxyActive() { return hostUsesCodexProxy; },
get codexProductPromptDelivery() { return codexProductPromptDelivery; },
+ validateSendOptions(sendOpts: SendOptions) {
+ if (
+ sendOpts.turnPermissionPolicy &&
+ mutablePermissionMode === 'bypassPermissions'
+ ) {
+ throw new TurnPermissionPolicyUnsupportedError(
+ 'codex',
+ mutablePermissionMode,
+ );
+ }
+ },
+
async send(message: UserMessage, sendOpts?: SendOptions) {
if (rejectClosedOrCancelledSend(sendOpts, 'before start')) {
return;
}
+ if (sendOpts) handle.validateSendOptions?.(sendOpts);
+ activeTurnPermissionPolicy = sendOpts?.turnPermissionPolicy ?? null;
assertCurrentHost('turn/start');
resubscribeAfterTransportErrorIfNeeded();
// 新 turn 总是携带当前 (可能已收紧的) 策略, 上一轮残留的延迟中断标记
diff --git a/packages/maker-core/src/maker.test.ts b/packages/maker-core/src/maker.test.ts
index ab46c639d5..16146baf5f 100644
--- a/packages/maker-core/src/maker.test.ts
+++ b/packages/maker-core/src/maker.test.ts
@@ -751,6 +751,102 @@ describe('Session turn send guard', () => {
expect(handle.send).toHaveBeenCalledTimes(1);
});
+ it('does not run accepted persistence or provider send when beforeProviderStart fails', async () => {
+ const beforeError = new Error('durable acceptance CAS failed');
+ const handle = createHandle({ id: 'thread-before-provider-start' });
+ handle.send = vi.fn(async () => undefined);
+ const session = new Session({
+ id: 'before-provider-start-failure',
+ agentKind: 'codex',
+ workDir: '/repo',
+ handle,
+ capabilities: createAgent(async () => handle).capabilities,
+ logger: createLogger(),
+ });
+ const onAccepted = vi.fn();
+
+ await expect(
+ session.send('first', {
+ beforeProviderStart: () => {
+ throw beforeError;
+ },
+ onAccepted,
+ }),
+ ).rejects.toBe(beforeError);
+
+ expect(onAccepted).not.toHaveBeenCalled();
+ expect(handle.send).not.toHaveBeenCalled();
+ await expect(session.send('second')).resolves.toEqual({ accepted: true });
+ });
+
+ it('runs provider option preflight before durable or accepted side effects', async () => {
+ const preflightError = new Error('unsupported policy/mode combination');
+ const handle = createHandle({ id: 'thread-send-preflight' });
+ handle.validateSendOptions = vi.fn(() => {
+ throw preflightError;
+ });
+ handle.send = vi.fn(async () => undefined);
+ const session = new Session({
+ id: 'send-preflight',
+ agentKind: 'codex',
+ workDir: '/repo',
+ handle,
+ capabilities: createAgent(async () => handle).capabilities,
+ logger: createLogger(),
+ });
+ const beforeProviderStart = vi.fn();
+ const onAccepted = vi.fn();
+
+ await expect(
+ session.send('first', {
+ beforeProviderStart,
+ onAccepted,
+ }),
+ ).rejects.toBe(preflightError);
+
+ expect(handle.validateSendOptions).toHaveBeenCalledOnce();
+ expect(beforeProviderStart).not.toHaveBeenCalled();
+ expect(onAccepted).not.toHaveBeenCalled();
+ expect(handle.send).not.toHaveBeenCalled();
+ });
+
+ it('awaits beforeProviderStart before accepted persistence and provider dispatch', async () => {
+ const order: string[] = [];
+ let releaseBarrier!: () => void;
+ const barrier = new Promise<void>((resolve) => {
+ releaseBarrier = resolve;
+ });
+ const handle = createHandle({ id: 'thread-before-provider-order' });
+ handle.send = vi.fn(async () => {
+ order.push('provider');
+ });
+ const session = new Session({
+ id: 'before-provider-start-order',
+ agentKind: 'codex',
+ workDir: '/repo',
+ handle,
+ capabilities: createAgent(async () => handle).capabilities,
+ logger: createLogger(),
+ });
+
+ const sending = session.send('first', {
+ beforeProviderStart: async () => {
+ order.push('barrier-start');
+ await barrier;
+ order.push('barrier-end');
+ },
+ onAccepted: () => {
+ order.push('accepted');
+ },
+ });
+ await vi.waitFor(() => expect(order).toEqual(['barrier-start']));
+ await expect(session.send('second')).rejects.toMatchObject({ code: 'SESSION_RUNNING' });
+
+ releaseBarrier();
+ await expect(sending).resolves.toEqual({ accepted: true });
+ expect(order).toEqual(['barrier-start', 'barrier-end', 'accepted', 'provider']);
+ });
+
it('runs onDispatching after acceptance and immediately before vendor send', async () => {
const calls: string[] = [];
const handle = createHandle({ id: 'thread-1' });
diff --git a/packages/maker-core/src/session.ts b/packages/maker-core/src/session.ts
index 41043d2804..dcc57b8036 100644
--- a/packages/maker-core/src/session.ts
+++ b/packages/maker-core/src/session.ts
@@ -140,6 +140,15 @@ function redactNestedStrings(value: unknown, onChange: () => void): unknown {
}
export interface SessionSendOptions extends SendOptions {
+ /**
+ * Provider 启动前的安全屏障。
+ *
+ * Session 在 active/running 守卫通过、turn reservation 建立后调用;只有该
+ * hook 成功完成,才会继续执行产品层 onAccepted 与 vendor handle.send。
+ * 适合 durable queue 用 CAS 把任务从 dispatching 标成 accepted_running:
+ * hook 失败时 provider/model/tool 均不会启动。
+ */
+ beforeProviderStart?: () => void | Promise<void>;
/**
* 产品层 accepted hook。
* Session 在 active/running 守卫通过、turn reservation 建立后调用;
@@ -228,7 +237,7 @@ export class Session {
const msg: UserMessage = typeof message === 'string'
? { type: 'user', content: message }
: message;
- const { onAccepted, onDispatching, ...handleOpts } = opts ?? {};
+ const { beforeProviderStart, onAccepted, onDispatching, ...handleOpts } = opts ?? {};
this.logger.debug('send', summarizeUserMessage(msg));
this.ensureActive();
if (this.isTurnRunning()) {
@@ -247,6 +256,8 @@ export class Session {
let turnDispatched = false;
let previousTurnOrigin: SendOrigin | null = null;
try {
+ this.handle.validateSendOptions?.(handleOpts);
+ if (beforeProviderStart) await beforeProviderStart();
await onAccepted?.();
this.ensureActive();
if (reservation.cancelled || this.sendReservation !== reservation) {
diff --git a/packages/maker-core/src/types/capabilities.ts b/packages/maker-core/src/types/capabilities.ts
index 1f19d858af..4a2f07bb2a 100644
--- a/packages/maker-core/src/types/capabilities.ts
+++ b/packages/maker-core/src/types/capabilities.ts
@@ -45,6 +45,18 @@ export interface Capabilities {
/** 权限模式 */
permissionModes: PermissionModeDescriptor[];
setPermissionModeMidSession: CapabilityStatus;
+ /**
+ * Per-turn host policy that can force selected tool calls through the
+ * interaction resolver before execution. Optional for older/custom agents.
+ *
+ * `unsupportedPermissionModes` is load-bearing: a host must reject those
+ * combinations instead of silently weakening either the selected permission
+ * mode or the per-turn safety policy.
+ */
+ turnPermissionPolicy?: {
+ supported: CapabilityStatus;
+ unsupportedPermissionModes: PermissionMode[];
+ };
/**
* 计划模式(Plan Mode)—— 与 permissionMode 正交的独立会话状态:
diff --git a/packages/wechat-ilink/LICENSE.tencent-openclaw-weixin b/packages/wechat-ilink/LICENSE.tencent-openclaw-weixin
new file mode 100644
index 0000000000..5de9210c67
--- /dev/null
+++ b/packages/wechat-ilink/LICENSE.tencent-openclaw-weixin
@@ -0,0 +1,26 @@
+Tencent is pleased to support the open source community by making openclaw-weixin available.
+
+Copyright (C) 2026 Tencent. All rights reserved.
+
+openclaw-weixin is licensed under the MIT.
+
+Terms of the MIT:
+--------------------------------------------------------------------
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/packages/wechat-ilink/README.md b/packages/wechat-ilink/README.md
new file mode 100644
index 0000000000..84803a8bdd
--- /dev/null
+++ b/packages/wechat-ilink/README.md
@@ -0,0 +1,37 @@
+# @cindy/wechat-ilink
+
+Host-agnostic Tencent iLink protocol client used by Cindy's personal WeChat IM
+connector.
+
+The package owns wire encoding, QR authorization, long polling, text sending,
+typing status, message decoding, text filtering/chunking, and media crypto
+primitives. It deliberately does not own:
+
+- credential or cursor persistence;
+- filesystem paths or temporary files;
+- Electron, Renderer, SQLite, or Maker integration;
+- logging or telemetry;
+- retry queues and task execution.
+
+The host must inject `fetch`, an `AbortSignal` for every operation, and any
+verification-code UX. Authorization challenges expose only the QR content
+needed for display; the polling token and prior bot tokens remain in package
+memory and are erased when authorization finishes.
+
+```ts
+const transport = new TencentIlinkTransport({
+ baseUrl: "https://ilinkai.weixin.qq.com",
+ token,
+ botAgent: `Cindy/${version}`,
+ clientVersion: version,
+ fetch,
+});
+```
+
+Only credential-free HTTPS origins under `weixin.qq.com` are accepted. Errors
+cross the package boundary as `WechatIlinkError` with stable codes and never
+include response bodies, authorization headers, QR polling tokens, or bot
+tokens.
+
+Upstream protocol provenance and license details are recorded in
+[`UPSTREAM.md`](UPSTREAM.md).
diff --git a/packages/wechat-ilink/UPSTREAM.md b/packages/wechat-ilink/UPSTREAM.md
new file mode 100644
index 0000000000..1151b2b252
--- /dev/null
+++ b/packages/wechat-ilink/UPSTREAM.md
@@ -0,0 +1,21 @@
+# Tencent iLink protocol provenance
+
+Protocol behavior and selected pure utility logic were independently adapted from:
+
+- Repository: <https://github.com/Tencent/openclaw-weixin>
+- Tag: `v2.4.6`
+- Commit: `cef0bfc390393f716903e16d50408118047f87e0`
+- Retrieved: 2026-07-27
+- License: MIT; see `LICENSE.tencent-openclaw-weixin`
+
+Derived or behaviorally adapted areas:
+
+- `src/types.ts`: `src/api/types.ts`
+- `src/apiClient.ts`: `src/api/api.ts`
+- `src/auth.ts`: `src/auth/login-qr.ts`
+- `src/mediaCrypto.ts`: `src/cdn/aes-ecb.ts`
+- `src/markdown.ts`: `src/messaging/markdown-filter.ts`
+
+Cindy does not copy the OpenClaw plugin runtime, filesystem persistence, account store,
+logging, or host integration. Storage, cancellation, credentials, and network execution
+remain explicit host concerns.
diff --git a/packages/wechat-ilink/package.json b/packages/wechat-ilink/package.json
new file mode 100644
index 0000000000..b33365a82d
--- /dev/null
+++ b/packages/wechat-ilink/package.json
@@ -0,0 +1,27 @@
+{
+ "name": "@cindy/wechat-ilink",
+ "version": "0.0.0",
+ "private": true,
+ "description": "Electron-agnostic Tencent iLink protocol client for Cindy personal WeChat IM.",
+ "type": "module",
+ "main": "./src/index.ts",
+ "types": "./src/index.ts",
+ "exports": {
+ ".": "./src/index.ts"
+ },
+ "scripts": {
+ "build": "tsc --noEmit",
+ "test": "vitest run",
+ "typecheck": "tsc --noEmit"
+ },
+ "author": {
+ "name": "X.D. Network Inc.",
+ "email": "[email protected]"
+ },
+ "license": "Apache-2.0",
+ "devDependencies": {
+ "@types/node": "*",
+ "typescript": "^5.7.0",
+ "vitest": "^3.2.4"
+ }
+}
diff --git a/packages/wechat-ilink/src/__tests__/authorization.test.ts b/packages/wechat-ilink/src/__tests__/authorization.test.ts
new file mode 100644
index 0000000000..2e34bdb74b
--- /dev/null
+++ b/packages/wechat-ilink/src/__tests__/authorization.test.ts
@@ -0,0 +1,149 @@
+import { describe, expect, it, vi } from "vitest";
+import { TencentIlinkTransport, WechatIlinkError } from "../index.js";
+
+function jsonResponse(value: unknown): Response {
+ return new Response(JSON.stringify(value), { status: 200 });
+}
+
+describe("QR authorization", () => {
+ it("follows a Tencent redirect and returns credentials without persisting them", async () => {
+ const urls: string[] = [];
+ const responses = [
+ { qrcode: "qr-secret", qrcode_img_content: "https://weixin.qq.com/qr" },
+ { status: "scaned_but_redirect", redirect_host: "edge.weixin.qq.com" },
+ {
+ status: "confirmed",
+ bot_token: "fake-token",
+ ilink_bot_id: "bot-id",
+ ilink_user_id: "user-id",
+ baseurl: "https://edge.weixin.qq.com",
+ },
+ ];
+ const fetchMock = vi.fn(async (input: string | URL) => {
+ urls.push(String(input));
+ return jsonResponse(responses.shift());
+ });
+ const transport = new TencentIlinkTransport({
+ baseUrl: "https://ilinkai.weixin.qq.com",
+ botAgent: "Cindy/1.0.0",
+ fetch: fetchMock,
+ });
+
+ const challenge = await transport.beginAuthorization(
+ new AbortController().signal,
+ );
+ expect(challenge).not.toHaveProperty("qrCode");
+ expect(challenge).not.toHaveProperty("pollBaseUrl");
+ const credentials = await transport.waitAuthorization(
+ challenge,
+ new AbortController().signal,
+ );
+
+ expect(credentials).toEqual({
+ token: "fake-token",
+ botId: "bot-id",
+ userId: "user-id",
+ baseUrl: "https://edge.weixin.qq.com",
+ });
+ expect(urls[2]).toContain("https://edge.weixin.qq.com/");
+ });
+
+ it("refreshes an expired QR and reuses only the in-memory local token list", async () => {
+ const requestBodies: string[] = [];
+ const events: string[] = [];
+ const responses = [
+ { qrcode: "qr-1", qrcode_img_content: "https://weixin.qq.com/qr-1" },
+ { status: "expired" },
+ { qrcode: "qr-2", qrcode_img_content: "https://weixin.qq.com/qr-2" },
+ {
+ status: "confirmed",
+ bot_token: "fake-token-2",
+ ilink_bot_id: "bot-2",
+ ilink_user_id: "user-2",
+ baseurl: "https://ilinkai.weixin.qq.com",
+ },
+ ];
+ const transport = new TencentIlinkTransport({
+ baseUrl: "https://ilinkai.weixin.qq.com",
+ botAgent: "Cindy/1.0.0",
+ localTokens: async () => ["old-fake-token"],
+ authorizationObserver: {
+ onEvent: (event) => {
+ events.push(event.status);
+ },
+ },
+ fetch: async (_input, init) => {
+ if (typeof init?.body === "string") requestBodies.push(init.body);
+ return jsonResponse(responses.shift());
+ },
+ });
+
+ const challenge = await transport.beginAuthorization(
+ new AbortController().signal,
+ );
+ await expect(
+ transport.waitAuthorization(challenge, new AbortController().signal),
+ ).resolves.toMatchObject({ botId: "bot-2" });
+ expect(events).toContain("qr-refreshed");
+ expect(
+ requestBodies.filter((body) => body.includes("old-fake-token")),
+ ).toHaveLength(2);
+ });
+
+ it("rejects non-Tencent or credential-bearing base URLs", () => {
+ for (const baseUrl of [
+ "http://ilinkai.weixin.qq.com",
+ "https://user:[email protected]",
+ "https://attacker.invalid",
+ "https://ilinkai.weixin.qq.com/unexpected-path",
+ ]) {
+ expect(
+ () =>
+ new TencentIlinkTransport({
+ baseUrl,
+ botAgent: "Cindy/1.0.0",
+ fetch: async () => jsonResponse({}),
+ }),
+ ).toThrowError(WechatIlinkError);
+ }
+ });
+
+ it("surfaces an unknown status as a stable protocol error", async () => {
+ const responses = [
+ { qrcode: "qr", qrcode_img_content: "https://weixin.qq.com/qr" },
+ { status: "surprise" },
+ ];
+ const transport = new TencentIlinkTransport({
+ baseUrl: "https://ilinkai.weixin.qq.com",
+ botAgent: "Cindy/1.0.0",
+ fetch: async () => jsonResponse(responses.shift()),
+ });
+ const challenge = await transport.beginAuthorization(
+ new AbortController().signal,
+ );
+ await expect(
+ transport.waitAuthorization(challenge, new AbortController().signal),
+ ).rejects.toMatchObject({ code: "BAD_RESPONSE" });
+ });
+
+ it("rejects malformed verification codes before they enter a request URL", async () => {
+ const responses = [
+ { qrcode: "qr", qrcode_img_content: "https://weixin.qq.com/qr" },
+ { status: "need_verifycode" },
+ ];
+ const transport = new TencentIlinkTransport({
+ baseUrl: "https://ilinkai.weixin.qq.com",
+ botAgent: "Cindy/1.0.0",
+ authorizationObserver: {
+ requestVerificationCode: async () => "not-a-number",
+ },
+ fetch: async () => jsonResponse(responses.shift()),
+ });
+ const challenge = await transport.beginAuthorization(
+ new AbortController().signal,
+ );
+ await expect(
+ transport.waitAuthorization(challenge, new AbortController().signal),
+ ).rejects.toMatchObject({ code: "PROTOCOL_ERROR" });
+ });
+});
diff --git a/packages/wechat-ilink/src/__tests__/protocol.test.ts b/packages/wechat-ilink/src/__tests__/protocol.test.ts
new file mode 100644
index 0000000000..9a2219b64e
--- /dev/null
+++ b/packages/wechat-ilink/src/__tests__/protocol.test.ts
@@ -0,0 +1,517 @@
+import { createHash } from "node:crypto";
+import { describe, expect, it, vi } from "vitest";
+import {
+ IlinkApiClient,
+ TencentIlinkTransport,
+ WechatIlinkError,
+ aes128EcbPaddedSize,
+ chunkWechatText,
+ decodeInboundMessage,
+ downloadWechatMedia,
+ decryptAes128Ecb,
+ encryptAes128Ecb,
+ filterWechatMarkdown,
+ prepareWechatUpload,
+} from "../index.js";
+
+const signal = () => new AbortController().signal;
+
+describe("pure protocol utilities", () => {
+ it("round-trips AES-128-ECB and validates padded sizes", () => {
+ const key = Uint8Array.from({ length: 16 }, (_, index) => index);
+ const input = Buffer.from("Cindy WeChat");
+ const encrypted = encryptAes128Ecb(input, key);
+ expect(Buffer.from(decryptAes128Ecb(encrypted, key))).toEqual(input);
+ expect(aes128EcbPaddedSize(0)).toBe(16);
+ expect(aes128EcbPaddedSize(16)).toBe(32);
+ });
+
+ it("chunks by code point rather than splitting surrogate pairs", () => {
+ expect(chunkWechatText("A😀B", 2)).toEqual(["A😀", "B"]);
+ const softBoundary = chunkWechatText("abcd efgh", 6);
+ expect(softBoundary).toEqual(["abcd ", "efgh"]);
+ expect(softBoundary.join("")).toBe("abcd efgh");
+ const fenced = chunkWechatText(
+ "before\n```ts\nconst value = 1234567890;\n```\nafter",
+ 24,
+ );
+ expect(fenced.length).toBeGreaterThan(1);
+ expect(fenced.every((chunk) => Array.from(chunk).length <= 24)).toBe(true);
+ expect(fenced[0]).toMatch(/\n```$/);
+ expect(fenced[1]).toMatch(/^```\n/);
+ });
+
+ it("filters unsupported markdown without changing code or bold", () => {
+ expect(
+ filterWechatMarkdown("##### 标题\n*中文* **保留** ![x](https://x)"),
+ ).toBe("标题\n中文 **保留** ");
+ expect(
+ filterWechatMarkdown(
+ "```\n##### untouched ![x](url)\n```\n`*中文*` *中文*",
+ ),
+ ).toBe("```\n##### untouched ![x](url)\n```\n`*中文*` 中文");
+ });
+
+ it("filters image syntax in linear time for adversarial incomplete input", () => {
+ const repeatedOpen = "![".repeat(50_000);
+ const repeatedDestination = "![](".repeat(50_000);
+ expect(filterWechatMarkdown(repeatedOpen)).toBe(repeatedOpen);
+ expect(filterWechatMarkdown(repeatedDestination)).toBe(
+ repeatedDestination,
+ );
+ expect(
+ filterWechatMarkdown("before ![broken] text ![ok](url) after"),
+ ).toBe("before ![broken] text after");
+ });
+
+ it("rejects incomplete inbound messages before they reach the host", () => {
+ expect(decodeInboundMessage({ message_id: 1 })).toBeNull();
+ expect(
+ decodeInboundMessage({
+ message_id: 1,
+ from_user_id: "user",
+ to_user_id: "bot",
+ context_token: "ctx",
+ item_list: [{ type: 1, text_item: { text: "hello" } }],
+ }),
+ ).toMatchObject({
+ messageId: "message:1",
+ senderId: "user",
+ text: "hello",
+ });
+ expect(
+ decodeInboundMessage({
+ message_id: 2,
+ message_type: 2,
+ from_user_id: "bot",
+ to_user_id: "user",
+ context_token: "ctx",
+ }),
+ ).toBeNull();
+ expect(
+ decodeInboundMessage({
+ message_id: 3,
+ from_user_id: "user",
+ to_user_id: "bot",
+ context_token: "ctx",
+ item_list: [null] as never,
+ }),
+ ).toMatchObject({ messageId: "message:3", media: [] });
+ });
+
+ it("preserves a legitimate zero-byte file length", () => {
+ expect(
+ decodeInboundMessage({
+ message_id: 4,
+ from_user_id: "user",
+ to_user_id: "bot",
+ context_token: "ctx",
+ item_list: [
+ {
+ type: 4,
+ file_item: {
+ file_name: "empty.txt",
+ len: "0",
+ },
+ },
+ ],
+ }),
+ ).toMatchObject({
+ media: [{ kind: "file", fileName: "empty.txt", byteLength: 0 }],
+ });
+ });
+
+ it("decodes quoted text and media without inventing prior history", () => {
+ expect(
+ decodeInboundMessage({
+ message_id: 4,
+ from_user_id: "user",
+ to_user_id: "bot",
+ context_token: "ctx",
+ item_list: [
+ {
+ type: 1,
+ text_item: { text: "继续分析" },
+ ref_msg: {
+ title: "Alice",
+ message_item: {
+ type: 2,
+ image_item: {
+ media: {
+ full_url: "https://cdn.weixin.qq.com/quoted",
+ aes_key: Buffer.alloc(16, 1).toString("base64"),
+ },
+ mid_size: 32,
+ },
+ },
+ },
+ },
+ ],
+ }),
+ ).toMatchObject({
+ text: "继续分析",
+ quote: {
+ title: "Alice",
+ media: [{ kind: "image", encryptedByteLength: 32 }],
+ },
+ });
+ });
+
+ it("decrypts bounded Tencent media and validates file metadata", async () => {
+ const plaintext = Buffer.from("verified attachment");
+ const key = Buffer.alloc(16, 7);
+ const encrypted = encryptAes128Ecb(plaintext, key);
+ const result = await downloadWechatMedia(
+ {
+ kind: "file",
+ downloadUrl: "https://cdn.weixin.qq.com/c2c/download?id=1",
+ aesKeyBase64: key.toString("base64"),
+ byteLength: plaintext.byteLength,
+ md5Hex: createHash("md5").update(plaintext).digest("hex"),
+ },
+ async (_input, init) => {
+ expect(init?.redirect).toBe("manual");
+ return new Response(Buffer.from(encrypted));
+ },
+ signal(),
+ );
+ expect(Buffer.from(result)).toEqual(plaintext);
+ });
+
+ it("rejects untrusted media origins before issuing a request", async () => {
+ const fetchMock = vi.fn();
+ await expect(
+ downloadWechatMedia(
+ {
+ kind: "image",
+ downloadUrl: "https://example.com/file",
+ aesKeyBase64: Buffer.alloc(16).toString("base64"),
+ },
+ fetchMock,
+ signal(),
+ ),
+ ).rejects.toMatchObject({ code: "PROTOCOL_ERROR" });
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+});
+
+describe("iLink HTTP boundary", () => {
+ it("notifies iLink when the channel starts and stops", async () => {
+ const calls: Array<{ url: string; init?: RequestInit }> = [];
+ const transport = new TencentIlinkTransport({
+ baseUrl: "https://ilinkai.weixin.qq.com",
+ token: "fake-token",
+ clientVersion: "1.1.21",
+ botAgent: "Cindy/1.1.21",
+ fetch: async (input, init) => {
+ calls.push({ url: String(input), init });
+ return new Response(JSON.stringify({ ret: 0 }));
+ },
+ });
+
+ await expect(transport.notifyStart(signal())).resolves.toBeUndefined();
+ await expect(transport.notifyStop(signal())).resolves.toBeUndefined();
+
+ expect(calls.map(({ url }) => new URL(url).pathname)).toEqual([
+ "/ilink/bot/msg/notifystart",
+ "/ilink/bot/msg/notifystop",
+ ]);
+ expect(
+ calls.map(({ init }) => JSON.parse(String(init?.body))),
+ ).toEqual([
+ {
+ base_info: {
+ channel_version: "1.1.21",
+ bot_agent: "Cindy/1.1.21",
+ },
+ },
+ {
+ base_info: {
+ channel_version: "1.1.21",
+ bot_agent: "Cindy/1.1.21",
+ },
+ },
+ ]);
+ });
+
+ it("accepts inbound messages with an omitted recipient and a 64-bit identifier", () => {
+ expect(
+ decodeInboundMessage({
+ message_id: 9_223_372_036_854_775_807,
+ client_id: "stable-client-id",
+ from_user_id: "user",
+ context_token: "ctx",
+ item_list: [{ type: 1, text_item: { text: "hello" } }],
+ }),
+ ).toMatchObject({
+ messageId: "client:stable-client-id",
+ senderId: "user",
+ text: "hello",
+ });
+ expect(
+ decodeInboundMessage({
+ message_id: "9223372036854775807",
+ from_user_id: "user",
+ context_token: "ctx",
+ }),
+ ).toMatchObject({
+ messageId: "message:9223372036854775807",
+ senderId: "user",
+ });
+ });
+
+ it("builds authenticated poll requests without exposing response bodies in errors", async () => {
+ const fetchMock = vi.fn(
+ async (_input: string | URL, init?: RequestInit) => {
+ expect(init?.headers).toMatchObject({
+ Authorization: "Bearer fake-token",
+ AuthorizationType: "ilink_bot_token",
+ });
+ expect(init?.redirect).toBe("manual");
+ return new Response(
+ JSON.stringify({ ret: 0, msgs: [], get_updates_buf: "next" }),
+ );
+ },
+ );
+ const transport = new TencentIlinkTransport({
+ baseUrl: "https://ilinkai.weixin.qq.com",
+ token: "fake-token",
+ botAgent: "Cindy/1.0.0",
+ fetch: fetchMock,
+ });
+ await expect(transport.poll("old", signal())).resolves.toEqual({
+ cursor: "next",
+ messages: [],
+ suggestedTimeoutMs: undefined,
+ });
+ });
+
+ it("maps HTTP failures to stable secret-free errors", async () => {
+ const api = new IlinkApiClient({
+ baseUrl: "https://ilinkai.weixin.qq.com",
+ token: "top-secret",
+ botAgent: "Cindy/1.0.0",
+ fetch: async () => new Response("token=top-secret", { status: 503 }),
+ });
+ await expect(api.getUpdates("", signal())).rejects.toMatchObject({
+ code: "HTTP_ERROR",
+ retryable: true,
+ } satisfies Partial<WechatIlinkError>);
+ await expect(api.getUpdates("", signal())).rejects.not.toThrow(
+ /top-secret/,
+ );
+ });
+
+ it("builds deterministic text messages and includes the declared client identity", async () => {
+ let request: RequestInit | undefined;
+ const transport = new TencentIlinkTransport({
+ baseUrl: "https://ilinkai.weixin.qq.com",
+ token: "fake-token",
+ clientVersion: "1.1.21",
+ botAgent: "Cindy/1.1.21 invalid",
+ fetch: async (_input, init) => {
+ request = init;
+ return new Response(JSON.stringify({ ret: 0 }));
+ },
+ });
+ await expect(
+ transport.sendMessage(
+ {
+ peerId: "peer",
+ text: "hello",
+ contextToken: "context",
+ clientId: "stable-client-id",
+ runId: "run",
+ },
+ signal(),
+ ),
+ ).resolves.toEqual({ clientId: "stable-client-id" });
+
+ expect(request?.headers).toMatchObject({
+ "iLink-App-ClientVersion": String((1 << 16) | (1 << 8) | 21),
+ });
+ expect(JSON.parse(String(request?.body))).toMatchObject({
+ msg: {
+ to_user_id: "peer",
+ client_id: "stable-client-id",
+ context_token: "context",
+ },
+ base_info: {
+ channel_version: "1.1.21",
+ bot_agent: "Cindy/1.1.21",
+ },
+ });
+ });
+
+ it("uploads encrypted media and sends the returned CDN reference", async () => {
+ const calls: Array<{ url: string; init?: RequestInit }> = [];
+ const transport = new TencentIlinkTransport({
+ baseUrl: "https://ilinkai.weixin.qq.com",
+ token: "fake-token",
+ botAgent: "Cindy/1.0.0",
+ fetch: async (input, init) => {
+ const url = String(input);
+ calls.push({ url, init });
+ if (url.endsWith("/ilink/bot/getuploadurl")) {
+ return new Response(
+ JSON.stringify({
+ ret: 0,
+ upload_full_url: "https://cdn.weixin.qq.com/c2c/upload?id=1",
+ }),
+ );
+ }
+ if (url.startsWith("https://cdn.weixin.qq.com/")) {
+ return new Response(null, {
+ status: 200,
+ headers: { "x-encrypted-param": "download-token" },
+ });
+ }
+ return new Response(JSON.stringify({ ret: 0 }));
+ },
+ });
+ const bytes = Buffer.from("image bytes");
+ const uploaded = await transport.uploadMedia(
+ { peerId: "peer", bytes, fileName: "image.png", kind: "image" },
+ signal(),
+ );
+ expect(uploaded).toMatchObject({
+ fileName: "image.png",
+ ref: {
+ kind: "image",
+ encryptedQuery: "download-token",
+ byteLength: bytes.byteLength,
+ },
+ });
+ expect(uploaded.ref.encryptedByteLength).toBe(
+ prepareWechatUpload(bytes).ciphertext.byteLength,
+ );
+ const decodedAesKey = Buffer.from(
+ String(uploaded.ref.aesKeyBase64),
+ "base64",
+ );
+ expect(decodedAesKey).toHaveLength(32);
+ const uploadUrlRequest = calls.find(({ url }) =>
+ url.endsWith("/ilink/bot/getuploadurl"),
+ );
+ const uploadBody = JSON.parse(String(uploadUrlRequest?.init?.body));
+ expect(uploadBody).toMatchObject({
+ aeskey: decodedAesKey.toString("ascii"),
+ });
+
+ await expect(
+ transport.sendMedia(
+ {
+ peerId: "peer",
+ contextToken: "context",
+ clientId: "stable-media-id",
+ uploaded,
+ },
+ signal(),
+ ),
+ ).resolves.toEqual({ clientId: "stable-media-id" });
+
+ const uploadRequest = calls.find(({ url }) =>
+ url.startsWith("https://cdn.weixin.qq.com/"),
+ );
+ expect(uploadRequest?.init?.body).toBeInstanceOf(Buffer);
+ const sendRequest = calls.at(-1)?.init;
+ expect(JSON.parse(String(sendRequest?.body))).toMatchObject({
+ msg: {
+ client_id: "stable-media-id",
+ item_list: [
+ {
+ type: 2,
+ image_item: {
+ mid_size: uploaded.ref.encryptedByteLength,
+ media: {
+ encrypt_query_param: "download-token",
+ aes_key: uploaded.ref.aesKeyBase64,
+ encrypt_type: 1,
+ },
+ },
+ },
+ ],
+ },
+ });
+ });
+
+ it("maps stale credentials and malformed message lists to stable errors", async () => {
+ const responses = [
+ { ret: 1, errcode: -14 },
+ { ret: 0, msgs: "not-an-array" },
+ ];
+ const transport = new TencentIlinkTransport({
+ baseUrl: "https://ilinkai.weixin.qq.com",
+ token: "fake-token",
+ botAgent: "Cindy/1.0.0",
+ fetch: async () => new Response(JSON.stringify(responses.shift())),
+ });
+ await expect(transport.poll("", signal())).rejects.toMatchObject({
+ code: "AUTH_REPLACED",
+ retryable: false,
+ });
+ await expect(transport.poll("", signal())).rejects.toMatchObject({
+ code: "BAD_RESPONSE",
+ });
+ });
+
+ it("propagates host cancellation instead of treating it as a long-poll timeout", async () => {
+ const controller = new AbortController();
+ const transport = new TencentIlinkTransport({
+ baseUrl: "https://ilinkai.weixin.qq.com",
+ token: "fake-token",
+ botAgent: "Cindy/1.0.0",
+ fetch: async (_input, init) =>
+ await new Promise<Response>((_resolve, reject) => {
+ init?.signal?.addEventListener("abort", () => {
+ const error = new Error("cancelled");
+ error.name = "AbortError";
+ reject(error);
+ });
+ }),
+ });
+ const pending = transport.poll("", controller.signal);
+ controller.abort();
+ await expect(pending).rejects.toMatchObject({ code: "ABORTED" });
+ });
+
+ it("rejects oversized responses and bounded poll collections", async () => {
+ const oversized = new TencentIlinkTransport({
+ baseUrl: "https://ilinkai.weixin.qq.com",
+ token: "fake-token",
+ botAgent: "Cindy/1.0.0",
+ maxResponseBytes: 16,
+ fetch: async () =>
+ new Response(JSON.stringify({ ret: 0, padding: "x".repeat(100) })),
+ });
+ await expect(oversized.poll("", signal())).rejects.toMatchObject({
+ code: "BAD_RESPONSE",
+ });
+
+ const tooMany = new TencentIlinkTransport({
+ baseUrl: "https://ilinkai.weixin.qq.com",
+ token: "fake-token",
+ botAgent: "Cindy/1.0.0",
+ maxPollMessages: 1,
+ fetch: async () =>
+ new Response(JSON.stringify({ ret: 0, msgs: [{}, {}] })),
+ });
+ await expect(tooMany.poll("", signal())).rejects.toMatchObject({
+ code: "BAD_RESPONSE",
+ });
+
+ const tooManyItems = new TencentIlinkTransport({
+ baseUrl: "https://ilinkai.weixin.qq.com",
+ token: "fake-token",
+ botAgent: "Cindy/1.0.0",
+ maxItemsPerMessage: 1,
+ fetch: async () =>
+ new Response(
+ JSON.stringify({ ret: 0, msgs: [{ item_list: [{}, {}] }] }),
+ ),
+ });
+ await expect(tooManyItems.poll("", signal())).rejects.toMatchObject({
+ code: "BAD_RESPONSE",
+ });
+ });
+});
diff --git a/packages/wechat-ilink/src/apiClient.ts b/packages/wechat-ilink/src/apiClient.ts
new file mode 100644
index 0000000000..eaab17fb63
--- /dev/null
+++ b/packages/wechat-ilink/src/apiClient.ts
@@ -0,0 +1,661 @@
+import { randomBytes } from "node:crypto";
+import { asWechatIlinkError, WechatIlinkError } from "./errors.js";
+import { parseJsonObject } from "./codec.js";
+import type {
+ IlinkMessage,
+ IlinkMessageItem,
+ WechatMediaRef,
+ WechatSendMediaRequest,
+ WechatSendRequest,
+} from "./types.js";
+import {
+ MessageItemType,
+ MessageState,
+ MessageType,
+ TypingStatus,
+} from "./types.js";
+
+export type FetchLike = (
+ input: string | URL,
+ init?: RequestInit,
+) => Promise<Response>;
+
+export interface IlinkApiClientOptions {
+ baseUrl: string;
+ token?: string;
+ appId?: string;
+ clientVersion?: string;
+ botAgent: string;
+ routeTag?: string;
+ fetch: FetchLike;
+ apiTimeoutMs?: number;
+ longPollTimeoutMs?: number;
+ maxResponseBytes?: number;
+ maxPollMessages?: number;
+ maxItemsPerMessage?: number;
+}
+
+export interface QrStatusResponse {
+ status:
+ | "wait"
+ | "scaned"
+ | "confirmed"
+ | "expired"
+ | "scaned_but_redirect"
+ | "need_verifycode"
+ | "verify_code_blocked"
+ | "binded_redirect";
+ bot_token?: string;
+ ilink_bot_id?: string;
+ ilink_user_id?: string;
+ baseurl?: string;
+ redirect_host?: string;
+}
+
+const AUTHORIZATION_ORIGIN = new URL("https://ilinkai.weixin.qq.com");
+
+function versionInteger(version: string): number {
+ const [major = 0, minor = 0, patch = 0] = version
+ .split(".")
+ .map((part) => Number.parseInt(part, 10) || 0);
+ return ((major & 0xff) << 16) | ((minor & 0xff) << 8) | (patch & 0xff);
+}
+
+export function sanitizeBotAgent(raw: string): string {
+ const product = /^[A-Za-z0-9_.-]{1,32}\/[A-Za-z0-9_.+-]{1,32}$/;
+ const accepted = raw
+ .trim()
+ .split(/\s+/)
+ .filter((token) => product.test(token));
+ const result: string[] = [];
+ let length = 0;
+ for (const token of accepted) {
+ const next = length + (result.length ? 1 : 0) + Buffer.byteLength(token);
+ if (next > 256) break;
+ result.push(token);
+ length = next;
+ }
+ return result.join(" ") || "Cindy/unknown";
+}
+
+export function validateTencentIlinkBaseUrl(value: string): URL {
+ let url: URL;
+ try {
+ url = new URL(value);
+ } catch {
+ throw new WechatIlinkError(
+ "PROTOCOL_ERROR",
+ "iLink base URL is invalid.",
+ false,
+ );
+ }
+ if (
+ url.protocol !== "https:" ||
+ url.username ||
+ url.password ||
+ (url.port !== "" && url.port !== "443") ||
+ url.search ||
+ url.hash ||
+ url.pathname !== "/" ||
+ !(
+ url.hostname === "weixin.qq.com" ||
+ url.hostname.endsWith(".weixin.qq.com")
+ )
+ ) {
+ throw new WechatIlinkError(
+ "PROTOCOL_ERROR",
+ "iLink base URL must be a Tencent credential-free HTTPS origin.",
+ false,
+ );
+ }
+ return url;
+}
+
+async function readBoundedText(
+ response: Response,
+ maxBytes: number,
+): Promise<string> {
+ const declaredLength = Number(response.headers.get("content-length"));
+ if (Number.isFinite(declaredLength) && declaredLength > maxBytes) {
+ throw new WechatIlinkError(
+ "BAD_RESPONSE",
+ "iLink response exceeded the size limit.",
+ true,
+ );
+ }
+ if (!response.body) return "";
+ const reader = response.body.getReader();
+ const chunks: Uint8Array[] = [];
+ let total = 0;
+ try {
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ total += value.byteLength;
+ if (total > maxBytes) {
+ await reader.cancel();
+ throw new WechatIlinkError(
+ "BAD_RESPONSE",
+ "iLink response exceeded the size limit.",
+ true,
+ );
+ }
+ chunks.push(value);
+ }
+ } finally {
+ reader.releaseLock();
+ }
+ return Buffer.concat(chunks.map((chunk) => Buffer.from(chunk))).toString(
+ "utf8",
+ );
+}
+
+function combineSignal(
+ signal: AbortSignal,
+ timeoutMs: number,
+): {
+ signal: AbortSignal;
+ timedOut(): boolean;
+ cleanup(): void;
+} {
+ const controller = new AbortController();
+ let timeoutReached = false;
+ const abort = () => controller.abort(signal.reason);
+ if (signal.aborted) abort();
+ else signal.addEventListener("abort", abort, { once: true });
+ const timer = setTimeout(() => {
+ timeoutReached = true;
+ controller.abort();
+ }, timeoutMs);
+ return {
+ signal: controller.signal,
+ timedOut: () => timeoutReached,
+ cleanup: () => {
+ clearTimeout(timer);
+ signal.removeEventListener("abort", abort);
+ },
+ };
+}
+
+/** Stateless JSON/HTTP client. Tokens and cursor persistence remain host-owned. */
+export class IlinkApiClient {
+ private readonly fetchImpl: FetchLike;
+ private readonly baseUrl: URL;
+
+ constructor(private readonly options: IlinkApiClientOptions) {
+ this.baseUrl = validateTencentIlinkBaseUrl(options.baseUrl);
+ this.fetchImpl = options.fetch;
+ }
+
+ private baseInfo() {
+ return {
+ channel_version: this.options.clientVersion ?? "unknown",
+ bot_agent: sanitizeBotAgent(this.options.botAgent),
+ };
+ }
+
+ private headers(
+ authenticated: boolean,
+ jsonBody: boolean,
+ ): Record<string, string> {
+ const headers: Record<string, string> = {
+ "iLink-App-Id": this.options.appId ?? "bot",
+ "iLink-App-ClientVersion": String(
+ versionInteger(this.options.clientVersion ?? "0.0.0"),
+ ),
+ "X-WECHAT-UIN": Buffer.from(
+ String(randomBytes(4).readUInt32BE(0)),
+ ).toString("base64"),
+ };
+ if (this.options.routeTag) headers.SKRouteTag = this.options.routeTag;
+ if (jsonBody) {
+ headers["Content-Type"] = "application/json";
+ headers.AuthorizationType = "ilink_bot_token";
+ }
+ if (authenticated) {
+ if (this.options.token?.trim())
+ headers.Authorization = `Bearer ${this.options.token.trim()}`;
+ }
+ return headers;
+ }
+
+ private async request(
+ endpoint: string,
+ init: { method: "GET" | "POST"; body?: unknown; authenticated: boolean },
+ signal: AbortSignal,
+ timeoutMs = this.options.apiTimeoutMs ?? 15_000,
+ baseUrl = this.baseUrl,
+ ): Promise<Record<string, unknown>> {
+ const url = new URL(endpoint, baseUrl);
+ const combined = combineSignal(signal, timeoutMs);
+ try {
+ const response = await this.fetchImpl(url, {
+ method: init.method,
+ headers: this.headers(init.authenticated, init.method === "POST"),
+ signal: combined.signal,
+ redirect: "manual",
+ ...(init.body === undefined ? {} : { body: JSON.stringify(init.body) }),
+ });
+ const text = await readBoundedText(
+ response,
+ this.options.maxResponseBytes ?? 4 * 1024 * 1024,
+ );
+ if (!response.ok) {
+ throw new WechatIlinkError(
+ "HTTP_ERROR",
+ `iLink request failed with HTTP ${response.status}.`,
+ response.status >= 500,
+ );
+ }
+ return parseJsonObject(text);
+ } catch (error) {
+ if (error instanceof Error && error.name === "AbortError") {
+ if (signal.aborted) {
+ throw new WechatIlinkError(
+ "ABORTED",
+ "The iLink operation was cancelled.",
+ true,
+ {
+ cause: error,
+ },
+ );
+ }
+ if (combined.timedOut()) {
+ throw new WechatIlinkError(
+ "TIMEOUT",
+ "The iLink request timed out.",
+ true,
+ {
+ cause: error,
+ },
+ );
+ }
+ }
+ throw asWechatIlinkError(error);
+ } finally {
+ combined.cleanup();
+ }
+ }
+
+ beginQr(
+ localTokens: string[],
+ signal: AbortSignal,
+ ): Promise<Record<string, unknown>> {
+ return this.request(
+ "ilink/bot/get_bot_qrcode?bot_type=3",
+ {
+ method: "POST",
+ body: { local_token_list: localTokens.slice(-10) },
+ authenticated: false,
+ },
+ signal,
+ this.options.apiTimeoutMs ?? 15_000,
+ AUTHORIZATION_ORIGIN,
+ );
+ }
+
+ async pollQr(
+ qrCode: string,
+ verificationCode: string | undefined,
+ signal: AbortSignal,
+ baseUrl?: string,
+ ): Promise<QrStatusResponse> {
+ const query = new URLSearchParams({ qrcode: qrCode });
+ if (verificationCode) query.set("verify_code", verificationCode);
+ try {
+ return (await this.request(
+ `ilink/bot/get_qrcode_status?${query}`,
+ { method: "GET", authenticated: false },
+ signal,
+ this.options.longPollTimeoutMs ?? 35_000,
+ baseUrl ? validateTencentIlinkBaseUrl(baseUrl) : this.baseUrl,
+ )) as unknown as QrStatusResponse;
+ } catch (error) {
+ if (error instanceof WechatIlinkError && error.code === "TIMEOUT") {
+ return { status: "wait" };
+ }
+ throw error;
+ }
+ }
+
+ async getUpdates(cursor: string, signal: AbortSignal) {
+ try {
+ return await this.request(
+ "ilink/bot/getupdates",
+ {
+ method: "POST",
+ authenticated: true,
+ body: {
+ get_updates_buf: cursor,
+ base_info: this.baseInfo(),
+ },
+ },
+ signal,
+ this.options.longPollTimeoutMs ?? 35_000,
+ );
+ } catch (error) {
+ if (error instanceof WechatIlinkError && error.code === "TIMEOUT") {
+ return { ret: 0, msgs: [], get_updates_buf: cursor };
+ }
+ throw error;
+ }
+ }
+
+ notifyStart(signal: AbortSignal): Promise<Record<string, unknown>> {
+ return this.notifyLifecycle("ilink/bot/msg/notifystart", signal);
+ }
+
+ notifyStop(signal: AbortSignal): Promise<Record<string, unknown>> {
+ return this.notifyLifecycle("ilink/bot/msg/notifystop", signal);
+ }
+
+ async sendText(
+ request: WechatSendRequest,
+ signal: AbortSignal,
+ ): Promise<void> {
+ if (
+ !request.peerId.trim() ||
+ !request.contextToken.trim() ||
+ !request.clientId.trim() ||
+ request.text.length === 0 ||
+ Array.from(request.text).length > 3500
+ ) {
+ throw new WechatIlinkError(
+ "PROTOCOL_ERROR",
+ "The iLink text message is incomplete.",
+ false,
+ );
+ }
+ const response = await this.request(
+ "ilink/bot/sendmessage",
+ {
+ method: "POST",
+ authenticated: true,
+ body: {
+ msg: {
+ from_user_id: "",
+ to_user_id: request.peerId,
+ client_id: request.clientId,
+ message_type: MessageType.BOT,
+ message_state: MessageState.FINISH,
+ item_list: [
+ { type: MessageItemType.TEXT, text_item: { text: request.text } },
+ ],
+ context_token: request.contextToken,
+ run_id: request.runId,
+ },
+ base_info: this.baseInfo(),
+ },
+ },
+ signal,
+ );
+ if (typeof response.ret === "number" && response.ret !== 0) {
+ throw new WechatIlinkError(
+ "PROTOCOL_ERROR",
+ "iLink rejected the message.",
+ true,
+ );
+ }
+ }
+
+ async getUploadUrl(
+ request: {
+ peerId: string;
+ fileKey: string;
+ mediaType: number;
+ rawSize: number;
+ rawMd5: string;
+ encryptedSize: number;
+ aesKeyHex: string;
+ },
+ signal: AbortSignal,
+ ): Promise<{
+ uploadParam?: string;
+ uploadFullUrl?: string;
+ }> {
+ const response = await this.request(
+ "ilink/bot/getuploadurl",
+ {
+ method: "POST",
+ authenticated: true,
+ body: {
+ filekey: request.fileKey,
+ media_type: request.mediaType,
+ to_user_id: request.peerId,
+ rawsize: request.rawSize,
+ rawfilemd5: request.rawMd5,
+ filesize: request.encryptedSize,
+ no_need_thumb: true,
+ aeskey: request.aesKeyHex,
+ base_info: this.baseInfo(),
+ },
+ },
+ signal,
+ );
+ if (typeof response.ret === "number" && response.ret !== 0) {
+ throw new WechatIlinkError(
+ "PROTOCOL_ERROR",
+ "iLink rejected the media upload request.",
+ true,
+ );
+ }
+ return {
+ uploadParam:
+ typeof response.upload_param === "string"
+ ? response.upload_param
+ : undefined,
+ uploadFullUrl:
+ typeof response.upload_full_url === "string"
+ ? response.upload_full_url
+ : undefined,
+ };
+ }
+
+ async sendMedia(
+ request: WechatSendMediaRequest,
+ signal: AbortSignal,
+ ): Promise<void> {
+ const { ref, fileName } = request.uploaded;
+ if (
+ !request.peerId.trim() ||
+ !request.contextToken.trim() ||
+ !request.clientId.trim() ||
+ !ref.encryptedQuery ||
+ !ref.aesKeyBase64
+ ) {
+ throw new WechatIlinkError(
+ "PROTOCOL_ERROR",
+ "The iLink media message is incomplete.",
+ false,
+ );
+ }
+ const item = mediaItemFor(ref, fileName);
+ const response = await this.request(
+ "ilink/bot/sendmessage",
+ {
+ method: "POST",
+ authenticated: true,
+ body: {
+ msg: {
+ from_user_id: "",
+ to_user_id: request.peerId,
+ client_id: request.clientId,
+ message_type: MessageType.BOT,
+ message_state: MessageState.FINISH,
+ item_list: [item],
+ context_token: request.contextToken,
+ run_id: request.runId,
+ },
+ base_info: this.baseInfo(),
+ },
+ },
+ signal,
+ );
+ if (typeof response.ret === "number" && response.ret !== 0) {
+ throw new WechatIlinkError(
+ "PROTOCOL_ERROR",
+ "iLink rejected the media message.",
+ true,
+ );
+ }
+ }
+
+ getConfig(peerId: string, contextToken: string, signal: AbortSignal) {
+ if (!peerId.trim() || !contextToken.trim()) {
+ throw new WechatIlinkError(
+ "PROTOCOL_ERROR",
+ "The iLink typing request is incomplete.",
+ false,
+ );
+ }
+ return this.request(
+ "ilink/bot/getconfig",
+ {
+ method: "POST",
+ authenticated: true,
+ body: {
+ ilink_user_id: peerId,
+ context_token: contextToken,
+ base_info: this.baseInfo(),
+ },
+ },
+ signal,
+ );
+ }
+
+ async setTyping(
+ peerId: string,
+ ticket: string,
+ active: boolean,
+ signal: AbortSignal,
+ ): Promise<void> {
+ if (!peerId.trim() || !ticket.trim()) {
+ throw new WechatIlinkError(
+ "PROTOCOL_ERROR",
+ "The iLink typing request is incomplete.",
+ false,
+ );
+ }
+ const response = await this.request(
+ "ilink/bot/sendtyping",
+ {
+ method: "POST",
+ authenticated: true,
+ body: {
+ ilink_user_id: peerId,
+ typing_ticket: ticket,
+ status: active ? TypingStatus.TYPING : TypingStatus.CANCEL,
+ base_info: this.baseInfo(),
+ },
+ },
+ signal,
+ );
+ if (typeof response.ret === "number" && response.ret !== 0) {
+ throw new WechatIlinkError(
+ "PROTOCOL_ERROR",
+ "iLink rejected the typing request.",
+ true,
+ );
+ }
+ }
+
+ static messagesFrom(response: Record<string, unknown>): IlinkMessage[] {
+ if (response.msgs === undefined) return [];
+ if (!Array.isArray(response.msgs)) {
+ throw new WechatIlinkError(
+ "BAD_RESPONSE",
+ "iLink returned an invalid message list.",
+ true,
+ );
+ }
+ return response.msgs.filter(
+ (message): message is IlinkMessage =>
+ message !== null &&
+ typeof message === "object" &&
+ !Array.isArray(message),
+ );
+ }
+
+ messagesFrom(response: Record<string, unknown>): IlinkMessage[] {
+ const messages = IlinkApiClient.messagesFrom(response);
+ if (messages.length > (this.options.maxPollMessages ?? 100)) {
+ throw new WechatIlinkError(
+ "BAD_RESPONSE",
+ "iLink returned too many messages in one poll.",
+ true,
+ );
+ }
+ for (const message of messages) {
+ if (
+ message.item_list !== undefined &&
+ (!Array.isArray(message.item_list) ||
+ message.item_list.length > (this.options.maxItemsPerMessage ?? 20))
+ ) {
+ throw new WechatIlinkError(
+ "BAD_RESPONSE",
+ "iLink returned an invalid message item list.",
+ true,
+ );
+ }
+ }
+ return messages;
+ }
+
+ private notifyLifecycle(
+ endpoint: "ilink/bot/msg/notifystart" | "ilink/bot/msg/notifystop",
+ signal: AbortSignal,
+ ): Promise<Record<string, unknown>> {
+ return this.request(
+ endpoint,
+ {
+ method: "POST",
+ authenticated: true,
+ body: { base_info: this.baseInfo() },
+ },
+ signal,
+ 5_000,
+ );
+ }
+}
+
+function mediaItemFor(ref: WechatMediaRef, fileName: string): IlinkMessageItem {
+ const media = {
+ encrypt_query_param: ref.encryptedQuery,
+ aes_key: ref.aesKeyBase64,
+ encrypt_type: 1,
+ };
+ switch (ref.kind) {
+ case "image":
+ return {
+ type: MessageItemType.IMAGE,
+ image_item: {
+ media,
+ mid_size: ref.encryptedByteLength ?? ref.byteLength,
+ },
+ };
+ case "video":
+ return {
+ type: MessageItemType.VIDEO,
+ video_item: {
+ media,
+ video_size: ref.encryptedByteLength ?? ref.byteLength,
+ },
+ };
+ case "file":
+ return {
+ type: MessageItemType.FILE,
+ file_item: {
+ media,
+ file_name: fileName,
+ len:
+ ref.byteLength === undefined ? undefined : String(ref.byteLength),
+ },
+ };
+ case "voice":
+ throw new WechatIlinkError(
+ "PROTOCOL_ERROR",
+ "Outbound voice messages are not supported.",
+ false,
+ );
+ }
+}
diff --git a/packages/wechat-ilink/src/auth.ts b/packages/wechat-ilink/src/auth.ts
new file mode 100644
index 0000000000..cfc40ced7b
--- /dev/null
+++ b/packages/wechat-ilink/src/auth.ts
@@ -0,0 +1,230 @@
+import { randomUUID } from "node:crypto";
+import {
+ IlinkApiClient,
+ type QrStatusResponse,
+ validateTencentIlinkBaseUrl,
+} from "./apiClient.js";
+import { WechatIlinkError } from "./errors.js";
+import type {
+ WechatAuthChallenge,
+ WechatAuthorizationObserver,
+ WechatCredentials,
+} from "./types.js";
+
+function requiredString(value: unknown, field: string): string {
+ if (typeof value === "string" && value.trim()) return value;
+ throw new WechatIlinkError("BAD_RESPONSE", `iLink omitted ${field}.`, false);
+}
+
+function requiredTencentQrUrl(value: unknown): string {
+ const raw = requiredString(value, "qrcode_img_content");
+ let url: URL;
+ try {
+ url = new URL(raw);
+ } catch {
+ throw new WechatIlinkError(
+ "BAD_RESPONSE",
+ "iLink returned an invalid QR URL.",
+ false,
+ );
+ }
+ if (
+ url.protocol !== "https:" ||
+ url.username ||
+ url.password ||
+ !(
+ url.hostname === "weixin.qq.com" ||
+ url.hostname.endsWith(".weixin.qq.com")
+ )
+ ) {
+ throw new WechatIlinkError(
+ "BAD_RESPONSE",
+ "iLink returned an invalid QR URL.",
+ false,
+ );
+ }
+ return url.toString();
+}
+
+interface ActiveAuthorization {
+ qrCode: string;
+ pollBaseUrl: string;
+ localTokens: string[];
+ createdAt: number;
+}
+
+const AUTHORIZATION_TTL_MS = 5 * 60_000;
+
+/** QR authorization state machine with host-injected verification-code UX. */
+export class IlinkAuthorization {
+ private readonly active = new Map<string, ActiveAuthorization>();
+
+ constructor(
+ private readonly api: IlinkApiClient,
+ private readonly observer: WechatAuthorizationObserver = {},
+ ) {}
+
+ async begin(
+ localTokens: string[],
+ signal: AbortSignal,
+ ): Promise<WechatAuthChallenge> {
+ const response = await this.api.beginQr(localTokens, signal);
+ const challenge = {
+ id: randomUUID(),
+ qrCodeUrl: requiredTencentQrUrl(response.qrcode_img_content),
+ createdAt: Date.now(),
+ };
+ this.active.set(challenge.id, {
+ qrCode: requiredString(response.qrcode, "qrcode"),
+ pollBaseUrl: "https://ilinkai.weixin.qq.com",
+ localTokens: [...localTokens],
+ createdAt: challenge.createdAt,
+ });
+ return challenge;
+ }
+
+ async wait(
+ challenge: WechatAuthChallenge,
+ signal: AbortSignal,
+ ): Promise<WechatCredentials> {
+ const active = this.active.get(challenge.id);
+ if (!active) {
+ throw new WechatIlinkError(
+ "AUTH_EXPIRED",
+ "The WeChat authorization challenge is no longer active.",
+ true,
+ );
+ }
+ let verificationCode: string | undefined;
+ let currentChallenge = { ...challenge };
+ let refreshCount = 0;
+ try {
+ while (!signal.aborted) {
+ if (Date.now() - active.createdAt > AUTHORIZATION_TTL_MS) {
+ throw new WechatIlinkError(
+ "AUTH_TIMEOUT",
+ "The WeChat authorization timed out.",
+ true,
+ );
+ }
+ const status = (await this.api.pollQr(
+ active.qrCode,
+ verificationCode,
+ signal,
+ active.pollBaseUrl,
+ )) as QrStatusResponse;
+ switch (status.status) {
+ case "wait":
+ await this.observer.onEvent?.({ status: "waiting" });
+ break;
+ case "scaned":
+ verificationCode = undefined;
+ await this.observer.onEvent?.({ status: "scanned" });
+ break;
+ case "need_verifycode":
+ if (!this.observer.requestVerificationCode) {
+ throw new WechatIlinkError(
+ "PROTOCOL_ERROR",
+ "A WeChat verification code is required.",
+ true,
+ );
+ }
+ await this.observer.onEvent?.({
+ status: "verification-required",
+ retry: verificationCode !== undefined,
+ });
+ verificationCode = await this.observer.requestVerificationCode(
+ verificationCode !== undefined,
+ signal,
+ );
+ if (!/^\d{1,12}$/.test(verificationCode)) {
+ throw new WechatIlinkError(
+ "PROTOCOL_ERROR",
+ "The WeChat verification code is invalid.",
+ false,
+ );
+ }
+ break;
+ case "verify_code_blocked":
+ throw new WechatIlinkError(
+ "AUTH_TIMEOUT",
+ "Verification attempts were blocked.",
+ true,
+ );
+ case "expired":
+ refreshCount += 1;
+ if (refreshCount > 3) {
+ throw new WechatIlinkError(
+ "AUTH_EXPIRED",
+ "The WeChat QR code expired too many times.",
+ true,
+ );
+ }
+ {
+ const response = await this.api.beginQr(
+ active.localTokens,
+ signal,
+ );
+ active.qrCode = requiredString(response.qrcode, "qrcode");
+ active.pollBaseUrl = "https://ilinkai.weixin.qq.com";
+ currentChallenge = {
+ id: challenge.id,
+ qrCodeUrl: requiredTencentQrUrl(response.qrcode_img_content),
+ createdAt: Date.now(),
+ };
+ }
+ verificationCode = undefined;
+ await this.observer.onEvent?.({
+ status: "qr-refreshed",
+ challenge: currentChallenge,
+ });
+ break;
+ case "binded_redirect":
+ throw new WechatIlinkError(
+ "AUTH_ALREADY_BOUND",
+ "This WeChat connection is already bound.",
+ false,
+ );
+ case "scaned_but_redirect":
+ if (
+ !status.redirect_host ||
+ !/^[A-Za-z0-9.-]+$/.test(status.redirect_host)
+ ) {
+ throw new WechatIlinkError(
+ "BAD_RESPONSE",
+ "iLink returned an invalid authorization redirect.",
+ true,
+ );
+ }
+ active.pollBaseUrl = validateTencentIlinkBaseUrl(
+ `https://${status.redirect_host}`,
+ ).origin;
+ break;
+ case "confirmed":
+ validateTencentIlinkBaseUrl(
+ requiredString(status.baseurl, "baseurl"),
+ );
+ return {
+ token: requiredString(status.bot_token, "bot_token"),
+ botId: requiredString(status.ilink_bot_id, "ilink_bot_id"),
+ userId: requiredString(status.ilink_user_id, "ilink_user_id"),
+ baseUrl: requiredString(status.baseurl, "baseurl"),
+ };
+ default:
+ throw new WechatIlinkError(
+ "BAD_RESPONSE",
+ "iLink returned an unknown authorization status.",
+ true,
+ );
+ }
+ }
+ throw new WechatIlinkError(
+ "ABORTED",
+ "The iLink operation was cancelled.",
+ true,
+ );
+ } finally {
+ this.active.delete(challenge.id);
+ }
+ }
+}
diff --git a/packages/wechat-ilink/src/chunk.ts b/packages/wechat-ilink/src/chunk.ts
new file mode 100644
index 0000000000..6478413d54
--- /dev/null
+++ b/packages/wechat-ilink/src/chunk.ts
@@ -0,0 +1,51 @@
+function splitRawText(text: string, maxCodePoints: number): string[] {
+ const points = Array.from(text);
+ const chunks: string[] = [];
+ let offset = 0;
+ while (offset < points.length) {
+ let end = Math.min(offset + maxCodePoints, points.length);
+ if (end < points.length) {
+ while (end > offset && (points[end - 1] === "`" || points[end] === "`")) {
+ end -= 1;
+ }
+ if (end === offset) end = Math.min(offset + maxCodePoints, points.length);
+ const minimumBreak = offset + Math.floor(maxCodePoints * 0.6);
+ for (let candidate = end; candidate > minimumBreak; candidate -= 1) {
+ if (
+ points[candidate - 1] === "\n" ||
+ /\s/u.test(points[candidate - 1])
+ ) {
+ end = candidate;
+ break;
+ }
+ }
+ }
+ chunks.push(points.slice(offset, end).join(""));
+ offset = end;
+ }
+ return chunks;
+}
+
+function togglesFence(text: string): number {
+ return (text.match(/^\s*```/gm) ?? []).length;
+}
+
+export function chunkWechatText(text: string, maxCodePoints = 3500): string[] {
+ if (!Number.isSafeInteger(maxCodePoints) || maxCodePoints < 1) {
+ throw new RangeError("maxCodePoints must be a positive integer");
+ }
+ const points = Array.from(text);
+ if (points.length === 0) return [];
+ if (maxCodePoints < 9) return splitRawText(text, maxCodePoints);
+
+ const rawChunks = splitRawText(text, maxCodePoints - 8);
+ const chunks: string[] = [];
+ let fenceOpen = false;
+ for (const raw of rawChunks) {
+ const prefix = fenceOpen ? "```\n" : "";
+ if (togglesFence(raw) % 2 === 1) fenceOpen = !fenceOpen;
+ const suffix = fenceOpen ? "\n```" : "";
+ chunks.push(`${prefix}${raw}${suffix}`);
+ }
+ return chunks;
+}
diff --git a/packages/wechat-ilink/src/codec.ts b/packages/wechat-ilink/src/codec.ts
new file mode 100644
index 0000000000..d06ec49bf5
--- /dev/null
+++ b/packages/wechat-ilink/src/codec.ts
@@ -0,0 +1,184 @@
+import { WechatIlinkError } from "./errors.js";
+import {
+ MessageItemType,
+ MessageType,
+ type IlinkCdnMedia,
+ type IlinkMessage,
+ type IlinkMessageItem,
+ type WechatInboundMessage,
+ type WechatMediaRef,
+} from "./types.js";
+
+export function parseJsonObject(text: string): Record<string, unknown> {
+ try {
+ const value: unknown = JSON.parse(text);
+ if (value && typeof value === "object" && !Array.isArray(value)) {
+ return value as Record<string, unknown>;
+ }
+ } catch {
+ // Converted to the stable package error below.
+ }
+ throw new WechatIlinkError(
+ "BAD_RESPONSE",
+ "iLink returned invalid JSON.",
+ true,
+ );
+}
+
+function mediaBase(
+ kind: WechatMediaRef["kind"],
+ media?: IlinkCdnMedia,
+): WechatMediaRef {
+ return {
+ kind,
+ downloadUrl: media?.full_url,
+ encryptedQuery: media?.encrypt_query_param,
+ aesKeyBase64: media?.aes_key,
+ };
+}
+
+function optionalByteLength(value: unknown): number | undefined {
+ if (typeof value !== "string" || value.trim() === "") return undefined;
+ const parsed = Number(value);
+ return Number.isSafeInteger(parsed) && parsed >= 0 ? parsed : undefined;
+}
+
+function decodeQuote(item: IlinkMessageItem) {
+ const ref = item.ref_msg;
+ if (!ref) return undefined;
+ const quoted = ref.message_item;
+ if (!quoted) {
+ return ref.title ? { title: ref.title, media: [] } : undefined;
+ }
+ const text =
+ quoted.type === MessageItemType.TEXT &&
+ typeof quoted.text_item?.text === "string"
+ ? quoted.text_item.text
+ : quoted.type === MessageItemType.VOICE &&
+ typeof quoted.voice_item?.text === "string"
+ ? quoted.voice_item.text
+ : undefined;
+ const decoded = decodeItemMedia(quoted);
+ return {
+ ...(ref.title ? { title: ref.title } : {}),
+ ...(text ? { text } : {}),
+ media: decoded ? [decoded] : [],
+ };
+}
+
+function decodeItemMedia(item: IlinkMessageItem): WechatMediaRef | null {
+ switch (item.type) {
+ case MessageItemType.IMAGE:
+ return {
+ ...mediaBase("image", item.image_item?.media),
+ aesKeyHex: item.image_item?.aeskey,
+ encryptedByteLength: item.image_item?.mid_size,
+ };
+ case MessageItemType.VOICE:
+ return {
+ ...mediaBase("voice", item.voice_item?.media),
+ voiceEncoding: item.voice_item?.encode_type,
+ transcript: item.voice_item?.text,
+ };
+ case MessageItemType.FILE:
+ return {
+ ...mediaBase("file", item.file_item?.media),
+ fileName: item.file_item?.file_name,
+ byteLength: optionalByteLength(item.file_item?.len),
+ md5Hex: item.file_item?.md5,
+ };
+ case MessageItemType.VIDEO:
+ return {
+ ...mediaBase("video", item.video_item?.media),
+ encryptedByteLength: item.video_item?.video_size,
+ };
+ default:
+ return null;
+ }
+}
+
+export function decodeInboundMessage(
+ message: IlinkMessage,
+): WechatInboundMessage | null {
+ if (!message || typeof message !== "object") return null;
+ if (message.message_type != null && message.message_type !== MessageType.USER)
+ return null;
+ const senderId =
+ typeof message.from_user_id === "string" ? message.from_user_id.trim() : "";
+ const recipientId =
+ typeof message.to_user_id === "string" ? message.to_user_id.trim() : "";
+ const contextToken =
+ typeof message.context_token === "string"
+ ? message.context_token.trim()
+ : "";
+ const messageId = stableInboundMessageId(message);
+ if (!senderId || !contextToken || !messageId) return null;
+
+ const textParts: string[] = [];
+ const media: WechatMediaRef[] = [];
+ let quote: WechatInboundMessage["quote"];
+ const items = Array.isArray(message.item_list) ? message.item_list : [];
+ for (const item of items) {
+ if (!item || typeof item !== "object") continue;
+ quote ??= decodeQuote(item);
+ switch (item.type) {
+ case MessageItemType.TEXT:
+ if (typeof item.text_item?.text === "string" && item.text_item.text) {
+ textParts.push(item.text_item.text);
+ }
+ break;
+ case MessageItemType.IMAGE:
+ media.push(decodeItemMedia(item)!);
+ break;
+ case MessageItemType.VOICE:
+ if (typeof item.voice_item?.text === "string" && item.voice_item.text) {
+ textParts.push(item.voice_item.text);
+ }
+ media.push(decodeItemMedia(item)!);
+ break;
+ case MessageItemType.FILE:
+ media.push(decodeItemMedia(item)!);
+ break;
+ case MessageItemType.VIDEO:
+ media.push(decodeItemMedia(item)!);
+ break;
+ }
+ }
+
+ return {
+ messageId,
+ senderId,
+ ...(recipientId ? { recipientId } : {}),
+ clientId: message.client_id,
+ createdAt: message.create_time_ms,
+ contextToken,
+ text: textParts.join("\n"),
+ media,
+ ...(quote ? { quote } : {}),
+ };
+}
+
+function stableInboundMessageId(message: IlinkMessage): string {
+ const clientId =
+ typeof message.client_id === "string" ? message.client_id.trim() : "";
+ if (clientId) return `client:${clientId}`;
+
+ if (
+ typeof message.message_id === "number" &&
+ Number.isFinite(message.message_id) &&
+ Number.isInteger(message.message_id)
+ ) {
+ return `message:${message.message_id}`;
+ }
+ if (typeof message.message_id === "string" && message.message_id.trim()) {
+ return `message:${message.message_id.trim()}`;
+ }
+ if (
+ typeof message.seq === "number" &&
+ Number.isFinite(message.seq) &&
+ Number.isInteger(message.seq)
+ ) {
+ return `seq:${message.seq}`;
+ }
+ return "";
+}
diff --git a/packages/wechat-ilink/src/errors.ts b/packages/wechat-ilink/src/errors.ts
new file mode 100644
index 0000000000..07a4214260
--- /dev/null
+++ b/packages/wechat-ilink/src/errors.ts
@@ -0,0 +1,47 @@
+export type WechatIlinkErrorCode =
+ | "ABORTED"
+ | "AUTH_EXPIRED"
+ | "AUTH_ALREADY_BOUND"
+ | "AUTH_REPLACED"
+ | "AUTH_TIMEOUT"
+ | "BAD_RESPONSE"
+ | "HTTP_ERROR"
+ | "NETWORK_ERROR"
+ | "PROTOCOL_ERROR"
+ | "TIMEOUT"
+ | "UNSUPPORTED";
+
+/** Stable, secret-free error surfaced across the package boundary. */
+export class WechatIlinkError extends Error {
+ constructor(
+ readonly code: WechatIlinkErrorCode,
+ message: string,
+ readonly retryable: boolean,
+ options?: { cause?: unknown },
+ ) {
+ super(message, options);
+ this.name = "WechatIlinkError";
+ }
+}
+
+export function asWechatIlinkError(error: unknown): WechatIlinkError {
+ if (error instanceof WechatIlinkError) return error;
+ if (error instanceof Error && error.name === "AbortError") {
+ return new WechatIlinkError(
+ "ABORTED",
+ "The iLink operation was cancelled.",
+ true,
+ {
+ cause: error,
+ },
+ );
+ }
+ return new WechatIlinkError(
+ "NETWORK_ERROR",
+ "The iLink request failed.",
+ true,
+ {
+ cause: error,
+ },
+ );
+}
diff --git a/packages/wechat-ilink/src/index.ts b/packages/wechat-ilink/src/index.ts
new file mode 100644
index 0000000000..f22ad9545a
--- /dev/null
+++ b/packages/wechat-ilink/src/index.ts
@@ -0,0 +1,10 @@
+export * from "./apiClient.js";
+export * from "./auth.js";
+export * from "./chunk.js";
+export * from "./codec.js";
+export * from "./errors.js";
+export * from "./markdown.js";
+export * from "./mediaCrypto.js";
+export * from "./mediaTransfer.js";
+export * from "./transport.js";
+export * from "./types.js";
diff --git a/packages/wechat-ilink/src/markdown.ts b/packages/wechat-ilink/src/markdown.ts
new file mode 100644
index 0000000000..091eefb023
--- /dev/null
+++ b/packages/wechat-ilink/src/markdown.ts
@@ -0,0 +1,66 @@
+const CJK = /[\u2e80-\u9fff\uac00-\ud7af\uf900-\ufaff]/;
+
+function removeMarkdownImages(markdown: string): string {
+ let output = "";
+ let offset = 0;
+ while (offset < markdown.length) {
+ const start = markdown.indexOf("![", offset);
+ if (start < 0) return output + markdown.slice(offset);
+ const altEnd = markdown.indexOf("]", start + 2);
+ if (altEnd < 0) return output + markdown.slice(offset);
+ if (markdown[altEnd + 1] !== "(") {
+ output += markdown.slice(offset, altEnd + 1);
+ offset = altEnd + 1;
+ continue;
+ }
+ const destinationEnd = markdown.indexOf(")", altEnd + 2);
+ if (destinationEnd < 0) return output + markdown.slice(offset);
+ output += markdown.slice(offset, start);
+ offset = destinationEnd + 1;
+ }
+ return output;
+}
+
+function filterPlainMarkdown(markdown: string): string {
+ return removeMarkdownImages(markdown)
+ .replace(/^#{5,6}\s+/gm, "")
+ .replace(/~~([^~]+)~~/g, "$1")
+ .replace(
+ /(\*{1,3}|_{1,3})([^*_\n]+)\1/g,
+ (whole, marker: string, body: string) =>
+ CJK.test(body) && marker.length !== 2 ? body : whole,
+ );
+}
+
+function filterInlineCodeAware(markdown: string): string {
+ let output = "";
+ let offset = 0;
+ while (offset < markdown.length) {
+ const start = markdown.indexOf("`", offset);
+ if (start < 0) return output + filterPlainMarkdown(markdown.slice(offset));
+ output += filterPlainMarkdown(markdown.slice(offset, start));
+ let markerEnd = start;
+ while (markdown[markerEnd] === "`") markerEnd += 1;
+ const marker = markdown.slice(start, markerEnd);
+ const end = markdown.indexOf(marker, markerEnd);
+ if (end < 0) return output + markdown.slice(start);
+ output += markdown.slice(start, end + marker.length);
+ offset = end + marker.length;
+ }
+ return output;
+}
+
+/** Remove unsupported markdown while preserving fenced and inline code verbatim. */
+export function filterWechatMarkdown(markdown: string): string {
+ const lines = markdown.match(/[^\n]*\n|[^\n]+$/g) ?? [];
+ let fenced = false;
+ return lines
+ .map((line) => {
+ if (/^\s*```/.test(line)) {
+ fenced = !fenced;
+ return line;
+ }
+ return fenced ? line : filterInlineCodeAware(line);
+ })
+ .join("");
+}
diff --git a/packages/wechat-ilink/src/mediaCrypto.ts b/packages/wechat-ilink/src/mediaCrypto.ts
new file mode 100644
index 0000000000..a5b60cefe8
--- /dev/null
+++ b/packages/wechat-ilink/src/mediaCrypto.ts
@@ -0,0 +1,40 @@
+import { createCipheriv, createDecipheriv } from "node:crypto";
+import { WechatIlinkError } from "./errors.js";
+
+function assertKey(key: Uint8Array): Buffer {
+ if (key.byteLength !== 16) {
+ throw new WechatIlinkError(
+ "PROTOCOL_ERROR",
+ "iLink media key must be 16 bytes.",
+ false,
+ );
+ }
+ return Buffer.from(key);
+}
+
+export function encryptAes128Ecb(
+ plaintext: Uint8Array,
+ key: Uint8Array,
+): Uint8Array {
+ const cipher = createCipheriv("aes-128-ecb", assertKey(key), null);
+ return Buffer.concat([cipher.update(plaintext), cipher.final()]);
+}
+
+export function decryptAes128Ecb(
+ ciphertext: Uint8Array,
+ key: Uint8Array,
+): Uint8Array {
+ const decipher = createDecipheriv("aes-128-ecb", assertKey(key), null);
+ return Buffer.concat([decipher.update(ciphertext), decipher.final()]);
+}
+
+export function aes128EcbPaddedSize(plaintextSize: number): number {
+ if (!Number.isSafeInteger(plaintextSize) || plaintextSize < 0) {
+ throw new WechatIlinkError(
+ "PROTOCOL_ERROR",
+ "Media size must be a safe integer.",
+ false,
+ );
+ }
+ return Math.ceil((plaintextSize + 1) / 16) * 16;
+}
diff --git a/packages/wechat-ilink/src/mediaTransfer.ts b/packages/wechat-ilink/src/mediaTransfer.ts
new file mode 100644
index 0000000000..0322fd424d
--- /dev/null
+++ b/packages/wechat-ilink/src/mediaTransfer.ts
@@ -0,0 +1,264 @@
+import { createHash, randomBytes } from "node:crypto";
+
+import type { FetchLike } from "./apiClient.js";
+import { WechatIlinkError } from "./errors.js";
+import {
+ aes128EcbPaddedSize,
+ decryptAes128Ecb,
+ encryptAes128Ecb,
+} from "./mediaCrypto.js";
+import type { WechatMediaRef } from "./types.js";
+
+export const WECHAT_MEDIA_MAX_BYTES = 5 * 1024 * 1024;
+const WECHAT_MEDIA_CIPHERTEXT_MAX_BYTES = WECHAT_MEDIA_MAX_BYTES + 16;
+const CDN_FALLBACK_ORIGIN = "https://novac2c.cdn.weixin.qq.com";
+
+function isTencentMediaUrl(url: URL): boolean {
+ return (
+ url.protocol === "https:" &&
+ !url.username &&
+ !url.password &&
+ (url.port === "" || url.port === "443") &&
+ (url.hostname === "weixin.qq.com" ||
+ url.hostname.endsWith(".weixin.qq.com"))
+ );
+}
+
+function requireTencentMediaUrl(raw: string, label: string): URL {
+ let url: URL;
+ try {
+ url = new URL(raw);
+ } catch {
+ throw new WechatIlinkError(
+ "PROTOCOL_ERROR",
+ `${label} is not a valid URL.`,
+ false,
+ );
+ }
+ if (!isTencentMediaUrl(url)) {
+ throw new WechatIlinkError(
+ "PROTOCOL_ERROR",
+ `${label} must be a credential-free Tencent HTTPS URL.`,
+ false,
+ );
+ }
+ return url;
+}
+
+function downloadUrlFor(ref: WechatMediaRef): URL {
+ if (ref.downloadUrl) {
+ return requireTencentMediaUrl(ref.downloadUrl, "iLink media download URL");
+ }
+ if (!ref.encryptedQuery?.trim()) {
+ throw new WechatIlinkError(
+ "PROTOCOL_ERROR",
+ "iLink media omitted its download reference.",
+ false,
+ );
+ }
+ const url = new URL("/c2c/download", CDN_FALLBACK_ORIGIN);
+ url.searchParams.set("encrypted_query_param", ref.encryptedQuery);
+ return url;
+}
+
+function parseAesKey(ref: WechatMediaRef): Buffer {
+ if (ref.aesKeyHex && /^[0-9a-fA-F]{32}$/.test(ref.aesKeyHex)) {
+ return Buffer.from(ref.aesKeyHex, "hex");
+ }
+ if (!ref.aesKeyBase64) {
+ throw new WechatIlinkError(
+ "PROTOCOL_ERROR",
+ "iLink media omitted its AES key.",
+ false,
+ );
+ }
+ const decoded = Buffer.from(ref.aesKeyBase64, "base64");
+ if (decoded.byteLength === 16) return decoded;
+ if (
+ decoded.byteLength === 32 &&
+ /^[0-9a-fA-F]{32}$/.test(decoded.toString("ascii"))
+ ) {
+ return Buffer.from(decoded.toString("ascii"), "hex");
+ }
+ throw new WechatIlinkError(
+ "PROTOCOL_ERROR",
+ "iLink media AES key has an invalid encoding.",
+ false,
+ );
+}
+
+async function readBoundedBytes(
+ response: Response,
+ maxBytes: number,
+): Promise<Uint8Array> {
+ const declared = Number(response.headers.get("content-length"));
+ if (Number.isFinite(declared) && declared > maxBytes) {
+ throw new WechatIlinkError(
+ "BAD_RESPONSE",
+ "iLink media exceeded the size limit.",
+ false,
+ );
+ }
+ if (!response.body) return new Uint8Array();
+ const reader = response.body.getReader();
+ const chunks: Uint8Array[] = [];
+ let total = 0;
+ try {
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ total += value.byteLength;
+ if (total > maxBytes) {
+ await reader.cancel();
+ throw new WechatIlinkError(
+ "BAD_RESPONSE",
+ "iLink media exceeded the size limit.",
+ false,
+ );
+ }
+ chunks.push(value);
+ }
+ } finally {
+ reader.releaseLock();
+ }
+ return Buffer.concat(chunks.map((chunk) => Buffer.from(chunk)));
+}
+
+export async function downloadWechatMedia(
+ ref: WechatMediaRef,
+ fetchImpl: FetchLike,
+ signal: AbortSignal,
+): Promise<Uint8Array> {
+ const response = await fetchImpl(downloadUrlFor(ref), {
+ method: "GET",
+ redirect: "manual",
+ signal,
+ });
+ if (!response.ok || response.status < 200 || response.status >= 300) {
+ throw new WechatIlinkError(
+ "HTTP_ERROR",
+ `iLink media download failed with HTTP ${response.status}.`,
+ response.status >= 500,
+ );
+ }
+ const encrypted = await readBoundedBytes(
+ response,
+ WECHAT_MEDIA_CIPHERTEXT_MAX_BYTES,
+ );
+ let plaintext: Uint8Array;
+ try {
+ plaintext = decryptAes128Ecb(encrypted, parseAesKey(ref));
+ } catch (error) {
+ throw new WechatIlinkError(
+ "PROTOCOL_ERROR",
+ "iLink media decryption failed.",
+ false,
+ { cause: error },
+ );
+ }
+ if (
+ plaintext.byteLength === 0 ||
+ plaintext.byteLength > WECHAT_MEDIA_MAX_BYTES ||
+ (ref.kind === "file" &&
+ ref.byteLength !== undefined &&
+ plaintext.byteLength !== ref.byteLength)
+ ) {
+ throw new WechatIlinkError(
+ "PROTOCOL_ERROR",
+ "iLink media plaintext size did not match its metadata.",
+ false,
+ );
+ }
+ if (
+ ref.md5Hex &&
+ createHash("md5").update(plaintext).digest("hex") !==
+ ref.md5Hex.toLowerCase()
+ ) {
+ throw new WechatIlinkError(
+ "PROTOCOL_ERROR",
+ "iLink media checksum did not match its metadata.",
+ false,
+ );
+ }
+ return plaintext;
+}
+
+export interface PreparedWechatUpload {
+ aesKey: Buffer;
+ aesKeyHex: string;
+ ciphertext: Uint8Array;
+ fileKey: string;
+ md5Hex: string;
+}
+
+export function prepareWechatUpload(bytes: Uint8Array): PreparedWechatUpload {
+ if (bytes.byteLength === 0 || bytes.byteLength > WECHAT_MEDIA_MAX_BYTES) {
+ throw new WechatIlinkError(
+ "PROTOCOL_ERROR",
+ "WeChat outbound media must be between 1 byte and 5 MB.",
+ false,
+ );
+ }
+ const aesKey = randomBytes(16);
+ return {
+ aesKey,
+ aesKeyHex: aesKey.toString("hex"),
+ ciphertext: encryptAes128Ecb(bytes, aesKey),
+ fileKey: randomBytes(16).toString("hex"),
+ md5Hex: createHash("md5").update(bytes).digest("hex"),
+ };
+}
+
+export function expectedWechatCiphertextSize(bytes: number): number {
+ return aes128EcbPaddedSize(bytes);
+}
+
+export async function uploadWechatCiphertext(
+ args: {
+ uploadFullUrl?: string;
+ uploadParam?: string;
+ fileKey: string;
+ ciphertext: Uint8Array;
+ },
+ fetchImpl: FetchLike,
+ signal: AbortSignal,
+): Promise<string> {
+ const rawUrl = args.uploadFullUrl?.trim();
+ let url: URL;
+ if (rawUrl) {
+ url = requireTencentMediaUrl(rawUrl, "iLink media upload URL");
+ } else if (args.uploadParam?.trim()) {
+ url = new URL("/c2c/upload", CDN_FALLBACK_ORIGIN);
+ url.searchParams.set("encrypted_query_param", args.uploadParam);
+ url.searchParams.set("filekey", args.fileKey);
+ } else {
+ throw new WechatIlinkError(
+ "BAD_RESPONSE",
+ "iLink omitted its media upload URL.",
+ true,
+ );
+ }
+ const response = await fetchImpl(url, {
+ method: "POST",
+ headers: { "Content-Type": "application/octet-stream" },
+ body: Buffer.from(args.ciphertext),
+ redirect: "manual",
+ signal,
+ });
+ if (!response.ok || response.status !== 200) {
+ throw new WechatIlinkError(
+ "HTTP_ERROR",
+ `iLink media upload failed with HTTP ${response.status}.`,
+ response.status >= 500,
+ );
+ }
+ const downloadParam = response.headers.get("x-encrypted-param")?.trim();
+ if (!downloadParam) {
+ throw new WechatIlinkError(
+ "BAD_RESPONSE",
+ "iLink media upload omitted x-encrypted-param.",
+ true,
+ );
+ }
+ return downloadParam;
+}
diff --git a/packages/wechat-ilink/src/transport.ts b/packages/wechat-ilink/src/transport.ts
new file mode 100644
index 0000000000..f5dcaf2337
--- /dev/null
+++ b/packages/wechat-ilink/src/transport.ts
@@ -0,0 +1,271 @@
+import { IlinkApiClient, type IlinkApiClientOptions } from "./apiClient.js";
+import { IlinkAuthorization } from "./auth.js";
+import { decodeInboundMessage } from "./codec.js";
+import { WechatIlinkError } from "./errors.js";
+import type {
+ WechatAuthChallenge,
+ WechatAuthorizationObserver,
+ WechatCredentials,
+ WechatMediaRef,
+ WechatPollResult,
+ WechatSendMediaRequest,
+ WechatSendRequest,
+ WechatSendResult,
+ WechatUploadedMedia,
+ WechatUploadRequest,
+} from "./types.js";
+import {
+ downloadWechatMedia,
+ expectedWechatCiphertextSize,
+ prepareWechatUpload,
+ uploadWechatCiphertext,
+} from "./mediaTransfer.js";
+
+export interface WechatTransport {
+ beginAuthorization(signal: AbortSignal): Promise<WechatAuthChallenge>;
+ waitAuthorization(
+ challenge: WechatAuthChallenge,
+ signal: AbortSignal,
+ ): Promise<WechatCredentials>;
+ notifyStart(signal: AbortSignal): Promise<void>;
+ notifyStop(signal: AbortSignal): Promise<void>;
+ poll(cursor: string, signal: AbortSignal): Promise<WechatPollResult>;
+ sendMessage(
+ request: WechatSendRequest,
+ signal: AbortSignal,
+ ): Promise<WechatSendResult>;
+ getTypingTicket(
+ peerId: string,
+ contextToken: string,
+ signal: AbortSignal,
+ ): Promise<string>;
+ setTyping(
+ peerId: string,
+ ticket: string,
+ active: boolean,
+ signal: AbortSignal,
+ ): Promise<void>;
+ downloadMedia(ref: WechatMediaRef, signal: AbortSignal): Promise<Uint8Array>;
+ uploadMedia(
+ request: WechatUploadRequest,
+ signal: AbortSignal,
+ ): Promise<WechatUploadedMedia>;
+ sendMedia(
+ request: WechatSendMediaRequest,
+ signal: AbortSignal,
+ ): Promise<WechatSendResult>;
+}
+
+export interface TencentIlinkTransportOptions extends IlinkApiClientOptions {
+ localTokens?: () => Promise<string[]>;
+ authorizationObserver?: WechatAuthorizationObserver;
+}
+
+/** Default pure transport; the Desktop host owns all persistence and lifecycle. */
+export class TencentIlinkTransport implements WechatTransport {
+ private readonly api: IlinkApiClient;
+ private readonly authorization: IlinkAuthorization;
+
+ constructor(private readonly options: TencentIlinkTransportOptions) {
+ this.api = new IlinkApiClient(options);
+ this.authorization = new IlinkAuthorization(
+ this.api,
+ options.authorizationObserver,
+ );
+ }
+
+ beginAuthorization(signal: AbortSignal): Promise<WechatAuthChallenge> {
+ return Promise.resolve(this.options.localTokens?.() ?? []).then((tokens) =>
+ this.authorization.begin(tokens, signal),
+ );
+ }
+
+ waitAuthorization(
+ challenge: WechatAuthChallenge,
+ signal: AbortSignal,
+ ): Promise<WechatCredentials> {
+ return this.authorization.wait(challenge, signal);
+ }
+
+ async notifyStart(signal: AbortSignal): Promise<void> {
+ this.assertLifecycleResponse(await this.api.notifyStart(signal), "start");
+ }
+
+ async notifyStop(signal: AbortSignal): Promise<void> {
+ this.assertLifecycleResponse(await this.api.notifyStop(signal), "stop");
+ }
+
+ async poll(cursor: string, signal: AbortSignal): Promise<WechatPollResult> {
+ const response = await this.api.getUpdates(cursor, signal);
+ if (response.ret !== undefined && typeof response.ret !== "number") {
+ throw new WechatIlinkError(
+ "BAD_RESPONSE",
+ "iLink returned an invalid poll status.",
+ true,
+ );
+ }
+ if (
+ response.errcode !== undefined &&
+ typeof response.errcode !== "number"
+ ) {
+ throw new WechatIlinkError(
+ "BAD_RESPONSE",
+ "iLink returned an invalid poll error code.",
+ true,
+ );
+ }
+ const ret = typeof response.ret === "number" ? response.ret : 0;
+ if (response.errcode === -14) {
+ throw new WechatIlinkError(
+ "AUTH_REPLACED",
+ "The iLink credential is no longer active.",
+ false,
+ );
+ }
+ if (ret !== 0) {
+ throw new WechatIlinkError(
+ "PROTOCOL_ERROR",
+ "iLink rejected the poll request.",
+ true,
+ );
+ }
+ const messages = this.api
+ .messagesFrom(response)
+ .map(decodeInboundMessage)
+ .filter((message) => message !== null);
+ return {
+ cursor:
+ typeof response.get_updates_buf === "string"
+ ? response.get_updates_buf
+ : cursor,
+ messages,
+ suggestedTimeoutMs:
+ typeof response.longpolling_timeout_ms === "number"
+ ? response.longpolling_timeout_ms
+ : undefined,
+ };
+ }
+
+ async sendMessage(
+ request: WechatSendRequest,
+ signal: AbortSignal,
+ ): Promise<WechatSendResult> {
+ await this.api.sendText(request, signal);
+ return { clientId: request.clientId };
+ }
+
+ async getTypingTicket(
+ peerId: string,
+ contextToken: string,
+ signal: AbortSignal,
+ ): Promise<string> {
+ const response = await this.api.getConfig(peerId, contextToken, signal);
+ if (typeof response.ret === "number" && response.ret !== 0) {
+ throw new WechatIlinkError(
+ "PROTOCOL_ERROR",
+ "iLink rejected the typing configuration request.",
+ true,
+ );
+ }
+ if (typeof response.typing_ticket !== "string" || !response.typing_ticket) {
+ throw new WechatIlinkError(
+ "BAD_RESPONSE",
+ "iLink omitted typing_ticket.",
+ true,
+ );
+ }
+ return response.typing_ticket;
+ }
+
+ setTyping(
+ peerId: string,
+ ticket: string,
+ active: boolean,
+ signal: AbortSignal,
+ ): Promise<void> {
+ return this.api.setTyping(peerId, ticket, active, signal);
+ }
+
+ downloadMedia(ref: WechatMediaRef, signal: AbortSignal): Promise<Uint8Array> {
+ return downloadWechatMedia(ref, this.options.fetch, signal);
+ }
+
+ async uploadMedia(
+ request: WechatUploadRequest,
+ signal: AbortSignal,
+ ): Promise<WechatUploadedMedia> {
+ if (request.kind === "voice") {
+ throw new WechatIlinkError(
+ "PROTOCOL_ERROR",
+ "Outbound voice messages are not supported.",
+ false,
+ );
+ }
+ const prepared = prepareWechatUpload(request.bytes);
+ const mediaType =
+ request.kind === "image" ? 1 : request.kind === "video" ? 2 : 3;
+ const upload = await this.api.getUploadUrl(
+ {
+ peerId: request.peerId,
+ fileKey: prepared.fileKey,
+ mediaType,
+ rawSize: request.bytes.byteLength,
+ rawMd5: prepared.md5Hex,
+ encryptedSize: expectedWechatCiphertextSize(request.bytes.byteLength),
+ aesKeyHex: prepared.aesKeyHex,
+ },
+ signal,
+ );
+ const encryptedQuery = await uploadWechatCiphertext(
+ {
+ uploadFullUrl: upload.uploadFullUrl,
+ uploadParam: upload.uploadParam,
+ fileKey: prepared.fileKey,
+ ciphertext: prepared.ciphertext,
+ },
+ this.options.fetch,
+ signal,
+ );
+ return {
+ fileName: request.fileName,
+ ref: {
+ kind: request.kind,
+ encryptedQuery,
+ // iLink's sendmessage media.aes_key uses base64(hex-text), matching
+ // the official WorkBuddy client. The upload request above still uses
+ // the raw AES key as a hex string.
+ aesKeyBase64: Buffer.from(prepared.aesKeyHex).toString("base64"),
+ byteLength: request.bytes.byteLength,
+ encryptedByteLength: prepared.ciphertext.byteLength,
+ },
+ };
+ }
+
+ async sendMedia(
+ request: WechatSendMediaRequest,
+ signal: AbortSignal,
+ ): Promise<WechatSendResult> {
+ await this.api.sendMedia(request, signal);
+ return { clientId: request.clientId };
+ }
+
+ private assertLifecycleResponse(
+ response: Record<string, unknown>,
+ operation: "start" | "stop",
+ ): void {
+ if (response.ret !== undefined && typeof response.ret !== "number") {
+ throw new WechatIlinkError(
+ "BAD_RESPONSE",
+ `iLink returned an invalid ${operation} notification status.`,
+ true,
+ );
+ }
+ if (typeof response.ret === "number" && response.ret !== 0) {
+ throw new WechatIlinkError(
+ "PROTOCOL_ERROR",
+ `iLink rejected the ${operation} notification.`,
+ true,
+ );
+ }
+ }
+}
diff --git a/packages/wechat-ilink/src/types.ts b/packages/wechat-ilink/src/types.ts
new file mode 100644
index 0000000000..2d19a99f71
--- /dev/null
+++ b/packages/wechat-ilink/src/types.ts
@@ -0,0 +1,163 @@
+/** Raw iLink wire constants mirrored from Tencent's public client. */
+export const MessageType = { NONE: 0, USER: 1, BOT: 2 } as const;
+export const MessageState = { NEW: 0, GENERATING: 1, FINISH: 2 } as const;
+export const MessageItemType = {
+ NONE: 0,
+ TEXT: 1,
+ IMAGE: 2,
+ VOICE: 3,
+ FILE: 4,
+ VIDEO: 5,
+} as const;
+export const TypingStatus = { TYPING: 1, CANCEL: 2 } as const;
+
+export interface IlinkCdnMedia {
+ encrypt_query_param?: string;
+ aes_key?: string;
+ encrypt_type?: number;
+ full_url?: string;
+}
+
+export interface IlinkMessageItem {
+ type?: number;
+ msg_id?: string;
+ ref_msg?: {
+ title?: string;
+ message_item?: IlinkMessageItem;
+ };
+ text_item?: { text?: string };
+ image_item?: {
+ media?: IlinkCdnMedia;
+ aeskey?: string;
+ mid_size?: number;
+ };
+ voice_item?: {
+ media?: IlinkCdnMedia;
+ encode_type?: number;
+ text?: string;
+ playtime?: number;
+ };
+ file_item?: {
+ media?: IlinkCdnMedia;
+ file_name?: string;
+ len?: string;
+ md5?: string;
+ };
+ video_item?: {
+ media?: IlinkCdnMedia;
+ video_size?: number;
+ play_length?: number;
+ };
+}
+
+export interface IlinkMessage {
+ seq?: number;
+ message_id?: number | string;
+ from_user_id?: string;
+ to_user_id?: string;
+ client_id?: string;
+ create_time_ms?: number;
+ message_type?: number;
+ message_state?: number;
+ item_list?: IlinkMessageItem[];
+ context_token?: string;
+ run_id?: string;
+}
+
+export interface WechatAuthChallenge {
+ id: string;
+ qrCodeUrl: string;
+ createdAt: number;
+}
+
+export interface WechatCredentials {
+ token: string;
+ botId: string;
+ userId: string;
+ baseUrl: string;
+}
+
+export type WechatAuthorizationEvent =
+ | { status: "waiting" | "scanned" }
+ | { status: "verification-required"; retry: boolean }
+ | { status: "qr-refreshed"; challenge: WechatAuthChallenge };
+
+export interface WechatAuthorizationObserver {
+ onEvent?(event: WechatAuthorizationEvent): void | Promise<void>;
+ requestVerificationCode?(
+ retry: boolean,
+ signal: AbortSignal,
+ ): Promise<string>;
+}
+
+export interface WechatMediaRef {
+ kind: "image" | "voice" | "file" | "video";
+ downloadUrl?: string;
+ encryptedQuery?: string;
+ aesKeyBase64?: string;
+ aesKeyHex?: string;
+ fileName?: string;
+ /** Plaintext byte length when the wire format exposes it. */
+ byteLength?: number;
+ /** AES-padded ciphertext byte length used by image/video send payloads. */
+ encryptedByteLength?: number;
+ voiceEncoding?: number;
+ transcript?: string;
+ md5Hex?: string;
+}
+
+export interface WechatQuote {
+ title?: string;
+ text?: string;
+ media: WechatMediaRef[];
+}
+
+export interface WechatInboundMessage {
+ messageId: string;
+ senderId: string;
+ recipientId?: string;
+ clientId?: string;
+ createdAt?: number;
+ contextToken: string;
+ text: string;
+ media: WechatMediaRef[];
+ quote?: WechatQuote;
+}
+
+export interface WechatPollResult {
+ cursor: string;
+ messages: WechatInboundMessage[];
+ suggestedTimeoutMs?: number;
+}
+
+export interface WechatSendRequest {
+ peerId: string;
+ text: string;
+ contextToken: string;
+ clientId: string;
+ runId?: string;
+}
+
+export interface WechatSendResult {
+ clientId: string;
+}
+
+export interface WechatUploadRequest {
+ peerId: string;
+ bytes: Uint8Array;
+ fileName: string;
+ kind: WechatMediaRef["kind"];
+}
+
+export interface WechatUploadedMedia {
+ ref: WechatMediaRef;
+ fileName: string;
+}
+
+export interface WechatSendMediaRequest {
+ peerId: string;
+ contextToken: string;
+ clientId: string;
+ uploaded: WechatUploadedMedia;
+ runId?: string;
+}
diff --git a/packages/wechat-ilink/tsconfig.json b/packages/wechat-ilink/tsconfig.json
new file mode 100644
index 0000000000..d7c3bc9124
--- /dev/null
+++ b/packages/wechat-ilink/tsconfig.json
@@ -0,0 +1,16 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "ESNext",
+ "moduleResolution": "Bundler",
+ "strict": true,
+ "esModuleInterop": true,
+ "skipLibCheck": true,
+ "forceConsistentCasingInFileNames": true,
+ "isolatedModules": true,
+ "noEmit": true,
+ "lib": ["ES2022", "DOM"],
+ "types": ["node"]
+ },
+ "include": ["src/**/*"]
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index f861723e41..20b9bb076f 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -116,6 +116,9 @@ importers:
'@cindy/voice-input-core':
specifier: workspace:*
version: link:../../packages/voice-input-core
+ '@cindy/wechat-ilink':
+ specifier: workspace:*
+ version: link:../../packages/wechat-ilink
'@codemirror/commands':
specifier: ^6.10.3
version: 6.10.4
@@ -371,6 +374,9 @@ importers:
sharp:
specifier: ^0.35.0
version: 0.35.3(@types/[email protected])
+ silk-wasm:
+ specifier: ^3.7.1
+ version: 3.7.1
smol-toml:
specifier: ^1.6.1
version: 1.7.0
@@ -1314,6 +1320,18 @@ importers:
specifier: ^3.2.4
+ packages/wechat-ilink:
+ devDependencies:
+ '@types/node':
+ specifier: '*'
+ version: 25.9.5
+ typescript:
+ specifier: ^5.7.0
+ version: 5.9.3
+ vitest:
+ specifier: ^3.2.4
+
packages:
@@ -9370,6 +9388,10 @@ packages:
resolution: {integrity: sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==}
engines: {node: '>=14'}
+ resolution: {integrity: sha512-mXPwLRtZxrYV3TZx41jMAeKc80wvmyrcXIcs8HctFxK15Ahz2OJQENYhNgEPeCEOdI6Mbx1NxQsqxzwc3DKerw==}
+ engines: {node: '>=16.11.0'}
+
resolution: {integrity: sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==}
@@ -13694,7 +13716,9 @@ snapshots:
metro-runtime: 0.84.4
transitivePeerDependencies:
- '@babel/core'
+ - bufferutil
- supports-color
+ - utf-8-validate
'@react-native/[email protected]': {}
@@ -14162,7 +14186,7 @@ snapshots:
dependencies:
- '@types/node': 22.20.1
+ '@types/node': 25.9.5
dependencies:
@@ -20083,6 +20107,8 @@ snapshots:
+
diff --git a/scripts/generate-third-party-notices.mjs b/scripts/generate-third-party-notices.mjs
index bf1f969872..078581605f 100644
--- a/scripts/generate-third-party-notices.mjs
+++ b/scripts/generate-third-party-notices.mjs
@@ -793,6 +793,20 @@ function buildDesktopCommonEntries(apacheText, sharpPackageNames) {
}),
);
+ // Tencent's public iLink client is the pinned protocol reference for the
+ // Cindy-owned, host-agnostic implementation under packages/wechat-ilink.
+ entries.push(
+ bundledComponent({
+ name: "Tencent openclaw-weixin protocol sources (adapted)",
+ version: "2.4.6",
+ license: "MIT",
+ url: "https://github.com/Tencent/openclaw-weixin/tree/v2.4.6",
+ licenseText: readBundledLicense(
+ "packages/wechat-ilink/LICENSE.tencent-openclaw-weixin",
+ ),
+ }),
+ );
+
// ProviderLogoMark / MobileProviderMark 共享的上游 SVG path,桌面与移动端均随包分发。
entries.push(...buildProviderBrandingEntries());
diff --git a/scripts/test-workspaces.config.mjs b/scripts/test-workspaces.config.mjs
index 5956973514..8021cc112c 100644
--- a/scripts/test-workspaces.config.mjs
+++ b/scripts/test-workspaces.config.mjs
@@ -173,6 +173,7 @@ export default {
noCollectableWorkspace('project-context', 'packages/project-context'),
requiredUnitWorkspace('@cindy/remote-file-service', 'packages/remote-file-service'),
requiredUnitWorkspace('@cindy/voice-input-core', 'packages/voice-input-core'),
+ requiredUnitWorkspace('@cindy/wechat-ilink', 'packages/wechat-ilink'),
noCollectableWorkspace('@cindy/device-link-protocol', 'cindy-protocol/packages/device-link-protocol'),
requiredUnitWorkspace('@cindy/plugin-protocol', 'cindy-protocol/packages/plugin-protocol'),
requiredUnitWorkspace('@cindy/skill-protocol', 'cindy-protocol/packages/skill-protocol'),