Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): 远程 Agent——Agent 在同账号另一台电脑运行,任务与文件留在本机
Lizid7b3de5d1e3f
diff --git a/apps/desktop/drizzle/0123_wonderful_oracle.sql b/apps/desktop/drizzle/0123_wonderful_oracle.sqlnew file mode 100644index 0000000000..3aec20111e--- /dev/null+++ b/apps/desktop/drizzle/0123_wonderful_oracle.sql@@ -0,0 +1 @@+ALTER TABLE `sessions` ADD `agent_device_id` text;\ No newline at end of filediff --git a/apps/desktop/drizzle/meta/0123_snapshot.json b/apps/desktop/drizzle/meta/0123_snapshot.jsonnew file mode 100644index 0000000000..84666af0e0--- /dev/null+++ b/apps/desktop/drizzle/meta/0123_snapshot.json@@ -0,0 +1,6850 @@+{+ "version": "6",+ "dialect": "sqlite",+ "id": "d06b22f6-84f0-4f67-b5ab-0f13f2e21a2a",+ "prevId": "caa7f32c-7494-48d9-a5cb-aa88d267b9bd",+ "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": {}+ },+ "auto_review_projections": {+ "name": "auto_review_projections",+ "columns": {+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "lead_id": {+ "name": "lead_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "revision": {+ "name": "revision",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "projected_revision": {+ "name": "projected_revision",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": -1+ },+ "version": {+ "name": "version",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 1+ },+ "payload": {+ "name": "payload",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "auto_review_projections_lead_idx": {+ "name": "auto_review_projections_lead_idx",+ "columns": [+ "lead_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "auto_review_projections_session_id_sessions_id_fk": {+ "name": "auto_review_projections_session_id_sessions_id_fk",+ "tableFrom": "auto_review_projections",+ "tableTo": "sessions",+ "columnsFrom": [+ "session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "auto_review_projections_lead_id_sessions_id_fk": {+ "name": "auto_review_projections_lead_id_sessions_id_fk",+ "tableFrom": "auto_review_projections",+ "tableTo": "sessions",+ "columnsFrom": [+ "lead_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "auto_review_projections_session_id_lead_id_pk": {+ "columns": [+ "session_id",+ "lead_id"+ ],+ "name": "auto_review_projections_session_id_lead_id_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "bot_delegations": {+ "name": "bot_delegations",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "requesting_bot_id": {+ "name": "requesting_bot_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "target_bot_id": {+ "name": "target_bot_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "parent_session_id": {+ "name": "parent_session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "child_session_id": {+ "name": "child_session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "objective": {+ "name": "objective",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "context_refs_json": {+ "name": "context_refs_json",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'[]'"+ },+ "artifact_refs_json": {+ "name": "artifact_refs_json",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'[]'"+ },+ "permission_snapshot_json": {+ "name": "permission_snapshot_json",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'{}'"+ },+ "lineage_json": {+ "name": "lineage_json",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'[]'"+ },+ "target_profile_version": {+ "name": "target_profile_version",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "depth": {+ "name": "depth",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 1+ },+ "budget_tokens": {+ "name": "budget_tokens",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "tokens_used": {+ "name": "tokens_used",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'queued'"+ },+ "result_summary": {+ "name": "result_summary",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "output_artifacts_json": {+ "name": "output_artifacts_json",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'[]'"+ },+ "pending_interaction_json": {+ "name": "pending_interaction_json",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_error": {+ "name": "last_error",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "run_sequence": {+ "name": "run_sequence",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 1+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "accepted_at": {+ "name": "accepted_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "completed_at": {+ "name": "completed_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "completion_delivered_at": {+ "name": "completion_delivered_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_bot_delegations_requester_status": {+ "name": "idx_bot_delegations_requester_status",+ "columns": [+ "requesting_bot_id",+ "status"+ ],+ "isUnique": false+ },+ "idx_bot_delegations_target_status": {+ "name": "idx_bot_delegations_target_status",+ "columns": [+ "target_bot_id",+ "status"+ ],+ "isUnique": false+ },+ "idx_bot_delegations_parent_session": {+ "name": "idx_bot_delegations_parent_session",+ "columns": [+ "parent_session_id"+ ],+ "isUnique": false+ },+ "uniq_bot_delegations_child_session": {+ "name": "uniq_bot_delegations_child_session",+ "columns": [+ "child_session_id"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "bot_delegations_requesting_bot_id_bot_profiles_id_fk": {+ "name": "bot_delegations_requesting_bot_id_bot_profiles_id_fk",+ "tableFrom": "bot_delegations",+ "tableTo": "bot_profiles",+ "columnsFrom": [+ "requesting_bot_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "bot_delegations_target_bot_id_bot_profiles_id_fk": {+ "name": "bot_delegations_target_bot_id_bot_profiles_id_fk",+ "tableFrom": "bot_delegations",+ "tableTo": "bot_profiles",+ "columnsFrom": [+ "target_bot_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "bot_delegations_parent_session_id_sessions_id_fk": {+ "name": "bot_delegations_parent_session_id_sessions_id_fk",+ "tableFrom": "bot_delegations",+ "tableTo": "sessions",+ "columnsFrom": [+ "parent_session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "bot_delegations_child_session_id_sessions_id_fk": {+ "name": "bot_delegations_child_session_id_sessions_id_fk",+ "tableFrom": "bot_delegations",+ "tableTo": "sessions",+ "columnsFrom": [+ "child_session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "bot_direct_message_threads": {+ "name": "bot_direct_message_threads",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "bot_a_id": {+ "name": "bot_a_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "bot_b_id": {+ "name": "bot_b_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'active'"+ },+ "close_reason": {+ "name": "close_reason",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "message_count": {+ "name": "message_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "max_messages": {+ "name": "max_messages",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "blocked_until": {+ "name": "blocked_until",+ "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+ },+ "closed_at": {+ "name": "closed_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "uniq_bot_dm_threads_active_pair": {+ "name": "uniq_bot_dm_threads_active_pair",+ "columns": [+ "bot_a_id",+ "bot_b_id"+ ],+ "isUnique": true,+ "where": "\"bot_direct_message_threads\".\"status\" = 'active'"+ },+ "idx_bot_dm_threads_pair_updated": {+ "name": "idx_bot_dm_threads_pair_updated",+ "columns": [+ "bot_a_id",+ "bot_b_id",+ "updated_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "bot_direct_messages": {+ "name": "bot_direct_messages",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "thread_id": {+ "name": "thread_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "sequence": {+ "name": "sequence",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "sender_bot_id": {+ "name": "sender_bot_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "recipient_bot_id": {+ "name": "recipient_bot_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "sender_session_id": {+ "name": "sender_session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "recipient_session_id": {+ "name": "recipient_session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "delivery_status": {+ "name": "delivery_status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'pending'"+ },+ "sender_name": {+ "name": "sender_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "recipient_name": {+ "name": "recipient_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "bridge_session_id": {+ "name": "bridge_session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "uniq_bot_direct_messages_thread_sequence": {+ "name": "uniq_bot_direct_messages_thread_sequence",+ "columns": [+ "thread_id",+ "sequence"+ ],+ "isUnique": true+ },+ "idx_bot_direct_messages_thread_created": {+ "name": "idx_bot_direct_messages_thread_created",+ "columns": [+ "thread_id",+ "created_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "bot_direct_messages_thread_id_bot_direct_message_threads_id_fk": {+ "name": "bot_direct_messages_thread_id_bot_direct_message_threads_id_fk",+ "tableFrom": "bot_direct_messages",+ "tableTo": "bot_direct_message_threads",+ "columnsFrom": [+ "thread_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "bot_direct_messages_sender_session_id_sessions_id_fk": {+ "name": "bot_direct_messages_sender_session_id_sessions_id_fk",+ "tableFrom": "bot_direct_messages",+ "tableTo": "sessions",+ "columnsFrom": [+ "sender_session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "bot_direct_messages_recipient_session_id_sessions_id_fk": {+ "name": "bot_direct_messages_recipient_session_id_sessions_id_fk",+ "tableFrom": "bot_direct_messages",+ "tableTo": "sessions",+ "columnsFrom": [+ "recipient_session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "bot_group_members": {+ "name": "bot_group_members",+ "columns": {+ "group_id": {+ "name": "group_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "bot_id": {+ "name": "bot_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "last_seen_sequence": {+ "name": "last_seen_sequence",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "joined_at": {+ "name": "joined_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_bot_group_members_bot": {+ "name": "idx_bot_group_members_bot",+ "columns": [+ "bot_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "bot_group_members_group_id_bot_groups_id_fk": {+ "name": "bot_group_members_group_id_bot_groups_id_fk",+ "tableFrom": "bot_group_members",+ "tableTo": "bot_groups",+ "columnsFrom": [+ "group_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "bot_group_members_bot_id_bot_profiles_id_fk": {+ "name": "bot_group_members_bot_id_bot_profiles_id_fk",+ "tableFrom": "bot_group_members",+ "tableTo": "bot_profiles",+ "columnsFrom": [+ "bot_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "bot_group_members_group_id_bot_id_pk": {+ "columns": [+ "group_id",+ "bot_id"+ ],+ "name": "bot_group_members_group_id_bot_id_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "bot_group_messages": {+ "name": "bot_group_messages",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "group_id": {+ "name": "group_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "sequence": {+ "name": "sequence",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'message'"+ },+ "author_kind": {+ "name": "author_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "author_bot_id": {+ "name": "author_bot_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "author_name": {+ "name": "author_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ },+ "mentions_json": {+ "name": "mentions_json",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'{\"all\":false,\"botIds\":[]}'"+ },+ "notice_code": {+ "name": "notice_code",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "client_id": {+ "name": "client_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "plan_id": {+ "name": "plan_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "files_json": {+ "name": "files_json",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'[]'"+ },+ "attachments_json": {+ "name": "attachments_json",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'[]'"+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "uniq_bot_group_messages_group_sequence": {+ "name": "uniq_bot_group_messages_group_sequence",+ "columns": [+ "group_id",+ "sequence"+ ],+ "isUnique": true+ },+ "uniq_bot_group_messages_group_client": {+ "name": "uniq_bot_group_messages_group_client",+ "columns": [+ "group_id",+ "client_id"+ ],+ "isUnique": true,+ "where": "\"bot_group_messages\".\"client_id\" IS NOT NULL"+ }+ },+ "foreignKeys": {+ "bot_group_messages_group_id_bot_groups_id_fk": {+ "name": "bot_group_messages_group_id_bot_groups_id_fk",+ "tableFrom": "bot_group_messages",+ "tableTo": "bot_groups",+ "columnsFrom": [+ "group_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "bot_group_plan_steps": {+ "name": "bot_group_plan_steps",+ "columns": {+ "plan_id": {+ "name": "plan_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "bot_id": {+ "name": "bot_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "bot_name": {+ "name": "bot_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "task": {+ "name": "task",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'pending'"+ },+ "result_message_id": {+ "name": "result_message_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "started_at": {+ "name": "started_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "finished_at": {+ "name": "finished_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "bot_group_plan_steps_plan_id_bot_group_plans_id_fk": {+ "name": "bot_group_plan_steps_plan_id_bot_group_plans_id_fk",+ "tableFrom": "bot_group_plan_steps",+ "tableTo": "bot_group_plans",+ "columnsFrom": [+ "plan_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "bot_group_plan_steps_plan_id_position_pk": {+ "columns": [+ "plan_id",+ "position"+ ],+ "name": "bot_group_plan_steps_plan_id_position_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "bot_group_plans": {+ "name": "bot_group_plans",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "group_id": {+ "name": "group_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "request_text": {+ "name": "request_text",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "attachments_json": {+ "name": "attachments_json",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'[]'"+ },+ "organizer_bot_id": {+ "name": "organizer_bot_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "organizer_name": {+ "name": "organizer_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "current_step": {+ "name": "current_step",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "work_dir": {+ "name": "work_dir",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "branch": {+ "name": "branch",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_bot_group_plans_group_created": {+ "name": "idx_bot_group_plans_group_created",+ "columns": [+ "group_id",+ "created_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "bot_group_plans_group_id_bot_groups_id_fk": {+ "name": "bot_group_plans_group_id_bot_groups_id_fk",+ "tableFrom": "bot_group_plans",+ "tableTo": "bot_groups",+ "columnsFrom": [+ "group_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "bot_groups": {+ "name": "bot_groups",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "reply_mode": {+ "name": "reply_mode",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'all'"+ },+ "speaking_mode": {+ "name": "speaking_mode",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'auto'"+ },+ "organizer_bot_id": {+ "name": "organizer_bot_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "project_dir": {+ "name": "project_dir",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_bot_groups_updated": {+ "name": "idx_bot_groups_updated",+ "columns": [+ "updated_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "bot_lifecycle_events": {+ "name": "bot_lifecycle_events",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "bot_id": {+ "name": "bot_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "event_type": {+ "name": "event_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "payload_json": {+ "name": "payload_json",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'{}'"+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_bot_lifecycle_events_bot_created": {+ "name": "idx_bot_lifecycle_events_bot_created",+ "columns": [+ "bot_id",+ "created_at"+ ],+ "isUnique": false+ },+ "idx_bot_lifecycle_events_session_created": {+ "name": "idx_bot_lifecycle_events_session_created",+ "columns": [+ "session_id",+ "created_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "bot_lifecycle_events_bot_id_bot_profiles_id_fk": {+ "name": "bot_lifecycle_events_bot_id_bot_profiles_id_fk",+ "tableFrom": "bot_lifecycle_events",+ "tableTo": "bot_profiles",+ "columnsFrom": [+ "bot_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "bot_lifecycle_events_session_id_sessions_id_fk": {+ "name": "bot_lifecycle_events_session_id_sessions_id_fk",+ "tableFrom": "bot_lifecycle_events",+ "tableTo": "sessions",+ "columnsFrom": [+ "session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "bot_profile_versions": {+ "name": "bot_profile_versions",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "bot_id": {+ "name": "bot_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "version": {+ "name": "version",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "identity_source": {+ "name": "identity_source",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ },+ "capabilities_json": {+ "name": "capabilities_json",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'{}'"+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "uniq_bot_profile_versions_bot_version": {+ "name": "uniq_bot_profile_versions_bot_version",+ "columns": [+ "bot_id",+ "version"+ ],+ "isUnique": true+ },+ "idx_bot_profile_versions_bot_created": {+ "name": "idx_bot_profile_versions_bot_created",+ "columns": [+ "bot_id",+ "created_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "bot_profile_versions_bot_id_bot_profiles_id_fk": {+ "name": "bot_profile_versions_bot_id_bot_profiles_id_fk",+ "tableFrom": "bot_profile_versions",+ "tableTo": "bot_profiles",+ "columnsFrom": [+ "bot_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "bot_profiles": {+ "name": "bot_profiles",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "display_name": {+ "name": "display_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ },+ "avatar": {+ "name": "avatar",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'🤖'"+ },+ "avatar_color": {+ "name": "avatar_color",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'violet'"+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'active'"+ },+ "hidden_at": {+ "name": "hidden_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "pinned_at": {+ "name": "pinned_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "attention_reason": {+ "name": "attention_reason",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "attention_at": {+ "name": "attention_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "current_version": {+ "name": "current_version",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 1+ },+ "canonical_session_id": {+ "name": "canonical_session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_bot_profiles_status_updated": {+ "name": "idx_bot_profiles_status_updated",+ "columns": [+ "status",+ "updated_at"+ ],+ "isUnique": false+ },+ "idx_bot_profiles_canonical_session": {+ "name": "idx_bot_profiles_canonical_session",+ "columns": [+ "canonical_session_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "bot_profiles_canonical_session_id_sessions_id_fk": {+ "name": "bot_profiles_canonical_session_id_sessions_id_fk",+ "tableFrom": "bot_profiles",+ "tableTo": "sessions",+ "columnsFrom": [+ "canonical_session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "bot_runtime_snapshots": {+ "name": "bot_runtime_snapshots",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "bot_id": {+ "name": "bot_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "profile_version": {+ "name": "profile_version",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "agent_kind": {+ "name": "agent_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "working_dir": {+ "name": "working_dir",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "memory_scope_key": {+ "name": "memory_scope_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "configured_json": {+ "name": "configured_json",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'{}'"+ },+ "resolved_json": {+ "name": "resolved_json",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'{}'"+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "prepared_at": {+ "name": "prepared_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "applied_at": {+ "name": "applied_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "failed_at": {+ "name": "failed_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "failure_json": {+ "name": "failure_json",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_bot_runtime_snapshots_bot_prepared": {+ "name": "idx_bot_runtime_snapshots_bot_prepared",+ "columns": [+ "bot_id",+ "prepared_at"+ ],+ "isUnique": false+ },+ "idx_bot_runtime_snapshots_session_prepared": {+ "name": "idx_bot_runtime_snapshots_session_prepared",+ "columns": [+ "session_id",+ "prepared_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "bot_runtime_snapshots_bot_id_bot_profiles_id_fk": {+ "name": "bot_runtime_snapshots_bot_id_bot_profiles_id_fk",+ "tableFrom": "bot_runtime_snapshots",+ "tableTo": "bot_profiles",+ "columnsFrom": [+ "bot_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "bot_runtime_snapshots_session_id_sessions_id_fk": {+ "name": "bot_runtime_snapshots_session_id_sessions_id_fk",+ "tableFrom": "bot_runtime_snapshots",+ "tableTo": "sessions",+ "columnsFrom": [+ "session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "bot_session_links": {+ "name": "bot_session_links",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "bot_id": {+ "name": "bot_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "profile_version": {+ "name": "profile_version",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 1+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "route_key": {+ "name": "route_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "archived_at": {+ "name": "archived_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "uniq_bot_session_links_session": {+ "name": "uniq_bot_session_links_session",+ "columns": [+ "session_id"+ ],+ "isUnique": true+ },+ "uniq_bot_session_links_canonical_per_bot": {+ "name": "uniq_bot_session_links_canonical_per_bot",+ "columns": [+ "bot_id"+ ],+ "isUnique": true,+ "where": "\"bot_session_links\".\"role\" = 'canonical'"+ },+ "idx_bot_session_links_bot_role": {+ "name": "idx_bot_session_links_bot_role",+ "columns": [+ "bot_id",+ "role"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "bot_session_links_bot_id_bot_profiles_id_fk": {+ "name": "bot_session_links_bot_id_bot_profiles_id_fk",+ "tableFrom": "bot_session_links",+ "tableTo": "bot_profiles",+ "columnsFrom": [+ "bot_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "bot_session_links_session_id_sessions_id_fk": {+ "name": "bot_session_links_session_id_sessions_id_fk",+ "tableFrom": "bot_session_links",+ "tableTo": "sessions",+ "columnsFrom": [+ "session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "custom_mcp_servers": {+ "name": "custom_mcp_servers",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "transport": {+ "name": "transport",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "url": {+ "name": "url",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "headers": {+ "name": "headers",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'{}'"+ },+ "sort_order": {+ "name": "sort_order",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_custom_mcp_servers_sort_order": {+ "name": "idx_custom_mcp_servers_sort_order",+ "columns": [+ "sort_order"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "custom_providers": {+ "name": "custom_providers",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "runtimes": {+ "name": "runtimes",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'{}'"+ },+ "auth": {+ "name": "auth",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "sort_order": {+ "name": "sort_order",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_custom_providers_sort_order": {+ "name": "idx_custom_providers_sort_order",+ "columns": [+ "sort_order"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "daily_model_usage": {+ "name": "daily_model_usage",+ "columns": {+ "day": {+ "name": "day",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "agent_kind": {+ "name": "agent_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "model": {+ "name": "model",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "cost_usd": {+ "name": "cost_usd",+ "type": "real",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "cost_amount": {+ "name": "cost_amount",+ "type": "real",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "cost_currency": {+ "name": "cost_currency",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'USD'"+ },+ "cost_is_approximate": {+ "name": "cost_is_approximate",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "input_tokens": {+ "name": "input_tokens",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "output_tokens": {+ "name": "output_tokens",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "cache_read_tokens": {+ "name": "cache_read_tokens",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "cache_create_tokens": {+ "name": "cache_create_tokens",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "daily_model_usage_day_agent_kind_model_cost_currency_pk": {+ "columns": [+ "day",+ "agent_kind",+ "model",+ "cost_currency"+ ],+ "name": "daily_model_usage_day_agent_kind_model_cost_currency_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "daily_session_usage": {+ "name": "daily_session_usage",+ "columns": {+ "day": {+ "name": "day",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "tokens": {+ "name": "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_session_usage_day_session_id_pk": {+ "columns": [+ "day",+ "session_id"+ ],+ "name": "daily_session_usage_day_session_id_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "daily_spend": {+ "name": "daily_spend",+ "columns": {+ "day": {+ "name": "day",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "cost_usd": {+ "name": "cost_usd",+ "type": "real",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "cost_amount": {+ "name": "cost_amount",+ "type": "real",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "cost_currency": {+ "name": "cost_currency",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'USD'"+ },+ "cost_is_approximate": {+ "name": "cost_is_approximate",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "daily_spend_day_cost_currency_pk": {+ "columns": [+ "day",+ "cost_currency"+ ],+ "name": "daily_spend_day_cost_currency_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "device_link_ownership": {+ "name": "device_link_ownership",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "owner_id": {+ "name": "owner_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "owner_pid": {+ "name": "owner_pid",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "owner_label": {+ "name": "owner_label",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "heartbeat_at": {+ "name": "heartbeat_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "embedding_jobs": {+ "name": "embedding_jobs",+ "columns": {+ "rowid": {+ "name": "rowid",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": true+ },+ "source": {+ "name": "source",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "source_id": {+ "name": "source_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "chunk_index": {+ "name": "chunk_index",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "model_id": {+ "name": "model_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "vec_table": {+ "name": "vec_table",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'pending'"+ },+ "attempts": {+ "name": "attempts",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "last_error": {+ "name": "last_error",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "scheduled_at": {+ "name": "scheduled_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "locked_at": {+ "name": "locked_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "uniq_embedding_jobs_natural": {+ "name": "uniq_embedding_jobs_natural",+ "columns": [+ "source",+ "source_id",+ "chunk_index",+ "model_id"+ ],+ "isUnique": true+ },+ "idx_embedding_jobs_status_scheduled": {+ "name": "idx_embedding_jobs_status_scheduled",+ "columns": [+ "status",+ "scheduled_at"+ ],+ "isUnique": false+ },+ "idx_embedding_jobs_source_id": {+ "name": "idx_embedding_jobs_source_id",+ "columns": [+ "source",+ "source_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "embedding_meta": {+ "name": "embedding_meta",+ "columns": {+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "value": {+ "name": "value",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "ghost_cards": {+ "name": "ghost_cards",+ "columns": {+ "call_id": {+ "name": "call_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "ghost_id": {+ "name": "ghost_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "html": {+ "name": "html",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "height": {+ "name": "height",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "v": {+ "name": "v",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 1+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "ghost_cards_updated_at_idx": {+ "name": "ghost_cards_updated_at_idx",+ "columns": [+ "updated_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "hook_group_context_cursors": {+ "name": "hook_group_context_cursors",+ "columns": {+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "cursor_key": {+ "name": "cursor_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "cursor_id": {+ "name": "cursor_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "hook_group_context_cursors_updated_at_idx": {+ "name": "hook_group_context_cursors_updated_at_idx",+ "columns": [+ "updated_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "hook_group_context_cursors_provider_cursor_key_pk": {+ "columns": [+ "provider",+ "cursor_key"+ ],+ "name": "hook_group_context_cursors_provider_cursor_key_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "hook_group_message_stats": {+ "name": "hook_group_message_stats",+ "columns": {+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "row_count": {+ "name": "row_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "text_bytes": {+ "name": "text_bytes",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "hook_group_messages": {+ "name": "hook_group_messages",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": true+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "chat_id": {+ "name": "chat_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "thread_id": {+ "name": "thread_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ },+ "message_id": {+ "name": "message_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "chat_name": {+ "name": "chat_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "author": {+ "name": "author",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "is_bot": {+ "name": "is_bot",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "text": {+ "name": "text",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "file_names": {+ "name": "file_names",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "sent_at": {+ "name": "sent_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "hook_group_messages_msg_idx": {+ "name": "hook_group_messages_msg_idx",+ "columns": [+ "provider",+ "chat_id",+ "thread_id",+ "message_id"+ ],+ "isUnique": true+ },+ "hook_group_messages_window_idx": {+ "name": "hook_group_messages_window_idx",+ "columns": [+ "provider",+ "chat_id",+ "thread_id",+ "id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "im_bindings": {+ "name": "im_bindings",+ "columns": {+ "channel": {+ "name": "channel",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "bot_context_id": {+ "name": "bot_context_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "scope_key": {+ "name": "scope_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ },+ "target_session_id": {+ "name": "target_session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "attached_at": {+ "name": "attached_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "attached_via_card_message_id": {+ "name": "attached_via_card_message_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_im_bindings_target": {+ "name": "idx_im_bindings_target",+ "columns": [+ "target_session_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "im_bindings_target_session_id_sessions_id_fk": {+ "name": "im_bindings_target_session_id_sessions_id_fk",+ "tableFrom": "im_bindings",+ "tableTo": "sessions",+ "columnsFrom": [+ "target_session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "im_bindings_channel_bot_context_id_user_id_scope_key_pk": {+ "columns": [+ "channel",+ "bot_context_id",+ "user_id",+ "scope_key"+ ],+ "name": "im_bindings_channel_bot_context_id_user_id_scope_key_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "im_notification_origins": {+ "name": "im_notification_origins",+ "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+ },+ "message_id": {+ "name": "message_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "chat_id": {+ "name": "chat_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "im_notification_origins_channel_bot_context_id_user_id_message_id_pk": {+ "columns": [+ "channel",+ "bot_context_id",+ "user_id",+ "message_id"+ ],+ "name": "im_notification_origins_channel_bot_context_id_user_id_message_id_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "media_blobs": {+ "name": "media_blobs",+ "columns": {+ "hash": {+ "name": "hash",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "ext": {+ "name": "ext",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "mime_type": {+ "name": "mime_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "bytes": {+ "name": "bytes",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "is_cache": {+ "name": "is_cache",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "last_access_at": {+ "name": "last_access_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "media_invocations": {+ "name": "media_invocations",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "owner": {+ "name": "owner",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "model_id": {+ "name": "model_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "capability": {+ "name": "capability",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "guide_revision": {+ "name": "guide_revision",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "guide_json": {+ "name": "guide_json",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "state": {+ "name": "state",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "response_json": {+ "name": "response_json",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "media_invocations_owner_created_at_idx": {+ "name": "media_invocations_owner_created_at_idx",+ "columns": [+ "owner",+ "created_at"+ ],+ "isUnique": false+ },+ "media_invocations_owner_state_idx": {+ "name": "media_invocations_owner_state_idx",+ "columns": [+ "owner",+ "state"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "media_refs": {+ "name": "media_refs",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "hash": {+ "name": "hash",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "ref_kind": {+ "name": "ref_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "ref_id": {+ "name": "ref_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "origin_session_id": {+ "name": "origin_session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "origin_kind": {+ "name": "origin_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "origin_id": {+ "name": "origin_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "label": {+ "name": "label",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "media_refs_hash_idx": {+ "name": "media_refs_hash_idx",+ "columns": [+ "hash"+ ],+ "isUnique": false+ },+ "media_refs_ref_idx": {+ "name": "media_refs_ref_idx",+ "columns": [+ "ref_kind",+ "ref_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "media_refs_hash_media_blobs_hash_fk": {+ "name": "media_refs_hash_media_blobs_hash_fk",+ "tableFrom": "media_refs",+ "tableTo": "media_blobs",+ "columnsFrom": [+ "hash"+ ],+ "columnsTo": [+ "hash"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "messages": {+ "name": "messages",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "client_id": {+ "name": "client_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "tool_use_id": {+ "name": "tool_use_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "agent_meta": {+ "name": "agent_meta",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "agent_kind": {+ "name": "agent_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "rewind_at": {+ "name": "rewind_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "uniq_messages_session_client": {+ "name": "uniq_messages_session_client",+ "columns": [+ "session_id",+ "client_id"+ ],+ "isUnique": true+ },+ "idx_messages_session_created": {+ "name": "idx_messages_session_created",+ "columns": [+ "session_id",+ "created_at"+ ],+ "isUnique": false+ },+ "idx_messages_created_at": {+ "name": "idx_messages_created_at",+ "columns": [+ "created_at",+ "id"+ ],+ "isUnique": false+ },+ "idx_messages_rewind_at": {+ "name": "idx_messages_rewind_at",+ "columns": [+ "rewind_at"+ ],+ "isUnique": false+ },+ "idx_messages_active_error_tail": {+ "name": "idx_messages_active_error_tail",+ "columns": [+ "session_id",+ "created_at"+ ],+ "isUnique": false,+ "where": "\"messages\".\"role\" = 'error' AND \"messages\".\"rewind_at\" IS NULL"+ }+ },+ "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": {}+ },+ "messages_fts_rows": {+ "name": "messages_fts_rows",+ "columns": {+ "fts_rowid": {+ "name": "fts_rowid",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": true+ },+ "message_id": {+ "name": "message_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "messages_fts_rows_message_id_idx": {+ "name": "messages_fts_rows_message_id_idx",+ "columns": [+ "message_id"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {},+ "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": {}+ },+ "plugin_task_requests": {+ "name": "plugin_task_requests",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "plugin_id": {+ "name": "plugin_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "operation": {+ "name": "operation",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "target_id": {+ "name": "target_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "request_key": {+ "name": "request_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "fingerprint": {+ "name": "fingerprint",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "payload": {+ "name": "payload",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "revision": {+ "name": "revision",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "plugin_task_request_key": {+ "name": "plugin_task_request_key",+ "columns": [+ "plugin_id",+ "operation",+ "target_id",+ "request_key"+ ],+ "isUnique": true+ },+ "plugin_task_target": {+ "name": "plugin_task_target",+ "columns": [+ "target_id",+ "plugin_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "project_aliases": {+ "name": "project_aliases",+ "columns": {+ "project_key": {+ "name": "project_key",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "alias": {+ "name": "alias",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_project_aliases_updated_at": {+ "name": "idx_project_aliases_updated_at",+ "columns": [+ "updated_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "project_automation_consents": {+ "name": "project_automation_consents",+ "columns": {+ "working_dir": {+ "name": "working_dir",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "consented_at": {+ "name": "consented_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "config_hash": {+ "name": "config_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "recent_workdirs": {+ "name": "recent_workdirs",+ "columns": {+ "path": {+ "name": "path",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "last_used_at": {+ "name": "last_used_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_recent_workdirs_last_used_at": {+ "name": "idx_recent_workdirs_last_used_at",+ "columns": [+ "last_used_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "right_sidebar_tabs": {+ "name": "right_sidebar_tabs",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "is_active": {+ "name": "is_active",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "state": {+ "name": "state",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'{}'"+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "right_sidebar_tabs_session_idx": {+ "name": "right_sidebar_tabs_session_idx",+ "columns": [+ "session_id",+ "position"+ ],+ "isUnique": false+ },+ "right_sidebar_tabs_subagents_singleton_idx": {+ "name": "right_sidebar_tabs_subagents_singleton_idx",+ "columns": [+ "session_id"+ ],+ "isUnique": true,+ "where": "\"right_sidebar_tabs\".\"kind\" = 'subagents'"+ },+ "right_sidebar_tabs_bot_artifacts_singleton_idx": {+ "name": "right_sidebar_tabs_bot_artifacts_singleton_idx",+ "columns": [+ "session_id"+ ],+ "isUnique": true,+ "where": "\"right_sidebar_tabs\".\"kind\" = 'bot-artifacts'"+ }+ },+ "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+ },+ "idx_schedule_runs_running_schedule": {+ "name": "idx_schedule_runs_running_schedule",+ "columns": [+ "schedule_id"+ ],+ "isUnique": false,+ "where": "\"schedule_runs\".\"status\" = 'running'"+ },+ "idx_schedule_runs_running_heartbeat": {+ "name": "idx_schedule_runs_running_heartbeat",+ "columns": [+ "heartbeat_at"+ ],+ "isUnique": false,+ "where": "\"schedule_runs\".\"status\" = 'running' AND \"schedule_runs\".\"heartbeat_at\" IS NOT NULL"+ },+ "idx_schedule_runs_running_legacy": {+ "name": "idx_schedule_runs_running_legacy",+ "columns": [+ "fired_at"+ ],+ "isUnique": false,+ "where": "\"schedule_runs\".\"status\" = 'running' AND \"schedule_runs\".\"heartbeat_at\" IS NULL"+ },+ "idx_schedule_runs_unread_terminal": {+ "name": "idx_schedule_runs_unread_terminal",+ "columns": [+ "schedule_id",+ "status",+ "fired_at"+ ],+ "isUnique": false,+ "where": "\"schedule_runs\".\"read_at\" IS NULL AND \"schedule_runs\".\"status\" IN ('success', 'failed', 'aborted', 'interrupted')"+ },+ "idx_schedule_runs_session_latest": {+ "name": "idx_schedule_runs_session_latest",+ "columns": [+ "session_id",+ "fired_at",+ "id"+ ],+ "isUnique": false,+ "where": "\"schedule_runs\".\"session_id\" IS NOT NULL"+ }+ },+ "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": {}+ },+ "schedule_session_latest_runs": {+ "name": "schedule_session_latest_runs",+ "columns": {+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "run_id": {+ "name": "run_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "fired_at": {+ "name": "fired_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_schedule_session_latest_runs_run": {+ "name": "idx_schedule_session_latest_runs_run",+ "columns": [+ "run_id"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "schedule_session_latest_runs_session_id_sessions_id_fk": {+ "name": "schedule_session_latest_runs_session_id_sessions_id_fk",+ "tableFrom": "schedule_session_latest_runs",+ "tableTo": "sessions",+ "columnsFrom": [+ "session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "schedule_session_latest_runs_run_id_schedule_runs_id_fk": {+ "name": "schedule_session_latest_runs_run_id_schedule_runs_id_fk",+ "tableFrom": "schedule_session_latest_runs",+ "tableTo": "schedule_runs",+ "columnsFrom": [+ "run_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "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_agent_kind": {+ "name": "model_agent_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "model": {+ "name": "model",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "provider_id": {+ "name": "provider_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "effort": {+ "name": "effort",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "fast_mode": {+ "name": "fast_mode",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "working_dir": {+ "name": "working_dir",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "workspace_kind": {+ "name": "workspace_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'project'"+ },+ "use_worktree": {+ "name": "use_worktree",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "target_session_id": {+ "name": "target_session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "persistent_session": {+ "name": "persistent_session",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "silent_when_idle": {+ "name": "silent_when_idle",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "pre_run_hook_command": {+ "name": "pre_run_hook_command",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "pre_run_hook_timeout_ms": {+ "name": "pre_run_hook_timeout_ms",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "skip_log_session_id": {+ "name": "skip_log_session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "notify_desktop": {+ "name": "notify_desktop",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": true+ },+ "notify_feishu": {+ "name": "notify_feishu",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "notify_wecom_group": {+ "name": "notify_wecom_group",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'active'"+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "last_fired_at": {+ "name": "last_fired_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_finished_at": {+ "name": "last_finished_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "next_fire_at": {+ "name": "next_fire_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "expire_at": {+ "name": "expire_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_schedules_active_next": {+ "name": "idx_schedules_active_next",+ "columns": [+ "status",+ "next_fire_at"+ ],+ "isUnique": false+ },+ "idx_schedules_target_session": {+ "name": "idx_schedules_target_session",+ "columns": [+ "target_session_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "schedules_target_session_id_sessions_id_fk": {+ "name": "schedules_target_session_id_sessions_id_fk",+ "tableFrom": "schedules",+ "tableTo": "sessions",+ "columnsFrom": [+ "target_session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "schedules_skip_log_session_id_sessions_id_fk": {+ "name": "schedules_skip_log_session_id_sessions_id_fk",+ "tableFrom": "schedules",+ "tableTo": "sessions",+ "columnsFrom": [+ "skip_log_session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "session_goals": {+ "name": "session_goals",+ "columns": {+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "objective": {+ "name": "objective",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'active'"+ },+ "budget_tokens": {+ "name": "budget_tokens",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "max_turns": {+ "name": "max_turns",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "no_progress_limit": {+ "name": "no_progress_limit",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "turns_used": {+ "name": "turns_used",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "tokens_used": {+ "name": "tokens_used",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "no_progress_streak": {+ "name": "no_progress_streak",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "usage_reset_at": {+ "name": "usage_reset_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_reason": {+ "name": "last_reason",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "agent_kind": {+ "name": "agent_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "started_at": {+ "name": "started_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_session_goals_status": {+ "name": "idx_session_goals_status",+ "columns": [+ "status"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "session_goals_session_id_sessions_id_fk": {+ "name": "session_goals_session_id_sessions_id_fk",+ "tableFrom": "session_goals",+ "tableTo": "sessions",+ "columnsFrom": [+ "session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "session_pr_refs": {+ "name": "session_pr_refs",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "owner": {+ "name": "owner",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "repo": {+ "name": "repo",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "pr_number": {+ "name": "pr_number",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "url": {+ "name": "url",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "first_seen_at": {+ "name": "first_seen_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "last_seen_at": {+ "name": "last_seen_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "uniq_session_pr_refs": {+ "name": "uniq_session_pr_refs",+ "columns": [+ "session_id",+ "owner",+ "repo",+ "pr_number"+ ],+ "isUnique": true+ },+ "idx_session_pr_refs_session_last_seen": {+ "name": "idx_session_pr_refs_session_last_seen",+ "columns": [+ "session_id",+ "last_seen_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "session_pr_refs_session_id_sessions_id_fk": {+ "name": "session_pr_refs_session_id_sessions_id_fk",+ "tableFrom": "session_pr_refs",+ "tableTo": "sessions",+ "columnsFrom": [+ "session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "session_task_tags": {+ "name": "session_task_tags",+ "columns": {+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "tag_id": {+ "name": "tag_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "session_task_tags_tag_idx": {+ "name": "session_task_tags_tag_idx",+ "columns": [+ "tag_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "session_task_tags_session_id_sessions_id_fk": {+ "name": "session_task_tags_session_id_sessions_id_fk",+ "tableFrom": "session_task_tags",+ "tableTo": "sessions",+ "columnsFrom": [+ "session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "session_task_tags_tag_id_task_tags_id_fk": {+ "name": "session_task_tags_tag_id_task_tags_id_fk",+ "tableFrom": "session_task_tags",+ "tableTo": "task_tags",+ "columnsFrom": [+ "tag_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "session_task_tags_session_id_tag_id_pk": {+ "columns": [+ "session_id",+ "tag_id"+ ],+ "name": "session_task_tags_session_id_tag_id_pk"+ }+ },+ "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+ },+ "context_window_runtime": {+ "name": "context_window_runtime",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "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+ },+ "im_default_route": {+ "name": "im_default_route",+ "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+ },+ "codex_plan_json": {+ "name": "codex_plan_json",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "extra_dirs": {+ "name": "extra_dirs",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'[]'"+ },+ "writable_dirs": {+ "name": "writable_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+ },+ "agent_device_id": {+ "name": "agent_device_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+ },+ "list_preview": {+ "name": "list_preview",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "list_preview_role": {+ "name": "list_preview_role",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "list_message_count": {+ "name": "list_message_count",+ "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": {}+ },+ "shared_task_events": {+ "name": "shared_task_events",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": true+ },+ "shared_task_id": {+ "name": "shared_task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "revision": {+ "name": "revision",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "terminal": {+ "name": "terminal",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "snapshot": {+ "name": "snapshot",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "recorded_at": {+ "name": "recorded_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "shared_task_events_revision_idx": {+ "name": "shared_task_events_revision_idx",+ "columns": [+ "shared_task_id",+ "kind",+ "revision"+ ],+ "isUnique": true+ },+ "shared_task_events_session_idx": {+ "name": "shared_task_events_session_idx",+ "columns": [+ "session_id",+ "id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "shared_task_events_session_id_sessions_id_fk": {+ "name": "shared_task_events_session_id_sessions_id_fk",+ "tableFrom": "shared_task_events",+ "tableTo": "sessions",+ "columnsFrom": [+ "session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "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_skill_recent": {+ "name": "idx_skill_usage_exposures_skill_recent",+ "columns": [+ "skill_name",+ "analyzer_version",+ "seen_at"+ ],+ "isUnique": false+ },+ "idx_skill_usage_exposures_skill_recent_any_version": {+ "name": "idx_skill_usage_exposures_skill_recent_any_version",+ "columns": [+ "skill_name",+ "seen_at"+ ],+ "isUnique": false+ },+ "idx_skill_usage_exposures_analyzer_recent_source": {+ "name": "idx_skill_usage_exposures_analyzer_recent_source",+ "columns": [+ "analyzer_version",+ "seen_at",+ "raw_file_path"+ ],+ "isUnique": false+ },+ "idx_skill_usage_exposures_session": {+ "name": "idx_skill_usage_exposures_session",+ "columns": [+ "session_id"+ ],+ "isUnique": false+ },+ "idx_skill_usage_exposures_raw_file": {+ "name": "idx_skill_usage_exposures_raw_file",+ "columns": [+ "raw_file_path"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "skill_usage_exposures_raw_file_path_skill_usage_sources_raw_file_path_fk": {+ "name": "skill_usage_exposures_raw_file_path_skill_usage_sources_raw_file_path_fk",+ "tableFrom": "skill_usage_exposures",+ "tableTo": "skill_usage_sources",+ "columnsFrom": [+ "raw_file_path"+ ],+ "columnsTo": [+ "raw_file_path"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "skill_usage_sources": {+ "name": "skill_usage_sources",+ "columns": {+ "raw_file_path": {+ "name": "raw_file_path",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "analyzer_version": {+ "name": "analyzer_version",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'6'"+ },+ "agent_kind": {+ "name": "agent_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "sdk_session_id": {+ "name": "sdk_session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "mtime_ms": {+ "name": "mtime_ms",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "size_bytes": {+ "name": "size_bytes",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "last_scanned_at": {+ "name": "last_scanned_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'ok'"+ },+ "error": {+ "name": "error",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_skill_usage_sources_session": {+ "name": "idx_skill_usage_sources_session",+ "columns": [+ "session_id"+ ],+ "isUnique": false+ },+ "idx_skill_usage_sources_sdk_session": {+ "name": "idx_skill_usage_sources_sdk_session",+ "columns": [+ "sdk_session_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "subagent_run_aliases": {+ "name": "subagent_run_aliases",+ "columns": {+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "alias": {+ "name": "alias",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "run_id": {+ "name": "run_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "subagent_run_aliases_lookup_idx": {+ "name": "subagent_run_aliases_lookup_idx",+ "columns": [+ "session_id",+ "provider",+ "alias",+ "created_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "subagent_run_aliases_session_id_sessions_id_fk": {+ "name": "subagent_run_aliases_session_id_sessions_id_fk",+ "tableFrom": "subagent_run_aliases",+ "tableTo": "sessions",+ "columnsFrom": [+ "session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "subagent_run_aliases_run_id_subagent_runs_id_fk": {+ "name": "subagent_run_aliases_run_id_subagent_runs_id_fk",+ "tableFrom": "subagent_run_aliases",+ "tableTo": "subagent_runs",+ "columnsFrom": [+ "run_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "subagent_run_aliases_run_id_alias_pk": {+ "columns": [+ "run_id",+ "alias"+ ],+ "name": "subagent_run_aliases_run_id_alias_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "subagent_runs": {+ "name": "subagent_runs",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "logical_agent_id": {+ "name": "logical_agent_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "parent_tool_use_id": {+ "name": "parent_tool_use_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "aliases": {+ "name": "aliases",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'[]'"+ },+ "provider_run_ids": {+ "name": "provider_run_ids",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'[]'"+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'running'"+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "summary": {+ "name": "summary",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "returned_result": {+ "name": "returned_result",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "returned_result_empty": {+ "name": "returned_result_empty",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "returned_result_truncated": {+ "name": "returned_result_truncated",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "model": {+ "name": "model",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "reasoning_effort": {+ "name": "reasoning_effort",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "total_tokens": {+ "name": "total_tokens",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "tool_uses": {+ "name": "tool_uses",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "duration_ms": {+ "name": "duration_ms",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "cost_usd": {+ "name": "cost_usd",+ "type": "real",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "capabilities": {+ "name": "capabilities",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'{}'"+ },+ "activity": {+ "name": "activity",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'[]'"+ },+ "started_at": {+ "name": "started_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "ended_at": {+ "name": "ended_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "rewind_at": {+ "name": "rewind_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "deleted_at": {+ "name": "deleted_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "subagent_runs_logical_idx": {+ "name": "subagent_runs_logical_idx",+ "columns": [+ "session_id",+ "provider",+ "logical_agent_id"+ ],+ "isUnique": false+ },+ "subagent_runs_session_idx": {+ "name": "subagent_runs_session_idx",+ "columns": [+ "session_id",+ "rewind_at",+ "deleted_at",+ "started_at"+ ],+ "isUnique": false+ },+ "subagent_runs_parent_tool_use_idx": {+ "name": "subagent_runs_parent_tool_use_idx",+ "columns": [+ "session_id",+ "parent_tool_use_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "subagent_runs_session_id_sessions_id_fk": {+ "name": "subagent_runs_session_id_sessions_id_fk",+ "tableFrom": "subagent_runs",+ "tableTo": "sessions",+ "columnsFrom": [+ "session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "task_tags": {+ "name": "task_tags",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name_customized": {+ "name": "name_customized",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "favorite_order": {+ "name": "favorite_order",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "sort_order": {+ "name": "sort_order",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "revision": {+ "name": "revision",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 1+ }+ },+ "indexes": {+ "task_tags_name_idx": {+ "name": "task_tags_name_idx",+ "columns": [+ "name"+ ],+ "isUnique": true+ }+ },+ "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 filediff --git a/apps/desktop/drizzle/meta/_journal.json b/apps/desktop/drizzle/meta/_journal.jsonindex 80c0d15567..8bb39609fd 100644--- a/apps/desktop/drizzle/meta/_journal.json+++ b/apps/desktop/drizzle/meta/_journal.json@@ -862,6 +862,13 @@"when": 1790618518784,"tag": "0122_auto_review_projections","breakpoints": true+ },+ {+ "idx": 123,+ "version": "6",+ "when": 1791260458468,+ "tag": "0123_wonderful_oracle",+ "breakpoints": true}]}\ No newline at end of filediff --git a/apps/desktop/src/main/__tests__/fork.test.ts b/apps/desktop/src/main/__tests__/fork.test.tsindex 545f26dd4d..41a688c6bd 100644--- a/apps/desktop/src/main/__tests__/fork.test.ts+++ b/apps/desktop/src/main/__tests__/fork.test.ts@@ -990,6 +990,25 @@ describe('forkSessionAtMessage', () => {expect(txArgs.newMessageIds).toHaveLength(2);});+ it('refuses to fork a task whose agent runs on another computer (its agent record is there)', async () => {+ selectQueue.push([makeSourceRow({ agentDeviceId: 'device-b' })]);++ await expect(forkSessionAtMessage('src-session', 'any-msg')).rejects.toMatchObject({+ code: 'REMOTE_NOT_SUPPORTED',+ });+ expect(forkSdkSessionMock).not.toHaveBeenCalled();+ expect(txCalls).toHaveLength(0);+ });++ it('refuses the encrypted-content fork for a Codex task whose agent runs on another computer', async () => {+ selectQueue.push([makeSourceRow({ agentKind: 'codex', agentDeviceId: 'device-b' })]);++ await expect(forkSessionStripEncrypted('src-session')).rejects.toMatchObject({+ code: 'REMOTE_NOT_SUPPORTED',+ });+ expect(forkSdkSessionMock).not.toHaveBeenCalled();+ });+it('throws SOURCE_NEVER_RAN when source.sdkSessionId is null; maker not invoked', async () => {selectQueue.push([makeSourceRow({ sdkSessionId: null })]);selectQueue.push([makeMessageRow({ clientId: 'any-msg' })]);diff --git a/apps/desktop/src/main/__tests__/gitSnapshotCoordinator.test.ts b/apps/desktop/src/main/__tests__/gitSnapshotCoordinator.test.tsindex 3bca41f96a..8b9a98f742 100644--- a/apps/desktop/src/main/__tests__/gitSnapshotCoordinator.test.ts+++ b/apps/desktop/src/main/__tests__/gitSnapshotCoordinator.test.ts@@ -513,6 +513,26 @@ describe('GitSnapshotCoordinator', () => {});});+ it('marks Claude Code turns as rewind-blocked when its agent runs on another computer', async () => {+ // 那台没有本机的文件检查点,文件回退走保存点链,缺口必须像 Codex / Pi 一样记下。+ const deps = makeDeps({+ getSessionContext: vi.fn().mockResolvedValue({ workingDir: '/repo', agentKind: 'claude-code', savepointRewind: true }),+ createShadowSavepoint: vi.fn()+ .mockResolvedValueOnce(savepointResult('hash1'))+ .mockRejectedValueOnce(new Error('index locked')),+ });+ const coordinator = new GitSnapshotCoordinator(deps);++ await coordinator.onTurnStart('s1');+ await coordinator.onTurnEnd('s1');++ expect(deps.createShadowMarker).toHaveBeenCalledWith('/repo', {+ sessionId: 's1',+ label: 'File rewind gap: after-edit savepoint failed',+ meta: { kind: 'rewind-blocked', anchor: 'msg-1' },+ });+ });+it('skips the rewind gap marker for agents that do not consume the savepoint chain', async () => {// 默认 agentKind 为 claude-code:缺基线只打 debug 日志,不建 marker,// 也不提前解析可选 metadata。diff --git a/apps/desktop/src/main/__tests__/remoteAgentSetModelWiring.test.ts b/apps/desktop/src/main/__tests__/remoteAgentSetModelWiring.test.tsnew file mode 100644index 0000000000..d3585b69ca--- /dev/null+++ b/apps/desktop/src/main/__tests__/remoteAgentSetModelWiring.test.ts@@ -0,0 +1,94 @@+/**+ * Agent 在另一台电脑运行的任务:换模型时不拿本机模型目录去校验那台的模型(那台的 Agent 裁决),+ * 点选仍只记意图、在发送边界落地;建任务与恢复时同样跳过本机路由检查。+ */+import fs from 'node:fs';+import path from 'node:path';++import { describe, expect, it } from 'vitest';++const source = fs.readFileSync(path.join(__dirname, '../maker-ipc/register.ts'), 'utf8');++function handlerBody(): string {+ const start = source.indexOf('const handleSetModel = async (');+ const end = source.indexOf('applyPiModelSettingsRefresh = async', start);+ expect(start).toBeGreaterThan(0);+ expect(end).toBeGreaterThan(start);+ return source.slice(start, end);+}++describe('agent-device model selection wiring', () => {+ it('routes agent-device tasks before any local catalog check', () => {+ const body = handlerBody();+ expect(body).toContain('agentDeviceId: sessions.agentDeviceId,');+ const branch = body.indexOf('if (runtimeStatus.agentDeviceId && !runtimeStatus.remoteHostId) {');+ expect(branch).toBeGreaterThan(0);+ const applyLocked = body.indexOf('const applyLocked = async () => {');+ const firstCatalogCheck = body.indexOf('await assertModelRouteUsable(', applyLocked);+ const firstCatalogLookup = body.indexOf('findCatalogModel(', applyLocked);+ expect(branch).toBeGreaterThan(applyLocked);+ expect(branch).toBeLessThan(firstCatalogCheck);+ expect(branch).toBeLessThan(firstCatalogLookup);+ });++ it('keeps picker clicks as intents and applies them through the live session at send time', () => {+ const body = handlerBody();+ const start = source.indexOf('const applyAgentDeviceRuntimeSelection = async');+ const end = source.indexOf('const handleSetModel = async (', start);+ expect(start).toBeGreaterThan(0);+ expect(end).toBeGreaterThan(start);+ const branch = source.slice(start, end);+ expect(body).toContain('return applyAgentDeviceRuntimeSelection({');+ expect(branch).toMatch(/internalOptions\.source === 'user' && !internalOptions\.applyingUserSelectionOnSend/);+ expect(branch).toContain('agentSwitchPending.set(sessionId, intent);');+ expect(branch).toContain('pendingUntilSend: true');+ expect(branch).toContain('live.requiresModelSwitchRebuild?.(model, { providerId: targetProviderId })');+ expect(branch).toContain('await live.setModel?.(model');+ expect(branch).toContain('await persistSessionFields(sessionId, patch);');+ expect(branch).not.toContain('assertModelRouteUsable');+ expect(branch).not.toContain('getActiveCatalog');+ });++ it('restores the agent computer from the task record when starting', () => {+ const start = source.indexOf('async function bootstrapSession(');+ const body = source.slice(start, start + 4000);+ expect(body).toContain('const agentDeviceId = await readSessionAgentDeviceId(o.id);');+ expect(body).toContain('if (agentDeviceId) o.agentDeviceId = agentDeviceId;');+ expect(body).toContain('const agentOnOtherDevice = Boolean(o.agentDeviceId) && !o.remoteHostId;');+ });++ it('treats a failed task lookup as a local task', () => {+ const start = source.indexOf('async function readSessionAgentDeviceId(');+ const body = source.slice(start, source.indexOf('\n }\n', start));+ expect(body).toContain('return row?.agentDeviceId && !row.remoteHostId ? row.agentDeviceId : null;');+ expect(body).toMatch(/catch \(error\) \{[\s\S]*treating the task as local[\s\S]*return null;/);+ });++ it('refuses Review for these tasks before collecting evidence', () => {+ const select = source.indexOf('.where(eq(sessions.id, request.sourceSessionId))');+ const guard = source.indexOf('if (source.agentDeviceId) {', select);+ const evidence = source.indexOf('const sourceWorkingDir = source.workingDir;', select);+ expect(select).toBeGreaterThan(0);+ expect(guard).toBeGreaterThan(select);+ expect(guard).toBeLessThan(evidence);+ expect(source.slice(guard, evidence)).toContain("throwIpcError('UNSUPPORTED_CAPABILITY'");+ });++ it('keeps tasks created from these tasks on the same computer', () => {+ const start = source.indexOf('async function sendToSessionInternal(');+ const body = source.slice(start, source.indexOf('assertDesktopSendDispatched(sendResult', start));+ expect(body).toContain('if (meta.agentDeviceId && !meta.remoteHostId) inheritedAgentDeviceId = meta.agentDeviceId;');+ expect(body).toContain('...(inheritedAgentDeviceId ? { agentDeviceId: inheritedAgentDeviceId } : {}),');+ // 换模型时按那台的目录校验,而不是本机目录。+ expect(body).toContain('availableModels: deviceRouting?.remoteCodexModels ?? maker.getCapabilities(targetAgent).availableModels,');+ expect(body).toContain('providerRouting: deviceRouting ?? await getProviderRoutingContext(),');+ });++ it("lists the other computer's models for Orca leads whose agent runs there", () => {+ const start = source.indexOf('listAvailableModels: async ({ agent, callerSessionId }) => {');+ expect(start).toBeGreaterThan(0);+ const body = source.slice(start, source.indexOf('const providerRouting = await getProviderRoutingContext();', start));+ expect(body).toContain('const agentDeviceId = callerSessionId ? await readSessionAgentDeviceId(callerSessionId) : null;');+ expect(body).toContain('deviceAvailableModels(views, a)');+ });+});diff --git a/apps/desktop/src/main/__tests__/rewind.test.ts b/apps/desktop/src/main/__tests__/rewind.test.tsindex fde4b2a8ad..9c42f4b969 100644--- a/apps/desktop/src/main/__tests__/rewind.test.ts+++ b/apps/desktop/src/main/__tests__/rewind.test.ts@@ -908,6 +908,58 @@ describe('commitRewindAtMessage', () => {expect(result.id).toBe('sess-1');});+ it('Claude Code on another computer: restores files from local savepoints and only truncates the conversation there', async () => {+ getSessionMetaMock.mockImplementation(async () => ({ sdkSessionId: 'sdk-uuid-old', agentDeviceId: 'device-b' }));+ detectCwdMock.mockResolvedValueOnce({ gitInstalled: true, isGitRepo: true, repoRoot: '/repo', isInsideWorktree: false });+ listShadowSavepointsMock.mockResolvedValueOnce([+ {+ commit: 'sc1', sessionId: 'sess-1', kind: 'after-edit', source: 'cindy', parentCount: 1,+ anchor: 'client-id', baselineCommit: 'base1', label: '本轮修改', time: '2026-10-06T00:00:00+08:00',+ },+ ]);+ selectQueue.push([makeUserMessageRow()]); // target user msg+ selectQueue.push([]); // agent_switch 边界守卫:无边界+ selectQueue.push([makeAssistantMessageRow()]); // prior assistants+ selectQueue.push([makeUserMessageRow()]); // target 及之后的 user 时间线+ selectQueue.push([makeSessionRow()]); // post-update select++ const result = await commitRewindAtMessage('sess-1', 'client-id');++ expect(executeCodexFileRestorePlanWithThreadRollbackMock).toHaveBeenCalledWith(+ expect.objectContaining({ mode: 'file-restore', repoRoot: '/repo', baselineCommit: 'base1' }),+ 'sess-1',+ expect.objectContaining({ commitThreadRollback: expect.any(Function), onCompensationError: expect.any(Function) }),+ );+ // 那台没有本机的文件检查点:空 userUuid 只截断对话。+ expect(commitRewindFilesMock).toHaveBeenCalledTimes(1);+ expect(commitRewindFilesMock).toHaveBeenCalledWith('', 'sdk-msg-uuid-prior-asst');+ const txCall = txCalls.find((c) => c.name === 'rewind.commit');+ if (!txCall) throw new Error('缺少 rewind.commit tx 调用');+ expect(txCall.args).toMatchObject({ targetClientId: 'client-id', preserveMessageUuid: 'sdk-msg-uuid-prior-asst' });+ expect(result.id).toBe('sess-1');+ });++ it('Claude Code on another computer: previews the local savepoint plan instead of native checkpoints', async () => {+ getSessionMetaMock.mockImplementation(async () => ({ sdkSessionId: 'sdk-uuid-old', agentDeviceId: 'device-b' }));+ detectCwdMock.mockResolvedValueOnce({ gitInstalled: true, isGitRepo: true, repoRoot: '/repo', isInsideWorktree: false });+ listSnapshotsMock.mockResolvedValueOnce([{ commit: 'sp1', sessionId: 'sess-1', kind: 'after-edit', source: 'legacy-xdt', branch: 'main', parentCount: 1, anchor: 'client-id' }]);+ gitExecMock.mockResolvedValueOnce({ stdout: '3\t1\tsrc/a.ts\n', stderr: '' });+ selectQueue.push([makeUserMessageRow()], [], [makeAssistantMessageRow()], [makeUserMessageRow()]);++ await expect(previewRewindAtMessage('sess-1', 'client-id')).resolves.toEqual({+ canRewind: true, filesChanged: ['src/a.ts'], insertions: 1, deletions: 3,+ });+ expect(previewRewindFilesMock).not.toHaveBeenCalled();+ });++ it('Claude Code on another computer: refuses a target that is no longer on the timeline', async () => {+ getSessionMetaMock.mockImplementation(async () => ({ sdkSessionId: 'sdk-uuid-old', agentDeviceId: 'device-b' }));+ selectQueue.push([makeUserMessageRow()], [], [makeAssistantMessageRow()], [makeUserMessageRow({ rowid: 99 })]);++ await expect(commitRewindAtMessage('sess-1', 'client-id')).rejects.toMatchObject({ code: 'MESSAGE_NOT_FOUND' });+ expect(commitRewindFilesMock).not.toHaveBeenCalled();+ });+it('Codex: uses tail turn count and does not require prior assistant uuid', async () => {useFakeSession('codex');commitRewindFilesMock.mockResolvedValueOnce({ sdkSessionId: 'rollback-thread-id' });diff --git a/apps/desktop/src/main/__tests__/sessionRuntimeFallbackIntent.test.ts b/apps/desktop/src/main/__tests__/sessionRuntimeFallbackIntent.test.tsindex 26980d9445..fda9f26f0b 100644--- a/apps/desktop/src/main/__tests__/sessionRuntimeFallbackIntent.test.ts+++ b/apps/desktop/src/main/__tests__/sessionRuntimeFallbackIntent.test.ts@@ -27,6 +27,7 @@ function harness() {const clearCredential = vi.fn();const pendingCredential = vi.fn(() => ({ model: 'next', providerId: 'openai' }));const failed = vi.fn(() => true);+ const readSessionAgentDeviceId = vi.fn<(sessionId: string) => Promise<string | null>>(async () => null);const query = { from: () => query, where: () => query, limit: async () => [{ status: 'active' }] };const deps = {agentSwitchPending: pending,@@ -48,6 +49,7 @@ function harness() {clearPendingCredentialSwitchForSession: clearCredential,broadcastSessionRuntimeProjection: vi.fn(async () => {}),recordFailedSessionRuntimeFallbackCandidate: failed,+ readSessionAgentDeviceId,getDbClient: () => ({ drizzle: { select: () => query } }),sessions: { status: 'status', id: 'id' }, eq: vi.fn(),runtimeSelectionRequiresModelWindowConfirmation: (result: { contextWindowConfirmationRequired?: number }) => result.contextWindowConfirmationRequired !== undefined,@@ -62,10 +64,20 @@ function harness() {pending.set('session', { sameAgentSelection: true, targetAgentKind: 'codex', model: 'chosen', providerId: 'xd' });generation += 1;};- return { ...runtime, pending, pick, readCandidate, switchAgent, accept, withLock, apply, cancel, clearCredential, pendingCredential, failed, current, candidate, generation: () => generation };+ return { ...runtime, pending, pick, readCandidate, switchAgent, accept, withLock, apply, cancel, clearCredential, pendingCredential, failed, readSessionAgentDeviceId, current, candidate, generation: () => generation };}describe('automatic runtime selection respects the user send boundary', () => {+ it('never replaces the route of a task whose agent runs on another computer with a local candidate', async () => {+ const h = harness();+ h.readSessionAgentDeviceId.mockResolvedValue('device-b');+ expect(await h.run('session', 1, 1, true)).toMatchObject({ session: null, outcome: 'exhausted' });+ expect(await h.run('session', 1, 1, false)).toMatchObject({ session: null, outcome: 'unchanged' });+ expect(h.readCandidate).not.toHaveBeenCalled();+ expect(h.switchAgent).not.toHaveBeenCalled();+ expect(h.apply).not.toHaveBeenCalled();+ });+it('stops after a committed harness switch whose engine failed to start', async () => {const h = harness();h.switchAgent.mockResolvedValue({ switched: true, engineReady: false });diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.tsindex bd22eae8c9..50bf8b6e32 100644--- a/apps/desktop/src/main/device-link/dispatch.ts+++ b/apps/desktop/src/main/device-link/dispatch.ts@@ -2,6 +2,7 @@ import { executeTaskTags, TASK_TAG_CHANNEL } from '../localDb/ipc/taskTags.js';import type { TaskTagRequest } from '@cindy/maker-shared';import {FILE_PEER_CHANNEL,+ REMOTE_AGENT_CHANNEL,TASK_MIGRATION_CHANNEL,encodeSessionTagCatalog,decodeSessionTagCatalog,@@ -324,6 +325,20 @@ export function setRemoteReviewInputGuard(guard: RemoteReviewInputGuard | null):remoteReviewInputGuard = guard;}+/**+ * 远程 Agent(同账号另一台电脑的任务让 Agent 在本机运行)的处理器;maker 就绪后由+ * remote-agent/host/service.ts 接入。+ */+export interface RemoteAgentHandler {+ handle(controller: string, raw: unknown): Promise<unknown>;+ abortAll(): void;+}+let remoteAgentHandler: RemoteAgentHandler | null = null;++export function setRemoteAgentHandler(handler: RemoteAgentHandler | null): void {+ remoteAgentHandler = handler;+}+// Local renderer IPC keeps its sender guard; remote mutations enter the shared action here.type RemoteTurnChangeAction = (sessionId: unknown, id: unknown, action: unknown, assertAccess: () => Promise<void>,@@ -2171,6 +2186,7 @@ export function dropAllControllers(reason: 'user' | 'toggle-off' | 'shutdown',): void {stopFilePeers();+ remoteAgentHandler?.abortAll();remoteDesktop.stop();void remoteCredentialHost.closeAll().catch(() => remoteCredentialHost.dispose());const controllerIds = new Set([@@ -3142,7 +3158,9 @@ function sendInvokeResultSafe(const attempt = trySendInvokeResult(client, src, requestId, proactive, channel, args);// 以真正能上 wire 的结果作为去重真相:超限原结果若被 compact/改成结构化错误,// 不能把缓存留在原始大对象上,否则缓存可能自淘汰且重复 requestId 会再次执行。- if (fingerprint !== undefined) {+ // 远程 Agent 的每个 op 自带幂等(poll 按游标、其余按各自 id 去重),高频的事件流结果不进+ // 全局去重缓存,免得冲掉其它控制端非幂等调用的去重记录。+ if (fingerprint !== undefined && channel !== REMOTE_AGENT_CHANNEL) {rememberRemoteInvokeResult(key, fingerprint, attempt.result);}if (attempt.sent) {@@ -3862,6 +3880,33 @@ async function executeRemoteInvoke(src: string, payload: InvokePayload | undefintry { return { ok: true, result: await requestPluginOauth(src, payload.args[0]) }; }catch { return { ok: false, error: { code: 'IPC_ERROR', message: '[PRECONDITION_FAILED] Remote authorization unavailable' } }; }}+ if (payload.channel === REMOTE_AGENT_CHANNEL) {+ // 同账号的另一台电脑让 Agent 在本机运行;共享任务访客无权使用本机的 Agent 登录与额度+ // (共享任务的通道清单里也没有它,这里再兜一层)。+ if (isSharedTaskPeer(src)) {+ return { ok: false, error: { code: 'IPC_ERROR', message: '[REMOTE_AGENT_UNSUPPORTED] not available to shared tasks' } };+ }+ const handler = remoteAgentHandler;+ if (!handler) {+ return { ok: false, error: { code: 'IPC_ERROR', message: '[REMOTE_AGENT_UNAVAILABLE] not ready yet' } };+ }+ try {+ return { ok: true, result: await timing.measure('handler', () => handler.handle(src, payload.args?.[0])) };+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ return {+ ok: false,+ error: {+ code: 'IPC_ERROR',+ message: /^\[REMOTE_AGENT_[A-Z_]+\]/.test(message)+ ? message+ : message === 'REMOTE_AGENT_INVALID'+ ? '[REMOTE_AGENT_INVALID] invalid remote agent request'+ : '[REMOTE_AGENT_UNAVAILABLE] remote agent request failed',+ },+ };+ }+ }if (payload.channel === REMOTE_DESKTOP_CHANNEL) {try { return { ok: true, result: await timing.measure('handler', () => requestRemoteDesktop(src, payload.args?.[0])) }; }catch (error) { return { ok: false, error: { code: 'IPC_ERROR', message: error instanceof Error ? error.message : 'DESKTOP_UNAVAILABLE' } }; }@@ -4204,6 +4249,7 @@ export const __testing = {setBroadcastTapListener(null);presenceOfflineCheck = null;remoteReviewInputGuard = null;+ remoteAgentHandler = null;remoteTurnChangeAction = null;remoteXaiSubscriptionUsageReader = null;remoteClaudeSubscriptionUsageReader = null;diff --git a/apps/desktop/src/main/git-snapshot/gitSnapshotCoordinator.ts b/apps/desktop/src/main/git-snapshot/gitSnapshotCoordinator.tsindex 6cfca73a89..8f112bc68f 100644--- a/apps/desktop/src/main/git-snapshot/gitSnapshotCoordinator.ts+++ b/apps/desktop/src/main/git-snapshot/gitSnapshotCoordinator.ts@@ -27,6 +27,11 @@ export interface GitSnapshotSessionContext {agentKind: AgentKind;workspaceKind?: string | null;remoteHostId?: string | null;+ /**+ * 文件回退走保存点链(与 Codex / Pi 一样,需要记录缺口标记)。Agent 在另一台电脑运行的+ * Claude Code 任务没有原生文件检查点,也走保存点链;本机 Claude Code 任务不走。+ */+ savepointRewind?: boolean;}export interface GitSnapshotCoordinatorDeps {@@ -66,6 +71,8 @@ export interface GitSnapshotCoordinatorDeps {interface ResolvedSnapshotSession {repoRoot: string;agentKind: AgentKind;+ /** 文件回退走保存点链(Codex / Pi,以及另一台电脑上运行的 Claude Code)。 */+ savepointRewind: boolean;}interface TurnStartState {@@ -246,14 +253,18 @@ export class GitSnapshotCoordinator {}if (!repoRoot) return null;- const resolved = { repoRoot, agentKind: ctx.agentKind };+ const resolved = {+ repoRoot,+ agentKind: ctx.agentKind,+ savepointRewind: ctx.agentKind === 'codex' || ctx.agentKind === 'pi' || ctx.savepointRewind === true,+ };this.sessionCache.set(sessionId, resolved);return resolved;}private async snapshotAfterEdit(sessionId: string,- { repoRoot, agentKind }: ResolvedSnapshotSession,+ { repoRoot, agentKind, savepointRewind }: ResolvedSnapshotSession,turnStart: TurnStartRecord | undefined,): Promise<void> {const baseline =@@ -266,7 +277,7 @@ export class GitSnapshotCoordinator {// Without a baseline this turn's delta is unrecoverable; append a gap// marker so the file-rewind planner truncates ranges that cross it.// Only codex/pi consume the savepoint chain for file rewind.- if (agentKind === 'codex' || agentKind === 'pi') {+ if (savepointRewind) {await this.createRewindBlockedMarker(sessionId,repoRoot,@@ -288,7 +299,7 @@ export class GitSnapshotCoordinator {sessionId,repoRoot,});- if (agentKind === 'codex' || agentKind === 'pi') {+ if (savepointRewind) {await this.createRewindBlockedMarker(sessionId,repoRoot,@@ -328,7 +339,7 @@ export class GitSnapshotCoordinator {// This turn's delta is unrecorded; without a gap marker a later rewind// across this turn would restore to a newer baseline and silently keep// the failed turn's file changes while dropping its conversation.- if (agentKind === 'codex' || agentKind === 'pi') {+ if (savepointRewind) {await this.createRewindBlockedMarker(sessionId,repoRoot,@@ -360,7 +371,7 @@ export class GitSnapshotCoordinator {// - 两端都被过滤但 lstat 指纹(大小/mtime,不含内容)变化:文件本轮被// 改写(如超限文件被 Agent 重写后仍超限),同样没有任何快照可恢复。// 指纹完全一致的常驻过滤文件不打 gap,否则文件回退会被永久禁用。- if (agentKind === 'codex' || agentKind === 'pi') {+ if (savepointRewind) {const baseline = new Map((turnStart?.turnStartSkippedFingerprints ?? []).map((fp) => [fp.path, fp]),);diff --git a/apps/desktop/src/main/localDb/__tests__/conversationSearch.test.ts b/apps/desktop/src/main/localDb/__tests__/conversationSearch.test.tsindex 0580f4eda2..c9ed53acc8 100644--- a/apps/desktop/src/main/localDb/__tests__/conversationSearch.test.ts+++ b/apps/desktop/src/main/localDb/__tests__/conversationSearch.test.ts@@ -120,6 +120,7 @@ function createSearchDb(): Database.Database {extra_dirs TEXT NOT NULL DEFAULT '[]',writable_dirs TEXT NOT NULL DEFAULT '[]',remote_host_id TEXT,+ agent_device_id TEXT,active_turn_started_at INTEGER,active_turn_pid INTEGER,last_turn_ended_at INTEGER,diff --git a/apps/desktop/src/main/localDb/__tests__/orcaTeamStore.test.ts b/apps/desktop/src/main/localDb/__tests__/orcaTeamStore.test.tsindex f0d04db511..6dbb19158c 100644--- a/apps/desktop/src/main/localDb/__tests__/orcaTeamStore.test.ts+++ b/apps/desktop/src/main/localDb/__tests__/orcaTeamStore.test.ts@@ -433,6 +433,7 @@ describe('orcaTeamStore', () => {extra_dirs TEXT NOT NULL DEFAULT '[]',writable_dirs TEXT NOT NULL DEFAULT '[]',remote_host_id TEXT,+ agent_device_id TEXT,provider_id TEXT,active_turn_started_at INTEGER,active_turn_pid INTEGER,diff --git a/apps/desktop/src/main/localDb/__tests__/sessionOpening.test.ts b/apps/desktop/src/main/localDb/__tests__/sessionOpening.test.tsindex ab13a885e8..ccbda58b6f 100644--- a/apps/desktop/src/main/localDb/__tests__/sessionOpening.test.ts+++ b/apps/desktop/src/main/localDb/__tests__/sessionOpening.test.ts@@ -62,3 +62,15 @@ it('lets a queued commit recheck the account before its actual insert', async ()})).rejects.toThrow('账号已变化');expect(h.run).not.toHaveBeenCalled();});++it("leaves model admission to the computer running the agent when the task's agent runs elsewhere", async () => {+ // 那台的模型(如内网 Spark)本机目录里没有:本机不校验,由那台启动时按它的目录裁决。+ const opened = await openSession({ id: 'device-task', body: { ...body, model: 'spark/qwen', providerId: 'spark', agentDeviceId: 'device-b' } });+ expect(opened.row).toMatchObject({ model: 'spark/qwen', providerId: 'spark', agentDeviceId: 'device-b' });+ expect(h.run).toHaveBeenCalledOnce();+});++it('still admits the model here for a blank agent computer', async () => {+ await expect(openSession({ body: { ...body, providerId: 'disconnected', agentDeviceId: ' ' } })).rejects.toThrow('供应商');+ expect(h.values).not.toHaveBeenCalled();+});diff --git a/apps/desktop/src/main/localDb/client/__tests__/drizzleProxy.test.ts b/apps/desktop/src/main/localDb/client/__tests__/drizzleProxy.test.tsindex dc42af68f3..563b09d6a8 100644--- a/apps/desktop/src/main/localDb/client/__tests__/drizzleProxy.test.ts+++ b/apps/desktop/src/main/localDb/client/__tests__/drizzleProxy.test.ts@@ -54,6 +54,7 @@ const DRIZZLE_PROXY_SCHEMA = [extra_dirs TEXT NOT NULL DEFAULT '[]',writable_dirs TEXT NOT NULL DEFAULT '[]',remote_host_id TEXT,+ agent_device_id TEXT,active_turn_started_at INTEGER,active_turn_pid INTEGER,last_turn_ended_at INTEGER,diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.tsindex 07ce361a8f..da9878890c 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts@@ -290,6 +290,7 @@ function createDb(filename = ':memory:'): void {extra_dirs TEXT NOT NULL DEFAULT '[]',writable_dirs TEXT NOT NULL DEFAULT '[]',remote_host_id TEXT,+ agent_device_id TEXT,source TEXT NOT NULL DEFAULT 'desktop',created_at INTEGER NOT NULL,updated_at INTEGER NOT NULL,@@ -4254,6 +4255,8 @@ describe('Bot Session task end-to-end runtime', () => {readSessionRuntimeProfiles: async () => ({ effective: { providerId: 'openai', model: 'gpt-6-astra' },control: { generation: 1, visitedRoutes: [], fallbackHop: 0 } }),canApplyAutomaticRuntimeSelection: () => true,+ // 本机任务(Agent 不在另一台电脑运行)。+ readSessionAgentDeviceId: async () => null,readBotFallbackCandidate: async () => ({ isBot: false, candidate: null }),readSessionRuntimeFallbackSettings: () => ({ enabled: true }),getDesktopProviderService: () => ({ listProviders: async () => [] }),diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionAutoTitlePersist.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionAutoTitlePersist.test.tsindex 97fedf8972..d80715cd7d 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionAutoTitlePersist.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionAutoTitlePersist.test.ts@@ -106,6 +106,7 @@ function createDb(initialTitle: string): void {workspace_kind TEXT NOT NULL DEFAULT 'project',orca_role TEXT,remote_host_id TEXT,+ agent_device_id TEXT,codex_history_has_product_prompt INTEGER,codex_plan_json TEXT,im_bot_context_id TEXT,diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsRestoreIfArchived.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsRestoreIfArchived.test.tsindex f3af100fa9..8b11f92d9d 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsRestoreIfArchived.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsRestoreIfArchived.test.ts@@ -123,6 +123,7 @@ function createDb(): void {workspace_kind TEXT NOT NULL DEFAULT 'project',orca_role TEXT,remote_host_id TEXT,+ agent_device_id TEXT,codex_history_has_product_prompt INTEGER,codex_plan_json TEXT,im_bot_context_id TEXT,diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.tsindex 991e137ed7..ae05185701 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts@@ -238,6 +238,7 @@ function createDb(): void {workspace_kind TEXT NOT NULL DEFAULT 'project',orca_role TEXT,remote_host_id TEXT,+ agent_device_id TEXT,codex_history_has_product_prompt INTEGER,codex_plan_json TEXT,im_bot_context_id TEXT,diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.tsindex 39ccfc69aa..b1f52a6cc1 100644--- a/apps/desktop/src/main/localDb/ipc/sessions.ts+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts@@ -1361,6 +1361,14 @@ export function registerSessionIpc() {throwIpcError('INVALID_PARAMS', `invalid orcaRole: ${String(bodyObj.orcaRole)}`);}+ // Agent 在同账号另一台电脑运行:只接受设备 id 形态的值(与 maker:create-session 同一规则)。+ if (+ bodyObj.agentDeviceId !== undefined &&+ bodyObj.agentDeviceId !== null &&+ (typeof bodyObj.agentDeviceId !== 'string' || !/^[A-Za-z0-9_.:-]{1,128}$/.test(bodyObj.agentDeviceId))+ ) {+ throwIpcError('INVALID_PARAMS', 'agentDeviceId must be a device id');+ }const workspaceKind =(createBody?.workspaceKind as 'project' | 'dialogue' | undefined) ?? 'project';const explicitWorkingDir =diff --git a/apps/desktop/src/main/localDb/mapper.ts b/apps/desktop/src/main/localDb/mapper.tsindex 84a9b8e004..09b1763d3a 100644--- a/apps/desktop/src/main/localDb/mapper.ts+++ b/apps/desktop/src/main/localDb/mapper.ts@@ -267,6 +267,7 @@ export function sessionToCamel(row: SessionRowWithCount): Session {extraDirs: safeParseStringArray(row.extraDirs),writableDirs: safeParseStringArray(row.writableDirs),remoteHostId: row.remoteHostId ?? null,+ agentDeviceId: row.agentDeviceId ?? null,// interrupted-turn-resume:「疑似中断」判定的两个时间戳(unix ms 原样透出,// renderer 打开会话时比较 startedAt > endedAt,见 sessionActiveTurn.ts)。activeTurnStartedAt: row.activeTurnStartedAt ?? null,@@ -372,6 +373,8 @@ export function sessionCreateToRow(writableDirs?: string[];/** Remote codex (P2): 远端 SSH host alias; null/undefined = 本地。 */remoteHostId?: string | null;+ /** Agent 在同账号另一台电脑上运行时那台电脑的 deviceId; null/undefined = Agent 在本机。 */+ agentDeviceId?: string | null;/*** per-session 来源(供应商)显式选择,落盘 sessions.provider_id(与 update 同列)。* null/undefined = 不显式选,跟随该 agent 的原生默认路由(no-break)。草稿态首次@@ -416,6 +419,8 @@ export function sessionCreateToRow(extraDirs: safeStringify(body?.extraDirs ?? []),writableDirs: safeStringify(body?.writableDirs ?? []),remoteHostId: normalizeRemoteHostId(body?.remoteHostId),+ // Agent 运行在另一台电脑时与 SSH 远端互斥:两者同时给出时以 SSH 远端为准、不记录设备。+ agentDeviceId: normalizeRemoteHostId(body?.remoteHostId) ? null : normalizeRemoteHostId(body?.agentDeviceId),// 显式来源:trim 后非空才入库,其余(undefined / null / 空串 / 纯空白)一律落 null,// 与 session-provider-store 的 null 语义对齐(null → 回落默认路由,字节级不变)。providerId:diff --git a/apps/desktop/src/main/localDb/schema.ts b/apps/desktop/src/main/localDb/schema.tsindex e196bac6d0..730c883e78 100644--- a/apps/desktop/src/main/localDb/schema.ts+++ b/apps/desktop/src/main/localDb/schema.ts@@ -230,6 +230,11 @@ export const sessions = sqliteTable(* daemon);两端 in-process MCP 都经 SSH remote-forward 回本机 HTTP bridge。*/remoteHostId: text('remote_host_id'),+ /**+ * Agent 在同账号另一台电脑上运行时,那台电脑的设备 id(任务、项目文件与命令仍在本机)。+ * NULL = Agent 在本机(或 SSH 远端,见 remote_host_id)。与 remote_host_id 互斥。+ */+ agentDeviceId: text('agent_device_id'),/*** interrupted-turn-resume: 最近一次 turn 的启动时刻(unix ms)。与* lastTurnEndedAt 配对做「疑似中断」纯读判定(startedAt > endedAt),两个diff --git a/apps/desktop/src/main/localDb/sessionOpening.ts b/apps/desktop/src/main/localDb/sessionOpening.tsindex 10de9b09f6..6c9b64778a 100644--- a/apps/desktop/src/main/localDb/sessionOpening.ts+++ b/apps/desktop/src/main/localDb/sessionOpening.ts@@ -17,6 +17,10 @@ export function setSessionOpeningModelAdmission(admission: ModelAdmission): voidadmitModel = admission;}+function agentRunsOnOtherDevice(body: SessionOpenBody): boolean {+ return typeof body.agentDeviceId === 'string' && body.agentDeviceId.trim().length > 0;+}+/*** Open a normal Cindy Session. No messages are sent and no callback Agent is started.* Entry adapters authorize the caller/directory. A companion may atomically commit@@ -43,7 +47,10 @@ export async function openSession<T = void>(input: {const now = input.now ?? Date.now();if (!admitModel) throw new Error('任务模型服务尚未就绪,请稍后重试');// Remote model admission belongs to the execution host. Preserve the existing remote path.- const selected = input.body.remoteHostId ? input.body : await admitModel({ ...input.body });+ // Agent 在另一台电脑运行的任务同理:模型与来源来自那台,由那台启动时按它的目录校验。+ const selected = input.body.remoteHostId || agentRunsOnOtherDevice(input.body)+ ? input.body+ : await admitModel({ ...input.body });assertCurrent();const workspaceKind = selected.workspaceKind ?? 'project';const explicitDir = normalizeWorkingDirForStorage(selected.workingDir) ?? undefined;diff --git a/apps/desktop/src/main/maker-host/git-snapshot-host.ts b/apps/desktop/src/main/maker-host/git-snapshot-host.tsindex e20660e35f..8d9d4c8570 100644--- a/apps/desktop/src/main/maker-host/git-snapshot-host.ts+++ b/apps/desktop/src/main/maker-host/git-snapshot-host.ts@@ -138,6 +138,8 @@ export function createGitSnapshotCoordinator(agentKind: meta.agentKind as AgentKind,workspaceKind: meta.workspaceKind,remoteHostId: meta.remoteHostId,+ // Agent 在另一台电脑运行:文件回退统一走本机保存点链(含 Claude Code)。+ ...(meta.agentDeviceId ? { savepointRewind: true } : {}),};},resolveAnchor: async (sessionId) => (await getLatestUserMessageOnce(sessionId))?.clientId,diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.tsindex c4423d2b28..de6e6ee08d 100644--- a/apps/desktop/src/main/maker-host/index.ts+++ b/apps/desktop/src/main/maker-host/index.ts@@ -117,7 +117,7 @@ import {} from '../maker-ipc/register.js';import { MAKER_PUSH } from '../maker-ipc/channels.js';import { tapWindowBroadcast } from '../device-link/broadcast-tap.js';-import { remoteInvoke } from '../device-link/index.js';+import { remoteBackgroundInvoke, remoteInvoke } from '../device-link/index.js';import { handleListDevices, defaultDeps as deviceDirectoryDeps } from '../device-link/ipc.js';import { createHistoryRemoteDeps } from '../mcp-integrations/historyDevices.js';import { WorktreePool } from '../worktree/index.js';@@ -213,7 +213,11 @@ import {buildDesktopClaudeRuntimeConfig,desktopCodexRuntimeConfig,ensureBundledRipgrepReady,+ getRipgrepBinaryPath,} from './runtime-configs.js';+import { createDeviceAgentStarter } from '../remote-agent/controller/service.js';+import { extractReviewPdfTextInChild } from '../reviewer/reviewPdfProcess.js';+import { disposeRemoteAgentHost, installRemoteAgentHost } from '../remote-agent/host/service.js';import {getClaudeEndpoint,setClaudeProxyGatewayKeyReader,@@ -256,7 +260,7 @@ import {} from './codex-proxy-host.js';import { createDesktopMcpProviders } from '../mcp-integrations/mcp-providers.js';import { getGhostRosterPrompt } from '../mcp-integrations/ghost.js';-import { invalidatePiEnvironment } from '../mcp-integrations/piEnvironment.js';+import { getPiExtraSpawnConfig, invalidatePiEnvironment } from '../mcp-integrations/piEnvironment.js';import { readContactsSettings } from './contacts-settings-store.js';import { captureKnownFileBefore, noteOpaqueTurnChange } from '../turn-change-set/store.js';@@ -549,6 +553,9 @@ const staleInvalidatedCcSessions = new Set<string>();* ensureRemoteForward 顺延探测,断线重连由 RemoteHost re-arm 保持。*/const PI_MCP_FORWARD_PORT_START = 47981;+/** Agent 在另一台电脑运行的任务里 Read 读 PDF:抽取进程超时与输入上限(与执行器的 PDF 上限一致)。 */+const REMOTE_AGENT_PDF_TIMEOUT_MS = 30_000;+const REMOTE_AGENT_PDF_MAX_BYTES = 32 * 1024 * 1024;/*** 本进程见过的 bridge 实例 — ensureCodexMcpBridgeStartedForRemote 据此检测* bridge 重建并清空 forcedFreshCcBridgeSessions (旧 bridge 的@@ -2666,6 +2673,25 @@ export function getMaker(): Maker {agents: makerAgents,storage: desktopSessionStorage,logger: desktopMakerLogger,+ // Agent 在同账号另一台电脑上运行、任务与文件留在本机(见 remote-agent/)。+ startDeviceAgentSession: createDeviceAgentStarter({+ remoteInvoke: remoteBackgroundInvoke,+ rgPath: getRipgrepBinaryPath,+ // 对方的 Codex 把本机当 exec-server 执行环境:用本机随包的同一个 codex。+ codexPath: () => getCachedBinaryStatus('codex').binaryPath ?? undefined,+ mcpProviders: () => _mcpProviders.pi ?? _mcpProviders.codex ?? [],+ prepareMcpBridge: getPiExtraSpawnConfig,+ makerMemory: () => makerMemoryManager,+ captureKnownFileBefore,+ noteOpaqueTurnChange,+ // 与审查读 PDF 交付物同一个一次性抽取进程。+ extractPdfText: (data, lastPage, maxChars) => extractReviewPdfTextInChild(data, maxChars, {+ timeoutMs: REMOTE_AGENT_PDF_TIMEOUT_MS,+ maxPages: lastPage,+ maxInputBytes: REMOTE_AGENT_PDF_MAX_BYTES,+ }),+ logger: desktopMakerLogger,+ }),makerMemory: makerMemoryManager,visionBridge: _visionBridgeInstance.hook,toolLoopReviewer: reviewToolLoop,@@ -2674,6 +2700,20 @@ export function getMaker(): Maker {lifecycleHooks: {prepareStartOptions: async (sessionId, opts) => {pendingBotRuntimeSnapshots.delete(sessionId);+ // Agent 在另一台电脑上运行的任务:所有入口(界面、定时任务、IM、协同等)恢复时都以任务+ // 记录为准,Agent 回到原来那台电脑。读失败按本机任务处理(本机任务的启动与原来完全一致;+ // 另一台电脑上的任务这时用的是那台的模型来源,本机没有,会在路由上明确报错)。+ if (opts.agentDeviceId === undefined && !opts.remoteHostId) {+ try {+ const persisted = await desktopSessionStorage.get(sessionId);+ if (persisted?.agentDeviceId) opts.agentDeviceId = persisted.agentDeviceId;+ } catch (error) {+ desktopMakerLogger.warn('session agent device lookup failed; starting the task here', {+ sessionId,+ error: error instanceof Error ? error.message : String(error),+ });+ }+ }const providerReady = await ensureCurrentAccountProviderReadiness();if (!providerReady) {// 未登录 / 正在切账号时这里恒 false。主机通路只把失败压成 errorCode +@@ -2872,6 +2912,8 @@ export function getMaker(): Maker {},},});+ // 本机作为「Agent 运行的电脑」:同账号另一台电脑的任务可让 Agent 在这里运行。+ installRemoteAgentHost({ getMaker: () => getMaker(), userDataDir: app.getPath('userData') });botRuntimeResourcePreflight = async (opts) => {const preflightOpts = { ...opts };return hydrateBotProfileRuntime(preflightOpts, buildBotRuntimeDeps(), {@@ -3061,6 +3103,7 @@ export async function preflightBotRuntimeResources(* 重置 Maker 单例(切账号 / 测试用)。*/export function resetMaker(): void {+ disposeRemoteAgentHost();_sessionArchiveSync?.stop();_sessionArchiveSync = null;setSessionArchiveSyncRequester(null);diff --git a/apps/desktop/src/main/maker-host/session-storage.ts b/apps/desktop/src/main/maker-host/session-storage.tsindex e83a4abbe8..e811ccbe7b 100644--- a/apps/desktop/src/main/maker-host/session-storage.ts+++ b/apps/desktop/src/main/maker-host/session-storage.ts@@ -61,6 +61,7 @@ function rowToMeta(row: SessionRow): SessionMeta {sdkSessionId: row.sdkSessionId ?? undefined,parentSessionId: row.parentSessionId ?? undefined,remoteHostId: row.remoteHostId ?? undefined,+ ...(row.agentDeviceId ? { agentDeviceId: row.agentDeviceId } : {}),createdAt: row.createdAt,updatedAt: row.updatedAt,};@@ -89,6 +90,7 @@ export class DesktopSessionStorage implements SessionStorage {// 避免 maker.createSession (maker:create-session / scheduler / Feishu / Orca 等入口)// 把空白 host 原样入库,导致 renderer 按 local 分组、maker 按 remote-like 处理的分裂。remoteHostId: normalizeRemoteHostId(meta.remoteHostId),+ agentDeviceId: normalizeRemoteHostId(meta.remoteHostId) ? null : normalizeRemoteHostId(meta.agentDeviceId),source: meta.reviewMode === true ? 'review' : 'desktop',createdAt: now,updatedAt: now,diff --git a/apps/desktop/src/main/maker-ipc/__tests__/orcaProviderRoutingSnapshotWiring.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/orcaProviderRoutingSnapshotWiring.test.tsindex af58ef211a..1bd54052e5 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/orcaProviderRoutingSnapshotWiring.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaProviderRoutingSnapshotWiring.test.ts@@ -27,7 +27,9 @@ describe('Orca provider routing snapshot wiring', () => {expect(wiring).toContain('providerService: getDesktopProviderService()');expect(wiring).toContain('getCatalog: getActiveCatalog');expect(routingSource).toContain('waitForDiscovery: true');- expect(registerSource).toContain('getProviderRoutingContext: async (agent, remoteHostId)');+ expect(registerSource).toContain('getProviderRoutingContext: async (agent, remoteHostId, agentDeviceId) => agentDeviceId && !remoteHostId');+ // lead 的 Agent 在另一台电脑运行时按那台的目录;其余与原来一致。+ expect(registerSource).toContain("deviceWorkerRoutingContext(await readDeviceProviderViews(remoteBackgroundInvoke, agentDeviceId), agent ?? 'claude-code')");expect(registerSource).toContain('sshCodexWorkerRoutingContext(await readSshCodexModelList({ id: remoteHostId }, listSshCodexProviders))');});diff --git a/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.tsindex 522a2f14e4..0ed4664b60 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts@@ -22,7 +22,7 @@ import { createOrcaTeamService, type OrcaTeamServiceDeps, type OrcaWorkerRecordSimport type { MakerSessionCreateOpts } from '../sessionRequest';import { CredentialModeSwitchBusyError } from '../../maker-host/codex-credential-switch';import { isActiveWorkerStatus } from '../../../shared/orca-worker-status';-import { sshCodexWorkerRoutingContext } from '../orcaProviderRoutingContext';+import { deviceAvailableModels, deviceWorkerRoutingContext, sshCodexWorkerRoutingContext } from '../orcaProviderRoutingContext';import type { ProviderView } from '@cindy/model-providers';import { createOrcaLifecycleService, type OrcaLifecycleDeps } from '../orcaLifecycleService';@@ -240,6 +240,68 @@ describe('SSH Codex Worker catalog', () => {});});+describe('Worker of a lead whose agent runs on another computer', () => {+ const sparkModels = ['spark/qwen', 'spark/deepseek'].map((id) => ({+ id, name: id, efforts: ['low', 'high'], defaultEffort: 'high', supportsFastMode: false,+ }));+ const views = [+ { id: 'spark', name: 'Spark', source: 'user', agents: ['claude-code', 'pi'], connected: true,+ models: { 'claude-code': sparkModels, pi: sparkModels }, routing: { 'claude-code': {}, pi: {} } },+ { id: 'offline', name: 'Offline', source: 'user', agents: ['pi'], connected: false,+ models: { pi: [{ id: 'offline/model', name: 'Offline', efforts: [], defaultEffort: null }] }, routing: { pi: {} } },+ ] as unknown as ProviderView[];+ const deviceLead = (overrides: Record<string, unknown> = {}) => ({+ id: 'lead-1', agentKind: 'pi' as const, workspaceKind: 'project' as const, workingDir: '/Users/me/repo',+ model: 'spark/qwen', effort: 'high', permissionMode: 'default', fastMode: false, providerId: 'spark',+ remoteHostId: null, agentDeviceId: 'device-b', ...overrides,+ });++ it.each([undefined, 'spark/deepseek', 'local-only'])('uses that computer for membership and defaults (%s)', async (model) => {+ const routing = deviceWorkerRoutingContext(views, 'pi');+ const { deps, service } = createDeps({+ getLeadSessionRow: vi.fn(async () => deviceLead()),+ getProviderRoutingContext: vi.fn(async () => routing),+ getWorkerDefaults: vi.fn(() => ({ model: 'local-only', providerId: 'xd', effort: 'high' })),+ });+ const result = await service.createWorker({ leadSessionId: 'lead-1', role: 'reviewer', label: 'reviewer', agent: 'pi', model });+ expect(deps.getProviderRoutingContext).toHaveBeenCalledWith('pi', null, 'device-b');+ expect(deps.getAvailableModels).not.toHaveBeenCalled();+ expect(deps.getWorkerDefaults).not.toHaveBeenCalled();+ if (model === 'local-only') {+ expect(result.ok).toBe(false);+ expect(deps.bootstrapSession).not.toHaveBeenCalled();+ return;+ }+ expect(result.ok).toBe(true);+ // Worker 跟 lead 在同一台电脑运行,模型与来源按那台的目录。+ expect(deps.bootstrapSession).toHaveBeenCalledWith(expect.objectContaining({+ model: model ?? 'spark/qwen', providerId: 'spark', agentDeviceId: 'device-b',+ }));+ expect(deps.buildCreateOptsWithStderr).toHaveBeenCalledWith(expect.objectContaining({ agentDeviceId: 'device-b' }));+ });++ it("starts from that computer's first model when the lead uses another agent", async () => {+ const routing = deviceWorkerRoutingContext(views, 'claude-code');+ const { deps, service } = createDeps({+ getLeadSessionRow: vi.fn(async () => deviceLead({ agentKind: 'codex', model: 'gpt-5.5', providerId: 'openai' })),+ getProviderRoutingContext: vi.fn(async () => routing),+ });+ const result = await service.createWorker({ leadSessionId: 'lead-1', role: 'reviewer', label: 'reviewer', agent: 'claude-code' });+ expect(result.ok).toBe(true);+ expect(deps.bootstrapSession).toHaveBeenCalledWith(expect.objectContaining({+ agentKind: 'claude-code', model: 'spark/qwen', providerId: 'spark', agentDeviceId: 'device-b',+ }));+ });++ it('lists only connected sources of that computer', () => {+ expect(deviceAvailableModels(views, 'pi')).toEqual([+ { id: 'spark/qwen', label: 'spark/qwen', providers: [{ id: 'spark', name: 'Spark' }], defaultProviderId: 'spark' },+ { id: 'spark/deepseek', label: 'spark/deepseek', providers: [{ id: 'spark', name: 'Spark' }], defaultProviderId: 'spark' },+ ]);+ expect(deviceAvailableModels(views, 'codex')).toEqual([]);+ });+});+const UUID_V4_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;const WORKER_SESSION_ID = '123e4567-e89b-42d3-a456-426614174000';diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.tsindex 470008a370..c3bc95c808 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.ts@@ -491,6 +491,16 @@ describe('performSessionAgentSwitch', () => {expect(onPendingSwitchChanged).not.toHaveBeenCalled();});+ it('passes the switched task to the route check so a task whose agent runs elsewhere is judged there', async () => {+ const assertModelRouteUsable = vi.fn(async () => undefined);+ const { deps } = makeDeps({ assertModelRouteUsable });+ await performSessionAgentSwitch(deps, validParams);+ expect(assertModelRouteUsable).toHaveBeenCalled();+ for (const call of assertModelRouteUsable.mock.calls as unknown[][]) {+ expect(call[3]).toBe(validParams.sessionId);+ }+ });+it('turn 进行中抛 SESSION_RUNNING,不触碰任何状态', async () => {const { deps, calls } = makeDeps({getLiveSession: vi.fn(() => ({ isTurnRunning: () => true })),diff --git a/apps/desktop/src/main/maker-ipc/orcaProviderRoutingContext.ts b/apps/desktop/src/main/maker-ipc/orcaProviderRoutingContext.tsindex 5f2f6ab138..309fad5e01 100644--- a/apps/desktop/src/main/maker-ipc/orcaProviderRoutingContext.ts+++ b/apps/desktop/src/main/maker-ipc/orcaProviderRoutingContext.ts@@ -6,6 +6,7 @@ import {isModelSelectableForNewRoute,isLocalOnlyProviderForAgent,type Catalog,+ type CatalogModel,type ProviderView,} from '@cindy/model-providers';@@ -34,6 +35,78 @@ export function sshCodexWorkerRoutingContext(views: ProviderView[]): OrcaWorkerP};}+/**+ * 运行 Agent 的另一台电脑的目录(那台经设备互联给出的供应商视图):准入与默认值都以那台为准,+ * 不掺本机目录。默认沿用 lead 的模型与来源(同一种 Agent 且那台仍提供时),否则取该 Agent 在+ * 那台的第一个可选模型、来源交给那台的默认路由。+ */+export function deviceWorkerRoutingContext(views: ProviderView[], agent: AgentKind): OrcaWorkerProviderRoutingContext {+ const availabilityFor = (kind: AgentKind) =>+ connectedProvidersForAgent(views, kind).map((provider) => {+ const models = routableModels(provider, kind);+ return {+ id: provider.id,+ name: provider.name,+ models: models.map((model) => model.id),+ fastModels: models.filter((model) => model.supportsFastMode).map((model) => model.id),+ effortMetaByModel: Object.fromEntries(+ models.map((model) => [model.id, { efforts: model.efforts, defaultEffort: model.defaultEffort }]),+ ),+ };+ });+ const availability = {+ 'claude-code': availabilityFor('claude-code'),+ codex: availabilityFor('codex'),+ pi: availabilityFor('pi'),+ };+ const models = deviceRoutableModels(views, agent);+ return {+ remoteCodexModels: models,+ availability,+ remoteWorkerDefaults: (lead, kind) => {+ const sameAgent = lead.agentKind === kind;+ const leadModelOffered = sameAgent && models.some((model) => model.id === lead.model);+ return {+ model: leadModelOffered ? lead.model : models[0]?.id,+ providerId: leadModelOffered ? lead.providerId : null,+ };+ },+ resolveDefaultProviderIdForModel: (kind, model) => effectiveSourceIdForModel(views, null, model, kind),+ };+}++function routableModels(provider: ProviderView, kind: AgentKind): CatalogModel[] {+ return (provider.models[kind] ?? []).filter((model) =>+ isModelSelectableForNewRoute(model, { userProvider: provider.source === 'user' }),+ );+}++/** 那台电脑上某种 Agent 可选的模型(各来源去重,按来源顺序)。 */+function deviceRoutableModels(views: ProviderView[], agent: AgentKind): CatalogModel[] {+ const seen = new Set<string>();+ return connectedProvidersForAgent(views, agent)+ .flatMap((provider) => routableModels(provider, agent))+ .filter((model) => (seen.has(model.id) ? false : (seen.add(model.id), true)));+}++/** list_available_models 用:那台电脑上某种 Agent 的模型、提供它的来源与默认来源。 */+export function deviceAvailableModels(views: ProviderView[], agent: AgentKind): Array<{+ id: string;+ label: string;+ providers: Array<{ id: string; name: string }>;+ defaultProviderId: string | null;+}> {+ const providers = connectedProvidersForAgent(views, agent);+ return deviceRoutableModels(views, agent).map((model) => ({+ id: model.id,+ label: model.name || model.id,+ providers: providers+ .filter((provider) => routableModels(provider, agent).some((entry) => entry.id === model.id))+ .map((provider) => ({ id: provider.id, name: provider.name })),+ defaultProviderId: effectiveSourceIdForModel(views, null, model.id, agent),+ }));+}+/*** Build the Orca worker route snapshot from one post-claim full catalog.*diff --git a/apps/desktop/src/main/maker-ipc/orcaWorkerCreationService.ts b/apps/desktop/src/main/maker-ipc/orcaWorkerCreationService.tsindex a1a521e863..61da67cc0c 100644--- a/apps/desktop/src/main/maker-ipc/orcaWorkerCreationService.ts+++ b/apps/desktop/src/main/maker-ipc/orcaWorkerCreationService.ts@@ -34,6 +34,11 @@ export interface OrcaLeadSessionSnapshot {* 本机目录。null = 本地 lead,worker 也是本地。*/remoteHostId: string | null;+ /**+ * lead 的 Agent 在同账号另一台电脑上运行时那台电脑的设备 id。worker 继承它(Agent 同样在+ * 那台运行,模型与来源按那台的目录选);任务与文件都在本机。缺省 = Agent 在本机。+ */+ agentDeviceId?: string | null;}/** worker limit 与 duplicate label 校验只需要 worker 的身份、label 与占槽状态。 */@@ -99,8 +104,13 @@ export function providerRouteRequiresExplicitSelection(/** 同一次 provider registry 快照派生出的可用性与默认模型路由,避免两次读取产生竞态。 */export interface OrcaWorkerProviderRoutingContext {- /** SSH catalogs own both admission and defaults; never mix controller capabilities. */+ /**+ * SSH catalogs own both admission and defaults; never mix controller capabilities.+ * 运行 Agent 的另一台电脑的目录同理(本机目录里没有那台的模型)。+ */remoteCodexModels?: OrcaWorkerModelCapabilities[];+ /** 远端目录的 worker 默认值(缺省时沿用 SSH Codex 的默认规则)。 */+ remoteWorkerDefaults?: (lead: OrcaLeadSessionSnapshot, agent: AgentKind) => OrcaWorkerDefaultsSnapshot;availability: Record<AgentKind, OrcaWorkerProviderSnapshot[]>;resolveDefaultProviderIdForModel(agent: AgentKind, model: string): string | null;}@@ -229,7 +239,12 @@ export interface OrcaWorkerCreationDeps {* availability 只保留已连接 provider 的最小视图;显式 model 的默认来源解析复用* model-providers 的 effectiveSourceIdForModel,避免在创建服务里复制供应商优先级。*/- getProviderRoutingContext(agent?: AgentKind, remoteHostId?: string | null): Promise<OrcaWorkerProviderRoutingContext>;+ getProviderRoutingContext(+ agent?: AgentKind,+ remoteHostId?: string | null,+ /** lead 的 Agent 在另一台电脑运行时,按那台的目录。 */+ agentDeviceId?: string | null,+ ): Promise<OrcaWorkerProviderRoutingContext>;readClaudeApiKey(): string | null;reserveWorkerCreation(input: {reservationId: string;@@ -665,7 +680,9 @@ export function createOrcaWorkerCreationService(deps: OrcaWorkerCreationDeps): Otypeof params.providerId === 'string' && params.providerId.trim().length > 0? params.providerId.trim(): null;- const providerRouting = await deps.getProviderRoutingContext(params.agent, lead.remoteHostId);+ const providerRouting = lead.agentDeviceId+ ? await deps.getProviderRoutingContext(params.agent, lead.remoteHostId, lead.agentDeviceId)+ : await deps.getProviderRoutingContext(params.agent, lead.remoteHostId);const availableModels = providerRouting.remoteCodexModels ?? deps.getAvailableModels(params.agent);const providerAvailability = providerRouting.availability;const agentProviders = providerAvailability[params.agent] ?? [];@@ -727,10 +744,12 @@ export function createOrcaWorkerCreationService(deps: OrcaWorkerCreationDeps): O// workingDir), ensureRemoteReadyForSessionStart 对 pi 已支持 silent install +// pi-manager 预上传, orca_worker_bridge 工具面经 SSH remote-forward 隧道注入。// 与 CC/Codex remote worker 同构;此闸会让 remote pi lead 完全无法使用 pi worker。- const defaults: OrcaWorkerDefaultsSnapshot = providerRouting.remoteCodexModels- ? { model: lead.agentKind === 'codex' && availableModels.some((model) => model.id === lead.model)- ? lead.model : availableModels[0]?.id, providerId: 'openai' }- : deps.getWorkerDefaults(params.agent);+ const defaults: OrcaWorkerDefaultsSnapshot = providerRouting.remoteWorkerDefaults+ ? providerRouting.remoteWorkerDefaults(lead, params.agent)+ : providerRouting.remoteCodexModels+ ? { model: lead.agentKind === 'codex' && availableModels.some((model) => model.id === lead.model)+ ? lead.model : availableModels[0]?.id, providerId: 'openai' }+ : deps.getWorkerDefaults(params.agent);const workerDefaultProviderId =typeof defaults.providerId === 'string' && defaults.providerId.trim()? defaults.providerId.trim()@@ -1076,6 +1095,8 @@ export function createOrcaWorkerCreationService(deps: OrcaWorkerCreationDeps): O// remote lead 的 worker 继承 remoteHostId:在同一台远端主机上 spawn,// workingDir 在该远端校验;本地 lead 不带此字段(本地 worker)。...(lead.remoteHostId ? { remoteHostId: lead.remoteHostId } : {}),+ // lead 的 Agent 在另一台电脑运行:worker 的 Agent 也在那台(任务与文件在本机)。+ ...(lead.agentDeviceId && !lead.remoteHostId ? { agentDeviceId: lead.agentDeviceId } : {}),model: resolved.model,providerId: resolved.providerId,effort: resolved.effort as MakerSessionCreateOpts['effort'],diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex fac25d695e..b74bd2f6ca 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -20,7 +20,8 @@ import { getManagedLlamaCppService } from '../local-model-runtime/llamaCppServicimport { ensureManagedLlamaCppProvider } from '../local-model-runtime/managedLlamaCppProvider.js';import { setBotRemoteMessageService } from './botRemoteMessageReceiver.js';import { handleListDevices, defaultDeps as deviceDirectoryDeps } from '../device-link/ipc.js';-import { getHostSourceDevice, getSelfDeviceId, remoteInvoke as invokeBotPeer } from '../device-link/index.js';+import { getHostSourceDevice, getSelfDeviceId, remoteBackgroundInvoke, remoteInvoke as invokeBotPeer } from '../device-link/index.js';+import { readDeviceProviderViews } from '../remote-agent/controller/deviceCatalog.js';import { registerModelFavoritesSync } from './modelFavoritesSync.js';import { advanceRuntimeRecoveryNotice } from '../im/shared/runtimeRecoveryNotice.js';import { markImSessionManualRouteOverride } from '../im/shared/manualRouteOverride.js';@@ -919,7 +920,12 @@ import {refreshActiveCatalogFromSource,refreshCustomProvidersIntoCatalog,} from '../maker-host/createDesktopProviderService.js';-import { readOrcaWorkerProviderRoutingContext, sshCodexWorkerRoutingContext } from './orcaProviderRoutingContext.js';+import {+ deviceAvailableModels,+ deviceWorkerRoutingContext,+ readOrcaWorkerProviderRoutingContext,+ sshCodexWorkerRoutingContext,+} from './orcaProviderRoutingContext.js';import {clearSessionProvider,getSessionProvider,@@ -2174,7 +2180,7 @@ interface OrcaCollabService {}) => Promise<{ ok: true; workerId?: string } | { ok: false; errorCode: string; message: string }>;- listAvailableModels: (params: { agent?: AgentKind }) => Promise<+ listAvailableModels: (params: { agent?: AgentKind; callerSessionId?: string }) => Promise<| {ok: true;codex?: Array<{@@ -6975,6 +6981,27 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)}}+ /**+ * 任务记录里「Agent 在哪台电脑运行」(null = 本机)。读失败按本机处理:本机任务的行为与读取+ * 之前完全一致,只有确认是另一台电脑上的任务才走对应分支。+ */+ async function readSessionAgentDeviceId(sessionId: string): Promise<string | null> {+ try {+ const [row] = await getDbClient()+ .drizzle.select({ agentDeviceId: sessions.agentDeviceId, remoteHostId: sessions.remoteHostId })+ .from(sessions)+ .where(eq(sessions.id, sessionId))+ .limit(1);+ return row?.agentDeviceId && !row.remoteHostId ? row.agentDeviceId : null;+ } catch (error) {+ log.warn('session agent device lookup failed; treating the task as local', {+ sessionId,+ error: error instanceof Error ? error.message : String(error),+ });+ return null;+ }+ }+/*** 懒启动 / 队列恢复时,renderer 传来的 createOpts 可能没有 providerId,但 DB 里的* sessions.provider_id 才是这条会话的真实来源选择。必须在 maker.createSession 前补齐,@@ -7091,6 +7118,13 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)didInjectProjectContext: boolean;}> {assertAccess?.();+ // Agent 在另一台电脑上运行的任务:恢复时调用方可能没带设备,以任务记录为准。+ if (o.id && o.agentDeviceId === undefined && !o.remoteHostId) {+ const agentDeviceId = await readSessionAgentDeviceId(o.id);+ if (agentDeviceId) o.agentDeviceId = agentDeviceId;+ }+ // 模型与供应商来自那台电脑(由那台按它自己的目录校验),本机目录里没有它们。+ const agentOnOtherDevice = Boolean(o.agentDeviceId) && !o.remoteHostId;if (o.id && !o.remoteHostId) worktreeManager.assertPrecreatedSessionNotCancelled(o.id);if (o.id && o.workingDir && !o.remoteHostId) {o.workingDir = workingDirectoryRecovery.resolve(o.id, o.workingDir);@@ -7142,11 +7176,13 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)await hydrateProviderIdBeforeSessionStart(o);assertAccess?.();- await ensureManagedOllamaReadyForSession({- providerId: o.providerId,- remoteHostId: o.remoteHostId ?? null,- userDataDir: app.getPath('userData'),- });+ if (!agentOnOtherDevice) {+ await ensureManagedOllamaReadyForSession({+ providerId: o.providerId,+ remoteHostId: o.remoteHostId ?? null,+ userDataDir: app.getPath('userData'),+ });+ }// 停用轴准入(PR #744 review):**新建**会话不得路由到用户停用的模型 / 来源。// renderer 选择器已过滤,但 create-session 在 device-link allowlist 内,老控制端// 可直接点名 —— main 必须自己裁决。resume 豁免(运行中的会话不打断)只给@@ -7156,7 +7192,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// 隐式来源的原生默认落点被停用而有启用替代拷贝时,把会话显式改路由过去(下方// persistAndHydrateSessionProvider 会把它落库):实际路由层对隐式来源走原生// 默认、不查停用标志,仅放行等于继续用停用拷贝付费。- if (typeof o.model === 'string' && o.model) {+ if (typeof o.model === 'string' && o.model && !agentOnOtherDevice) {let verifiedResume = false;if (o.resumeSessionId && typeof o.id === 'string' && o.id) {try {@@ -8159,6 +8195,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)agentKind: sessions.agentKind,source: sessions.source,remoteHostId: sessions.remoteHostId,+ agentDeviceId: sessions.agentDeviceId,status: sessions.status,}).from(sessions)@@ -8176,6 +8213,11 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)if (source.remoteHostId) {throwIpcError('UNSUPPORTED_CAPABILITY', 'Review is local-only in this version');}+ // Agent 在另一台电脑运行的任务:审查任务会沿用它的模型与来源(都在那台),而只读审查还不能+ // 在那台运行。+ if (source.agentDeviceId) {+ throwIpcError('UNSUPPORTED_CAPABILITY', 'Review is not available for tasks whose agent runs on another computer');+ }if (!source.workingDir) {throwIpcError('INVALID_PARAMS', 'The source task has no working directory to review');}@@ -8745,8 +8787,11 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)const agentSwitchDeps: MakerSessionAgentSwitchHandlerDeps = {withSessionLock: withSendToSessionLock,// 停用轴边界裁决:目标路由被停用 → 抛错;隐式默认落点被停用 → 返回启用替代来源。- assertModelRouteUsable: (agent, model, providerId) =>- assertModelRouteUsable(agent, model, providerId),+ // Agent 在另一台电脑运行的任务:目标模型属于那台的目录,由那台的 Agent 启动时裁决。+ assertModelRouteUsable: async (agent, model, providerId, sessionId) =>+ (sessionId && await readSessionAgentDeviceId(sessionId))+ ? undefined+ : assertModelRouteUsable(agent, model, providerId),getSessionRow: async (sessionId) => {const db = getDbClient().drizzle;const [row] = await db@@ -8857,6 +8902,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)const result = await applySessionRuntimeSelection(sessionId, intent.model, intent.providerId, {effort: (intent.effort ?? null) as SessionRuntimeProfile['effort'],fastMode: intent.fastMode ?? false,+ // 只有 Agent 在另一台电脑运行的任务会在意图里带确认过的目标窗口。+ ...(intent.confirmedContextWindow ? { confirmedContextWindow: intent.confirmedContextWindow } : {}),}, { source: 'user', sessionLockHeld: true, applyingUserSelectionOnSend: applyNow,runtimeSource: intent.runtimeSource, configStaged: intent.configStaged === true,assertSelectionCurrent });@@ -9296,6 +9343,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)let createdPreviewClientId: string | null = null;let createdPreviewStarted = false;let handoffWorktree: { sessionId: string; meta: WorktreeMeta } | null = null;+ // 来源任务的 Agent 在另一台电脑运行:新任务继承同一台电脑(它的模型与来源都在那台)。+ let inheritedAgentDeviceId: string | undefined;try {const db = getDbClient().drizzle;let inherited: SendToSessionCreateDefaults;@@ -9336,6 +9385,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions).from(sessions).where(eq(sessions.id, dispatcherSessionId)).limit(1);+ if (meta.agentDeviceId && !meta.remoteHostId) inheritedAgentDeviceId = meta.agentDeviceId;const inheritedBase: SendToSessionCreateDefaults = {agentKind: meta.agentKind,workingDir: resolvedWorkDir,@@ -9362,6 +9412,12 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)executionOverrides.fastMode !== undefined);if (hasExecutionOverrides) {const targetAgent = executionOverrides.agentKind ?? inheritedBase.agentKind;+ const deviceRouting = inheritedAgentDeviceId+ ? deviceWorkerRoutingContext(+ await readDeviceProviderViews(remoteBackgroundInvoke, inheritedAgentDeviceId),+ targetAgent,+ )+ : null;const resolvedExecution = resolveSendToSessionExecutionConfig({source: {agentKind: inheritedBase.agentKind,@@ -9371,9 +9427,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)providerId: inheritedBase.providerId,},overrides: executionOverrides,- availableModels: maker.getCapabilities(targetAgent).availableModels,- providerRouting: await getProviderRoutingContext(),- hasCindyAiApiKey: readClaudeApiKey() != null,+ availableModels: deviceRouting?.remoteCodexModels ?? maker.getCapabilities(targetAgent).availableModels,+ providerRouting: deviceRouting ?? await getProviderRoutingContext(),+ hasCindyAiApiKey: inheritedAgentDeviceId ? true : readClaudeApiKey() != null,});if (!resolvedExecution.ok) {return {@@ -9441,13 +9497,15 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)providerId: inherited.providerId,title: newTitle,permissionMode: inherited.permissionMode ?? 'bypassPermissions',+ ...(inheritedAgentDeviceId ? { agentDeviceId: inheritedAgentDeviceId } : {}),});const { row: openedRow, value: { session } } = await openSession({id: createOpts.id, body: { title: newTitle,agentKind: inherited.agentKind === 'claude-code' ? 'cc' : inherited.agentKind,model: inherited.model, providerId: inherited.providerId, effort: inherited.effort,fastMode: !!inherited.fastMode, permissionMode: createOpts.permissionMode,- workspaceKind: inherited.workspaceKind, workingDir: createOpts.workingDir },+ workspaceKind: inherited.workspaceKind, workingDir: createOpts.workingDir,+ ...(inheritedAgentDeviceId ? { agentDeviceId: inheritedAgentDeviceId } : {}) },}, async (row, assertCurrent) => {const created = await bootstrapSession({ ...createOpts, id: row.id, model: row.model,providerId: row.providerId, effort: (row.effort || undefined) as CreateOpts['effort'],@@ -12458,6 +12516,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)fastMode: !!leadRow.fastMode,providerId: leadRow.providerId ?? null,remoteHostId: leadRow.remoteHostId ?? null,+ ...(leadRow.agentDeviceId && !leadRow.remoteHostId ? { agentDeviceId: leadRow.agentDeviceId } : {}),};},getWorkerDefaults: getWorkerDefaultsFromNewMaker,@@ -12478,9 +12537,12 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)return resolved;},getAvailableModels: (agent) => maker.getCapabilities(agent).availableModels,- getProviderRoutingContext: async (agent, remoteHostId) => agent === 'codex' && remoteHostId- ? sshCodexWorkerRoutingContext(await readSshCodexModelList({ id: remoteHostId }, listSshCodexProviders))- : getProviderRoutingContext(),+ getProviderRoutingContext: async (agent, remoteHostId, agentDeviceId) => agentDeviceId && !remoteHostId+ // lead 的 Agent 在另一台电脑运行:worker 的模型与来源按那台的目录。+ ? deviceWorkerRoutingContext(await readDeviceProviderViews(remoteBackgroundInvoke, agentDeviceId), agent ?? 'claude-code')+ : agent === 'codex' && remoteHostId+ ? sshCodexWorkerRoutingContext(await readSshCodexModelList({ id: remoteHostId }, listSshCodexProviders))+ : getProviderRoutingContext(),readClaudeApiKey,reserveWorkerCreation,renewWorkerCreationReservation,@@ -12922,6 +12984,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)route: SessionRouteSelection,currentAgentKind: AgentKind,): Promise<void> => {+ // 自动跟随(渠道默认 / 伙伴模型)给的是本机目录里的路由;Agent 在另一台电脑运行的任务+ // 用那台的目录,不跟随。+ if (await readSessionAgentDeviceId(sessionId)) return;if (route.agentKind !== currentAgentKind) {await performSessionAgentSwitch(agentSwitchDeps, {sessionId, targetAgentKind: route.agentKind, model: route.model,@@ -13209,6 +13274,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)try {const profiles = await readSessionRuntimeProfiles(sessionId);if (!profiles || !isCurrent()) return { session: null, outcome: 'superseded' };+ // 自动换模型的候选来自本机目录;Agent 在另一台电脑运行的任务不在本机换,照常重试原路由。+ if (await readSessionAgentDeviceId(sessionId)) {+ return { session: null, outcome: requireRouteChange ? 'exhausted' : 'unchanged' };+ }// A previously accepted Agent/fallback mutation owns the next boundary.// Do not let a later infrastructure retry replace that pending intent.if (profiles.control.pending ||@@ -13887,9 +13956,21 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)};}},- listAvailableModels: async ({ agent }) => {+ listAvailableModels: async ({ agent, callerSessionId }) => {try {const agents: AgentKind[] = agent ? [agent] : ['codex', 'claude-code', 'pi'];+ // Agent 在另一台电脑运行的任务:Worker 也在那台运行,列那台的模型与来源。+ const agentDeviceId = callerSessionId ? await readSessionAgentDeviceId(callerSessionId) : null;+ if (agentDeviceId) {+ const views = await readDeviceProviderViews(remoteBackgroundInvoke, agentDeviceId);+ return {+ ok: true,+ ...Object.fromEntries(agents.map((a) => [+ a === 'codex' ? 'codex' : a === 'pi' ? 'pi' : 'claude_code',+ deviceAvailableModels(views, a),+ ])),+ };+ }const providerRouting = await getProviderRoutingContext();const result: Record<string,@@ -17840,6 +17921,158 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// session 不存在(被 close / 还没 send 创建出来)就 no-op 不报错, 让 renderer// 可以乐观调用 (UI 更新先行, IPC 失败也不会回滚 UI, 老 agentManager 同语义)。+ /**+ * Agent 在另一台电脑上运行的任务:模型目录、来源、思考档与上下文窗口都属于那台电脑,本机目录+ * 不参与校验,由那台的 Agent 在切换时裁决(不认识的模型直接报错,任务保持原模型)。点选仍先+ * 记成意图、在发送时于同一把会话锁里落地,与本机任务一致。+ */+ const applyAgentDeviceRuntimeSelection = async (input: {+ sessionId: string;+ model: string;+ providerId: unknown;+ atomicSelection: { effort: SessionRuntimeProfile['effort']; fastMode: boolean } | undefined;+ /** 渲染端按那台的目录确认过的目标上下文窗口(换到更小窗口的模型时)。 */+ confirmedContextWindow?: number;+ internalOptions: InternalRuntimeSelectionOptions;+ runtimeStatus: {+ orcaRole: string | null;+ agentKind: string;+ providerId: string | null;+ effort: string | null;+ fastMode: boolean;+ };+ assertRuntimeOwnerCurrent(): void;+ assertSharedTaskCurrent: { admit(): void };+ supersededByOwnerBoundary(): boolean;+ }): ReturnType<typeof applySessionRuntimeSelection> => {+ const {+ sessionId, model, providerId, atomicSelection, internalOptions, runtimeStatus,+ assertRuntimeOwnerCurrent, assertSharedTaskCurrent, supersededByOwnerBoundary,+ } = input;+ const targetContextWindow = typeof input.confirmedContextWindow === 'number' && input.confirmedContextWindow > 0+ ? input.confirmedContextWindow+ : undefined;+ const currentProviderId = hasSessionProvider(sessionId)+ ? getSessionProvider(sessionId)+ : runtimeStatus.providerId?.trim() || null;+ const pendingSelection = agentSwitchPending.get(sessionId);+ const targetProviderId =+ typeof providerId === 'string' || providerId === null+ ? (normalizeSessionProviderId(providerId) ?? null)+ : internalOptions.source === 'user' && pendingSelection?.sameAgentSelection+ ? (pendingSelection.providerId ?? null)+ : currentProviderId;+ const targetEffort = atomicSelection+ ? atomicSelection.effort+ : ((runtimeStatus.effort ?? null) as SessionRuntimeProfile['effort']);+ const targetFastMode = atomicSelection?.fastMode ?? runtimeStatus.fastMode;+ const agentKind = dbToMakerAgentKind(runtimeStatus.agentKind as 'cc' | 'codex' | 'pi');+ if (internalOptions.source === 'user' && !internalOptions.applyingUserSelectionOnSend &&+ !runtimeStatus.orcaRole) {+ assertRuntimeOwnerCurrent();+ assertSharedTaskCurrent.admit();+ const intent = {+ ...(internalOptions.runtimeSource ? { runtimeSource: internalOptions.runtimeSource } : {}),+ ...(internalOptions.configStaged === true ? { configStaged: true } : {}),+ sameAgentSelection: true,+ targetAgentKind: agentKind,+ model,+ providerId: targetProviderId,+ effort: targetEffort ?? undefined,+ fastMode: targetFastMode,+ ...(targetContextWindow ? { confirmedContextWindow: targetContextWindow } : {}),+ };+ agentSwitchPending.set(sessionId, intent);+ agentSwitchDeps.onPendingSwitchChanged?.(sessionId, projectPendingAgentSwitchIntent(intent));+ wakeSessionInputAfterCredentialSwitch(sessionId);+ const response = { deferred: true, superseded: false, pendingUntilSend: true };+ return response;+ }+ if (supersededByOwnerBoundary()) return { deferred: false, superseded: true };+ const live = maker.getSession(sessionId);+ if (live && isSessionInTurn(sessionId)) {+ // 自动跟随(渠道默认 / 回退)在回合中不改;用户的选择由发送边界在回合外落地。+ if (internalOptions.source !== 'user') return { deferred: false, superseded: true };+ throwIpcError('PRECONDITION_FAILED', 'the agent is still working; change the model after this turn');+ }+ assertSharedTaskCurrent.admit();+ // 换到上下文更小的模型:与本机任务同一套保护——占用超过目标窗口的安全线时先把对话交接+ // 成摘要、关掉当前会话,下一次发送按新模型重新开始。目标窗口来自那台的目录(点选时已确认)。+ let rebuiltForWindow = false;+ if (live && targetContextWindow && contextOverflowRolloverHolder) {+ const prepared = await contextOverflowRolloverHolder.prepareModelWindowSwitch(sessionId, {+ contextWindow: targetContextWindow,+ recheckTargetPressure: true,+ confirmedTargetPressure: internalOptions.applyingUserSelectionOnSend === true,+ assertCanCommit: () => {+ assertRuntimeOwnerCurrent();+ assertSharedTaskCurrent.admit();+ },+ });+ if (prepared === 'busy') {+ throwIpcError('PRECONDITION_FAILED', 'the agent is still working; change the model after this turn');+ }+ if (prepared === 'confirmation-required') {+ return { deferred: false, superseded: false, contextWindowConfirmationRequired: targetContextWindow };+ }+ rebuiltForWindow = prepared === 'rebuilt';+ }+ if (live && !rebuiltForWindow) {+ // 那台的 Agent 认为需要换进程(跨来源等)时关掉本次连接,下一次发送按新路由重新启动+ // 并接上原来的对话;否则直接在那台的会话里切换。+ const rebuild = await live.requiresModelSwitchRebuild?.(model, { providerId: targetProviderId }) ?? false;+ if (rebuild) {+ await withRehydrateCloseSuppressed(sessionId, () => maker.closeSession(sessionId, 'runtime-refresh'));+ } else {+ await live.setModel?.(model, {+ providerId: targetProviderId,+ ...(targetEffort ? { effort: targetEffort } : {}),+ });+ if (atomicSelection) await live.setFastMode?.(targetFastMode);+ }+ }+ setSessionProvider(sessionId, targetProviderId);+ if (atomicSelection) {+ setSessionEffort(sessionId, targetEffort);+ setSessionFastMode(sessionId, targetFastMode);+ }+ const patch: Record<string, unknown> = { model, providerId: targetProviderId };+ if (atomicSelection) {+ if (targetEffort !== null) patch.effort = targetEffort;+ patch.fastMode = targetFastMode;+ }+ await persistSessionFields(sessionId, patch);+ if (!internalOptions.applyingUserSelectionOnSend) {+ agentSwitchPending.clear(sessionId);+ broadcastSessionPatched(sessionId, { agentSwitchIntent: null, agentSwitchIntentCanceled: true });+ }+ const profile: SessionRuntimeProfile = {+ agentKind,+ model,+ providerId: targetProviderId,+ effort: targetEffort ?? (getSessionEffort(sessionId) as SessionRuntimeProfile['effort']) ?? null,+ fastMode: targetFastMode,+ };+ const generation = internalOptions.source === 'user'+ ? recordUserSessionRuntimeMutation(sessionId)+ : acceptSessionRuntimeMutation({+ sessionId,+ source: internalOptions.source,+ previousProfile: internalOptions.previousProfile,+ deferred: false,+ profile,+ });+ wakeSessionInputAfterCredentialSwitch(sessionId);+ await broadcastSessionRuntimeProjection(sessionId, internalOptions.source === 'user' ? profile : undefined)+ .catch((error) => {+ log.debug('agent-device runtime projection broadcast failed', {+ sessionId,+ error: error instanceof Error ? error.message : String(error),+ });+ });+ return { deferred: false, superseded: false, generation, effectiveProviderId: targetProviderId };+ };+const handleSetModel = async (sessionId: unknown,model: unknown,@@ -17944,6 +18177,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)orcaRole: sessions.orcaRole,agentKind: sessions.agentKind,remoteHostId: sessions.remoteHostId,+ agentDeviceId: sessions.agentDeviceId,sdkSessionId: sessions.sdkSessionId,model: sessions.model,providerId: sessions.providerId,@@ -17984,6 +18218,13 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)) {return { deferred: false, superseded: true };}+ if (runtimeStatus.agentDeviceId && !runtimeStatus.remoteHostId) {+ return applyAgentDeviceRuntimeSelection({+ sessionId, model, providerId, atomicSelection, internalOptions, runtimeStatus,+ assertRuntimeOwnerCurrent, assertSharedTaskCurrent, supersededByOwnerBoundary,+ ...(typeof confirmedContextWindow === 'number' ? { confirmedContextWindow } : {}),+ });+ }// 停用轴准入(PR #744 review;第十二轮移入锁内):切换模型是一次新的路由选择,// 不得切到用户停用的模型 / 来源(本机选择器已过滤,但本 channel 在 device-link// allowlist 内,老控制端可直接点名)。裁决必须在拿到会话锁**之后**执行 ——diff --git a/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts b/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.tsindex 8c90780553..06f63a5967 100644--- a/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts+++ b/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts@@ -131,6 +131,8 @@ export interface MakerSessionAgentSwitchHandlerDeps {agent: 'claude-code' | 'codex' | 'pi',model: string,providerId: string | null,+ /** 被切换的任务;Agent 在另一台电脑运行的任务按那台的目录裁决(本机不校验)。 */+ sessionId?: string,): Promise<string | undefined>;getSessionRow(sessionId: string): Promise<AgentSwitchSessionRow | null>;getLiveSession(sessionId: string): { isTurnRunning(): boolean } | null | undefined;@@ -264,6 +266,11 @@ export interface PendingAgentSwitchIntent {providerId: string | null | undefined;effort?: string;fastMode?: boolean;+ /**+ * Agent 在另一台电脑运行的任务:点选时按那台的目录确认过的目标上下文窗口。本机目录里没有+ * 那台的模型,发送时据此做「换小窗口前先交接」。本机任务不设。+ */+ confirmedContextWindow?: number;/** resume 回落事务失败后的内部恢复载荷;下一次 send 先重试这笔原子事务。 */resumeFallbackRecovery?: {boundaryClientId: string | null;@@ -416,6 +423,7 @@ export async function performSessionAgentSwitch(targetAgentKind,model,typeof normalizedProviderId === 'string' ? normalizedProviderId : null,+ sessionId,);if (reroute && shouldApplyExclusiveProviderRerouteLive(normalizedProviderId)) {normalizedProviderId = reroute;@@ -581,6 +589,7 @@ export async function performSessionAgentSwitch(targetAgentKind,model,typeof normalizedProviderId === 'string' ? normalizedProviderId : null,+ sessionId,);if (rerouteAtCommit && typeof normalizedProviderId !== 'string') {normalizedProviderId = rerouteAtCommit;diff --git a/apps/desktop/src/main/maker-ipc/sessionRequest.ts b/apps/desktop/src/main/maker-ipc/sessionRequest.tsindex 6b077a16cc..4a020942bd 100644--- a/apps/desktop/src/main/maker-ipc/sessionRequest.ts+++ b/apps/desktop/src/main/maker-ipc/sessionRequest.ts@@ -49,6 +49,8 @@ export interface MakerSessionCreateOpts extends CreateSessionOptions {* 目前仅 Codex 支持,Claude session 会忽略。*/remoteHostId?: string;+ /** Agent 在同账号另一台电脑上运行时那台电脑的 deviceId(任务与文件仍在本机)。 */+ agentDeviceId?: string;/*** per-session 来源(供应商)显式选择。device-link 远程 create 由控制端透传被控端供应商 id* (见 deviceLinkCreateArgs);bootstrapSession 据此把 sessions.provider_id 落库,使新会话首个@@ -136,6 +138,15 @@ export function readCreateSessionOpts(deps.now ? deps.now() : Date.now(),): requireString(body.workingDir, 'workingDir');+ // Agent 运行在同账号另一台电脑上:只接受设备 id 形态的值,且不能与 SSH 远端同时使用。+ if (body.agentDeviceId !== undefined && body.agentDeviceId !== null) {+ if (typeof body.agentDeviceId !== 'string' || !/^[A-Za-z0-9_.:-]{1,128}$/.test(body.agentDeviceId)) {+ throwIpcError('INVALID_PARAMS', 'agentDeviceId must be a device id');+ }+ if (typeof body.remoteHostId === 'string' && body.remoteHostId.trim()) {+ throwIpcError('INVALID_PARAMS', 'agentDeviceId cannot be combined with remoteHostId');+ }+ }return {...body,id,diff --git a/apps/desktop/src/main/maker-orchestration/fork.ts b/apps/desktop/src/main/maker-orchestration/fork.tsindex 084bea2bcd..06583bfd33 100644--- a/apps/desktop/src/main/maker-orchestration/fork.ts+++ b/apps/desktop/src/main/maker-orchestration/fork.ts@@ -791,6 +791,10 @@ export async function forkSessionAtMessage(if (source.remoteHostId) {throw forkError('REMOTE_NOT_SUPPORTED', '远端会话暂不支持在本地 fork');}+ // Agent 在另一台电脑运行的任务:Agent 会话记录在那台,本机无法从中分叉。+ if (source.agentDeviceId) {+ throw forkError('REMOTE_NOT_SUPPORTED', '这个任务的 Agent 在另一台电脑运行,暂不支持分叉');+ }// 2. 读 target message + rowid —— 同毫秒边界必须按真实插入顺序判断。const [target] = await db@@ -1101,6 +1105,9 @@ export async function forkSessionStripEncrypted(sourceSessionId: string): Promis'远端 Codex 会话暂不支持剥离 fork(rollout 在远端,本地无法剥离)',);}+ if (source.agentDeviceId) {+ throw forkError('REMOTE_NOT_SUPPORTED', '这个任务的 Agent 在另一台电脑运行,暂不支持分叉');+ }if (!source.sdkSessionId) {throw forkError('SOURCE_NEVER_RAN', '原会话尚未运行,无法 fork');}diff --git a/apps/desktop/src/main/maker-orchestration/rewind.ts b/apps/desktop/src/main/maker-orchestration/rewind.tsindex de601f7928..1d3893629c 100644--- a/apps/desktop/src/main/maker-orchestration/rewind.ts+++ b/apps/desktop/src/main/maker-orchestration/rewind.ts@@ -167,6 +167,39 @@ interface RewindContext {codexUserMessages?: CodexRewindUserMessage[];/** DB 事务保留用 uuid;旧数据里可能是 synthetic block uuid,和 SDK anchor 不同。 */preserveMessageUuid?: string;+ /**+ * Claude Code 在另一台电脑运行:那台没有原生文件检查点,文件用本机保存点链回退(与 Codex /+ * Pi 同一套),对话只在那台截断。本机 Claude Code 任务不设。+ */+ savepointRewind?: true;+}++/** target 及其之后仍可见的 user 消息(按时间线);不含 target 时说明它已不在当前时间线。 */+async function loadTailUserTurns(+ sessionId: string,+ target: { rowid: number; createdAt: number },+): Promise<Array<{ rowid: number; clientId: string; createdAt: number }>> {+ const db = getDbClient().drizzle;+ return db+ .select({+ rowid: messageRowid,+ id: messages.id,+ clientId: messages.clientId,+ createdAt: messages.createdAt,+ })+ .from(messages)+ .where(+ and(+ eq(messages.sessionId, sessionId),+ eq(messages.role, 'user'),+ or(+ gt(messages.createdAt, target.createdAt),+ and(eq(messages.createdAt, target.createdAt), gte(messageRowid, target.rowid)),+ ),+ isNull(messages.rewindAt),+ ),+ )+ .orderBy(asc(messages.createdAt), asc(messageRowid));}async function loadRewindContext(@@ -262,26 +295,7 @@ async function loadRewindContext(}if (agentKind === 'codex' || agentKind === 'pi') {- const tailTurns = await db- .select({- rowid: messageRowid,- id: messages.id,- clientId: messages.clientId,- createdAt: messages.createdAt,- })- .from(messages)- .where(- and(- eq(messages.sessionId, sessionId),- eq(messages.role, 'user'),- or(- gt(messages.createdAt, target.createdAt),- and(eq(messages.createdAt, target.createdAt), gte(messageRowid, target.rowid)),- ),- isNull(messages.rewindAt),- ),- )- .orderBy(asc(messages.createdAt), asc(messageRowid));+ const tailTurns = await loadTailUserTurns(sessionId, target);const targetStillVisible = tailTurns.some((row) => row.rowid === target.rowid);if (!targetStillVisible) {throw rewindError('MESSAGE_NOT_FOUND', `Message ${clientId} 不在当前 agent turn 时间线`);@@ -363,6 +377,20 @@ async function loadRewindContext(`[rewind] sessionId=${sessionId.slice(0, 8)} clientId=${clientId} target.createdAt=${target.createdAt} userUuid=${userUuid ?? 'NONE'} assistantUuid=${assistantUuid} preserveMessageUuid=${preserveMessageUuid ?? assistantUuid}`,);+ // Claude Code 在另一台电脑运行:文件按本机保存点链回退,需要 target 之后的 user 消息时间线。+ let savepointTimeline: Pick<RewindContext, 'savepointRewind' | 'codexUserMessages' | 'targetRowid'> = {};+ if (currentSessionMeta?.agentDeviceId && !currentSessionMeta.remoteHostId) {+ const tailTurns = await loadTailUserTurns(sessionId, target);+ if (!tailTurns.some((row) => row.rowid === target.rowid)) {+ throw rewindError('MESSAGE_NOT_FOUND', `Message ${clientId} 不在当前 agent turn 时间线`);+ }+ savepointTimeline = {+ savepointRewind: true,+ targetRowid: target.rowid,+ codexUserMessages: tailTurns.map((row) => ({ clientId: row.clientId, createdAt: row.createdAt })),+ };+ }+return {targetCreatedAt: target.createdAt,targetMessageId: target.id,@@ -371,6 +399,7 @@ async function loadRewindContext(assistantUuid,userUuid,preserveMessageUuid: preserveMessageUuid ?? assistantUuid,+ ...savepointTimeline,};}@@ -393,7 +422,7 @@ export async function previewRewindAtMessage(if (!makerSession) {throw rewindError('NO_LIVE_QUERY', '会话未激活');}- if (ctx.agentKind === 'codex' || ctx.agentKind === 'pi') {+ if (ctx.agentKind === 'codex' || ctx.agentKind === 'pi' || ctx.savepointRewind) {return previewCodexFileRewindPlan(await buildCodexFilePlanForSession(sessionId, clientId, ctx.codexUserMessages ?? [], makerSession));}if (!ctx.userUuid) {@@ -795,6 +824,35 @@ export async function commitRewindAtMessage() {nativeForkAnchorSessionMap = [[previousSdkSessionId, rewindResult.sdkSessionId]];}+ } else if (ctx.savepointRewind) {+ // Claude Code 在另一台电脑运行:先用本机保存点链回退文件,再让那台的 Claude Code 只截断+ // 对话(空 userUuid = 不碰它那边并不存在的文件检查点);截断失败时撤回文件回退。+ expectedClearedAt = await rereadSessionClearedAt(sessionId);+ await assertClearGenerationUnchanged(sessionId, expectedClearedAt, ctx.targetCreatedAt);+ const commitConversationRewind = () => makerSession.commitRewindFiles('', ctx.assistantUuid!);+ if (opts?.allowFileRestore === false) {+ rewindResult = await commitConversationRewind();+ } else {+ const filePlan = await buildCodexFilePlanForSession(sessionId, clientId, ctx.codexUserMessages ?? [], makerSession);+ const onCompensationError = (compErr: unknown, execution: { rollbackCommit: string | null }) => {+ log.error('[rewind commit] claude-code (other computer) file rewind compensation failed', {+ sessionId,+ rollbackCommit: execution.rollbackCommit,+ error: compErr instanceof Error ? compErr.message : String(compErr),+ });+ };+ const result =+ filePlan.mode === 'file-restore'+ ? await executeCodexFileRestorePlanWithThreadRollback(filePlan, sessionId, {+ commitThreadRollback: commitConversationRewind,+ onCompensationError,+ })+ : await executeCodexFileRewindPlanWithThreadRollback(filePlan, sessionId, {+ commitThreadRollback: commitConversationRewind,+ onCompensationError,+ });+ rewindResult = result.threadRollback;+ }} else {expectedClearedAt = await rereadSessionClearedAt(sessionId);await assertClearGenerationUnchanged(sessionId, expectedClearedAt, ctx.targetCreatedAt);diff --git a/apps/desktop/src/main/mcp-integrations/moveSession.ts b/apps/desktop/src/main/mcp-integrations/moveSession.tsindex 170207267e..b3ec055ad8 100644--- a/apps/desktop/src/main/mcp-integrations/moveSession.ts+++ b/apps/desktop/src/main/mcp-integrations/moveSession.ts@@ -66,6 +66,9 @@ async function moveSessionProject(if (!target) throwIpcError('NOT_FOUND', 'Task does not exist in this account.');if (target.remoteHostId)throwIpcError('UNSUPPORTED_CAPABILITY', 'Remote tasks cannot be moved.');+ // The agent's conversation record lives on that computer, keyed by the project path.+ if (target.agentDeviceId)+ throwIpcError('UNSUPPORTED_CAPABILITY', 'Tasks whose agent runs on another computer cannot be moved.');if (target.status !== 'active')throwIpcError('PRECONDITION_FAILED', 'Only active tasks can be moved.');// Review immutability is also enforced by updateSessionInDb for all callers.diff --git a/apps/desktop/src/main/mcp-integrations/piEnvironment.ts b/apps/desktop/src/main/mcp-integrations/piEnvironment.tsindex 50c22739e4..79493826e3 100644--- a/apps/desktop/src/main/mcp-integrations/piEnvironment.ts+++ b/apps/desktop/src/main/mcp-integrations/piEnvironment.ts@@ -303,7 +303,7 @@ export async function getPiExtraSpawnConfig(vendorOptions[CODEX_ALLOWED_BUILTIN_PLUGIN_IDS_KEY] = allowedPluginIds;}const liziCtx: LiziMcpSessionContext = {- agentKind: 'pi',+ agentKind: sessionCtx?.agentKind ?? 'pi',sessionId,...(sessionCtx?.sessionInstanceId ? { sessionInstanceId: sessionCtx.sessionInstanceId } : {}),workingDir: sessionCtx?.workingDir ?? '',diff --git a/apps/desktop/src/main/remote-agent/__tests__/claudeHosted.e2e.test.ts b/apps/desktop/src/main/remote-agent/__tests__/claudeHosted.e2e.test.tsnew file mode 100644index 0000000000..1196fe1a13--- /dev/null+++ b/apps/desktop/src/main/remote-agent/__tests__/claudeHosted.e2e.test.ts@@ -0,0 +1,269 @@+/**+ * 远程 Agent × 真实 Claude Code 端到端:+ * 控制端(任务、项目文件) ⇄ 被控端运行服务 ⇄ 真 Claude Code(cwd = 影子目录) ⇄ 假 Anthropic 网关+ * 自带文件与命令工具关掉,由 cindy_exec(经隧道回到控制端执行)顶替;断言模型拿到的工具清单、+ * 系统提示里的真实路径,以及每一步都落在控制端的项目目录里。依赖 apps/claude-code-bin;缺失时跳过。+ */+import { randomUUID } from 'node:crypto';+import fs from 'node:fs';+import { createServer, type Server } from 'node:http';+import os from 'node:os';+import path from 'node:path';++import { ClaudeCodeAgent, type AgentDeps, type AgentEvent, type InteractionRequest, type Logger } from '@cindy/maker-core';+import { afterAll, beforeAll, describe, expect, it } from 'vitest';++import { remoteAgentEventMapper } from '../controller/eventMap';+import { startRemoteAgentSession } from '../controller/startRemote';+import { createRemoteAgentHost } from '../host/runHost';+import { hostedStartOptions } from '../host/service';++const REPO = path.resolve(__dirname, '../../../../../..');+const ARCH = `${process.platform}-${process.arch}`;+const CLAUDE = path.join(REPO, 'apps', 'claude-code-bin', ARCH, process.platform === 'win32' ? 'claude.exe' : 'claude');+const RG = path.join(REPO, 'apps', 'ripgrep-bin', ARCH, process.platform === 'win32' ? 'rg.exe' : 'rg');+const available = fs.existsSync(CLAUDE) && fs.existsSync(RG) && process.platform !== 'win32';+const MODEL = 'claude-sonnet-4-5';++const noopLogger: Logger = {+ trace: () => {}, debug: () => {}, info: () => {}, warn: () => {}, error: () => {}, fatal: () => {},+ child: () => noopLogger,+};++function sse(events: unknown[]): string {+ return events.map((event) => `event: ${(event as { type: string }).type}\ndata: ${JSON.stringify(event)}\n\n`).join('');+}++function toolUse(step: number, name: string, input: unknown): string {+ return sse([+ { type: 'message_start', message: { id: `msg_${step}`, type: 'message', role: 'assistant', model: MODEL, content: [], stop_reason: null, usage: { input_tokens: 10, output_tokens: 0 } } },+ { type: 'content_block_start', index: 0, content_block: { type: 'tool_use', id: `toolu_${step}_${randomUUID().slice(0, 6)}`, name, input: {} } },+ { type: 'content_block_delta', index: 0, delta: { type: 'input_json_delta', partial_json: JSON.stringify(input) } },+ { type: 'content_block_stop', index: 0 },+ { type: 'message_delta', delta: { stop_reason: 'tool_use', stop_sequence: null }, usage: { output_tokens: 5 } },+ { type: 'message_stop' },+ ]);+}++function text(value: string): string {+ return sse([+ { type: 'message_start', message: { id: 'msg_text', type: 'message', role: 'assistant', model: MODEL, content: [], stop_reason: null, usage: { input_tokens: 10, output_tokens: 0 } } },+ { type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } },+ { type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: value } },+ { type: 'content_block_stop', index: 0 },+ { type: 'message_delta', delta: { stop_reason: 'end_turn', stop_sequence: null }, usage: { output_tokens: 3 } },+ { type: 'message_stop' },+ ]);+}++interface MainRequest {+ system: string;+ firstUser: string;+ toolNames: string[];+ results: Array<{ text: string; isError: boolean }>;+}++function contentText(content: unknown): string {+ if (typeof content === 'string') return content;+ if (!Array.isArray(content)) return '';+ return content.map((part: { type?: string; text?: string }) => (part.type === 'text' ? part.text ?? '' : '')).join('');+}++describe.skipIf(!available)('remote agent with a real Claude Code', () => {+ let server: Server;+ let endpoint = '';+ let root = '';+ let steps: Array<{ name: string; input: unknown }> = [];+ const requests: MainRequest[] = [];+ const previousHome = process.env.HOME;++ beforeAll(async () => {+ root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-cc-hosted-')));+ // Claude Code 读写 ~/.claude:指向临时目录,不碰开发机的真实配置。+ process.env.HOME = path.join(root, 'home');+ fs.mkdirSync(process.env.HOME, { recursive: true });+ server = createServer((req, res) => {+ let body = '';+ req.on('data', (chunk) => { body += chunk; });+ req.on('end', () => {+ if (req.url?.includes('count_tokens')) {+ res.writeHead(200, { 'content-type': 'application/json' });+ res.end(JSON.stringify({ input_tokens: 100 }));+ return;+ }+ let parsed: { system?: unknown; tools?: Array<{ name: string }>; messages?: Array<{ role: string; content: unknown }> } = {};+ try {+ parsed = JSON.parse(body || '{}');+ } catch {+ parsed = {};+ }+ res.writeHead(200, { 'content-type': 'text/event-stream' });+ const toolNames = (parsed.tools ?? []).map((tool) => tool.name);+ // 只有带 cindy_exec 工具的主请求按脚本回;标题生成等辅助请求回一句话。+ if (!toolNames.some((name) => name.startsWith('mcp__cindy_exec__'))) {+ res.end(text('ok'));+ return;+ }+ const system = typeof parsed.system === 'string'+ ? parsed.system+ : Array.isArray(parsed.system) ? parsed.system.map((part: { text?: string }) => part.text ?? '').join('\n') : '';+ const results: MainRequest['results'] = [];+ let firstUser = '';+ for (const message of parsed.messages ?? []) {+ if (!firstUser && message.role === 'user') firstUser = contentText(message.content);+ if (!Array.isArray(message.content)) continue;+ for (const block of message.content as Array<Record<string, unknown>>) {+ if (block.type === 'tool_result') results.push({ text: contentText(block.content), isError: block.is_error === true });+ }+ }+ requests.push({ system, firstUser, toolNames, results });+ const step = steps[results.length];+ res.end(step ? toolUse(results.length, step.name, step.input) : text('all done'));+ });+ });+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));+ endpoint = `http://127.0.0.1:${(server.address() as { port: number }).port}`;+ });++ afterAll(async () => {+ process.env.HOME = previousHome;+ await new Promise<void>((resolve) => server.close(() => resolve()));+ // Claude Code 退出时可能还在写 ~/.claude,重试几次再删。+ fs.rmSync(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 });+ });++ function claudeDeps(): AgentDeps {+ return {+ auth: {+ getState: async () => ({ authenticated: true, identity: 'test', authSource: 'api-key' as const }),+ triggerLogin: async () => ({ authenticated: true }),+ logout: async () => {},+ getAuthEnv: async () => ({ ANTHROPIC_API_KEY: 'fake-test-key' }),+ },+ runtimeConfig: { endpoint },+ binaryPath: CLAUDE,+ logger: noopLogger,+ };+ }++ async function run(permissionMode: 'bypassPermissions' | 'default', resolve?: (request: InteractionRequest) => boolean) {+ const project = path.join(root, `project-${permissionMode}`);+ const hostRoot = path.join(root, `host-${permissionMode}`);+ fs.mkdirSync(project, { recursive: true });+ fs.writeFileSync(path.join(project, 'hello.txt'), 'hello from the controller\n');+ fs.writeFileSync(path.join(project, 'CLAUDE.md'), '# Project memory\nAlways answer briefly.\n');+ const agent = new ClaudeCodeAgent(claudeDeps());+ const host = createRemoteAgentHost({+ isAgentAvailable: (kind) => kind === 'claude-code',+ startHosted: (input) => agent.startSession(hostedStartOptions(input)),+ isControllerAuthorized: () => true,+ captureOwner: () => 'owner',+ isOwnerCurrent: () => true,+ runsRoot: hostRoot,+ });+ const captured: string[] = [];+ const handle = await startRemoteAgentSession('claude-code', {+ sessionId: `cc-hosted-${permissionMode}`,+ workingDir: project,+ model: MODEL,+ permissionMode,+ }, {+ invoke: async (args) => JSON.parse(JSON.stringify(await host.handle('controller-1', JSON.parse(JSON.stringify(args[0]))) ?? null)),+ rgPath: RG,+ prepareMcp: async () => ({ servers: new Map(), dispose() {} }),+ capture: () => ({+ beforeWrite: async (file) => {+ captured.push(file);+ },+ noteOpaqueWrite: () => {},+ }),+ collectProjectFiles: async () => [{ path: 'CLAUDE.md', data: fs.readFileSync(path.join(project, 'CLAUDE.md')).toString('base64') }],+ isGitRepo: async () => false,+ mapEvent: remoteAgentEventMapper,+ newId: randomUUID,+ });+ const asked: InteractionRequest[] = [];+ handle.setInteractionResolver(async (request) => {+ asked.push(request);+ const allow = resolve ? resolve(request) : true;+ return request.kind === 'permission'+ ? { kind: 'permission', behavior: allow ? 'allow' : 'deny', ...(allow ? {} : { reason: 'denied by test' }) }+ : { kind: 'permission', behavior: 'deny' };+ });+ const events: AgentEvent[] = [];+ const done = (async () => {+ for await (const event of handle.events()) {+ events.push(event);+ if (event.type === 'error' && (event.data as { isTerminal?: boolean }).isTerminal !== false) {+ throw new Error(JSON.stringify(event.data));+ }+ if (event.type === 'done') return;+ }+ })();+ await handle.send({ type: 'user', content: 'Do the scripted work.' });+ await done;+ await handle.close({ reason: 'navigation' });+ host.dispose();+ return { project, hostRoot, events, asked, captured };+ }++ it('replaces the built-in file and shell tools and runs every step on the controller', { timeout: 120_000 }, async () => {+ const projectPath = path.join(root, 'project-bypassPermissions');+ steps = [+ { name: 'mcp__cindy_exec__Bash', input: { command: 'pwd; ls', description: 'Show location' } },+ { name: 'mcp__cindy_exec__Write', input: { file_path: path.join(projectPath, 'made.txt'), content: 'one\n' } },+ { name: 'mcp__cindy_exec__Read', input: { file_path: path.join(projectPath, 'hello.txt') } },+ { name: 'mcp__cindy_exec__Edit', input: { file_path: path.join(projectPath, 'made.txt'), old_string: 'one', new_string: 'two' } },+ ];+ requests.length = 0;+ const { project, hostRoot, events, captured } = await run('bypassPermissions');+ const first = requests[0];+ // 模型看不到只能操作本机的自带文件与命令工具。+ for (const builtin of ['Bash', 'Read', 'Write', 'Edit', 'NotebookEdit', 'Glob', 'Grep']) {+ expect(first.toolNames).not.toContain(builtin);+ }+ expect(first.toolNames).toEqual(expect.arrayContaining([+ 'mcp__cindy_exec__Bash', 'mcp__cindy_exec__Read', 'mcp__cindy_exec__Write', 'mcp__cindy_exec__Edit',+ 'mcp__cindy_exec__NotebookEdit', 'mcp__cindy_exec__BashOutput', 'mcp__cindy_exec__KillShell',+ ]));+ // 系统提示说明了项目的真实位置;项目说明来自同步的影子目录。+ expect(first.system).toContain(`The project lives on the user's computer at \`${project}\``);+ expect(`${first.system}\n${first.firstUser}`).toContain('Always answer briefly.');+ const last = requests.at(-1)!;+ expect(last.results.map((result) => result.isError)).toEqual([false, false, false, false]);+ expect(last.results[0].text).toContain(project);+ expect(last.results[0].text).toContain('hello.txt');+ expect(last.results[2].text).toContain('hello from the controller');+ expect(fs.readFileSync(path.join(project, 'made.txt'), 'utf8')).toBe('two\n');+ expect(captured).toContain(path.join(project, 'made.txt'));+ const hostFiles = fs.readdirSync(hostRoot, { recursive: true }).map(String);+ expect(hostFiles.some((file) => file.endsWith('made.txt'))).toBe(false);+ // 界面看到的仍是自带工具名。+ const toolNames = events.filter((event) => event.type === 'tool_use').map((event) => (event.data as { toolName: string }).toolName);+ expect(toolNames).toEqual(['Bash', 'Write', 'Read', 'Edit']);+ });++ it('asks on this computer for commands that change things, but not for reads and read-only commands', { timeout: 120_000 }, async () => {+ const projectPath = path.join(root, 'project-default');+ steps = [+ { name: 'mcp__cindy_exec__Read', input: { file_path: path.join(projectPath, 'hello.txt') } },+ { name: 'mcp__cindy_exec__Bash', input: { command: 'ls', description: 'List files' } },+ { name: 'mcp__cindy_exec__Bash', input: { command: 'touch approved.txt', description: 'Create file' } },+ { name: 'mcp__cindy_exec__Bash', input: { command: 'touch denied.txt', description: 'Create file' } },+ ];+ requests.length = 0;+ const { project, asked } = await run('default', (request) =>+ !(request.kind === 'permission' && String(request.input.command ?? '').includes('denied')));+ const permissionAsks = asked.filter((request): request is Extract<InteractionRequest, { kind: 'permission' }> => request.kind === 'permission');+ expect(permissionAsks.map((request) => [request.toolName, request.input.command])).toEqual([+ ['Bash', 'touch approved.txt'],+ ['Bash', 'touch denied.txt'],+ ]);+ expect(fs.existsSync(path.join(project, 'approved.txt'))).toBe(true);+ expect(fs.existsSync(path.join(project, 'denied.txt'))).toBe(false);+ const last = requests.at(-1)!;+ expect(last.results[0].isError).toBe(false);+ expect(last.results[1].isError).toBe(false);+ expect(last.results[3].isError).toBe(true);+ });+});diff --git a/apps/desktop/src/main/remote-agent/__tests__/codexHosted.e2e.test.ts b/apps/desktop/src/main/remote-agent/__tests__/codexHosted.e2e.test.tsnew file mode 100644index 0000000000..431d78e589--- /dev/null+++ b/apps/desktop/src/main/remote-agent/__tests__/codexHosted.e2e.test.ts@@ -0,0 +1,205 @@+/**+ * 远程 Agent × 真实 Codex 端到端:+ * 控制端(任务、项目文件、本机 codex exec-server) ⇄ 被控端运行服务 ⇄ 真 Codex app-server ⇄ 假 Responses 网关+ * 被控端的 Codex 把控制端注册成 exec-server 执行环境(Codex 原生机制),命令与补丁都在控制端执行。+ * 依赖 apps/codex-package-bin;缺失时跳过。+ */+import { randomUUID } from 'node:crypto';+import fs from 'node:fs';+import { createServer, type Server } from 'node:http';+import os from 'node:os';+import path from 'node:path';++import { CodexAgent, type AgentDeps, type AgentEvent, type InteractionRequest, type Logger } from '@cindy/maker-core';+import { afterAll, beforeAll, describe, expect, it } from 'vitest';++import { startRemoteAgentSession } from '../controller/startRemote';+import { createRemoteAgentHost } from '../host/runHost';+import { hostedStartOptions } from '../host/service';++const REPO = path.resolve(__dirname, '../../../../../..');+const ARCH = `${process.platform}-${process.arch}`;+const CODEX = path.join(REPO, 'apps', 'codex-package-bin', ARCH, 'bin', process.platform === 'win32' ? 'codex.exe' : 'codex');+const RG = path.join(REPO, 'apps', 'ripgrep-bin', ARCH, process.platform === 'win32' ? 'rg.exe' : 'rg');+const available = fs.existsSync(CODEX) && fs.existsSync(RG) && process.platform !== 'win32';++const noopLogger: Logger = {+ trace: () => {}, debug: () => {}, info: () => {}, warn: () => {}, error: () => {}, fatal: () => {},+ child: () => noopLogger,+};++type Step = { kind: 'exec'; cmd: string } | { kind: 'patch'; patch: string };++describe.skipIf(!available)('remote agent with a real Codex', () => {+ let server: Server;+ let endpoint = '';+ let root = '';+ let steps: Step[] = [];+ const bodies: string[] = [];++ beforeAll(async () => {+ root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-codex-hosted-')));+ server = createServer((req, res) => {+ let body = '';+ req.on('data', (chunk) => { body += chunk; });+ req.on('end', () => {+ if (!req.url?.includes('/responses')) {+ res.writeHead(404).end('{}');+ return;+ }+ bodies.push(body);+ let parsed: { input?: Array<{ type?: string }> } = {};+ try {+ parsed = JSON.parse(body);+ } catch {+ parsed = {};+ }+ const done = (parsed.input ?? []).filter((item) => item.type === 'function_call_output' || item.type === 'custom_tool_call_output').length;+ const step = steps[done];+ const id = `resp_${bodies.length}`;+ const item = step?.kind === 'exec'+ ? { type: 'function_call', id: `fc_${done}`, call_id: `call_${done}`, name: 'exec_command', arguments: JSON.stringify({ cmd: step.cmd }), status: 'completed' }+ : step?.kind === 'patch'+ ? { type: 'custom_tool_call', id: `ctc_${done}`, call_id: `call_${done}`, name: 'apply_patch', input: step.patch, status: 'completed' }+ : { type: 'message', id: `msg_${done}`, role: 'assistant', status: 'completed', content: [{ type: 'output_text', text: 'DONE', annotations: [] }] };+ const events = [+ { type: 'response.created', response: { id, status: 'in_progress', output: [] } },+ { type: 'response.output_item.added', output_index: 0, item },+ { type: 'response.output_item.done', output_index: 0, item },+ { type: 'response.completed', response: { id, status: 'completed', output: [item], usage: { input_tokens: 10, output_tokens: 5, total_tokens: 15 } } },+ ];+ res.writeHead(200, { 'content-type': 'text/event-stream', connection: 'close' });+ res.end(events.map((event) => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`).join(''));+ });+ });+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));+ endpoint = `http://127.0.0.1:${(server.address() as { port: number }).port}/v1`;+ });++ afterAll(async () => {+ await new Promise<void>((resolve) => server.close(() => resolve()));+ fs.rmSync(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 });+ });++ function codexDeps(home: string): AgentDeps {+ fs.mkdirSync(home, { recursive: true });+ fs.writeFileSync(path.join(home, 'config.toml'), [+ 'model="gpt-5.5"',+ 'model_provider="fixture"',+ 'cli_auth_credentials_store="ephemeral"',+ 'check_for_update_on_startup=false',+ '[analytics]', 'enabled=false',+ '[model_providers.fixture]', 'name="Fixture"',+ `base_url="${endpoint}"`, 'wire_api="responses"',+ 'requires_openai_auth=false', 'request_max_retries=0', 'supports_websockets=false',+ ].join('\n'));+ return {+ binaryPath: CODEX,+ logger: noopLogger,+ runtimeConfig: {},+ resolveCodexLocalAuthPolicy: () => 'isolated',+ prepareCodexExtraSpawnConfig: async () => ({ extraArgs: [], extraEnv: {}, codexProxyActive: true }),+ auth: {+ getState: async () => ({ authenticated: true }),+ triggerLogin: async () => ({ authenticated: true }),+ logout: async () => {},+ getAuthEnv: async () => ({+ HOME: path.dirname(home), CODEX_HOME: home, OPENAI_API_KEY: '', CODEX_API_KEY: '',+ }),+ },+ } as AgentDeps;+ }++ async function run(permissionMode: 'bypassPermissions' | 'default', resolve?: (request: InteractionRequest) => boolean) {+ const project = path.join(root, `project-${permissionMode}`);+ const hostRoot = path.join(root, `host-${permissionMode}`);+ fs.mkdirSync(project, { recursive: true });+ fs.writeFileSync(path.join(project, 'hello.txt'), 'hello from the controller\n');+ fs.writeFileSync(path.join(project, 'AGENTS.md'), '# Rules\nKeep answers short.\n');+ const agent = new CodexAgent(codexDeps(path.join(root, `codex-home-${permissionMode}`)));+ const host = createRemoteAgentHost({+ isAgentAvailable: (kind) => kind === 'codex',+ startHosted: (input) => agent.startSession(hostedStartOptions(input)),+ isControllerAuthorized: () => true,+ captureOwner: () => 'owner',+ isOwnerCurrent: () => true,+ runsRoot: hostRoot,+ });+ const handle = await startRemoteAgentSession('codex', {+ sessionId: `codex-hosted-${permissionMode}`,+ workingDir: project,+ model: 'gpt-5.5',+ permissionMode,+ }, {+ invoke: async (args) => JSON.parse(JSON.stringify(await host.handle('controller-1', JSON.parse(JSON.stringify(args[0]))) ?? null)),+ rgPath: RG,+ codexPath: () => CODEX,+ prepareMcp: async () => ({ servers: new Map(), dispose() {} }),+ collectProjectFiles: async () => [],+ isGitRepo: async () => false,+ newId: randomUUID,+ });+ const asked: InteractionRequest[] = [];+ handle.setInteractionResolver(async (request) => {+ asked.push(request);+ const allow = resolve ? resolve(request) : true;+ return { kind: 'permission', behavior: allow ? 'allow' : 'deny' };+ });+ const events: AgentEvent[] = [];+ const done = (async () => {+ for await (const event of handle.events()) {+ events.push(event);+ if (event.type === 'error' && (event.data as { isTerminal?: boolean }).isTerminal !== false) {+ throw new Error(JSON.stringify(event.data));+ }+ if (event.type === 'done') return;+ }+ })();+ await handle.send({ type: 'user', content: 'Do the scripted work.' }, { throwOnStartFailure: true });+ await done;+ await handle.close({ reason: 'navigation' });+ agent.dispose?.();+ host.dispose();+ return { project, hostRoot, events, asked };+ }++ it('runs commands and patches on the controller through the native exec-server environment', { timeout: 180_000 }, async () => {+ steps = [+ { kind: 'exec', cmd: 'pwd; ls' },+ { kind: 'patch', patch: '*** Begin Patch\n*** Add File: made-by-codex.txt\n+hello codex\n*** End Patch\n' },+ ];+ bodies.length = 0;+ const { project, hostRoot } = await run('bypassPermissions');+ expect(fs.readFileSync(path.join(project, 'made-by-codex.txt'), 'utf8')).toBe('hello codex\n');+ const last = bodies.at(-1)!;+ // 命令在控制端的项目目录执行。+ expect(last).toContain(project);+ expect(last).toContain('hello.txt');+ // 模型看到的工作目录与项目说明都来自控制端。+ expect(bodies[0]).toContain(project);+ expect(bodies[0]).toContain('Keep answers short.');+ const hostFiles = fs.readdirSync(hostRoot, { recursive: true }).map(String);+ expect(hostFiles.some((file) => file.endsWith('made-by-codex.txt'))).toBe(false);+ });++ it('asks on this computer before Codex runs a risky command, and runs only what was approved', { timeout: 180_000 }, async () => {+ const approvedVictim = path.join(root, 'victim-approved');+ const deniedVictim = path.join(root, 'victim-denied');+ fs.mkdirSync(approvedVictim);+ fs.mkdirSync(deniedVictim);+ steps = [+ { kind: 'exec', cmd: `rm -rf ${approvedVictim}` },+ { kind: 'exec', cmd: `rm -rf ${deniedVictim}` },+ ];+ bodies.length = 0;+ const { asked } = await run('default', (request) =>+ !(request.kind === 'permission' && String(request.input.command ?? '').includes('victim-denied')));+ const commands = asked+ .filter((request): request is Extract<InteractionRequest, { kind: 'permission' }> => request.kind === 'permission')+ .map((request) => String(request.input.command));+ expect(commands.some((command) => command.includes(`rm -rf ${approvedVictim}`))).toBe(true);+ expect(commands.some((command) => command.includes(`rm -rf ${deniedVictim}`))).toBe(true);+ expect(fs.existsSync(approvedVictim)).toBe(false);+ expect(fs.existsSync(deniedVictim)).toBe(true);+ });+});diff --git a/apps/desktop/src/main/remote-agent/__tests__/deviceCatalog.test.ts b/apps/desktop/src/main/remote-agent/__tests__/deviceCatalog.test.tsnew file mode 100644index 0000000000..a2e804e1a4--- /dev/null+++ b/apps/desktop/src/main/remote-agent/__tests__/deviceCatalog.test.ts@@ -0,0 +1,64 @@+/**+ * 运行 Agent 的另一台电脑的模型目录:经设备互联读取,只做最小校验。+ */+import { CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2 } from '@cindy/device-link';+import { describe, expect, it, vi } from 'vitest';++import { parseDeviceProviderViews, readDeviceProviderViews } from '../controller/deviceCatalog';++const provider = (overrides: Record<string, unknown> = {}) => ({+ id: 'spark',+ name: 'Spark',+ agents: ['claude-code', 'pi'],+ connected: true,+ models: { pi: [{ id: 'spark/qwen', name: 'Qwen' }, { id: '' }, { name: 'no id' }] },+ ...overrides,+});++describe('parseDeviceProviderViews', () => {+ it('keeps valid providers, drops models without an id and fills defaults', () => {+ const [view] = parseDeviceProviderViews({ providers: [provider()] });+ expect(view.models.pi).toEqual([{ id: 'spark/qwen', name: 'Qwen', efforts: [], defaultEffort: null }]);+ expect(view.routing).toEqual({ 'claude-code': {}, pi: {} });+ });++ it('keeps routing the other computer sent and the model tuning it reported', () => {+ const [view] = parseDeviceProviderViews({ providers: [provider({+ routing: { pi: { kind: 'native' } },+ models: { pi: [{ id: 'm', name: 'M', efforts: ['low'], defaultEffort: 'low' }] },+ })] });+ expect(view.routing).toEqual({ pi: { kind: 'native' }, 'claude-code': {} });+ expect(view.models.pi?.[0]).toMatchObject({ efforts: ['low'], defaultEffort: 'low' });+ });++ it('skips malformed providers instead of failing the whole list', () => {+ expect(parseDeviceProviderViews({ providers: [+ provider({ id: '' }),+ provider({ agents: 'pi' }),+ provider({ connected: 'yes' }),+ provider({ models: { pi: 'nope' } }),+ null,+ provider({ id: 'ok' }),+ ] }).map((view) => view.id)).toEqual(['ok']);+ });++ it('rejects responses that are not a provider list', () => {+ expect(() => parseDeviceProviderViews(null)).toThrow(/Invalid provider list/);+ expect(() => parseDeviceProviderViews({ providers: {} })).toThrow(/Invalid provider list/);+ });+});++describe('readDeviceProviderViews', () => {+ it('asks the other computer for its provider list with the controller capabilities', async () => {+ const invoke = vi.fn(async () => ({ ok: true, result: { providers: [provider()] } }));+ expect((await readDeviceProviderViews(invoke, 'device-b')).map((view) => view.id)).toEqual(['spark']);+ expect(invoke).toHaveBeenCalledWith('device-b', 'maker:provider:list', [+ { capabilities: [CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2] },+ ]);+ });++ it('keeps the error code when the other computer cannot answer', async () => {+ const invoke = vi.fn(async () => ({ ok: false, error: { code: 'DEVICE_OFFLINE', message: 'offline' } }));+ await expect(readDeviceProviderViews(invoke, 'device-b')).rejects.toMatchObject({ message: 'offline', code: 'DEVICE_OFFLINE' });+ });+});diff --git a/apps/desktop/src/main/remote-agent/__tests__/mirror.test.ts b/apps/desktop/src/main/remote-agent/__tests__/mirror.test.tsnew file mode 100644index 0000000000..14ef2563f8--- /dev/null+++ b/apps/desktop/src/main/remote-agent/__tests__/mirror.test.ts@@ -0,0 +1,239 @@+/**+ * 影子目录按你这台的真实路径逐级镜像:上级目录里的说明文件放在对应的上级,个人配置+ * (Claude Code 的 ~/.claude、Codex 的 CODEX_HOME)随任务同步到那台;那台给出的影子路径逐级+ * 映射回你这台的真实路径。+ */+import { randomUUID } from 'node:crypto';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';++import type { AgentEvent, AgentSessionHandle } from '@cindy/maker-core';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import {+ collectAncestorInstructionFiles,+ collectPersonalConfig,+ collectProjectInstructionFiles,+} from '../controller/projectFiles';+import { shadowAliases, startRemoteAgentSession } from '../controller/startRemote';+import { createRemoteAgentHost, mirrorSegments, type HostedStartInput } from '../host/runHost';+import { MAX_ANCESTOR_LEVELS } from '../wire';++const RG = path.resolve(__dirname, '../../../../../ripgrep-bin', `${process.platform}-${process.arch}`, process.platform === 'win32' ? 'rg.exe' : 'rg');++let root: string;++beforeEach(() => {+ root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-ra-mirror-')));+});++afterEach(() => {+ fs.rmSync(root, { recursive: true, force: true });+});++function write(file: string, content: string): void {+ fs.mkdirSync(path.dirname(file), { recursive: true });+ fs.writeFileSync(file, content);+}++describe('mirrorSegments', () => {+ it('keeps each path level and replaces names the other computer cannot store', () => {+ expect(mirrorSegments('/Users/me/my proj')).toEqual(['Users', 'me', 'my proj']);+ expect(mirrorSegments('C:\\Users\\me\\a<b>|c. ')).toEqual(['C', 'Users', 'me', 'a_b__c']);+ expect(mirrorSegments('/a/../b')).toEqual(['a', '_', 'b']);+ expect(mirrorSegments(`/${'x'.repeat(100)}`)).toEqual(['x'.repeat(64)]);+ });++ it('keeps only as many levels as ancestor instructions can use', () => {+ const deep = `/${Array.from({ length: 40 }, (_, index) => `d${index}`).join('/')}`;+ const segments = mirrorSegments(deep);+ expect(segments).toHaveLength(MAX_ANCESTOR_LEVELS + 1);+ expect(segments.at(-1)).toBe('d39');+ });+});++describe('shadowAliases', () => {+ it('maps the shadow, each mirrored ancestor and personal directories back to this computer', () => {+ expect(shadowAliases(+ { shadowDir: '/runs/fs/Users/me/proj', mirrorRoot: '/runs/fs' },+ '/Users/me/proj',+ [{ relative: '.claude/skills/s1', local: '/Users/me/.claude/skills/s1' }],+ )).toEqual([+ { from: '/runs/fs/Users/me/proj/.claude/skills/s1', to: '/Users/me/.claude/skills/s1' },+ { from: '/runs/fs/Users/me/proj', to: '/Users/me/proj' },+ { from: '/runs/fs/Users/me', to: '/Users/me' },+ { from: '/runs/fs/Users', to: '/Users' },+ ]);+ });++ it('only maps the shadow itself when the other computer did not mirror the path', () => {+ expect(shadowAliases({ shadowDir: '/runs/shadow' }, '/Users/me/proj', [])).toEqual([+ { from: '/runs/shadow', to: '/Users/me/proj' },+ ]);+ expect(shadowAliases({ shadowDir: '' }, '/Users/me/proj', [])).toEqual([]);+ });++ it('accepts a Windows shadow path from the other computer', () => {+ const aliases = shadowAliases(+ { shadowDir: 'C:\\runs\\fs\\Users\\me\\proj', mirrorRoot: 'C:\\runs\\fs' },+ '/Users/me/proj',+ [],+ );+ expect(aliases.map((alias) => alias.to)).toEqual(['/Users/me/proj', '/Users/me', '/Users']);+ expect(aliases.at(-1)?.from).toBe('C:/runs/fs/Users');+ });+});++describe('collectAncestorInstructionFiles', () => {+ it('reads instruction files from parent directories with their level', async () => {+ const project = path.join(root, 'a', 'b', 'proj');+ fs.mkdirSync(project, { recursive: true });+ write(path.join(root, 'a', 'b', 'CLAUDE.md'), 'parent');+ write(path.join(root, 'a', 'AGENTS.md'), 'grandparent');+ write(path.join(root, 'a', 'b', 'notes.md'), 'not an instruction file');+ write(path.join(project, 'CLAUDE.md'), 'project itself is synced separately');+ const files = await collectAncestorInstructionFiles(project);+ const decoded = files.map((file) => ({ up: file.up, name: file.name, text: Buffer.from(file.data, 'base64').toString() }));+ expect(decoded).toContainEqual({ up: 1, name: 'CLAUDE.md', text: 'parent' });+ expect(decoded).toContainEqual({ up: 2, name: 'AGENTS.md', text: 'grandparent' });+ expect(decoded.some((file) => file.text.includes('not an instruction') || file.text.includes('project itself'))).toBe(false);+ });+});++describe('collectPersonalConfig', () => {+ it("collects Claude Code's personal memory, skills, agents, commands and permission rules", async () => {+ const home = path.join(root, 'home');+ write(path.join(home, '.claude', 'CLAUDE.md'), 'personal memory');+ write(path.join(home, '.claude', 'skills', 'mine', 'SKILL.md'), 'personal skill');+ write(path.join(home, '.claude', 'skills', 'shared', 'SKILL.md'), 'personal copy');+ write(path.join(home, '.claude', 'agents', 'helper.md'), '---\nname: helper\n---\n');+ write(path.join(home, '.claude', 'commands', 'go.md'), 'go');+ write(path.join(home, '.claude', 'settings.json'), JSON.stringify({+ permissions: { allow: ['Bash(npm test:*)'], deny: ['Read(./.env)'] },+ hooks: { PreToolUse: [] },+ env: { SECRET: 'x' },+ }));+ const { personal, roots } = await collectPersonalConfig('claude-code', [+ { path: '.claude/skills/shared/SKILL.md', data: Buffer.from('project copy').toString('base64') },+ ], { env: {}, home });+ expect(personal.memory).toBe('personal memory');+ expect(personal.files.map((file) => file.path).sort()).toEqual([+ '.claude/agents/helper.md',+ '.claude/commands/go.md',+ '.claude/skills/mine/SKILL.md',+ ]);+ expect(personal.permissions).toEqual({ allow: ['Bash(npm test:*)'], deny: ['Read(./.env)'], ask: [] });+ expect(JSON.stringify(personal)).not.toContain('SECRET');+ expect(roots).toContainEqual({ relative: '.claude/skills/mine', local: path.join(home, '.claude', 'skills', 'mine') });+ });++ it('honours CLAUDE_CONFIG_DIR and syncs nothing when there is no personal config', async () => {+ const configDir = path.join(root, 'custom-claude');+ write(path.join(configDir, 'CLAUDE.md'), 'from custom dir');+ expect((await collectPersonalConfig('claude-code', [], { env: { CLAUDE_CONFIG_DIR: configDir }, home: path.join(root, 'nobody') }))+ .personal.memory).toBe('from custom dir');+ expect(await collectPersonalConfig('claude-code', [], { env: {}, home: path.join(root, 'nobody') }))+ .toEqual({ personal: { files: [] }, roots: [] });+ });++ it("uses Codex's personal instructions, preferring the override file", async () => {+ const codexHome = path.join(root, 'codex');+ write(path.join(codexHome, 'AGENTS.md'), 'base');+ expect((await collectPersonalConfig('codex', [], { env: { CODEX_HOME: codexHome }, home: root })).personal)+ .toEqual({ files: [], instructions: 'base' });+ write(path.join(codexHome, 'AGENTS.override.md'), 'override');+ expect((await collectPersonalConfig('codex', [], { env: { CODEX_HOME: codexHome }, home: root })).personal.instructions)+ .toBe('override');+ });+});++function idleHandle(input: HostedStartInput): AgentSessionHandle {+ return {+ id: 'sdk-1',+ agentKind: input.kind,+ model: input.options.model,+ async send() {},+ async steer() {},+ async abort() {},+ async close() {},+ events: () => ({+ async *[Symbol.asyncIterator](): AsyncIterator<AgentEvent> {+ // 不产生事件。+ },+ }),+ getUsageSnapshot: () => ({ tokenUsage: 0, contextTokens: 0, contextWindow: 0, costUsd: 0 }),+ setInteractionResolver() {},+ };+}++describe('shadow on the other computer', () => {+ it('places ancestor instructions at mirrored levels and personal config without overriding the project', async () => {+ const project = path.join(root, 'work', 'team', 'proj');+ fs.mkdirSync(project, { recursive: true });+ write(path.join(project, 'CLAUDE.md'), 'project rules');+ write(path.join(project, '.claude', 'commands', 'go.md'), 'project go');+ write(path.join(project, '.claude', 'settings.local.json'), JSON.stringify({ permissions: { allow: ['Bash(ls:*)'] } }));+ write(path.join(root, 'work', 'team', 'AGENTS.md'), 'team rules');+ write(path.join(root, 'work', 'CLAUDE.md'), 'work rules');++ const inputs: HostedStartInput[] = [];+ const host = createRemoteAgentHost({+ isAgentAvailable: () => true,+ startHosted: async (input) => {+ inputs.push(input);+ return idleHandle(input);+ },+ isControllerAuthorized: () => true,+ captureOwner: () => 'owner',+ isOwnerCurrent: () => true,+ runsRoot: path.join(root, 'host'),+ });+ const handle = await startRemoteAgentSession('claude-code', {+ sessionId: 'task-1',+ workingDir: project,+ model: 'claude-opus',+ permissionMode: 'default',+ }, {+ invoke: async (args) => JSON.parse(JSON.stringify(await host.handle('controller-1', JSON.parse(JSON.stringify(args[0]))) ?? null)),+ rgPath: RG,+ prepareMcp: async () => ({ servers: new Map(), dispose() {} }),+ collectProjectFiles: collectProjectInstructionFiles,+ collectAncestorFiles: collectAncestorInstructionFiles,+ collectPersonal: async () => ({+ personal: {+ memory: 'personal memory',+ files: [+ { path: '.claude/commands/go.md', data: Buffer.from('personal go').toString('base64') },+ { path: '.claude/agents/helper.md', data: Buffer.from('personal helper').toString('base64') },+ ],+ permissions: { allow: ['Bash(npm test:*)'], deny: [], ask: [] },+ instructions: 'personal instructions',+ },+ roots: [],+ }),+ isGitRepo: async () => false,+ newId: randomUUID,+ });++ const [input] = inputs;+ const read = (file: string) => fs.readFileSync(file, 'utf8');+ expect(input.shadowDir.startsWith(`${input.mirrorRoot}${path.sep}`)).toBe(true);+ expect(input.shadowDir.endsWith(path.join('work', 'team', 'proj'))).toBe(true);+ expect(read(path.join(input.shadowDir, 'CLAUDE.md'))).toBe('project rules');+ expect(read(path.join(path.dirname(input.shadowDir), 'AGENTS.md'))).toBe('team rules');+ expect(read(path.join(path.dirname(path.dirname(input.shadowDir)), 'CLAUDE.md'))).toBe('work rules');+ // 个人说明放在镜像根之外的任务根目录(对应个人配置,不对应项目的任何上级)。+ expect(read(path.join(path.dirname(input.mirrorRoot), 'CLAUDE.md'))).toBe('personal memory');+ // 项目里已有的同名文件以项目为准;项目没有的个人文件补上。+ expect(read(path.join(input.shadowDir, '.claude', 'commands', 'go.md'))).toBe('project go');+ expect(read(path.join(input.shadowDir, '.claude', 'agents', 'helper.md'))).toBe('personal helper');+ expect(JSON.parse(read(path.join(input.shadowDir, '.claude', 'settings.local.json')))).toEqual({+ permissions: { allow: ['Bash(ls:*)', 'Bash(npm test:*)'] },+ });+ expect(input.personalInstructions).toBe('personal instructions');++ await handle.close({ reason: 'navigation' });+ host.dispose();+ });+});diff --git a/apps/desktop/src/main/remote-agent/__tests__/piHosted.e2e.test.ts b/apps/desktop/src/main/remote-agent/__tests__/piHosted.e2e.test.tsnew file mode 100644index 0000000000..489a56f9b6--- /dev/null+++ b/apps/desktop/src/main/remote-agent/__tests__/piHosted.e2e.test.ts@@ -0,0 +1,302 @@+/**+ * 远程 Agent × 真实 Pi 端到端:+ * 控制端(任务、项目文件) ⇄ 被控端运行服务 ⇄ 真 Pi 二进制(cwd = 影子目录) ⇄ 假模型网关+ * 模型按脚本依次调用 bash / write / read / edit / grep / ls / find,断言每一步都落在控制端的+ * 项目目录里(影子目录里没有项目文件),提示里的工作目录是控制端的真实路径。+ * 依赖 apps/pi-bin/<platform>/pi;缺失时跳过。+ */+import { randomUUID } from 'node:crypto';+import fs from 'node:fs';+import { createServer, type Server } from 'node:http';+import os from 'node:os';+import path from 'node:path';++import { PiAgent, type AgentDeps, type AgentEvent, type Logger } from '@cindy/maker-core';+import { afterAll, beforeAll, describe, expect, it } from 'vitest';++import { startRemoteAgentSession } from '../controller/startRemote';+import { createRemoteAgentHost } from '../host/runHost';++const REPO = path.resolve(__dirname, '../../../../../..');+const ARCH = `${process.platform}-${process.arch}`;+const PI = path.join(REPO, 'apps', 'pi-bin', ARCH, process.platform === 'win32' ? 'pi.exe' : 'pi');+const RG = path.join(REPO, 'apps', 'ripgrep-bin', ARCH, process.platform === 'win32' ? 'rg.exe' : 'rg');+const available = fs.existsSync(PI) && fs.existsSync(RG) && process.platform !== 'win32';++const noopLogger: Logger = {+ trace: () => {}, debug: () => {}, info: () => {}, warn: () => {}, error: () => {}, fatal: () => {},+ child: () => noopLogger,+};++function sse(events: Array<{ event: string; data: unknown }>): string {+ return events.map(({ event, data }) => `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`).join('');+}++function toolUseBody(step: number, name: string, input: unknown): string {+ return sse([+ { event: 'message_start', data: { type: 'message_start', message: { id: `msg_${step}`, type: 'message', role: 'assistant', model: 'pi-test-model', content: [], stop_reason: null, usage: { input_tokens: 10, output_tokens: 0 } } } },+ { event: 'content_block_start', data: { type: 'content_block_start', index: 0, content_block: { type: 'tool_use', id: `toolu_${step}`, name, input: {} } } },+ { event: 'content_block_delta', data: { type: 'content_block_delta', index: 0, delta: { type: 'input_json_delta', partial_json: JSON.stringify(input) } } },+ { event: 'content_block_stop', data: { type: 'content_block_stop', index: 0 } },+ { event: 'message_delta', data: { type: 'message_delta', delta: { stop_reason: 'tool_use', stop_sequence: null }, usage: { output_tokens: 5 } } },+ { event: 'message_stop', data: { type: 'message_stop' } },+ ]);+}++function textBody(text: string): string {+ return sse([+ { event: 'message_start', data: { type: 'message_start', message: { id: 'msg_end', type: 'message', role: 'assistant', model: 'pi-test-model', content: [], stop_reason: null, usage: { input_tokens: 10, output_tokens: 0 } } } },+ { event: 'content_block_start', data: { type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } } },+ { event: 'content_block_delta', data: { type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text } } },+ { event: 'content_block_stop', data: { type: 'content_block_stop', index: 0 } },+ { event: 'message_delta', data: { type: 'message_delta', delta: { stop_reason: 'end_turn', stop_sequence: null }, usage: { output_tokens: 3 } } },+ { event: 'message_stop', data: { type: 'message_stop' } },+ ]);+}++interface ModelRequest {+ system: string;+ toolNames: string[];+ results: string[];+}++describe.skipIf(!available)('remote agent with a real Pi', () => {+ let server: Server;+ let endpoint = '';+ let root = '';+ let steps: Array<{ name: string; input: unknown }> = [];+ const requests: ModelRequest[] = [];++ beforeAll(async () => {+ root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-pi-hosted-')));+ server = createServer((req, res) => {+ let body = '';+ req.on('data', (chunk) => { body += chunk; });+ req.on('end', () => {+ const parsed = JSON.parse(body || '{}') as {+ system?: string | Array<{ text?: string }>;+ tools?: Array<{ name: string }>;+ messages?: Array<{ content?: unknown }>;+ };+ const system = typeof parsed.system === 'string' ? parsed.system : (parsed.system ?? []).map((part) => part.text ?? '').join('\n');+ const results: string[] = [];+ for (const message of parsed.messages ?? []) {+ if (!Array.isArray(message.content)) continue;+ for (const block of message.content as Array<Record<string, unknown>>) {+ if (block.type !== 'tool_result') continue;+ const content = block.content;+ results.push(typeof content === 'string'+ ? content+ : Array.isArray(content) ? content.map((part: { text?: string }) => part.text ?? '').join('') : '');+ }+ }+ requests.push({ system, toolNames: (parsed.tools ?? []).map((tool) => tool.name), results });+ res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache' });+ const step = steps[results.length];+ res.end(step ? toolUseBody(results.length, step.name, step.input) : textBody('all done'));+ });+ });+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));+ const address = server.address();+ if (address && typeof address === 'object') endpoint = `http://127.0.0.1:${address.port}`;+ });++ afterAll(async () => {+ await new Promise<void>((resolve) => server.close(() => resolve()));+ fs.rmSync(root, { recursive: true, force: true });+ });++ function piDeps(agentHome: string): AgentDeps {+ return {+ auth: {+ getState: async () => ({ authenticated: true, identity: 'test', authSource: 'api-key' as const }),+ triggerLogin: async () => ({ authenticated: true }),+ logout: async () => {},+ getAuthEnv: async () => ({ CINDY_PI_API_KEY: 'test-key' }),+ },+ runtimeConfig: { endpoint, managedExecutablePaths: { ripgrep: RG } },+ binaryPath: PI,+ logger: noopLogger,+ capabilityAdditions: {+ availableModels: [{ id: 'pi-test-model', displayName: 'Pi Test', contextWindow: 200_000, efforts: [], defaultEffort: null }],+ },+ resolvePiAgentHome: () => agentHome,+ resolvePiGatewayModelApi: () => 'anthropic-messages',+ };+ }++ it('runs Pi on the provider computer while every tool lands in the project here', { timeout: 120_000 }, async () => {+ const project = path.join(root, 'project');+ const hostRoot = path.join(root, 'host');+ fs.mkdirSync(path.join(project, 'src'), { recursive: true });+ fs.writeFileSync(path.join(project, 'hello.txt'), 'hello from the controller\n');+ fs.writeFileSync(path.join(project, 'src', 'needle.ts'), 'export const needle = 42;\n');+ fs.writeFileSync(path.join(project, 'AGENTS.md'), '# Project rules\nAlways be precise.\n');+ steps = [+ { name: 'bash', input: { command: 'pwd; ls' } },+ { name: 'write', input: { path: 'made-by-pi.txt', content: 'first line\n' } },+ { name: 'read', input: { path: 'hello.txt' } },+ { name: 'edit', input: { path: 'made-by-pi.txt', edits: [{ oldText: 'first line', newText: 'edited line' }] } },+ { name: 'grep', input: { pattern: 'needle' } },+ { name: 'ls', input: { path: 'src' } },+ { name: 'find', input: { pattern: '*.ts' } },+ ];+ requests.length = 0;++ const agent = new PiAgent(piDeps(path.join(root, 'pi-home')));+ const host = createRemoteAgentHost({+ isAgentAvailable: (kind) => kind === 'pi',+ startHosted: (input) => agent.startSession({+ sessionId: input.hostSessionId,+ workingDir: input.shadowDir,+ model: input.options.model,+ permissionMode: input.options.permissionMode as never,+ extraDirs: input.workspace.extraDirs,+ writableDirs: input.workspace.writableDirs,+ deviceHosted: {+ ...input.workspace,+ tunnelUrl: input.tunnel.url,+ tunnelToken: input.tunnel.token,+ mcpServers: input.mcpServers,+ },+ }),+ isControllerAuthorized: () => true,+ captureOwner: () => 'owner',+ isOwnerCurrent: () => true,+ runsRoot: hostRoot,+ });+ const captured: string[] = [];+ const handle = await startRemoteAgentSession('pi', {+ sessionId: 'pi-hosted-1',+ workingDir: project,+ model: 'pi-test-model',+ permissionMode: 'bypassPermissions',+ }, {+ invoke: async (args) => JSON.parse(JSON.stringify(await host.handle('controller-1', JSON.parse(JSON.stringify(args[0]))) ?? null)),+ rgPath: RG,+ prepareMcp: async () => ({ servers: new Map(), dispose() {} }),+ capture: () => ({+ beforeWrite: async (file) => {+ captured.push(file);+ },+ noteOpaqueWrite: () => {},+ }),+ collectProjectFiles: async () => [{ path: 'AGENTS.md', data: fs.readFileSync(path.join(project, 'AGENTS.md')).toString('base64') }],+ isGitRepo: async () => false,+ newId: randomUUID,+ });++ const events: AgentEvent[] = [];+ const done = (async () => {+ for await (const event of handle.events()) {+ events.push(event);+ if (event.type === 'error' && (event.data as { isTerminal?: boolean }).isTerminal !== false) {+ throw new Error(JSON.stringify(event.data));+ }+ if (event.type === 'done') return;+ }+ })();+ await handle.send({ type: 'user', content: 'Do the scripted work.' });+ await done;++ const last = requests.at(-1)!;+ const [bash, write, read, edit, grep, ls, find] = last.results;+ // 命令在控制端的项目目录执行,看得到控制端的文件。+ expect(bash).toContain(project);+ expect(bash).toContain('hello.txt');+ expect(write).toMatch(/made-by-pi\.txt/);+ expect(read).toContain('hello from the controller');+ expect(edit).toMatch(/made-by-pi\.txt/);+ expect(fs.readFileSync(path.join(project, 'made-by-pi.txt'), 'utf8')).toBe('edited line\n');+ expect(grep).toContain('src/needle.ts');+ expect(grep).toContain('needle = 42');+ expect(ls).toContain('needle.ts');+ expect(find).toContain('needle.ts');+ // 影子目录里只有项目说明;Agent 写的文件不在那里。+ const hostFiles = fs.readdirSync(hostRoot, { recursive: true }).map(String);+ expect(hostFiles.some((file) => file.endsWith('made-by-pi.txt'))).toBe(false);+ expect(hostFiles.some((file) => file.endsWith('AGENTS.md'))).toBe(true);+ // 模型看到的是控制端的真实目录与项目说明。+ expect(requests[0].system).toContain(`<cwd>\n${project}\n</cwd>`);+ expect(requests[0].system).not.toContain(hostRoot);+ expect(requests[0].system).toContain(`<project_instructions path="${path.join(project, 'AGENTS.md')}">`);+ expect(requests[0].system).toContain('Always be precise.');+ // 工具清单与本机任务一致(读写编辑也有提示片段)。+ expect(requests[0].system).toMatch(/- read: /);+ expect(requests[0].system).toMatch(/- edit: /);+ expect(requests[0].system).toMatch(/- write: /);+ expect(requests[0].toolNames).toEqual(expect.arrayContaining(['read', 'bash', 'edit', 'write', 'grep', 'find', 'ls']));+ // 写入前本机抓取了改前内容。+ expect(captured).toContain(path.join(project, 'made-by-pi.txt'));+ expect(events.some((event) => event.type === 'tool_use')).toBe(true);++ await handle.close({ reason: 'navigation' });+ host.dispose();+ });++ it('asks the user here before running commands in ask mode, and holds high-impact commands until confirmed', { timeout: 120_000 }, async () => {+ const project = path.join(root, 'project-ask');+ const hostRoot = path.join(root, 'host-ask');+ fs.mkdirSync(project, { recursive: true });+ const victim = path.join(root, 'victim-dir');+ fs.mkdirSync(victim);+ steps = [+ { name: 'bash', input: { command: 'touch approved.txt' } },+ { name: 'bash', input: { command: `rm -rf ${victim}` } },+ { name: 'bash', input: { command: 'touch denied.txt' } },+ ];+ requests.length = 0;+ const agent = new PiAgent(piDeps(path.join(root, 'pi-home-ask')));+ const host = createRemoteAgentHost({+ isAgentAvailable: () => true,+ startHosted: (input) => agent.startSession({+ sessionId: input.hostSessionId,+ workingDir: input.shadowDir,+ model: input.options.model,+ permissionMode: input.options.permissionMode as never,+ deviceHosted: { ...input.workspace, tunnelUrl: input.tunnel.url, tunnelToken: input.tunnel.token, mcpServers: input.mcpServers },+ }),+ isControllerAuthorized: () => true,+ captureOwner: () => 'owner',+ isOwnerCurrent: () => true,+ runsRoot: hostRoot,+ });+ const handle = await startRemoteAgentSession('pi', {+ sessionId: 'pi-hosted-ask',+ workingDir: project,+ model: 'pi-test-model',+ permissionMode: 'default',+ }, {+ invoke: async (args) => JSON.parse(JSON.stringify(await host.handle('controller-1', JSON.parse(JSON.stringify(args[0]))) ?? null)),+ rgPath: RG,+ prepareMcp: async () => ({ servers: new Map(), dispose() {} }),+ collectProjectFiles: async () => [],+ isGitRepo: async () => false,+ newId: randomUUID,+ });+ const asked: Array<{ toolName: string; command: unknown }> = [];+ handle.setInteractionResolver(async (request) => {+ if (request.kind !== 'permission') throw new Error('unexpected interaction');+ asked.push({ toolName: request.toolName, command: request.input.command });+ const deny = String(request.input.command).includes('denied');+ return { kind: 'permission', behavior: deny ? 'deny' : 'allow' };+ });+ const done = (async () => {+ for await (const event of handle.events()) {+ if (event.type === 'done') return;+ }+ })();+ await handle.send({ type: 'user', content: 'Run the commands.' });+ await done;+ expect(asked.map((item) => item.command)).toEqual(['touch approved.txt', `rm -rf ${victim}`, 'touch denied.txt']);+ expect(asked.every((item) => item.toolName === 'bash')).toBe(true);+ expect(fs.existsSync(path.join(project, 'approved.txt'))).toBe(true);+ // 用户在本机允许了高危命令,执行器据此放行。+ expect(fs.existsSync(victim)).toBe(false);+ expect(fs.existsSync(path.join(project, 'denied.txt'))).toBe(false);+ const results = requests.at(-1)!.results;+ expect(results[2]).toMatch(/denied/i);+ await handle.close({ reason: 'navigation' });+ host.dispose();+ });+});diff --git a/apps/desktop/src/main/remote-agent/__tests__/plumbing.test.ts b/apps/desktop/src/main/remote-agent/__tests__/plumbing.test.tsnew file mode 100644index 0000000000..ad61eff391--- /dev/null+++ b/apps/desktop/src/main/remote-agent/__tests__/plumbing.test.ts@@ -0,0 +1,203 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';++import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import WebSocket from 'ws';++import { mapClaudeHostedEvent } from '../controller/eventMap';+import { execServerActions, execServerCommand } from '../controller/execServerRelay';+import { collectProjectInstructionFiles } from '../controller/projectFiles';+import { approvalActionsFor, innerShellScript } from '../controller/proxyHandle';+import { EventLog, LineSplitter } from '../eventLog';+import { ExecutorWorkspace } from '../executor/workspace';+import { createRunTunnel } from '../host/tunnel';+import { decodeOpenPayload, decodeSendOptions, encodeSendOptions, isSafeProjectFilePath } from '../wire';++let root: string;++beforeEach(() => {+ root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-ra-plumbing-')));+});++afterEach(() => {+ fs.rmSync(root, { recursive: true, force: true });+});++describe('event log', () => {+ it('serves bytes by cursor, re-reads idempotently and drops acknowledged data', async () => {+ const log = new EventLog(1024);+ log.append({ a: 1 });+ log.append({ b: 2 });+ const first = await log.read(0, 8, 0);+ expect(first).toMatchObject({ from: 0, cursor: 8 });+ // 回包丢失时同一游标重读,得到同一段。+ expect((await log.read(0, 8, 0)).data?.toString()).toBe(first.data?.toString());+ const rest = await log.read(first.cursor, 1024, 0);+ expect(Buffer.concat([first.data!, rest.data!]).toString()).toBe('{"a":1}\n{"b":2}\n');+ // 较旧的并发 poll:已确认的部分不再给,从仍保留的位置开始并标明起点。+ expect(await log.read(0, 8, 0)).toMatchObject({ from: 8, cursor: 16 });+ // 游标超出已写范围是无效的。+ await expect(log.read(99, 8, 0)).rejects.toThrow('REMOTE_AGENT_INVALID');+ log.end();+ expect(await log.read(rest.cursor, 1024, 0)).toEqual({ from: rest.cursor, cursor: rest.cursor, done: true });+ });++ it('waits for new data, refuses to grow past its limit, and splits lines across reads', async () => {+ const log = new EventLog(64);+ const pending = log.read(0, 1024, 2_000);+ setTimeout(() => log.append({ late: true }), 20);+ expect((await pending).data?.toString()).toBe('{"late":true}\n');+ expect(log.append({ big: 'x'.repeat(100) })).toBe(false);+ const splitter = new LineSplitter(1024);+ expect(splitter.push(Buffer.from('{"a":1}\n{"b"'))).toEqual(['{"a":1}']);+ expect(splitter.push(Buffer.from(':2}\n'))).toEqual(['{"b":2}']);+ expect(() => new LineSplitter(4).push(Buffer.from('abcdef'))).toThrow();+ });+});++describe('tunnel', () => {+ it('requires the run token in the header or the path prefix and strips the prefix', async () => {+ const seen: string[] = [];+ const tunnel = await createRunTunnel({+ http: async (request) => {+ seen.push(request.path);+ return { status: 200, headers: [['content-type', 'text/plain']], body: Buffer.from('ok') };+ },+ wsOpen: () => {},+ wsMessage: () => {},+ wsClose: () => {},+ });+ try {+ expect((await fetch(`${tunnel.url}/mcp/x`)).status).toBe(401);+ expect((await fetch(`${tunnel.url}/mcp/x`, { headers: { authorization: 'Bearer wrong' } })).status).toBe(401);+ expect((await fetch(`${tunnel.url}/t/wrong/mcp/x`)).status).toBe(401);+ expect((await fetch(`${tunnel.url}/mcp/a?q=1`, { headers: { authorization: `Bearer ${tunnel.token}` } })).status).toBe(200);+ expect((await fetch(`${tunnel.url}/t/${tunnel.token}/mcp/b`)).status).toBe(200);+ expect(seen).toEqual(['/mcp/a?q=1', '/mcp/b']);+ } finally {+ await tunnel.close();+ }+ });++ it('relays WebSocket frames only for authorized connections', async () => {+ const opened: string[] = [];+ const messages: string[] = [];+ const tunnel = await createRunTunnel({+ http: async () => ({ status: 404, headers: [] }),+ wsOpen: (connId, wsPath) => opened.push(`${connId}:${wsPath}`),+ wsMessage: (_connId, data) => messages.push(data),+ wsClose: () => {},+ });+ try {+ const wsUrl = tunnel.url.replace('http', 'ws');+ await new Promise<void>((resolve) => {+ const bad = new WebSocket(`${wsUrl}/ws/exec-server`);+ bad.on('error', () => resolve());+ bad.on('unexpected-response', () => resolve());+ });+ const good = new WebSocket(`${wsUrl}/ws/exec-server`, { headers: { authorization: `Bearer ${tunnel.token}` } });+ const echoed = new Promise<string>((resolve) => good.on('message', (data) => resolve(String(data))));+ await new Promise<void>((resolve) => good.on('open', () => resolve()));+ good.send('{"id":1}');+ await new Promise((resolve) => setTimeout(resolve, 50));+ expect(opened).toEqual(['c1:/ws/exec-server']);+ expect(messages).toEqual(['{"id":1}']);+ tunnel.sendWs('c1', '{"result":true}');+ expect(await echoed).toBe('{"result":true}');+ good.close();+ } finally {+ await tunnel.close();+ }+ });+});++describe('exec-server relay gate', () => {+ it('maps exec-server requests to the actions checked on this computer', () => {+ expect(execServerCommand(['/bin/zsh', '-lc', 'echo hi'])).toBe('echo hi');+ expect(execServerCommand(['git', 'status'])).toBe('git status');+ expect(execServerActions('process/start', { argv: ['/bin/bash', '-c', 'rm -rf /x'], cwd: `file://${root}` }, '/w'))+ .toEqual([{ kind: 'exec', command: 'rm -rf /x', cwd: root }]);+ expect(execServerActions('fs/writeFile', { path: `file://${root}/a.txt`, dataBase64: '' }, '/w'))+ .toEqual([{ kind: 'write', path: path.join(root, 'a.txt') }]);+ expect(execServerActions('fs/readFile', { path: `file://${root}/.env` }, '/w'))+ .toEqual([{ kind: 'read', path: path.join(root, '.env') }]);+ expect(execServerActions('fs/getMetadata', { path: `file://${root}/.git` }, '/w')).toEqual([]);+ expect(execServerActions('initialize', {}, '/w')).toEqual([]);+ });++ it('matches Codex and Claude Code confirmations to the commands and files that later run', () => {+ const workspace = new ExecutorWorkspace({ workingDir: root });+ expect(innerShellScript("/bin/zsh -lc 'rm -rf /tmp/x; echo it'\\''s'")).toBe("rm -rf /tmp/x; echo it's");+ expect(approvalActionsFor({+ kind: 'permission', requestId: 'r', toolName: 'exec', input: { command: "/bin/zsh -lc 'rm -rf /tmp/x'", cwd: root },+ }, workspace)).toEqual([{ kind: 'exec', command: 'rm -rf /tmp/x', cwd: root }]);+ expect(approvalActionsFor({+ kind: 'permission', requestId: 'r', toolName: 'file_change', input: { changes: [{ path: path.join(root, '.env') }] },+ }, workspace)).toEqual([{ kind: 'write', path: path.join(root, '.env') }]);+ expect(approvalActionsFor({+ kind: 'permission', requestId: 'r', toolName: 'Edit', input: { file_path: 'src/a.ts' },+ }, workspace)).toEqual([{ kind: 'write', path: path.join(root, 'src/a.ts') }]);+ expect(approvalActionsFor({ kind: 'ask_user_question', requestId: 'r', questions: [] }, workspace)).toEqual([]);+ });+});++describe('wire payloads', () => {+ it('rejects unsafe project file paths and unknown platforms', () => {+ for (const bad of ['../x', '/etc/passwd', 'a/../../b', '.git/config', 'C:/x', 'a\\b', '']) {+ expect(isSafeProjectFilePath(bad)).toBe(false);+ }+ expect(isSafeProjectFilePath('.claude/skills/a/SKILL.md')).toBe(true);+ const payload = decodeOpenPayload({+ sessionId: 's1',+ options: { model: 'm' },+ workspace: { workingDir: '/p', platform: 'darwin', extraDirs: [], writableDirs: [] },+ projectFiles: [{ path: '../evil', data: '' }, { path: 'AGENTS.md', data: 'eA==' }],+ mcpServers: ['cindy_memory', 'bad name'],+ });+ expect(payload.projectFiles.map((file) => file.path)).toEqual(['AGENTS.md']);+ expect(payload.mcpServers).toEqual(['cindy_memory']);+ expect(() => decodeOpenPayload({ sessionId: 's', options: { model: 'm' }, workspace: { workingDir: '/p', platform: 'beos' } })).toThrow();+ });++ it('restores known per-turn policies and confirms everything for unknown ones', async () => {+ const encoded = await encodeSendOptions({+ turnPermissionPolicy: {+ origin: { kind: 'desktop' },+ confirmationSurface: 'desktop',+ forceConfirmToolCall: () => false,+ },+ }, async () => Buffer.alloc(0));+ const decoded = await decodeSendOptions(encoded.wire, {+ onTranscriptUserEntry: async () => {},+ onInteractionStateChange: () => {},+ writeAttachment: async () => '',+ });+ expect(decoded.turnPermissionPolicy?.forceConfirmToolCall('Read', {})).toBe(true);+ });+});++describe('event mapping and project files', () => {+ it('shows the built-in tool names for Claude Code tools that run on this computer', () => {+ expect(mapClaudeHostedEvent({ type: 'tool_use', data: { toolName: 'mcp__cindy_exec__Bash', input: {} } }).data)+ .toEqual({ toolName: 'Bash', input: {} });+ expect(mapClaudeHostedEvent({ type: 'tool_use', data: { toolName: 'mcp__cindy_memory__x' } }).data)+ .toEqual({ toolName: 'mcp__cindy_memory__x' });+ });++ it('syncs instructions and skills but never hooks, env or source files', async () => {+ fs.mkdirSync(path.join(root, '.claude', 'skills', 'deploy'), { recursive: true });+ fs.writeFileSync(path.join(root, 'CLAUDE.md'), '# memory');+ fs.writeFileSync(path.join(root, 'index.ts'), 'source');+ fs.writeFileSync(path.join(root, '.claude', 'skills', 'deploy', 'SKILL.md'), 'skill');+ fs.writeFileSync(path.join(root, '.claude', 'settings.json'), JSON.stringify({+ permissions: { allow: ['Bash(npm test:*)'] },+ hooks: { PreToolUse: [] },+ env: { ANTHROPIC_BASE_URL: 'http://evil' },+ }));+ const files = await collectProjectInstructionFiles(root);+ expect(files.map((file) => file.path).sort()).toEqual(['.claude/settings.json', '.claude/skills/deploy/SKILL.md', 'CLAUDE.md']);+ const settings = JSON.parse(Buffer.from(files.find((file) => file.path === '.claude/settings.json')!.data, 'base64').toString());+ expect(settings).toEqual({ permissions: { allow: ['Bash(npm test:*)'] } });+ });+});diff --git a/apps/desktop/src/main/remote-agent/__tests__/poll.test.ts b/apps/desktop/src/main/remote-agent/__tests__/poll.test.tsnew file mode 100644index 0000000000..94e8b15745--- /dev/null+++ b/apps/desktop/src/main/remote-agent/__tests__/poll.test.ts@@ -0,0 +1,278 @@+/**+ * 多任务共用一个 poll:被控端按游标返回、控制端去重,链路抖动后不丢不重。+ */+import { randomUUID } from 'node:crypto';++import { REMOTE_AGENT_READ_MAX_BYTES, type RemoteAgentErrorInfo } from '@cindy/device-link';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { RemoteAgentPoller, type PolledRun } from '../controller/poller';+import { EventLog } from '../eventLog';++interface FakeRun {+ log: EventLog;+}++/** 与 runHost 的 poll 同一套语义的最小被控端(只关心事件流)。 */+function fakeHost() {+ const runs = new Map<string, FakeRun>();+ const calls: Array<{ runs: Array<{ runId: string; cursor: number }>; waitMs?: number }> = [];+ let failNext: Error | null = null;+ const host = {+ runs,+ calls,+ failNext(error: Error) {+ failNext = error;+ },+ add(runId: string) {+ const run = { log: new EventLog(1 << 20) };+ runs.set(runId, run);+ return run.log;+ },+ async invoke(args: unknown[]): Promise<unknown> {+ const request = args[0] as { op: string; runs: Array<{ runId: string; cursor: number }>; waitMs?: number };+ calls.push({ runs: request.runs, waitMs: request.waitMs });+ if (failNext) {+ const error = failNext;+ failNext = null;+ throw error;+ }+ const live = request.runs.flatMap(({ runId, cursor }) => {+ const run = runs.get(runId);+ return run && run.log.isValidCursor(cursor) ? [{ run, cursor }] : [];+ });+ const ready = live.length < request.runs.length || live.some(({ run, cursor }) => run.log.isReady(cursor));+ if (!ready && (request.waitMs ?? 0) > 0) {+ await new Promise<void>((resolve) => {+ const timer = setTimeout(finish, Math.min(request.waitMs ?? 0, 200));+ const offs = live.map(({ run }) => run.log.onChange(finish));+ function finish() {+ clearTimeout(timer);+ for (const off of offs) off();+ resolve();+ }+ });+ }+ return {+ runs: request.runs.flatMap(({ runId, cursor }): Array<Record<string, unknown>> => {+ const run = runs.get(runId);+ if (!run || !run.log.isValidCursor(cursor)) return [{ runId, cursor, missing: true }];+ const result = run.log.readNow(cursor, REMOTE_AGENT_READ_MAX_BYTES);+ if (!result.data?.length && !result.done) return [];+ return [{+ runId,+ ...(result.from !== cursor ? { from: result.from } : {}),+ cursor: result.cursor,+ ...(result.data?.length ? { data: result.data.toString('base64') } : {}),+ ...(result.done ? { done: true } : {}),+ }];+ }),+ };+ },+ };+ return host;+}++function collector(runId: string) {+ const chunks: Buffer[] = [];+ let done = false;+ let lost: { reason: string; error: RemoteAgentErrorInfo } | null = null;+ const run: PolledRun = {+ runId,+ onData(data, isDone) {+ chunks.push(data);+ if (isDone) done = true;+ },+ onLost(reason, error) {+ lost = { reason, error };+ },+ };+ return {+ run,+ text: () => Buffer.concat(chunks).toString(),+ get done() {+ return done;+ },+ get lost() {+ return lost;+ },+ };+}++async function until(check: () => boolean, ms = 3_000): Promise<void> {+ const deadline = Date.now() + ms;+ while (!check()) {+ if (Date.now() > deadline) throw new Error('timed out');+ await new Promise((resolve) => setTimeout(resolve, 5));+ }+}++afterEach(() => {+ vi.useRealTimers();+});++describe('multiplexed poll', () => {+ it('delivers every run exactly once with at most two polls in flight', async () => {+ const host = fakeHost();+ let inflight = 0;+ let peak = 0;+ const poller = new RemoteAgentPoller(async (args) => {+ inflight += 1;+ peak = Math.max(peak, inflight);+ try {+ return await host.invoke(args);+ } finally {+ inflight -= 1;+ }+ });+ const ids = Array.from({ length: 12 }, () => randomUUID());+ const logs = ids.map((runId) => host.add(runId));+ const sinks = ids.map((runId) => collector(runId));+ for (const sink of sinks) poller.register(sink.run);+ for (let round = 0; round < 5; round += 1) {+ logs.forEach((log, index) => log.append({ run: index, round }));+ await new Promise((resolve) => setTimeout(resolve, 10));+ }+ for (const log of logs) log.end();+ await until(() => sinks.every((sink) => sink.done));+ sinks.forEach((sink, index) => {+ const expected = Array.from({ length: 5 }, (_, round) => `${JSON.stringify({ run: index, round })}\n`).join('');+ expect(sink.text()).toBe(expected);+ });+ expect(peak).toBeLessThanOrEqual(2);+ expect(poller.size).toBe(0);+ });++ it('drops data already delivered by an overlapping poll', async () => {+ const r = randomUUID();+ const other = randomUUID();+ const sink = collector(r);+ const second = collector(other);+ const whole = Buffer.from('{"a":1}\n{"b":2}\n');+ let releaseFirst!: () => void;+ const firstHeld = new Promise<void>((resolve) => {+ releaseFirst = resolve;+ });+ const seen: Array<Array<{ runId: string; cursor: number }>> = [];+ const poller = new RemoteAgentPoller(async (args) => {+ const request = args[0] as { runs: Array<{ runId: string; cursor: number }> };+ seen.push(request.runs);+ const call = seen.length;+ if (call === 1) {+ // 第一个 poll 在途时第二个任务登记,第二个 poll 带着同样的游标出发。+ await firstHeld;+ return { runs: [{ runId: r, cursor: 8, data: whole.subarray(0, 8).toString('base64') }] };+ }+ if (call === 2) {+ releaseFirst();+ await new Promise((resolve) => setTimeout(resolve, 20));+ // 与第一个 poll 重叠:同一段再给一次,后面多了一段。+ return { runs: [{ runId: r, cursor: 16, data: whole.toString('base64') }, { runId: other, cursor: 0, done: true }] };+ }+ return { runs: [{ runId: r, from: 16, cursor: 16, done: true }] };+ });+ poller.register(sink.run);+ poller.register(second.run);+ await until(() => sink.done && second.done);+ expect(seen[1].find((item) => item.runId === r)?.cursor).toBe(0);+ expect(sink.text()).toBe('{"a":1}\n{"b":2}\n');+ });++ it('rejects streams whose data does not match the cursor or leaves a gap', async () => {+ const a = randomUUID();+ const mismatch = collector(a);+ new RemoteAgentPoller(async () => ({ runs: [{ runId: a, cursor: 10, data: Buffer.from('xy').toString('base64') }] }))+ .register(mismatch.run);+ await until(() => !!mismatch.lost);+ expect(mismatch.lost!.error.code).toBe('REMOTE_AGENT_INVALID');++ const b = randomUUID();+ const gap = collector(b);+ new RemoteAgentPoller(async () => ({ runs: [{ runId: b, from: 4, cursor: 6, data: Buffer.from('xy').toString('base64') }] }))+ .register(gap.run);+ await until(() => !!gap.lost);+ expect(gap.lost!.error.code).toBe('REMOTE_AGENT_INVALID');++ const garbage = collector(randomUUID());+ new RemoteAgentPoller(async () => ({ runs: 'nope' })).register(garbage.run);+ await until(() => !!garbage.lost);+ expect(garbage.lost!.error.code).toBe('REMOTE_AGENT_INVALID');+ });+ it('re-reads from the same cursor after a link reset and reports runs the other computer no longer has', async () => {+ const host = fakeHost();+ const keptId = randomUUID();+ const log = host.add(keptId);+ const kept = collector(keptId);+ const gone = collector(randomUUID());+ const poller = new RemoteAgentPoller((args) => host.invoke(args));+ log.append({ n: 1 });+ host.failNext(Object.assign(new Error('peer reset'), { code: 'PEER_RESET' }));+ poller.register(kept.run);+ poller.register(gone.run);+ await until(() => !!gone.lost);+ expect(gone.lost!.reason).toBe('missing');+ log.append({ n: 2 });+ log.end();+ await until(() => kept.done, 5_000);+ expect(kept.text()).toBe('{"n":1}\n{"n":2}\n');+ });++ it('ends every run when the other computer refuses the poll, and gives up after it stays unreachable', async () => {+ const refused = collector(randomUUID());+ new RemoteAgentPoller(async () => {+ throw Object.assign(new Error('[CHANNEL_NOT_ALLOWED] not allowed'), { code: 'CHANNEL_NOT_ALLOWED' });+ }).register(refused.run);+ await until(() => !!refused.lost);+ expect(refused.lost!.error.code).toBe('CHANNEL_NOT_ALLOWED');++ vi.useFakeTimers();+ let t = 0;+ const offline = collector(randomUUID());+ let attempts = 0;+ const poller = new RemoteAgentPoller(async () => {+ attempts += 1;+ throw Object.assign(new Error('offline'), { code: 'DEVICE_OFFLINE' });+ }, undefined, () => t);+ poller.register(offline.run);+ for (let step = 0; step < 40 && !offline.lost; step += 1) {+ await vi.advanceTimersByTimeAsync(5_000);+ t += 5_000;+ }+ expect(offline.lost!.reason).toBe('unreachable');+ expect(attempts).toBeGreaterThan(5);+ });++ it('slows down when the other computer keeps answering immediately with nothing new', async () => {+ vi.useFakeTimers();+ let polls = 0;+ const sink = collector(randomUUID());+ new RemoteAgentPoller(async () => {+ polls += 1;+ return { runs: [] };+ }).register(sink.run);+ await vi.advanceTimersByTimeAsync(0);+ const burst = polls;+ expect(burst).toBeLessThanOrEqual(4);+ await vi.advanceTimersByTimeAsync(1_100);+ expect(polls).toBeLessThanOrEqual(burst + 4);+ });+});++describe('link errors', () => {+ it('names an outdated other computer and keeps link codes for retry decisions', async () => {+ const { remoteAgentInvoker } = await import('../controller/runClient');+ const { isRetryableLinkError } = await import('../controller/poller');+ const old = remoteAgentInvoker('d', async () => ({ ok: false, error: { code: 'CHANNEL_NOT_ALLOWED', message: "channel 'x' not allowed remotely" } }));+ await expect(old([{ op: 'caps' }])).rejects.toMatchObject({ code: 'REMOTE_AGENT_PEER_TOO_OLD', message: expect.stringMatching(/^\[REMOTE_AGENT_PEER_TOO_OLD\]/) });+ const offline = remoteAgentInvoker('d', async () => {+ throw Object.assign(new Error('[DEVICE_LINK_NOT_CONNECTED] not connected'), { code: 'NOT_CONNECTED' });+ });+ const error = await offline([{ op: 'caps' }]).catch((e: unknown) => e);+ expect((error as Error).message).toMatch(/^\[REMOTE_AGENT_UNAVAILABLE\] \[DEVICE_LINK_NOT_CONNECTED\]/);+ expect(isRetryableLinkError(error)).toBe(true);+ const host = remoteAgentInvoker('d', async () => ({ ok: false, error: { code: 'IPC_ERROR', message: '[REMOTE_AGENT_BUSY] too many tasks' } }));+ const busy = await host([{ op: 'caps' }]).catch((e: unknown) => e);+ expect((busy as Error).message).toBe('[REMOTE_AGENT_BUSY] too many tasks');+ expect(isRetryableLinkError(busy)).toBe(false);+ });+});diff --git a/apps/desktop/src/main/remote-agent/__tests__/roundtrip.test.ts b/apps/desktop/src/main/remote-agent/__tests__/roundtrip.test.tsnew file mode 100644index 0000000000..7b3aa49c0f--- /dev/null+++ b/apps/desktop/src/main/remote-agent/__tests__/roundtrip.test.ts@@ -0,0 +1,314 @@+/**+ * 远程 Agent 端到端往返(两端同进程,经 JSON 序列化模拟设备互联):+ * 控制端 startRemoteAgentSession ⇄ 被控端 createRemoteAgentHost ⇄ 假 Agent(经隧道回到控制端+ * 读写文件、跑命令、调 Cindy 工具、请求权限确认)。+ */+import { randomUUID } from 'node:crypto';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';++import type {+ AgentEvent,+ AgentSessionHandle,+ InteractionDecision,+ InteractionRequest,+ InteractionResolver,+ SendOptions,+ UserMessage,+} from '@cindy/maker-core';+import { MAIN_OWNED_SEND_CONTEXT } from '@cindy/maker-core';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { RemoteAgentPoller } from '../controller/poller';+import { startRemoteAgentSession, type StartRemoteAgentDeps } from '../controller/startRemote';+import { createRemoteAgentHost, type HostedStartInput } from '../host/runHost';++const RG = path.resolve(__dirname, '../../../../../ripgrep-bin', `${process.platform}-${process.arch}`, process.platform === 'win32' ? 'rg.exe' : 'rg');+const CONTROLLER = 'controller-device-1';++let root: string;+let project: string;+let hostRoot: string;+let hostInputs: HostedStartInput[];+let hostSends: Array<{ message: UserMessage; opts: SendOptions }>;+let authorized: boolean;++function queue() {+ const items: AgentEvent[] = [];+ let wake: (() => void) | null = null;+ let ended = false;+ return {+ push(event: AgentEvent) {+ items.push(event);+ wake?.();+ wake = null;+ },+ end() {+ ended = true;+ wake?.();+ wake = null;+ },+ async *[Symbol.asyncIterator]() {+ for (;;) {+ if (items.length) {+ yield items.shift()!;+ continue;+ }+ if (ended) return;+ await new Promise<void>((resolve) => {+ wake = resolve;+ });+ }+ },+ };+}++/** 被控端的假 Agent:收到消息后经隧道回到控制端干活。 */+function fakeHostedAgent(input: HostedStartInput): AgentSessionHandle {+ const events = queue();+ let resolver: InteractionResolver | null = null;+ let running = false;+ const auth = { authorization: `Bearer ${input.tunnel.token}` };+ const exec = async (op: string, body: unknown, signal?: AbortSignal) => {+ const response = await fetch(`${input.tunnel.url}/exec/${op}`, {+ method: 'POST',+ headers: { ...auth, 'content-type': 'application/json' },+ body: JSON.stringify(body),+ signal,+ });+ return { status: response.status, json: await response.json() as Record<string, unknown> };+ };+ const mcp = async (body: unknown) => {+ const response = await fetch(`${input.tunnel.url}/mcp/cindy_exec`, {+ method: 'POST',+ headers: { ...auth, 'content-type': 'application/json', accept: 'application/json, text/event-stream' },+ body: JSON.stringify(body),+ });+ return response.json() as Promise<{ result: { tools: unknown[] } }>;+ };+ return {+ id: 'sdk-session-1',+ agentKind: input.kind,+ model: input.options.model,+ async send(message, opts) {+ hostSends.push({ message, opts: opts ?? {} });+ running = true;+ events.push({ type: 'status', data: { state: 'running' }, source: input.kind });+ // 读本机(控制端)文件。+ const read = await exec('fs.read', { path: 'hello.txt' });+ const text = Buffer.from(String(read.json.data), 'base64').toString();+ events.push({ type: 'text', data: { text: `read:${text}`, isFinal: true }, source: input.kind });+ // Claude Code 风格工具经 MCP。+ const listed = await mcp({ jsonrpc: '2.0', id: 1, method: 'tools/list' });+ events.push({ type: 'text', data: { text: `tools:${listed.result.tools.length}` }, source: input.kind });+ // 需要确认的操作:先问本机用户,再执行。+ const command = `rm -rf ${path.join(root, 'victim')}`;+ const before = await exec('exec.run', { command });+ events.push({ type: 'text', data: { text: `before:${before.status}` }, source: input.kind });+ const decision = await resolver!({ kind: 'permission', requestId: 'r1', toolName: 'bash', input: { command } } as InteractionRequest);+ if (decision.kind === 'permission' && decision.behavior === 'allow') {+ const after = await exec('exec.run', { command });+ events.push({ type: 'text', data: { text: `after:${after.status}` }, source: input.kind });+ }+ await opts?.onTranscriptUserEntry?.('entry-42');+ running = false;+ events.push({ type: 'done', data: {}, source: input.kind });+ },+ async steer() {},+ async abort() {},+ async close() {+ events.end();+ },+ events: () => events,+ getUsageSnapshot: () => ({ tokenUsage: 1, contextTokens: 2, contextWindow: 3, costUsd: 0 }),+ setInteractionResolver(next) {+ resolver = next;+ },+ isTurnRunning: () => running,+ async setPermissionMode() {},+ async setModel() {},+ };+}++function makeDeps(host: ReturnType<typeof createRemoteAgentHost>): StartRemoteAgentDeps {+ return {+ invoke: async (args) => {+ // JSON 往返模拟设备互联的序列化。+ const result = await host.handle(CONTROLLER, JSON.parse(JSON.stringify(args[0])));+ return JSON.parse(JSON.stringify(result ?? null));+ },+ rgPath: RG,+ prepareMcp: async () => ({ servers: new Map(), dispose() {} }),+ collectProjectFiles: async () => [{ path: 'AGENTS.md', data: Buffer.from('# rules').toString('base64') }],+ isGitRepo: async () => false,+ newId: randomUUID,+ };+}++beforeEach(() => {+ root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-ra-')));+ project = path.join(root, 'project');+ hostRoot = path.join(root, 'host');+ fs.mkdirSync(project);+ fs.mkdirSync(path.join(root, 'victim'));+ fs.writeFileSync(path.join(project, 'hello.txt'), 'from-controller');+ hostInputs = [];+ hostSends = [];+ authorized = true;+});++afterEach(() => {+ fs.rmSync(root, { recursive: true, force: true });+});++function createHost() {+ return createRemoteAgentHost({+ isAgentAvailable: () => true,+ startHosted: async (input) => {+ hostInputs.push(input);+ return fakeHostedAgent(input);+ },+ isControllerAuthorized: () => authorized,+ captureOwner: () => 'owner',+ isOwnerCurrent: () => true,+ runsRoot: hostRoot,+ });+}++describe('remote agent round trip', () => {+ it('runs a turn on the other computer while files, commands and confirmations stay here', async () => {+ const host = createHost();+ const handle = await startRemoteAgentSession('pi', {+ sessionId: 'session-1',+ workingDir: project,+ model: 'spark/qwen',+ providerId: 'spark',+ permissionMode: 'default',+ }, makeDeps(host));+ expect(handle.id).toBe('sdk-session-1');+ expect(hostInputs[0].workspace.workingDir).toBe(project);+ expect(hostInputs[0].options).toMatchObject({ model: 'spark/qwen', providerId: 'spark', permissionMode: 'default' });+ expect(fs.readFileSync(path.join(hostInputs[0].shadowDir, 'AGENTS.md'), 'utf8')).toBe('# rules');++ const requests: InteractionRequest[] = [];+ handle.setInteractionResolver(async (request): Promise<InteractionDecision> => {+ requests.push(request);+ return { kind: 'permission', behavior: 'allow' };+ });+ const entries: string[] = [];+ const png = path.join(project, 'shot.png');+ fs.writeFileSync(png, Buffer.from([0x89, 0x50, 0x4e, 0x47, 1, 2, 3]));+ const collected: AgentEvent[] = [];+ const reader = (async () => {+ for await (const event of handle.events()) {+ collected.push(event);+ if (event.type === 'done') break;+ }+ })();+ await handle.send(+ { type: 'user', content: [{ type: 'text', text: 'hi' }, { type: 'image', path: png, mimeType: 'image/png' }] },+ {+ messageUuid: 'u1',+ onTranscriptUserEntry: (entry) => {+ entries.push(entry);+ },+ [MAIN_OWNED_SEND_CONTEXT]: { origin: { kind: 'desktop' } },+ },+ );+ await reader;+ const texts = collected.filter((event) => event.type === 'text').map((event) => (event.data as { text: string }).text);+ expect(texts).toEqual(['read:from-controller', 'tools:7', 'before:403', 'after:200']);+ expect(fs.existsSync(path.join(root, 'victim'))).toBe(false);+ expect(requests).toHaveLength(1);+ expect(entries).toEqual(['entry-42']);++ // 图片字节随消息带到对方,换成对方本机路径;Symbol 证明在对方重新附上。+ const sent = hostSends[0];+ const image = (sent.message.content as Array<{ type: string; path?: string }>).find((block) => block.type === 'image');+ expect(image?.path && image.path !== png).toBe(true);+ expect(fs.readFileSync(image!.path!)).toEqual(fs.readFileSync(png));+ expect(sent.opts.messageUuid).toBe('u1');+ expect(sent.opts[MAIN_OWNED_SEND_CONTEXT]).toEqual({ origin: { kind: 'desktop' } });+ expect(handle.getUsageSnapshot()).toMatchObject({ tokenUsage: 1, contextTokens: 2 });++ await handle.close({ reason: 'navigation' });+ expect(host.runCount()).toBe(0);+ host.dispose();+ });++ it('runs several tasks on the same computer over one shared poll', async () => {+ const host = createHost();+ const base = makeDeps(host);+ let polls = 0;+ let peakPolls = 0;+ let peakAll = 0;+ let inflightAll = 0;+ const invoke: StartRemoteAgentDeps['invoke'] = async (args) => {+ const isPoll = (args[0] as { op?: string }).op === 'poll';+ inflightAll += 1;+ if (isPoll) polls += 1;+ peakAll = Math.max(peakAll, inflightAll);+ peakPolls = Math.max(peakPolls, polls);+ try {+ return await base.invoke(args);+ } finally {+ inflightAll -= 1;+ if (isPoll) polls -= 1;+ }+ };+ const poller = new RemoteAgentPoller(invoke);+ const handles = await Promise.all(Array.from({ length: 6 }, (_, index) => startRemoteAgentSession('pi', {+ sessionId: `shared-${index}`,+ workingDir: project,+ model: 'm',+ permissionMode: 'bypassPermissions',+ }, { ...base, invoke, poller })));+ await Promise.all(handles.map(async (handle) => {+ handle.setInteractionResolver(async () => ({ kind: 'permission', behavior: 'allow' }));+ const texts: string[] = [];+ const reader = (async () => {+ for await (const event of handle.events()) {+ if (event.type === 'text') texts.push((event.data as { text: string }).text);+ if (event.type === 'done') break;+ }+ })();+ await handle.send({ type: 'user', content: 'hi' }, {});+ await reader;+ expect(texts[0]).toBe('read:from-controller');+ }));+ // 六个任务同时进行,拉取始终最多两个在途,不会挤占设备互联的其它请求。+ expect(peakPolls).toBeLessThanOrEqual(2);+ expect(peakAll).toBeLessThan(12);+ await Promise.all(handles.map((handle) => handle.close({ reason: 'navigation' })));+ expect(host.runCount()).toBe(0);+ expect(poller.size).toBe(0);+ host.dispose();+ });++ it('reports a start failure from the other computer with its original error', async () => {+ const host = createRemoteAgentHost({+ isAgentAvailable: () => true,+ startHosted: async () => {+ const error = new Error('Claude Code is not signed in');+ error.name = 'AgentNotAuthenticatedError';+ throw error;+ },+ isControllerAuthorized: () => true,+ captureOwner: () => 'o',+ isOwnerCurrent: () => true,+ runsRoot: hostRoot,+ });+ await expect(startRemoteAgentSession('claude-code', { sessionId: 's2', workingDir: project, model: 'm' }, makeDeps(host)))+ .rejects.toMatchObject({ name: 'AgentNotAuthenticatedError', message: 'Claude Code is not signed in' });+ host.dispose();+ });++ it('refuses controllers that are no longer allowed', async () => {+ authorized = false;+ const host = createHost();+ await expect(startRemoteAgentSession('pi', { sessionId: 's3', workingDir: project, model: 'm' }, makeDeps(host)))+ .rejects.toThrow(/REMOTE_AGENT_UNAVAILABLE/);+ host.dispose();+ });+});diff --git a/apps/desktop/src/main/remote-agent/controller/deviceCatalog.ts b/apps/desktop/src/main/remote-agent/controller/deviceCatalog.tsnew file mode 100644index 0000000000..199aa25c0d--- /dev/null+++ b/apps/desktop/src/main/remote-agent/controller/deviceCatalog.ts@@ -0,0 +1,58 @@+/**+ * 运行 Agent 的另一台电脑的模型目录(本机主进程读取)。+ *+ * 那台电脑经设备互联的 `maker:provider:list` 给出去敏后的供应商视图;Agent 在那台运行的任务+ * (以及它的协同 Worker)按这份目录选模型与来源。与渲染端 useDeviceProviders 同一个通道、同一份+ * 投影;只做最小校验,缺少 routing 的 Agent 补空 entry(与渲染端解析边界一致)。+ */+import { CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2 } from '@cindy/device-link';+import type { ProviderView } from '@cindy/model-providers';++type RemoteInvoke = (+ deviceId: string,+ channel: string,+ args: unknown[],+) => Promise<{ ok: boolean; result?: unknown; error?: { code?: string; message?: string } }>;++function isRecord(value: unknown): value is Record<string, unknown> {+ return !!value && typeof value === 'object' && !Array.isArray(value);+}++function isModel(value: unknown): boolean {+ return isRecord(value) && typeof value.id === 'string' && value.id.length > 0;+}++/** 解析那台电脑的供应商视图;格式不对时抛错(调用方按「目录不可用」处理)。 */+export function parseDeviceProviderViews(value: unknown): ProviderView[] {+ if (!isRecord(value) || !Array.isArray(value.providers)) throw new Error('Invalid provider list response');+ return value.providers.flatMap((item): ProviderView[] => {+ if (!isRecord(item) || typeof item.id !== 'string' || !item.id || typeof item.name !== 'string') return [];+ if (!Array.isArray(item.agents) || !item.agents.every((agent) => typeof agent === 'string')) return [];+ if (typeof item.connected !== 'boolean' || !isRecord(item.models)) return [];+ const models: Record<string, unknown[]> = {};+ for (const [agent, entries] of Object.entries(item.models)) {+ if (!Array.isArray(entries)) return [];+ models[agent] = entries.filter(isModel).map((entry) => ({+ efforts: [],+ defaultEffort: null,+ ...(entry as Record<string, unknown>),+ }));+ }+ const routing: Record<string, unknown> = isRecord(item.routing) ? { ...item.routing } : {};+ for (const agent of item.agents as string[]) {+ if (routing[agent] === undefined) routing[agent] = {};+ }+ return [{ ...item, models, routing } as unknown as ProviderView];+ });+}++/** 读那台电脑的供应商视图。 */+export async function readDeviceProviderViews(invoke: RemoteInvoke, deviceId: string): Promise<ProviderView[]> {+ const result = await invoke(deviceId, 'maker:provider:list', [+ { capabilities: [CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2] },+ ]);+ if (!result.ok) {+ throw Object.assign(new Error(result.error?.message ?? 'provider list unavailable'), { code: result.error?.code });+ }+ return parseDeviceProviderViews(result.result);+}diff --git a/apps/desktop/src/main/remote-agent/controller/eventMap.ts b/apps/desktop/src/main/remote-agent/controller/eventMap.tsnew file mode 100644index 0000000000..f4452e75a6--- /dev/null+++ b/apps/desktop/src/main/remote-agent/controller/eventMap.ts@@ -0,0 +1,40 @@+/**+ * 来自对方电脑的 Agent 事件在本机的改写。+ *+ * Claude Code 的自带文件与命令工具在对方电脑上由 Cindy 工具(`mcp__cindy_exec__Bash` 等)顶替,+ * 本机界面、记录与统计看到的仍是自带工具名(Bash / Read / Edit …),和本机任务一样渲染。+ */+import type { AgentEvent, AgentKind } from '@cindy/maker-core';++const EXEC_PREFIX = 'mcp__cindy_exec__';+const EXEC_TOOLS = new Set(['Bash', 'BashOutput', 'KillShell', 'Read', 'Write', 'Edit', 'NotebookEdit']);++export function builtinToolName(name: unknown): string | null {+ if (typeof name !== 'string' || !name.startsWith(EXEC_PREFIX)) return null;+ const builtin = name.slice(EXEC_PREFIX.length);+ return EXEC_TOOLS.has(builtin) ? builtin : null;+}++function renameField(data: unknown, field: string): unknown {+ if (!data || typeof data !== 'object') return data;+ const record = data as Record<string, unknown>;+ const builtin = builtinToolName(record[field]);+ return builtin ? { ...record, [field]: builtin } : data;+}++export function mapClaudeHostedEvent(event: AgentEvent): AgentEvent {+ switch (event.type) {+ case 'tool_use':+ return { ...event, data: renameField(event.data, 'toolName') };+ case 'agent_task_update':+ return { ...event, data: renameField(event.data, 'lastToolName') };+ case 'interaction_request':+ return { ...event, data: renameField(event.data, 'toolName') };+ default:+ return event;+ }+}++export function remoteAgentEventMapper(kind: AgentKind): ((event: AgentEvent) => AgentEvent) | undefined {+ return kind === 'claude-code' ? mapClaudeHostedEvent : undefined;+}diff --git a/apps/desktop/src/main/remote-agent/controller/execServerRelay.ts b/apps/desktop/src/main/remote-agent/controller/execServerRelay.tsnew file mode 100644index 0000000000..f2d80c0596--- /dev/null+++ b/apps/desktop/src/main/remote-agent/controller/execServerRelay.ts@@ -0,0 +1,240 @@+/**+ * Codex exec-server 中继(控制端)。+ *+ * 对方电脑上的 Codex 把本机当成一个远程执行环境(Codex 原生的 environment/exec-server 机制):+ * 它连到对方本机隧道的 WebSocket,帧经设备互联到达这里,本机为每条连接起一个+ * `codex exec-server --listen stdio://`,命令、读写文件、补丁都在本机执行。+ *+ * 每个请求转给 exec-server 之前先过本机权限上限(与 Claude Code / Pi 同一个闸门):+ * 凭证类路径与高危命令只认本机用户批准过的同一操作;不通过就直接回 JSON-RPC 错误。+ */+import { spawn, type ChildProcessWithoutNullStreams } from 'node:child_process';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++import {+ REMOTE_AGENT_MAX_INLINE_PAYLOAD_CHARS,+ REMOTE_AGENT_MAX_PUSH_CHARS,+ REMOTE_AGENT_MAX_PUSH_FRAMES,+ type RemoteAgentPushFrame,+ type RemoteAgentStreamItem,+} from '@cindy/device-link';++import type { ExecutorAction, ExecutorGateDecision } from '../executor/gate';++export const EXEC_SERVER_WS_PATH = '/ws/exec-server';+/** exec-server 单行(一条 JSON-RPC 消息)上限:大文件读写的 base64 也在这里面。 */+const MAX_LINE_CHARS = 48 * 1024 * 1024;+/** 单帧数据上限,留出 JSON 包装余量。 */+const FRAME_CHARS = REMOTE_AGENT_MAX_INLINE_PAYLOAD_CHARS - 1024;++export interface ExecServerRelayDeps {+ codexPath: string;+ cwd: string;+ authorize(action: ExecutorAction): ExecutorGateDecision;+ push(frames: RemoteAgentPushFrame[]): Promise<void>;+ env?: NodeJS.ProcessEnv;+ log?: { warn(message: string, meta?: Record<string, unknown>): void };+}++interface Connection {+ child: ChildProcessWithoutNullStreams;+ buffer: string;+ closed: boolean;+}++/** `["/bin/zsh","-lc","cmd"]` → `cmd`;其它形态按空格拼接。 */+export function execServerCommand(argv: unknown): string | null {+ if (!Array.isArray(argv) || argv.length === 0 || !argv.every((part) => typeof part === 'string')) return null;+ const parts = argv as string[];+ if (parts.length >= 3 && /^-l?c$/.test(parts[parts.length - 2]) && /(^|\/)(ba|z|da|k)?sh$/.test(parts[0])) {+ return parts[parts.length - 1];+ }+ return parts.join(' ');+}++function fromFileUrl(value: unknown, base: string): string | null {+ if (typeof value !== 'string' || !value) return null;+ if (value.startsWith('file://')) {+ try {+ return fileURLToPath(value);+ } catch {+ return null;+ }+ }+ return path.isAbsolute(value) ? value : path.resolve(base, value);+}++const READ_METHODS = new Set(['fs/readFile', 'fs/readDirectory', 'fs/readDir', 'fs/listDirectory']);+/** 只看元数据、不读内容的操作不过闸门。 */+const METADATA_METHODS = new Set(['fs/getMetadata', 'fs/exists', 'fs/stat']);++/** 把一个 exec-server 请求换成要过闸门的操作。 */+export function execServerActions(method: string, params: unknown, cwd: string): ExecutorAction[] {+ const record = params && typeof params === 'object' ? params as Record<string, unknown> : {};+ if (method === 'process/start') {+ const command = execServerCommand(record.argv);+ const processCwd = fromFileUrl(record.cwd, cwd) ?? cwd;+ return command ? [{ kind: 'exec', command, cwd: processCwd }] : [{ kind: 'exec', command: '<unknown>', cwd: processCwd }];+ }+ if (!method.startsWith('fs/') || METADATA_METHODS.has(method)) return [];+ const paths = ['path', 'sourcePath', 'destinationPath', 'source', 'destination', 'from', 'to', 'target']+ .map((key) => fromFileUrl(record[key], cwd))+ .filter((value): value is string => !!value);+ const kind = READ_METHODS.has(method) ? 'read' : 'write';+ return paths.map((target) => ({ kind, path: target }) as ExecutorAction);+}++export class ExecServerRelay {+ private readonly connections = new Map<string, Connection>();+ private outbox: RemoteAgentPushFrame[] = [];+ private flushing: Promise<void> | null = null;+ private closed = false;++ constructor(private readonly deps: ExecServerRelayDeps) {}++ handle(item: Extract<RemoteAgentStreamItem, { t: 'ws' }>): void {+ if (this.closed) return;+ switch (item.kind) {+ case 'open':+ this.open(item.connId, item.path ?? '/');+ return;+ case 'message':+ if (typeof item.data === 'string') this.forward(item.connId, item.data);+ return;+ case 'close':+ this.dropConnection(item.connId, false);+ return;+ }+ }++ close(): void {+ if (this.closed) return;+ this.closed = true;+ for (const connId of [...this.connections.keys()]) this.dropConnection(connId, false);+ }++ private open(connId: string, wsPath: string): void {+ if (wsPath.split('?')[0] !== EXEC_SERVER_WS_PATH || this.connections.has(connId)) {+ this.send({ connId, kind: 'close' });+ return;+ }+ let child: ChildProcessWithoutNullStreams;+ try {+ child = spawn(this.deps.codexPath, ['exec-server', '--listen', 'stdio://'], {+ cwd: this.deps.cwd,+ env: this.deps.env ?? process.env,+ stdio: ['pipe', 'pipe', 'pipe'],+ windowsHide: true,+ });+ } catch (error) {+ this.deps.log?.warn('remote agent: exec-server failed to start', { error: String(error) });+ this.send({ connId, kind: 'close' });+ return;+ }+ const connection: Connection = { child, buffer: '', closed: false };+ this.connections.set(connId, connection);+ child.stdout.setEncoding('utf8');+ child.stdout.on('data', (chunk: string) => {+ connection.buffer += chunk;+ for (;;) {+ const index = connection.buffer.indexOf('\n');+ if (index < 0) break;+ const line = connection.buffer.slice(0, index);+ connection.buffer = connection.buffer.slice(index + 1);+ if (line.trim()) this.sendMessage(connId, line);+ }+ if (connection.buffer.length > MAX_LINE_CHARS) {+ this.deps.log?.warn('remote agent: exec-server line too long; closing', { connId });+ this.dropConnection(connId, true);+ }+ });+ child.stderr.resume();+ child.on('error', () => this.dropConnection(connId, true));+ child.on('exit', () => this.dropConnection(connId, true));+ }++ private forward(connId: string, data: string): void {+ const connection = this.connections.get(connId);+ if (!connection || connection.closed) return;+ type JsonRpcMessage = { id?: unknown; method?: unknown; params?: unknown };+ let message: JsonRpcMessage | null = null;+ try {+ const parsed: unknown = JSON.parse(data);+ message = parsed && typeof parsed === 'object' ? parsed as JsonRpcMessage : null;+ } catch {+ message = null;+ }+ if (message && typeof message.method === 'string' && message.id !== undefined) {+ for (const action of execServerActions(message.method, message.params, this.deps.cwd)) {+ const decision = this.deps.authorize(action);+ if (!decision.ok) {+ this.sendMessage(connId, JSON.stringify({+ id: message.id,+ error: { code: -32001, message: decision.reason ?? 'Not allowed on this computer.' },+ }));+ return;+ }+ }+ }+ connection.child.stdin.write(`${data}\n`);+ }++ private dropConnection(connId: string, notifyRemote: boolean): void {+ const connection = this.connections.get(connId);+ if (!connection || connection.closed) return;+ connection.closed = true;+ this.connections.delete(connId);+ try {+ connection.child.stdin.end();+ connection.child.kill();+ } catch {+ // 进程已退出。+ }+ if (notifyRemote) this.send({ connId, kind: 'close' });+ }++ /** 一条消息:超过单帧上限时拆成多段(除最后一段外带 more)。 */+ private sendMessage(connId: string, data: string): void {+ for (let offset = 0; offset < data.length; offset += FRAME_CHARS) {+ const part = data.slice(offset, offset + FRAME_CHARS);+ const more = offset + FRAME_CHARS < data.length;+ this.send({ connId, kind: 'message', data: part, ...(more ? { more: true as const } : {}) });+ }+ }++ /** 发往对方的帧按顺序成批推送(一次只有一个 push 在途)。 */+ private send(frame: RemoteAgentPushFrame): void {+ if (this.closed && frame.kind === 'message') return;+ this.outbox.push(frame);+ this.kick();+ }++ private kick(): void {+ if (this.flushing) return;+ this.flushing = this.flush().finally(() => {+ this.flushing = null;+ if (this.outbox.length) this.kick();+ });+ }++ private async flush(): Promise<void> {+ await Promise.resolve();+ while (this.outbox.length) {+ const batch: RemoteAgentPushFrame[] = [];+ let size = 0;+ while (this.outbox.length && batch.length < REMOTE_AGENT_MAX_PUSH_FRAMES) {+ const next = this.outbox[0];+ const length = next.data?.length ?? 0;+ if (batch.length && size + length > REMOTE_AGENT_MAX_PUSH_CHARS) break;+ batch.push(this.outbox.shift()!);+ size += length;+ }+ try {+ await this.deps.push(batch);+ } catch (error) {+ this.deps.log?.warn('remote agent: exec-server frames could not be delivered', { error: String(error) });+ }+ }+ }+}diff --git a/apps/desktop/src/main/remote-agent/controller/poller.ts b/apps/desktop/src/main/remote-agent/controller/poller.tsnew file mode 100644index 0000000000..c23db2d3e2--- /dev/null+++ b/apps/desktop/src/main/remote-agent/controller/poller.ts@@ -0,0 +1,255 @@+/**+ * 远程 Agent 事件拉取(控制端,每台运行 Agent 的电脑一个)。+ *+ * 同一台电脑上的全部任务共用一个 `poll`:一次带上每个任务的游标,对方没有新数据时挂起最多+ * READ_WAIT_MS。任务再多也只占设备互联一个长等待;新任务登记时另发一个覆盖全部任务的 poll,+ * 同时在途的 poll 不超过两个。两个 poll 返回的数据可能重叠,按 from 去重,游标只前进不后退。+ *+ * 链路抖动:poll 按游标幂等,可恢复的错误退避后重拉;对方长时间不可达时结束全部任务。+ */+import {+ REMOTE_AGENT_MAX_POLL_RUNS,+ REMOTE_AGENT_READ_WAIT_MS,+ parseRemoteAgentPollResult,+ type RemoteAgentErrorInfo,+ type RemoteAgentPollResult,+} from '@cindy/device-link';++/** 经设备互联调用对方;失败时抛出带 `code` 的错误(与 remoteBackgroundInvoke 一致)。 */+export type RemoteAgentInvoke = (args: unknown[]) => Promise<unknown>;++/** 对方不可达时持续重拉的最长时间。 */+export const REMOTE_AGENT_READ_GIVE_UP_MS = 2 * 60_000;+const RETRY_BASE_MS = 500;+const RETRY_MAX_MS = 5_000;+/** 同时在途的 poll 上限:一个长等待 + 一个覆盖新任务的。 */+const MAX_INFLIGHT_POLLS = 2;+/** 对方连续几次立刻返回、却没有任何新数据时,放慢重拉(防止对方行为异常时空转)。 */+const EMPTY_FAST_STREAK = 3;+const EMPTY_FAST_MS = 50;+const EMPTY_FAST_DELAY_MS = 1_000;++export interface PolledRun {+ readonly runId: string;+ /** 收到从当前游标开始的新数据(已去重);done 表示对方的流已结束且读完。 */+ onData(data: Buffer, done: boolean): void;+ /** 任务已不能再拉取(对方不认识这个任务、协议错误或对方长时间不可达)。 */+ onLost(reason: string, error: RemoteAgentErrorInfo): void;+}++interface Entry {+ run: PolledRun;+ cursor: number;+}++/** 可恢复的链路错误:重拉即可。 */+export function isRetryableLinkError(error: unknown): boolean {+ const code = (error as { code?: unknown })?.code;+ const message = error instanceof Error ? error.message : String(error);+ if (typeof code === 'string' && [+ 'PEER_RESET', 'TIMEOUT', 'INVOKE_TIMEOUT', 'BACKPRESSURE', 'DEVICE_OFFLINE', 'LINK_CLOSED', 'LINK_NOT_OPEN', 'NOT_CONNECTED',+ ].includes(code)) {+ return true;+ }+ return /PEER_RESET|TIMEOUT|BACKPRESSURE|OFFLINE|NOT_CONNECTED|LINK_CLOSED|timed out/i.test(message)+ && !/REMOTE_AGENT_(NOT_FOUND|INVALID|UNSUPPORTED|ACCOUNT_CHANGED)/.test(message);+}++export function remoteAgentErrorFrom(error: unknown, fallbackCode = 'REMOTE_AGENT_UNAVAILABLE'): RemoteAgentErrorInfo {+ const message = error instanceof Error ? error.message : String(error);+ const code = (error as { code?: unknown })?.code;+ return {+ code: /\[([A-Z_]+)\]/.exec(message)?.[1] ?? (typeof code === 'string' && code ? code : fallbackCode),+ message,+ };+}++export class RemoteAgentPoller {+ private readonly entries = new Map<string, Entry>();+ private inflight = 0;+ /** 有任务还没被任何在途 poll 覆盖。 */+ private needFresh = false;+ private unreachableSince: number | null = null;+ private attempt = 0;+ private retryTimer: ReturnType<typeof setTimeout> | null = null;+ private rotation = 0;+ private emptyFastStreak = 0;++ constructor(+ readonly invoke: RemoteAgentInvoke,+ private readonly log?: { warn(message: string, meta?: Record<string, unknown>): void },+ private readonly now: () => number = Date.now,+ ) {}++ /** 开始拉取一个任务(游标从 0 开始)。 */+ register(run: PolledRun): void {+ if (this.entries.has(run.runId)) return;+ this.entries.set(run.runId, { run, cursor: 0 });+ this.needFresh = true;+ this.ensure();+ }++ unregister(runId: string): void {+ this.entries.delete(runId);+ }++ get size(): number {+ return this.entries.size;+ }++ private ensure(): void {+ if (this.entries.size === 0 || this.retryTimer) return;+ if (this.inflight > 0 && !this.needFresh) return;+ if (this.inflight >= MAX_INFLIGHT_POLLS) return;+ this.needFresh = false;+ void this.pollOnce();+ }++ private snapshot(): Array<{ runId: string; cursor: number }> {+ const all = [...this.entries.values()].map((entry) => ({ runId: entry.run.runId, cursor: entry.cursor }));+ if (all.length <= REMOTE_AGENT_MAX_POLL_RUNS) return all;+ // 超出单次上限时轮流取(对方每台控制端的任务数远低于这个上限,正常走不到)。+ const start = this.rotation++ % all.length;+ this.needFresh = true;+ return [...all.slice(start), ...all.slice(0, start)].slice(0, REMOTE_AGENT_MAX_POLL_RUNS);+ }++ private async pollOnce(): Promise<void> {+ const wanted = this.snapshot();+ const startedAt = this.now();+ this.inflight += 1;+ let raw: unknown;+ let failure: unknown = null;+ try {+ raw = await this.invoke([{ op: 'poll', runs: wanted, waitMs: REMOTE_AGENT_READ_WAIT_MS }]);+ } catch (error) {+ failure = error;+ } finally {+ this.inflight -= 1;+ }+ let result: RemoteAgentPollResult | null = null;+ if (!failure) {+ try {+ result = parseRemoteAgentPollResult(raw);+ } catch {+ failure = Object.assign(new Error('[REMOTE_AGENT_INVALID] The other computer sent an invalid event stream.'), {+ code: 'REMOTE_AGENT_INVALID',+ });+ }+ }+ if (result) {+ if (this.retryTimer && this.attempt > 0) {+ // 另一个在途的 poll 成功了:链路已恢复,不必等退避。+ clearTimeout(this.retryTimer);+ this.retryTimer = null;+ }+ this.unreachableSince = null;+ this.attempt = 0;+ const delivered = this.apply(wanted, result);+ if (!delivered && this.now() - startedAt < EMPTY_FAST_MS) this.emptyFastStreak += 1;+ else this.emptyFastStreak = 0;+ if (this.emptyFastStreak >= EMPTY_FAST_STREAK) {+ this.emptyFastStreak = 0;+ this.retryLater(EMPTY_FAST_DELAY_MS);+ return;+ }+ this.ensureAfterReturn();+ return;+ }+ this.handleFailure(wanted, failure);+ }++ private ensureAfterReturn(): void {+ // 这个 poll 回来了:没有其它在途的就再发一个;有任务没被覆盖时也发。+ if (this.inflight === 0) this.needFresh = true;+ this.ensure();+ }++ /** 处理一次 poll 的结果;返回是否交付了任何新数据或状态变化。 */+ private apply(wanted: ReadonlyArray<{ runId: string; cursor: number }>, result: RemoteAgentPollResult): boolean {+ const requested = new Map(wanted.map((item) => [item.runId, item.cursor]));+ let delivered = false;+ for (const item of result.runs) {+ const entry = this.entries.get(item.runId);+ const requestedCursor = requested.get(item.runId);+ if (!entry || requestedCursor === undefined) continue;+ if (item.missing) {+ delivered = true;+ this.lose(entry, 'missing', {+ code: 'REMOTE_AGENT_EXPIRED',+ message: '[REMOTE_AGENT_EXPIRED] The task is no longer running on the other computer.',+ });+ continue;+ }+ const from = item.from ?? requestedCursor;+ const data = item.data ? Buffer.from(item.data, 'base64') : Buffer.alloc(0);+ if (from < requestedCursor || from + data.length !== item.cursor || from > entry.cursor) {+ // 数据与游标对不上,或在本机游标之后留了空洞:流已不可信。+ delivered = true;+ this.lose(entry, 'invalid-stream', {+ code: 'REMOTE_AGENT_INVALID',+ message: 'The other computer sent an invalid event stream.',+ });+ continue;+ }+ // 另一个 poll 已经交付过这一段。+ if (item.cursor < entry.cursor || (item.cursor === entry.cursor && !item.done)) continue;+ delivered = true;+ const fresh = data.subarray(entry.cursor - from);+ entry.cursor = item.cursor;+ if (item.done) this.entries.delete(item.runId);+ try {+ entry.run.onData(fresh, item.done === true);+ } catch (error) {+ this.log?.warn('remote agent: event handler failed', { runId: item.runId, error: String(error) });+ }+ }+ return delivered;+ }++ private handleFailure(wanted: ReadonlyArray<{ runId: string; cursor: number }>, error: unknown): void {+ if (!isRetryableLinkError(error)) {+ // 对方拒绝整个 poll(远程控制已关、版本不支持等):涉及的任务都无法继续。+ const info = remoteAgentErrorFrom(error);+ for (const { runId } of wanted) {+ const entry = this.entries.get(runId);+ if (entry) this.lose(entry, 'read-failed', info);+ }+ this.ensureAfterReturn();+ return;+ }+ this.unreachableSince ??= this.now();+ if (this.now() - this.unreachableSince > REMOTE_AGENT_READ_GIVE_UP_MS) {+ this.unreachableSince = null;+ this.attempt = 0;+ for (const entry of [...this.entries.values()]) {+ this.lose(entry, 'unreachable', {+ code: 'REMOTE_AGENT_UNAVAILABLE',+ message: '[REMOTE_AGENT_UNAVAILABLE] The computer running this agent is unreachable.',+ });+ }+ return;+ }+ this.attempt += 1;+ this.retryLater(Math.min(RETRY_MAX_MS, RETRY_BASE_MS * 2 ** Math.min(this.attempt, 4)));+ }++ private retryLater(delayMs: number): void {+ if (this.retryTimer) return;+ this.retryTimer = setTimeout(() => {+ this.retryTimer = null;+ this.needFresh = true;+ this.ensure();+ }, delayMs);+ }++ private lose(entry: Entry, reason: string, error: RemoteAgentErrorInfo): void {+ if (this.entries.get(entry.run.runId) !== entry) return;+ this.entries.delete(entry.run.runId);+ try {+ entry.run.onLost(reason, error);+ } catch (handlerError) {+ this.log?.warn('remote agent: close handler failed', { runId: entry.run.runId, error: String(handlerError) });+ }+ }+}diff --git a/apps/desktop/src/main/remote-agent/controller/projectFiles.ts b/apps/desktop/src/main/remote-agent/controller/projectFiles.tsnew file mode 100644index 0000000000..a5ed0ee145--- /dev/null+++ b/apps/desktop/src/main/remote-agent/controller/projectFiles.ts@@ -0,0 +1,238 @@+/**+ * 同步到对方影子目录的项目说明类文件(控制端读取)。+ *+ * 只同步 Agent 启动时需要从工作目录加载的东西:项目说明(CLAUDE.md / AGENTS.md)、Skill、+ * 子代理、命令模板,以及 Claude Code 项目设置里的权限规则。不同步会在对方电脑上执行代码的+ * 配置(hooks、扩展、MCP 启动命令、环境变量),也不同步任何项目源码。+ *+ * 另外两类(都只读你这台的文件,不执行任何东西):+ * - 项目上级目录里的说明文件:本机任务里 Agent 会沿目录向上加载它们;+ * - 你这台的个人配置(用户级说明、Skill、子代理、命令与权限规则):个人配置以你这台为准,+ * 那台电脑只提供登录、供应商与网络。+ */+import fs from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';++import type { RemoteAgentKind } from '@cindy/device-link';++import {+ ANCESTOR_INSTRUCTION_FILES,+ MAX_ANCESTOR_LEVELS,+ isSafeProjectFilePath,+ type RemoteAgentWireAncestorFile,+ type RemoteAgentWireFile,+ type RemoteAgentWirePersonal,+} from '../wire';++const TOP_LEVEL_FILES = ['CLAUDE.md', 'CLAUDE.local.md', 'AGENTS.md', 'AGENTS.override.md'];+const DIRECTORIES = [+ '.claude/skills',+ '.claude/agents',+ '.claude/commands',+ '.agents/skills',+ '.pi/skills',+ '.pi/prompts',+];+const SETTINGS_FILES = ['.claude/settings.json', '.claude/settings.local.json'];+const MAX_FILES = 512;+const MAX_FILE_BYTES = 512 * 1024;+const MAX_TOTAL_BYTES = 4 * 1024 * 1024;+const MAX_DEPTH = 6;++interface Budget {+ files: number;+ bytes: number;+}++async function readLimited(file: string, budget: Budget): Promise<Buffer | null> {+ if (budget.files >= MAX_FILES) return null;+ try {+ const stat = await fs.stat(file);+ if (!stat.isFile() || stat.size > MAX_FILE_BYTES || budget.bytes + stat.size > MAX_TOTAL_BYTES) return null;+ const data = await fs.readFile(file);+ budget.files += 1;+ budget.bytes += data.length;+ return data;+ } catch {+ return null;+ }+}++async function walk(+ root: string,+ relative: string,+ depth: number,+ budget: Budget,+ out: RemoteAgentWireFile[],+ rename: (relative: string) => string = (value) => value,+): Promise<void> {+ if (depth > MAX_DEPTH || budget.files >= MAX_FILES) return;+ let entries: import('node:fs').Dirent[];+ try {+ entries = await fs.readdir(path.join(root, relative), { withFileTypes: true });+ } catch {+ return;+ }+ for (const entry of entries) {+ if (entry.name === '.git' || entry.name === 'node_modules') continue;+ const child = `${relative}/${entry.name}`;+ const full = path.join(root, child);+ let isDir = entry.isDirectory();+ let isFile = entry.isFile();+ if (entry.isSymbolicLink()) {+ try {+ const stat = await fs.stat(full);+ isDir = stat.isDirectory();+ isFile = stat.isFile();+ } catch {+ continue;+ }+ }+ if (isDir) await walk(root, child, depth + 1, budget, out, rename);+ else if (isFile && isSafeProjectFilePath(rename(child))) {+ const data = await readLimited(full, budget);+ if (data) out.push({ path: rename(child), data: data.toString('base64') });+ }+ }+}++/** Claude Code 项目设置只保留权限规则:hooks、环境变量、状态栏命令等会在对方电脑上执行。 */+function sanitizeClaudeSettings(raw: Buffer): Buffer | null {+ try {+ const parsed = JSON.parse(raw.toString('utf8')) as Record<string, unknown>;+ const permissions = parsed.permissions;+ if (!permissions || typeof permissions !== 'object') return null;+ return Buffer.from(JSON.stringify({ permissions }, null, 2));+ } catch {+ return null;+ }+}++export async function collectProjectInstructionFiles(workingDir: string): Promise<RemoteAgentWireFile[]> {+ const budget: Budget = { files: 0, bytes: 0 };+ const out: RemoteAgentWireFile[] = [];+ for (const name of TOP_LEVEL_FILES) {+ const data = await readLimited(path.join(workingDir, name), budget);+ if (data) out.push({ path: name, data: data.toString('base64') });+ }+ for (const name of SETTINGS_FILES) {+ const data = await readLimited(path.join(workingDir, name), budget);+ const sanitized = data ? sanitizeClaudeSettings(data) : null;+ if (sanitized) out.push({ path: name, data: sanitized.toString('base64') });+ }+ for (const dir of DIRECTORIES) await walk(workingDir, dir, 0, budget, out);+ return out;+}++/**+ * 项目上级目录里的说明文件(不含文件系统根):本机任务里 Claude Code 与 Pi 会沿目录向上加载。+ * Codex 经执行环境在你这台直接读取,不需要同步。+ */+export async function collectAncestorInstructionFiles(workingDir: string): Promise<RemoteAgentWireAncestorFile[]> {+ const budget: Budget = { files: 0, bytes: 0 };+ const out: RemoteAgentWireAncestorFile[] = [];+ let dir = path.resolve(workingDir);+ for (let up = 1; up <= MAX_ANCESTOR_LEVELS; up += 1) {+ const parent = path.dirname(dir);+ if (parent === dir || path.dirname(parent) === parent) break;+ dir = parent;+ for (const name of ANCESTOR_INSTRUCTION_FILES) {+ const data = await readLimited(path.join(dir, name), budget);+ if (data) out.push({ up, name, data: data.toString('base64') });+ }+ }+ return out;+}++/** 本机 Claude Code 的配置目录(与 Cindy 启动本机 Claude Code 时一致:默认 ~/.claude)。 */+export function claudeConfigDir(env: NodeJS.ProcessEnv = process.env, home = os.homedir()): string {+ return env.CLAUDE_CONFIG_DIR && path.isAbsolute(env.CLAUDE_CONFIG_DIR) ? env.CLAUDE_CONFIG_DIR : path.join(home, '.claude');+}++/** 本机 Codex 的主目录(CODEX_HOME,默认 ~/.codex)。 */+export function codexHomeDir(env: NodeJS.ProcessEnv = process.env, home = os.homedir()): string {+ return env.CODEX_HOME && path.isAbsolute(env.CODEX_HOME) ? env.CODEX_HOME : path.join(home, '.codex');+}++const PERSONAL_CLAUDE_DIRECTORIES = ['skills', 'agents', 'commands'] as const;++function permissionRules(value: unknown): string[] {+ return Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string' && item.length > 0) : [];+}++export interface CollectedPersonalConfig {+ personal: RemoteAgentWirePersonal;+ /** 同步过去的个人 Skill / 子代理 / 命令目录:影子目录里的相对路径 → 你这台的真实目录。 */+ roots: Array<{ relative: string; local: string }>;+}++/**+ * 你这台的个人配置。项目里已有同名的 Skill / 子代理 / 命令时以项目为准(与本机加载顺序一致)。+ */+export async function collectPersonalConfig(+ kind: RemoteAgentKind,+ projectFiles: readonly RemoteAgentWireFile[],+ options: { env?: NodeJS.ProcessEnv; home?: string } = {},+): Promise<CollectedPersonalConfig> {+ const env = options.env ?? process.env;+ const home = options.home ?? os.homedir();+ const budget: Budget = { files: 0, bytes: 0 };+ const personal: RemoteAgentWirePersonal = { files: [] };+ const roots: CollectedPersonalConfig['roots'] = [];+ if (kind === 'claude-code') {+ const configDir = claudeConfigDir(env, home);+ const memory = await readLimited(path.join(configDir, 'CLAUDE.md'), budget);+ if (memory) personal.memory = memory.toString('utf8');+ const projectEntries = new Set(projectFiles.map((file) => file.path.split('/').slice(0, 3).join('/')));+ for (const dir of PERSONAL_CLAUDE_DIRECTORIES) {+ let entries: import('node:fs').Dirent[];+ try {+ entries = await fs.readdir(path.join(configDir, dir), { withFileTypes: true });+ } catch {+ continue;+ }+ for (const entry of entries) {+ const relative = `.claude/${dir}/${entry.name}`;+ if (projectEntries.has(relative) || !isSafeProjectFilePath(relative)) continue;+ const local = path.join(configDir, dir, entry.name);+ const before = personal.files.length;+ let stat: import('node:fs').Stats;+ try {+ stat = await fs.stat(local);+ } catch {+ continue;+ }+ if (stat.isDirectory()) {+ await walk(configDir, `${dir}/${entry.name}`, 1, budget, personal.files, (value) => `.claude/${value}`);+ } else if (stat.isFile()) {+ const data = await readLimited(local, budget);+ if (data) personal.files.push({ path: relative, data: data.toString('base64') });+ }+ if (personal.files.length > before) roots.push({ relative, local });+ }+ }+ try {+ const settings = JSON.parse(await fs.readFile(path.join(configDir, 'settings.json'), 'utf8')) as {+ permissions?: Record<string, unknown>;+ };+ const allow = permissionRules(settings.permissions?.allow);+ const deny = permissionRules(settings.permissions?.deny);+ const ask = permissionRules(settings.permissions?.ask);+ if (allow.length || deny.length || ask.length) personal.permissions = { allow, deny, ask };+ } catch {+ // 没有个人设置或格式不对:不同步。+ }+ } else if (kind === 'codex') {+ const codexHome = codexHomeDir(env, home);+ // 与 Codex 的读取顺序一致:AGENTS.override.md 优先于 AGENTS.md。+ for (const name of ['AGENTS.override.md', 'AGENTS.md']) {+ const data = await readLimited(path.join(codexHome, name), budget);+ if (data && data.toString('utf8').trim()) {+ personal.instructions = data.toString('utf8');+ break;+ }+ }+ }+ return { personal, roots };+}diff --git a/apps/desktop/src/main/remote-agent/controller/proxyHandle.ts b/apps/desktop/src/main/remote-agent/controller/proxyHandle.tsnew file mode 100644index 0000000000..88aefb5d32--- /dev/null+++ b/apps/desktop/src/main/remote-agent/controller/proxyHandle.ts@@ -0,0 +1,432 @@+/**+ * 远程 Agent 的本机会话句柄(控制端)。+ *+ * 对本机的 Maker / Session 来说,它就是一个普通的 AgentSessionHandle:方法调用经协议客户端+ * 交给对方电脑上真正运行的 Agent;同步读取的状态(用量、是否在跑、计划模式等)读本地镜像,+ * 镜像由对方事件流里的状态行更新;权限确认、问题与计划审阅由本机的交互回调回答。+ * 本机用户在确认卡上允许的文件 / 命令操作同时登记到执行器的权限上限里。+ */+import fsp from 'node:fs/promises';++import type { RemoteAgentMethod, RemoteAgentReply, RemoteAgentReverseRequest } from '@cindy/device-link';+import type {+ AgentEvent,+ AgentKind,+ AgentSessionHandle,+ AgentSessionTeardownOptions,+ BackgroundTaskSnapshot,+ Effort,+ InteractionDecision,+ InteractionRequest,+ InteractionResolver,+ SendOptions,+ UsageSnapshot,+ UserMessage,+} from '@cindy/maker-core';++import type { ExecutorAction } from '../executor/gate';+import type { ExecutorWorkspace } from '../executor/workspace';+import { encodeSendOptions, encodeUserMessage } from '../wire';+import { RemoteAgentRemoteError, type RemoteAgentRunClient } from './runClient';++const MAX_REMEMBERED_SEND_CALLBACKS = 64;++/** 对方运行的会话描述(open 成功时返回)。 */+export interface RemoteStartedInfo {+ id: string;+ agentKind: AgentKind;+ model: string;+ shadowDir: string;+ /** 影子目录按真实路径镜像时的镜像根(那台电脑上的路径)。 */+ mirrorRoot?: string;+ methods: string[];+ state: Record<string, unknown>;+ requestSessionId?: string;+ codexProxyActive?: boolean;+ codexHostKey?: string;+ codexCindyRemoteCompactionCompatible?: boolean;+ codexProductPromptDelivery?: { threadId: string; historyHasProductPrompt: boolean };+}++export function parseStartedInfo(value: Record<string, unknown>, kind: AgentKind): RemoteStartedInfo {+ const str = (v: unknown) => (typeof v === 'string' ? v : undefined);+ const id = str(value.id);+ if (!id) throw new Error('[REMOTE_AGENT_INVALID] the other computer returned an invalid session');+ const delivery = value.codexProductPromptDelivery as Record<string, unknown> | undefined;+ return {+ id,+ agentKind: kind,+ model: str(value.model) ?? '',+ shadowDir: str(value.shadowDir) ?? '',+ ...(str(value.mirrorRoot) ? { mirrorRoot: str(value.mirrorRoot) } : {}),+ methods: Array.isArray(value.methods) ? value.methods.filter((m): m is string => typeof m === 'string') : [],+ state: value.state && typeof value.state === 'object' ? value.state as Record<string, unknown> : {},+ ...(str(value.requestSessionId) ? { requestSessionId: str(value.requestSessionId) } : {}),+ ...(typeof value.codexProxyActive === 'boolean' ? { codexProxyActive: value.codexProxyActive } : {}),+ ...(str(value.codexHostKey) ? { codexHostKey: str(value.codexHostKey) } : {}),+ ...(typeof value.codexCindyRemoteCompactionCompatible === 'boolean'+ ? { codexCindyRemoteCompactionCompatible: value.codexCindyRemoteCompactionCompatible }+ : {}),+ ...(delivery && typeof delivery.threadId === 'string' && typeof delivery.historyHasProductPrompt === 'boolean'+ ? { codexProductPromptDelivery: { threadId: delivery.threadId, historyHasProductPrompt: delivery.historyHasProductPrompt } }+ : {}),+ };+}++/** 单消费者事件队列。 */+class EventQueue implements AsyncIterable<AgentEvent> {+ private readonly items: AgentEvent[] = [];+ private waiter: (() => void) | null = null;+ private ended = false;++ push(event: AgentEvent): void {+ if (this.ended) return;+ this.items.push(event);+ this.waiter?.();+ this.waiter = null;+ }++ end(): void {+ this.ended = true;+ this.waiter?.();+ this.waiter = null;+ }++ async *[Symbol.asyncIterator](): AsyncIterator<AgentEvent> {+ for (;;) {+ if (this.items.length) {+ yield this.items.shift()!;+ continue;+ }+ if (this.ended) return;+ await new Promise<void>((resolve) => {+ this.waiter = resolve;+ });+ }+ }+}++/** 工具名(含 Claude Code 的 Cindy 工具前缀)到执行器操作的对应;用于登记本机用户的批准。 */+const EXEC_TOOLS = new Set(['bash', 'powershell', 'exec', 'exec_command', 'shell', 'commandexecution']);+const WRITE_TOOLS = new Set(['write', 'edit', 'multiedit', 'notebookedit', 'apply_patch', 'filechange', 'file_change']);+const READ_TOOLS = new Set(['read', 'grep', 'find', 'ls', 'glob']);++/**+ * Codex 的命令确认给的是 `/bin/zsh -lc 'cmd'` 这样的完整命令行,而 exec-server 收到的是+ * argv;两边都还原成 shell 里实际执行的那段脚本再比对。+ */+export function innerShellScript(command: string): string {+ const match = /^(?:\S*\/)?(?:ba|z|da|k)?sh -l?c '((?:[^']|'\\'')*)'$/.exec(command.trim());+ return match ? match[1].replace(/'\\''/g, "'") : command;+}++export function approvalActionsFor(+ request: InteractionRequest,+ workspace: ExecutorWorkspace,+): ExecutorAction[] {+ if (request.kind !== 'permission') return [];+ const name = request.toolName.replace(/^mcp__cindy_exec__/, '').toLowerCase();+ const input = request.input ?? {};+ const actions: ExecutorAction[] = [];+ if (EXEC_TOOLS.has(name)) {+ const raw = input.command;+ const command = typeof raw === 'string'+ ? raw+ : Array.isArray(raw) && raw.every((part) => typeof part === 'string') ? (raw as string[]).join(' ') : undefined;+ const cwd = typeof input.cwd === 'string' ? workspace.resolve(input.cwd) : workspace.workingDir;+ if (command) actions.push({ kind: 'exec', command: workspace.mapCommand(innerShellScript(command)), cwd });+ }+ // Codex 的改文件确认:逐个目标路径登记。+ if (Array.isArray(input.changes)) {+ for (const change of input.changes as Array<{ path?: unknown }>) {+ if (typeof change?.path !== 'string' || !change.path) continue;+ try {+ actions.push({ kind: 'write', path: workspace.resolve(change.path) });+ } catch {+ // 路径不合法时不登记。+ }+ }+ }+ const target = ['file_path', 'path', 'notebook_path']+ .map((key) => input[key])+ .find((value): value is string => typeof value === 'string' && value.length > 0);+ if (target && (WRITE_TOOLS.has(name) || READ_TOOLS.has(name))) {+ try {+ actions.push({ kind: WRITE_TOOLS.has(name) ? 'write' : 'read', path: workspace.resolve(target) });+ } catch {+ // 路径不合法时不登记。+ }+ }+ return actions;+}++export interface RemoteHandleDeps {+ client: RemoteAgentRunClient;+ started: RemoteStartedInfo;+ workspace: ExecutorWorkspace;+ recordApproval(action: ExecutorAction): void;+ onInvalidResumeSession?: (expectedSdkSessionId: string) => Promise<boolean>;+ /** 读本机图片(随消息带给对方)。 */+ readImage?: (path: string) => Promise<Buffer>;+ /** 改写来自对方的事件(如把 Cindy 工具名换回 Agent 自带工具名)。 */+ mapEvent?: (event: AgentEvent) => AgentEvent;+ newId(): string;+ /** 权限档 / 附加目录等变化时同步给执行器。 */+ onPermissionMode?: (mode: string) => void;+ onPlanMode?: (enabled: boolean) => void;+ onExtraDirs?: (dirs: string[]) => void;+ /** 本机 MCP 身份引用的 vendorOptions 同步更新。 */+ onVendorOptions?: (patch: Record<string, unknown>) => void;+ /** 句柄关闭后释放本机资源(执行器、MCP 身份等)。 */+ dispose(): Promise<void>;+}++export interface RemoteAgentHandleController {+ handle: AgentSessionHandle;+ onEvent(event: unknown): void;+ onState(state: Record<string, unknown>): void;+ onRequest(request: RemoteAgentReverseRequest): Promise<RemoteAgentReply> | null;+ onClosed(reason: string, message?: string): void;+}++export function createRemoteAgentHandle(deps: RemoteHandleDeps): RemoteAgentHandleController {+ const { client, started } = deps;+ const queue = new EventQueue();+ let state: Record<string, unknown> = { ...started.state };+ let resolver: InteractionResolver | null = null;+ let disposed = false;+ const sendCallbacks = new Map<string, {+ onTranscriptUserEntry?: (entryId: string) => void | Promise<void>;+ onInteractionStateChange?: (state: 'waiting' | 'resolved' | 'cancelled') => void;+ }>();+ const readImage = deps.readImage ?? ((file: string) => fsp.readFile(file));+ const supported = new Set(started.methods);++ const dispose = async () => {+ if (disposed) return;+ disposed = true;+ queue.end();+ await deps.dispose().catch(() => undefined);+ };++ const call = (method: RemoteAgentMethod, ...args: unknown[]) => client.call(method, args);++ async function sendLike(method: 'send' | 'steer', message: UserMessage, opts?: SendOptions): Promise<void> {+ const encoded = await encodeSendOptions(opts, readImage);+ const wireMessage = await encodeUserMessage(message, readImage);+ const callId = deps.newId();+ if (encoded.onTranscriptUserEntry || encoded.onInteractionStateChange) {+ sendCallbacks.set(callId, {+ onTranscriptUserEntry: encoded.onTranscriptUserEntry,+ onInteractionStateChange: encoded.onInteractionStateChange,+ });+ while (sendCallbacks.size > MAX_REMEMBERED_SEND_CALLBACKS) {+ sendCallbacks.delete(sendCallbacks.keys().next().value as string);+ }+ }+ await client.callWithId(callId, method, [wireMessage, encoded.wire]);+ }++ const optional = <K extends keyof AgentSessionHandle>(method: RemoteAgentMethod, fn: AgentSessionHandle[K]) =>+ (supported.has(method) ? { [method]: fn } : {}) as Partial<AgentSessionHandle>;++ const handle: AgentSessionHandle = {+ get id() {+ return typeof state.id === 'string' ? state.id : started.id;+ },+ get requestSessionId() {+ return typeof state.requestSessionId === 'string' ? state.requestSessionId : started.requestSessionId;+ },+ agentKind: started.agentKind,+ get model() {+ return typeof state.model === 'string' ? state.model : started.model;+ },+ ...(started.codexProxyActive !== undefined ? { codexProxyActive: started.codexProxyActive } : {}),+ ...(started.codexHostKey ? { codexHostKey: started.codexHostKey } : {}),+ get codexThreadModelProviderId() {+ return typeof state.codexThreadModelProviderId === 'string' ? state.codexThreadModelProviderId : undefined;+ },+ get codexThreadMayHaveRollout() {+ return typeof state.codexThreadMayHaveRollout === 'boolean' ? state.codexThreadMayHaveRollout : undefined;+ },+ ...(started.codexCindyRemoteCompactionCompatible !== undefined+ ? { codexCindyRemoteCompactionCompatible: started.codexCindyRemoteCompactionCompatible }+ : {}),+ ...(started.codexProductPromptDelivery ? { codexProductPromptDelivery: started.codexProductPromptDelivery } : {}),+ get disabledSkillPaths() {+ return Array.isArray(state.disabledSkillPaths) ? state.disabledSkillPaths as string[] : undefined;+ },++ send: (message, opts) => sendLike('send', message, opts),+ steer: (message, opts) => sendLike('steer', message, opts),+ abort: async () => {+ await call('abort');+ },+ close: async (opts?: AgentSessionTeardownOptions) => {+ try {+ await client.close('close', opts?.reason ?? 'navigation');+ } finally {+ await dispose();+ }+ },+ detach: async (opts?: AgentSessionTeardownOptions) => {+ try {+ await client.close('detach', opts?.reason ?? 'navigation');+ } finally {+ await dispose();+ }+ },+ events: () => queue,+ getUsageSnapshot: () => (state.usage && typeof state.usage === 'object'+ ? state.usage as UsageSnapshot+ : { tokenUsage: 0, contextTokens: 0, contextWindow: 0, costUsd: 0 }),+ setInteractionResolver: (next) => {+ resolver = next;+ },+ isTurnRunning: () => state.turnRunning === true,+ isPreparingUserTurn: () => state.preparing === true,+ getCurrentTurnId: () => (typeof state.currentTurnId === 'string' ? state.currentTurnId : null),+ getPlanMode: () => (typeof state.planMode === 'boolean' ? state.planMode : null),+ getExecutionPlanMode: () => (typeof state.executionPlanMode === 'boolean' ? state.executionPlanMode : null),+ getFastMode: () => state.fastMode === true,+ getEffort: () => (typeof state.effort === 'string' ? state.effort as Effort : null),+ listBackgroundTasks: () => (Array.isArray(state.backgroundTasks) ? state.backgroundTasks as BackgroundTaskSnapshot[] : []),+ countPendingWakeContinuations: () => (typeof state.pendingWake === 'number' ? state.pendingWake : 0),+ ...optional('requestGracefulStop', async () => {+ await call('requestGracefulStop');+ }),+ ...optional('setModel', async (model: string, opts?: { providerId?: string | null; effort?: Effort }) => {+ await call('setModel', model, opts);+ }),+ ...optional('requiresModelSwitchRebuild', async (model: string, opts?: { providerId?: string | null }) =>+ (await call('requiresModelSwitchRebuild', model, opts)) === true),+ ...optional('previewModelSwitch', (async (model: string, opts?: { providerId?: string | null }) =>+ call('previewModelSwitch', model, opts)) as AgentSessionHandle['previewModelSwitch']),+ ...optional('setPermissionMode', async (mode: string) => {+ await call('setPermissionMode', mode);+ deps.onPermissionMode?.(mode);+ }),+ ...optional('setEffort', async (effort: Effort) => {+ await call('setEffort', effort);+ }),+ ...optional('setFastMode', async (enabled: boolean) => {+ await call('setFastMode', enabled);+ }),+ ...optional('setPlanMode', async (enabled: boolean) => {+ await call('setPlanMode', enabled);+ deps.onPlanMode?.(enabled);+ }),+ ...optional('setThinkingEnabled', async (enabled: boolean) => {+ await call('setThinkingEnabled', enabled);+ }),+ ...optional('setExtraDirs', async (dirs: string[], libraryRoot?: string | null) => {+ deps.onExtraDirs?.(dirs);+ await call('setExtraDirs', dirs, libraryRoot ?? null);+ }),+ ...optional('setWritableDirs', async (dirs: string[]) => {+ await call('setWritableDirs', dirs);+ }),+ // 本机 MCP 身份(协同等工具)必须立即看到改动;对方不支持时也照样更新本机这一份。+ setVendorOptions: async (patch: Record<string, unknown>) => {+ deps.onVendorOptions?.(patch ?? {});+ if (supported.has('setVendorOptions')) await call('setVendorOptions', JSON.parse(JSON.stringify(patch ?? {})));+ },+ ...optional('stopBackgroundTask', async (taskId: string) => {+ await call('stopBackgroundTask', taskId);+ }),+ ...optional('resumeBackgroundTask', async (taskId: string, message: string, childId?: string) => {+ await call('resumeBackgroundTask', taskId, message, childId);+ }),+ ...optional('compactSession', (async (instructions?: string) =>+ call('compactSession', instructions)) as AgentSessionHandle['compactSession']),+ ...optional('getContextUsage', (async () => call('getContextUsage')) as AgentSessionHandle['getContextUsage']),+ ...optional('getCodexContextWindowInfo', (async () =>+ call('getCodexContextWindowInfo')) as AgentSessionHandle['getCodexContextWindowInfo']),+ ...optional('useCindyAutoReviewFallback', async () => {+ await call('useCindyAutoReviewFallback');+ }),+ ...optional('previewRewindFiles', (async (userUuid: string) =>+ call('previewRewindFiles', userUuid)) as AgentSessionHandle['previewRewindFiles']),+ ...optional('commitRewindFiles', (async (userUuid: string, priorAssistantUuid: string, opts?: unknown) =>+ call('commitRewindFiles', userUuid, priorAssistantUuid, opts ?? null)) as AgentSessionHandle['commitRewindFiles']),+ };++ async function answerInteraction(request: InteractionRequest): Promise<RemoteAgentReply> {+ if (!resolver) {+ // 本机还没接上交互回调:按系统性拒绝处理,不替用户允许。+ const decision: InteractionDecision = request.kind === 'ask_user_question'+ ? { kind: 'ask_user_question', answers: {}, dismissed: true }+ : request.kind === 'plan_review'+ ? { kind: 'plan_review', behavior: 'deny', reason: 'interaction_unavailable', dismissed: true }+ : { kind: 'permission', behavior: 'deny', reason: 'interaction_unavailable' };+ return { type: 'interaction', result: decision };+ }+ const decision = await resolver(request);+ if (decision.kind === 'permission' && decision.behavior === 'allow') {+ const effective = decision.updatedInput ? { ...request, input: decision.updatedInput } : request;+ for (const action of approvalActionsFor(effective, deps.workspace)) deps.recordApproval(action);+ }+ return { type: 'interaction', result: JSON.parse(JSON.stringify(decision)) };+ }++ return {+ handle,+ onEvent(event) {+ if (!event || typeof event !== 'object' || typeof (event as AgentEvent).type !== 'string') return;+ const typed = event as AgentEvent;+ queue.push(deps.mapEvent ? deps.mapEvent(typed) : typed);+ },+ onState(next) {+ state = { ...state, ...next };+ },+ onRequest(request) {+ if (request.type === 'interaction') {+ return answerInteraction(request.request as InteractionRequest);+ }+ if (request.type === 'callback') {+ return (async (): Promise<RemoteAgentReply> => {+ const [first, second] = request.args;+ if (request.name === 'onInvalidResumeSession') {+ const value = typeof first === 'string' && deps.onInvalidResumeSession+ ? await deps.onInvalidResumeSession(first)+ : false;+ return { type: 'callback', value };+ }+ const callbacks = typeof first === 'string' ? sendCallbacks.get(first) : undefined;+ if (request.name === 'onTranscriptUserEntry' && typeof second === 'string') {+ await callbacks?.onTranscriptUserEntry?.(second);+ } else if (request.name === 'onInteractionStateChange'+ && (second === 'waiting' || second === 'resolved' || second === 'cancelled')) {+ callbacks?.onInteractionStateChange?.(second);+ }+ return { type: 'callback' };+ })();+ }+ return null;+ },+ onClosed(reason, message) {+ if (reason !== 'closed' && reason !== 'detached' && reason !== 'ended') {+ queue.push({+ type: 'error',+ data: {+ message: message ?? `[REMOTE_AGENT_UNAVAILABLE] The agent on the other computer stopped (${reason}).`,+ isTerminal: true,+ reason: 'remote_agent_closed',+ },+ source: started.agentKind,+ });+ }+ void dispose();+ },+ };+}++/** 对方错误还原成本机能识别的错误(保留类名,供 Maker 判断登录失效等)。 */+export function localizeRemoteError(error: unknown): Error {+ if (error instanceof RemoteAgentRemoteError) {+ const local = new Error(error.message);+ local.name = error.name;+ return local;+ }+ return error instanceof Error ? error : new Error(String(error));+}diff --git a/apps/desktop/src/main/remote-agent/controller/router.ts b/apps/desktop/src/main/remote-agent/controller/router.tsnew file mode 100644index 0000000000..41222620bf--- /dev/null+++ b/apps/desktop/src/main/remote-agent/controller/router.ts@@ -0,0 +1,136 @@+/**+ * 远程 Agent 反向 HTTP 请求的本机路由(控制端)。+ *+ * 对方电脑上的 Agent 经它本机隧道发来的 HTTP 请求在这里落地:+ * - `/exec/<op>`:执行器原始操作(Pi 的工具后端),JSON 进 JSON 出;+ * - `/mcp/cindy_exec`:Claude Code 风格文件与命令工具(MCP);+ * - `/mcp/<name>`:本机 Cindy 工具(MCP),转发到本机 MCP 桥,身份固定为本任务(对方给的+ * 查询参数一律丢弃,不能借它冒用别的任务)。+ * 其余路径一律 404。+ */+import type { RemoteAgentReply } from '@cindy/device-link';++import { CINDY_EXEC_MCP_SERVER, handleExecMcpRequest } from '../executor/ccMcp';+import { ExecutorRequestError, type RemoteExecutor } from '../executor/executor';++/** 本任务可用的一个本机 MCP 服务:完整地址(已带本任务身份)与要附加的请求头。 */+export interface LocalMcpTarget {+ url: string;+ headers: Record<string, string>;+}++export interface ReverseHttpRouterDeps {+ executor: RemoteExecutor;+ /** 本任务可用的本机 MCP 服务,按名字查。 */+ mcpTarget(name: string): LocalMcpTarget | undefined;+ fetch?: typeof fetch;+}++const FORWARD_REQUEST_HEADERS = new Set(['content-type', 'accept', 'mcp-session-id', 'mcp-protocol-version', 'last-event-id']);+const FORWARD_RESPONSE_HEADERS = new Set(['content-type', 'mcp-session-id', 'mcp-protocol-version']);++function json(status: number, value: unknown): Extract<RemoteAgentReply, { type: 'http' }> {+ return {+ type: 'http',+ status,+ headers: [['content-type', 'application/json']],+ body: Buffer.from(JSON.stringify(value)).toString('base64'),+ };+}++function errorStatus(code: string): number {+ switch (code) {+ case 'INVALID':+ return 400;+ case 'EACCES':+ case 'EPERM':+ return 403;+ case 'ENOENT':+ case 'ENOTDIR':+ return 404;+ case 'UNSUPPORTED':+ return 501;+ case 'CLOSED':+ return 410;+ default:+ return 500;+ }+}++export function createReverseHttpRouter(deps: ReverseHttpRouterDeps) {+ const doFetch = deps.fetch ?? fetch;++ async function forwardMcp(+ target: LocalMcpTarget,+ method: string,+ headers: Array<[string, string]>,+ body: Buffer | undefined,+ signal?: AbortSignal,+ ): Promise<RemoteAgentReply> {+ // 推送流(GET)对请求-响应式隧道没有意义,按协议回 405 让客户端不开推送流。+ if (method === 'GET') return { type: 'http', status: 405, headers: [['allow', 'POST, DELETE']] };+ const outgoing = new Headers(target.headers);+ for (const [name, value] of headers) {+ if (FORWARD_REQUEST_HEADERS.has(name.toLowerCase())) outgoing.set(name, value);+ }+ const response = await doFetch(target.url, {+ method,+ headers: outgoing,+ ...(body && method !== 'GET' && method !== 'HEAD' ? { body: new Uint8Array(body) } : {}),+ signal,+ });+ const data = Buffer.from(await response.arrayBuffer());+ const replyHeaders: Array<[string, string]> = [];+ response.headers.forEach((value, name) => {+ if (FORWARD_RESPONSE_HEADERS.has(name.toLowerCase())) replyHeaders.push([name, value]);+ });+ return {+ type: 'http',+ status: response.status,+ headers: replyHeaders,+ ...(data.length ? { body: data.toString('base64') } : {}),+ };+ }++ return async function route(+ request: { method: string; path: string; headers: Array<[string, string]>; body?: string },+ signal?: AbortSignal,+ ): Promise<RemoteAgentReply> {+ const url = new URL(request.path, 'http://tunnel.invalid');+ const body = request.body ? Buffer.from(request.body, 'base64') : undefined;+ const execMatch = /^\/exec\/([a-z]+\.[a-z]+)$/.exec(url.pathname);+ if (execMatch) {+ if (request.method !== 'POST') return json(405, { error: { code: 'INVALID', message: 'POST only' } });+ let parsed: unknown;+ try {+ parsed = JSON.parse(body?.toString('utf8') ?? '{}');+ } catch {+ return json(400, { error: { code: 'INVALID', message: 'invalid JSON body' } });+ }+ try {+ return json(200, await deps.executor.handle(execMatch[1], parsed, signal));+ } catch (error) {+ const code = error instanceof ExecutorRequestError ? error.code : 'EXECUTOR_ERROR';+ const message = error instanceof Error ? error.message : String(error);+ return json(errorStatus(code), { error: { code, message } });+ }+ }+ const mcpMatch = /^\/mcp\/([A-Za-z0-9_-]{1,64})$/.exec(url.pathname);+ if (mcpMatch) {+ const name = mcpMatch[1];+ if (name === CINDY_EXEC_MCP_SERVER) {+ const response = await handleExecMcpRequest(deps.executor, request.method, body, signal);+ return {+ type: 'http',+ status: response.status,+ headers: response.headers,+ ...(response.body?.length ? { body: response.body.toString('base64') } : {}),+ };+ }+ const target = deps.mcpTarget(name);+ if (!target) return json(404, { error: { code: 'NOT_FOUND', message: `MCP server ${name} is not available for this task` } });+ return forwardMcp(target, request.method, request.headers, body, signal);+ }+ return json(404, { error: { code: 'NOT_FOUND', message: 'unknown path' } });+ };+}diff --git a/apps/desktop/src/main/remote-agent/controller/runClient.ts b/apps/desktop/src/main/remote-agent/controller/runClient.tsnew file mode 100644index 0000000000..7a010dd922--- /dev/null+++ b/apps/desktop/src/main/remote-agent/controller/runClient.ts@@ -0,0 +1,316 @@+/**+ * 远程 Agent 任务的协议客户端(控制端:任务、文件与命令所在的电脑)。+ *+ * 一个任务一份:发 open 后登记到这台电脑的共享拉取器(RemoteAgentPoller),把事件流的行分发给+ * 调用方(Agent 事件、状态镜像、方法结果、反向请求、WebSocket 帧);反向请求处理完用 reply 回包。+ * 大载荷先分段上传再引用。+ *+ * 链路抖动由拉取器处理(poll 按游标幂等);其余 op 不自动重放(open / call / reply / push 在对方+ * 按 id 去重,结果不明时由调用方决定)。对方长时间不可达时拉取器结束任务并报告原因。+ */+import { promisify } from 'node:util';+import { gzip } from 'node:zlib';++import {+ REMOTE_AGENT_CHANNEL,+ REMOTE_AGENT_MAX_INLINE_PAYLOAD_CHARS,+ REMOTE_AGENT_MAX_PAYLOAD_BYTES,+ REMOTE_AGENT_UPLOAD_CHUNK_BYTES,+ parseRemoteAgentCaps,+ parseRemoteAgentStreamItem,+ type RemoteAgentCaps,+ type RemoteAgentErrorInfo,+ type RemoteAgentKind,+ type RemoteAgentMethod,+ type RemoteAgentPayload,+ type RemoteAgentPushFrame,+ type RemoteAgentReply,+ type RemoteAgentReverseRequest,+ type RemoteAgentStreamItem,+ type RemoteAgentTeardownReason,+} from '@cindy/device-link';++import { LineSplitter } from '../eventLog';+import { RemoteAgentPoller, type PolledRun, type RemoteAgentInvoke } from './poller';++export { isRetryableLinkError, RemoteAgentPoller, type RemoteAgentInvoke } from './poller';++const gzipAsync = promisify(gzip);++/** 单行事件上限(大工具结果)。 */+const MAX_LINE_BYTES = 64 * 1024 * 1024;+/** 结束时等对方收尾事件到达的最长时间。 */+const CLOSE_DRAIN_MS = 5_000;++export class RemoteAgentRemoteError extends Error {+ constructor(readonly info: RemoteAgentErrorInfo) {+ super(info.message || info.code);+ this.name = info.name ?? 'RemoteAgentRemoteError';+ }+}++export interface RemoteAgentRunHandlers {+ onEvent(event: unknown): void;+ onState(state: Record<string, unknown>): void;+ onRequest(request: RemoteAgentReverseRequest, signal: AbortSignal): Promise<RemoteAgentReply>;+ onWs(item: Extract<RemoteAgentStreamItem, { t: 'ws' }>): void;+ onClosed(reason: string, error?: RemoteAgentErrorInfo): void;+}++function sleep(ms: number): Promise<void> {+ return new Promise((resolve) => setTimeout(resolve, ms));+}++export class RemoteAgentRunClient implements PolledRun {+ private closed = false;+ private registered = false;+ private readonly drained: Promise<void>;+ private markDrained!: () => void;+ private pushSeq = 0;+ private readonly pendingCalls = new Map<string, { resolve(value: unknown): void; reject(error: Error): void }>();+ private started: { resolve(handle: Record<string, unknown>): void; reject(error: Error): void } | null = null;+ private readonly splitter = new LineSplitter(MAX_LINE_BYTES);+ private readonly inflight = new Map<string, AbortController>();++ private readonly invoke: RemoteAgentInvoke;++ constructor(+ readonly runId: string,+ private readonly poller: RemoteAgentPoller,+ private readonly handlers: RemoteAgentRunHandlers,+ private readonly newId: () => string,+ private readonly log?: { warn(message: string, meta?: Record<string, unknown>): void },+ ) {+ this.invoke = poller.invoke;+ this.drained = new Promise<void>((resolve) => {+ this.markDrained = resolve;+ });+ }++ static async caps(invoke: RemoteAgentInvoke): Promise<RemoteAgentCaps> {+ return parseRemoteAgentCaps(await invoke([{ op: 'caps' }]));+ }++ /** 把一个 JSON 值做成载荷:小的内联,大的 gzip 后分段上传。 */+ async payload(value: unknown): Promise<RemoteAgentPayload> {+ const text = JSON.stringify(value ?? null);+ if (text.length <= REMOTE_AGENT_MAX_INLINE_PAYLOAD_CHARS) return { json: JSON.parse(text) as unknown };+ const gz = await gzipAsync(Buffer.from(text, 'utf8'));+ if (gz.length > REMOTE_AGENT_MAX_PAYLOAD_BYTES) throw new Error('The request is too large to send to the other computer.');+ const uploadId = this.newId();+ const chunks = Math.max(1, Math.ceil(gz.length / REMOTE_AGENT_UPLOAD_CHUNK_BYTES));+ for (let index = 0; index < chunks; index += 1) {+ const data = gz.subarray(index * REMOTE_AGENT_UPLOAD_CHUNK_BYTES, (index + 1) * REMOTE_AGENT_UPLOAD_CHUNK_BYTES);+ await this.invoke([{ op: 'upload', uploadId, index, data: data.toString('base64') }]);+ }+ return { uploadId, chunks, bytes: gz.length };+ }++ /** 打开任务:等对方启动 Agent 成功(返回会话描述)或失败(抛出对方的错误)。 */+ async open(agentKind: RemoteAgentKind, openPayload: unknown): Promise<Record<string, unknown>> {+ const payload = await this.payload(openPayload);+ const started = new Promise<Record<string, unknown>>((resolve, reject) => {+ this.started = { resolve, reject };+ });+ try {+ await this.invoke([{ op: 'open', runId: this.runId, agentKind, payload }]);+ } catch (error) {+ this.started = null;+ throw error;+ }+ this.registered = true;+ this.poller.register(this);+ return started;+ }++ /** 调用对方会话的一个方法,等结果。 */+ call(method: RemoteAgentMethod, args: unknown[]): Promise<unknown> {+ return this.callWithId(this.newId(), method, args);+ }++ /** 预先分配的 callId(需要先把回调登记到 callId 上时用)。 */+ async callWithId(callId: string, method: RemoteAgentMethod, args: unknown[]): Promise<unknown> {+ if (this.closed) throw new Error('[REMOTE_AGENT_EXPIRED] The task has ended on the other computer.');+ const result = new Promise<unknown>((resolve, reject) => {+ this.pendingCalls.set(callId, { resolve, reject });+ });+ try {+ const payload = await this.payload(args);+ await this.invoke([{ op: 'call', runId: this.runId, callId, method, payload }]);+ } catch (error) {+ this.pendingCalls.delete(callId);+ throw error;+ }+ return result;+ }++ async push(frames: RemoteAgentPushFrame[]): Promise<void> {+ if (this.closed || frames.length === 0) return;+ this.pushSeq += 1;+ await this.invoke([{ op: 'push', runId: this.runId, seq: this.pushSeq, frames }]);+ }++ async close(mode: 'close' | 'detach', reason: RemoteAgentTeardownReason): Promise<void> {+ if (this.closed) return;+ try {+ await this.invoke([{ op: 'close', runId: this.runId, mode, reason }]);+ } finally {+ // 收尾事件仍会经 poll 到达;流结束时自行收口。+ if (this.registered) await Promise.race([this.drained, sleep(CLOSE_DRAIN_MS)]);+ this.finish('closed');+ }+ }++ /** 不再读取(本机任务已丢弃这个连接)。 */+ abandon(reason: string): void {+ this.finish(reason);+ }++ get isClosed(): boolean {+ return this.closed;+ }++ private finish(reason: string, error?: RemoteAgentErrorInfo): void {+ if (this.closed) return;+ this.closed = true;+ this.poller.unregister(this.runId);+ this.markDrained();+ const failure = new Error(error?.message ?? `[REMOTE_AGENT_EXPIRED] The task ended on the other computer (${reason}).`);+ this.started?.reject(error ? new RemoteAgentRemoteError(error) : failure);+ this.started = null;+ for (const abort of this.inflight.values()) abort.abort();+ this.inflight.clear();+ for (const pending of this.pendingCalls.values()) pending.reject(failure);+ this.pendingCalls.clear();+ this.handlers.onClosed(reason, error);+ }++ /** 拉取器交付的新数据(已去重,从上次的游标开始)。 */+ onData(data: Buffer, done: boolean): void {+ if (this.closed) return;+ if (data.length) {+ let lines: string[];+ try {+ lines = this.splitter.push(data);+ } catch {+ this.finish('invalid-stream', { code: 'REMOTE_AGENT_INVALID', message: 'The other computer sent an invalid event stream.' });+ return;+ }+ for (const line of lines) {+ if (!line) continue;+ let item: RemoteAgentStreamItem | null;+ try {+ item = parseRemoteAgentStreamItem(line);+ } catch {+ this.log?.warn('remote agent: dropped invalid stream item', { runId: this.runId });+ continue;+ }+ if (item) this.dispatch(item);+ if (this.closed) return;+ }+ }+ if (done) this.finish('ended');+ }++ onLost(reason: string, error: RemoteAgentErrorInfo): void {+ this.finish(reason, error);+ }++ private dispatch(item: RemoteAgentStreamItem): void {+ switch (item.t) {+ case 'started':+ this.started?.resolve(item.handle);+ this.started = null;+ return;+ case 'start-failed':+ this.started?.reject(new RemoteAgentRemoteError(item.error));+ this.started = null;+ return;+ case 'event':+ this.handlers.onEvent(item.event);+ return;+ case 'state':+ this.handlers.onState(item.state);+ return;+ case 'result': {+ const pending = this.pendingCalls.get(item.callId);+ if (!pending) return;+ this.pendingCalls.delete(item.callId);+ if (item.ok) pending.resolve(item.value);+ else pending.reject(new RemoteAgentRemoteError(item.error));+ return;+ }+ case 'request':+ void this.answer(item.requestId, item.request);+ return;+ case 'cancel':+ this.inflight.get(item.requestId)?.abort();+ this.inflight.delete(item.requestId);+ return;+ case 'ws':+ this.handlers.onWs(item);+ return;+ case 'closed':+ this.finish(item.reason, item.error);+ return;+ }+ }++ private async answer(requestId: string, request: RemoteAgentReverseRequest): Promise<void> {+ const abort = new AbortController();+ this.inflight.set(requestId, abort);+ let reply: RemoteAgentReply;+ try {+ reply = await this.handlers.onRequest(request, abort.signal);+ } catch (error) {+ reply = { type: 'error', error: { code: 'CONTROLLER_ERROR', message: error instanceof Error ? error.message : String(error) } };+ } finally {+ this.inflight.delete(requestId);+ }+ if (this.closed || abort.signal.aborted) return;+ try {+ const payload = await this.payload(reply);+ await this.invoke([{ op: 'reply', runId: this.runId, requestId, payload }]);+ } catch (error) {+ this.log?.warn('remote agent: reply failed', { runId: this.runId, error: String(error) });+ }+ }+}++/**+ * 把设备互联的失败换成带 `[REMOTE_AGENT_*]` 前缀的错误(界面按前缀给出对应文案),保留原 `code`+ * 供重试判断。对方版本过旧(没有这个通道)单独标出,提示去那台电脑更新。+ */+export function remoteAgentLinkError(error: { code?: string; message?: string } | unknown): Error {+ const code = (error as { code?: unknown })?.code;+ const message = error instanceof Error+ ? error.message+ : typeof (error as { message?: unknown })?.message === 'string'+ ? (error as { message: string }).message+ : 'remote agent request failed';+ if (code === 'CHANNEL_NOT_ALLOWED') {+ return Object.assign(+ new Error("[REMOTE_AGENT_PEER_TOO_OLD] Cindy on the other computer is too old to run agents for this computer."),+ { code: 'REMOTE_AGENT_PEER_TOO_OLD' },+ );+ }+ const wrapped = new Error(/^\[REMOTE_[A-Z_]+\]/.test(message) ? message : `[REMOTE_AGENT_UNAVAILABLE] ${message}`);+ return typeof code === 'string' ? Object.assign(wrapped, { code }) : wrapped;+}++/** 生产接线:经设备互联后台链路调用某台电脑的远程 Agent 通道。 */+export function remoteAgentInvoker(+ deviceId: string,+ invoke: (deviceId: string, channel: string, args: unknown[]) => Promise<{ ok: boolean; result?: unknown; error?: { code?: string; message?: string } }>,+): RemoteAgentInvoke {+ return async (args) => {+ let result: Awaited<ReturnType<typeof invoke>>;+ try {+ result = await invoke(deviceId, REMOTE_AGENT_CHANNEL, args);+ } catch (error) {+ throw remoteAgentLinkError(error);+ }+ if (result.ok) return result.result;+ throw remoteAgentLinkError(result.error ?? {});+ };+}diff --git a/apps/desktop/src/main/remote-agent/controller/service.ts b/apps/desktop/src/main/remote-agent/controller/service.tsnew file mode 100644index 0000000000..804e3e7900--- /dev/null+++ b/apps/desktop/src/main/remote-agent/controller/service.ts@@ -0,0 +1,170 @@+/**+ * 远程 Agent 的控制端接线:Maker 遇到「Agent 在另一台电脑上运行」的任务时调用这里。+ *+ * 本机为任务准备:+ * - 本机 Cindy 工具:与本机 Pi 任务同一套 MCP 桥身份登记(按任务、按实例),对方的工具请求经+ * 隧道转发到这里;外部 HTTP MCP 也从本机发出;+ * - 执行器:文件与命令在本机执行,写入前交给「每轮改动对比」抓取改前内容;+ * - 项目说明快照与记忆索引快照(记忆在本机,对方不读它自己的记忆库)。+ */+import { randomUUID } from 'node:crypto';+import fsp from 'node:fs/promises';+import path from 'node:path';++import type {+ AgentEvent,+ AgentKind,+ AgentSessionHandle,+ Logger,+ MakerMemoryManager,+ McpProvider,+ PiExtraSpawnConfig,+ PiExtraSpawnConfigContext,+ StartSessionOptions,+} from '@cindy/maker-core';+import { resolveMemoryScopeKey } from '@cindy/maker-core';++import type { ExecutorCaptureHooks } from '../executor/executor';+import type { PdfTextExtractor } from '../executor/files';+import { remoteAgentEventMapper } from './eventMap';+import {+ collectAncestorInstructionFiles,+ collectPersonalConfig,+ collectProjectInstructionFiles,+} from './projectFiles';+import type { LocalMcpTarget } from './router';+import { RemoteAgentPoller, remoteAgentInvoker } from './runClient';+import { startRemoteAgentSession, type PreparedRemoteMcp } from './startRemote';++export interface DeviceAgentServiceDeps {+ remoteInvoke(deviceId: string, channel: string, args: unknown[]): Promise<{ ok: boolean; result?: unknown; error?: { code?: string; message?: string } }>;+ rgPath(): string;+ /** 本机 codex 程序(给对方的 Codex 提供 exec-server 执行环境)。 */+ codexPath?(): string | undefined;+ /** 本机 Cindy 工具(与本机 Pi 任务同一组 provider)。 */+ mcpProviders(): McpProvider[];+ prepareMcpBridge(+ providers: McpProvider[],+ logger: Logger,+ ctx: PiExtraSpawnConfigContext,+ ): Promise<PiExtraSpawnConfig | null>;+ makerMemory(): MakerMemoryManager | undefined;+ captureKnownFileBefore(input: { sessionId: string; provider: 'claude-code' | 'pi'; cwd: string; targetPath: string }): Promise<void>;+ noteOpaqueTurnChange(input: { sessionId: string; provider: 'claude-code' | 'pi'; cwd: string }): void;+ /** 改写来自对方的事件(如 Claude Code 的 Cindy 工具名换回自带工具名)。 */+ mapEvent?: (kind: AgentKind) => ((event: AgentEvent) => AgentEvent) | undefined;+ /** Read 读 PDF 时取文字。 */+ extractPdfText?: PdfTextExtractor;+ logger: Logger;+}++function mcpTargets(extra: PiExtraSpawnConfig | null): Map<string, LocalMcpTarget> {+ const targets = new Map<string, LocalMcpTarget>();+ const bridge = extra?.mcpBridge;+ if (!bridge) return targets;+ for (const server of bridge.servers) {+ if (server.remote) {+ // 外部 HTTP MCP:请求头真值从本机 env 映射取(与本机 Pi 的 bridge 扩展同一口径)。+ const headers: Record<string, string> = {};+ for (const [name, envName] of Object.entries(server.remote.headerEnvVars)) {+ const value = extra?.mcpEnv?.[envName];+ if (typeof value === 'string') headers[name] = value;+ }+ targets.set(server.name, { url: server.url, headers });+ } else {+ targets.set(server.name, { url: server.url, headers: bridge.token ? { authorization: `Bearer ${bridge.token}` } : {} });+ }+ }+ return targets;+}++async function isGitRepo(workingDir: string): Promise<boolean> {+ let dir = path.resolve(workingDir);+ for (let i = 0; i < 64; i += 1) {+ try {+ await fsp.stat(path.join(dir, '.git'));+ return true;+ } catch {+ const parent = path.dirname(dir);+ if (parent === dir) return false;+ dir = parent;+ }+ }+ return false;+}++/** Maker 的 startDeviceAgentSession 实现。 */+export function createDeviceAgentStarter(deps: DeviceAgentServiceDeps) {+ const log = deps.logger.child('remote-agent');+ // 每台电脑一个拉取器:那台上的全部任务共用一个 poll,不挤占设备互联的其它请求。+ const pollers = new Map<string, RemoteAgentPoller>();+ // 空闲的拉取器不发任何请求,同账号电脑数量有限,留着复用。+ const pollerFor = (deviceId: string): RemoteAgentPoller => {+ let poller = pollers.get(deviceId);+ if (!poller) {+ poller = new RemoteAgentPoller(remoteAgentInvoker(deviceId, deps.remoteInvoke), log);+ pollers.set(deviceId, poller);+ }+ return poller;+ };+ return async (input: { agentKind: AgentKind; deviceId: string; options: StartSessionOptions }): Promise<AgentSessionHandle> => {+ const opts: StartSessionOptions = { ...input.options };+ const poller = pollerFor(input.deviceId);+ // 记忆在本机:对方只用这里给的索引快照,工具读写也回到本机记忆库。+ if (opts.makerMemoryEnabled === true) {+ const scopeKey = opts.makerMemoryScopeKey ?? await resolveMemoryScopeKey(opts.workingDir, undefined);+ opts.makerMemoryScopeKey = scopeKey;+ if (opts.makerMemoryIndexSnapshot === undefined) {+ try {+ opts.makerMemoryIndexSnapshot = await (await deps.makerMemory()?.getStore(scopeKey))?.getIndex() ?? '';+ } catch (error) {+ log.warn('remote agent: memory index unavailable; starting without it', { error: String(error) });+ opts.makerMemoryIndexSnapshot = '';+ }+ }+ }+ return startRemoteAgentSession(input.agentKind, opts, {+ invoke: poller.invoke,+ poller,+ rgPath: deps.rgPath(),+ codexPath: () => deps.codexPath?.(),+ prepareMcp: async ({ kind, opts: startOpts, vendorOptions }): Promise<PreparedRemoteMcp> => {+ const extra = await deps.prepareMcpBridge(deps.mcpProviders(), deps.logger, {+ agentKind: kind,+ sessionId: startOpts.sessionId,+ ...(startOpts.sessionInstanceId ? { sessionInstanceId: startOpts.sessionInstanceId } : {}),+ workingDir: startOpts.workingDir,+ ...(startOpts.makerMemoryScopeKey ? { memoryScopeKey: startOpts.makerMemoryScopeKey } : {}),+ memoryEnabled: startOpts.makerMemoryEnabled === true,+ ...(startOpts.botRuntimeProfile?.mcpPolicy ? { botMcpPolicy: startOpts.botRuntimeProfile.mcpPolicy } : {}),+ vendorOptions,+ mcpCallerKind: 'root',+ mcpCallerAttested: true,+ });+ return {+ servers: mcpTargets(extra),+ dispose: () => extra?.disposeSessionCtx?.(),+ };+ },+ capture: ({ kind, opts: startOpts }): ExecutorCaptureHooks | undefined => {+ // Codex 自己报告每轮改动;Claude Code 与 Pi 的写入由执行器在写之前抓取。+ if (kind === 'codex' || !startOpts.sessionId) return undefined;+ const sessionId = startOpts.sessionId;+ const provider = kind;+ return {+ beforeWrite: (targetPath) => deps.captureKnownFileBefore({ sessionId, provider, cwd: startOpts.workingDir, targetPath }),+ noteOpaqueWrite: () => deps.noteOpaqueTurnChange({ sessionId, provider, cwd: startOpts.workingDir }),+ };+ },+ collectProjectFiles: collectProjectInstructionFiles,+ // Codex 经执行环境在本机直接读取项目与上级目录的说明,不必同步。+ collectAncestorFiles: input.agentKind === 'codex' ? undefined : collectAncestorInstructionFiles,+ collectPersonal: (kind, projectFiles) => collectPersonalConfig(kind, projectFiles),+ isGitRepo,+ ...(deps.extractPdfText ? { extractPdfText: deps.extractPdfText } : {}),+ mapEvent: deps.mapEvent ?? remoteAgentEventMapper,+ newId: randomUUID,+ log,+ });+ };+}diff --git a/apps/desktop/src/main/remote-agent/controller/startRemote.ts b/apps/desktop/src/main/remote-agent/controller/startRemote.tsnew file mode 100644index 0000000000..19d51d3c31--- /dev/null+++ b/apps/desktop/src/main/remote-agent/controller/startRemote.ts@@ -0,0 +1,274 @@+/**+ * 在另一台电脑上启动 Agent、任务留在本机(控制端入口)。+ *+ * 本机为这个任务准备好执行器(文件与命令在本机执行,过本机权限上限)、本机 Cindy 工具的 MCP+ * 身份与项目说明快照,然后让对方用它自己的 Agent 程序、登录与供应商启动 Agent。返回的句柄对+ * 本机 Maker / Session 来说就是普通会话。+ */+import os from 'node:os';+import path from 'node:path';++import type { RemoteAgentKind, RemoteAgentReply, RemoteAgentReverseRequest, RemoteAgentStreamItem } from '@cindy/device-link';+import type { AgentEvent, AgentSessionHandle, StartSessionOptions } from '@cindy/maker-core';++import { RemoteExecutor, type ExecutorCaptureHooks } from '../executor/executor';+import type { PdfTextExtractor } from '../executor/files';+import { ExecutorGate, executorGateModeFor } from '../executor/gate';+import { ExecutorWorkspace } from '../executor/workspace';+import type {+ RemoteAgentOpenPayload,+ RemoteAgentWireAncestorFile,+ RemoteAgentWireFile,+ RemoteAgentWirePersonal,+} from '../wire';+import { encodeStartOptions } from '../wire';+import {+ createRemoteAgentHandle,+ localizeRemoteError,+ parseStartedInfo,+ type RemoteAgentHandleController,+} from './proxyHandle';+import { ExecServerRelay } from './execServerRelay';+import { createReverseHttpRouter, type LocalMcpTarget } from './router';+import { RemoteAgentPoller, RemoteAgentRunClient, type RemoteAgentInvoke } from './runClient';++export interface PreparedRemoteMcp {+ /** 本任务可用的本机 MCP 服务(名字 → 带本任务身份的地址与请求头)。 */+ servers: Map<string, LocalMcpTarget>;+ dispose(): void;+}++export interface StartRemoteAgentDeps {+ invoke: RemoteAgentInvoke;+ /** 这台电脑的共享拉取器(同一台电脑上的任务共用一个 poll);缺省时本任务单独一个。 */+ poller?: RemoteAgentPoller;+ rgPath: string;+ /** 为本任务登记本机 Cindy 工具的身份,返回可转发的 MCP 服务。 */+ /**+ * vendorOptions 是本任务唯一的一份可变对象:协同等工具改写它后(setVendorOptions),+ * 本机 MCP 身份要立即看到,所以登记时必须保留同一个引用。+ */+ prepareMcp(input: { kind: RemoteAgentKind; opts: StartSessionOptions; vendorOptions: Record<string, unknown> }): Promise<PreparedRemoteMcp>;+ /** 本机「每轮改动对比」的抓取钩子(按任务绑定)。 */+ capture?(input: { kind: RemoteAgentKind; opts: StartSessionOptions }): ExecutorCaptureHooks | undefined;+ /** 读取要同步到对方影子目录的项目说明类文件。 */+ collectProjectFiles(workingDir: string): Promise<RemoteAgentWireFile[]>;+ /** 项目上级目录里的说明文件;缺省不同步。 */+ collectAncestorFiles?(workingDir: string): Promise<RemoteAgentWireAncestorFile[]>;+ /** 你这台的个人配置;缺省不同步。 */+ collectPersonal?(kind: RemoteAgentKind, projectFiles: readonly RemoteAgentWireFile[]): Promise<{+ personal: RemoteAgentWirePersonal;+ roots: Array<{ relative: string; local: string }>;+ }>;+ isGitRepo(workingDir: string): Promise<boolean>;+ /** Read 读 PDF 时取文字(Claude Code)。 */+ extractPdfText?: PdfTextExtractor;+ /** 改写来自对方的事件(如工具名)。 */+ mapEvent?: (kind: RemoteAgentKind) => ((event: AgentEvent) => AgentEvent) | undefined;+ /** 本机 Codex 程序(给对方的 Codex 提供 exec-server 执行环境);缺省时不提供。 */+ codexPath?: () => string | undefined;+ newId(): string;+ log?: {+ info(message: string, meta?: Record<string, unknown>): void;+ warn(message: string, meta?: Record<string, unknown>): void;+ };+}++/** 去掉一层路径(两种分隔符都认),到根时返回 null。 */+function parentOf(value: string): string | null {+ const normalized = value.replace(/\\/g, '/').replace(/\/+$/, '');+ const index = normalized.lastIndexOf('/');+ if (index <= 0) return null;+ const parent = normalized.slice(0, index);+ return /^[A-Za-z]:$/.test(parent) ? null : parent;+}++/**+ * 影子目录(对方电脑上的路径) → 本机真实路径的映射。影子目录按真实路径逐级镜像,所以每一级+ * 上级目录都一一对应;同步过去的个人 Skill 等映射回你这台的个人配置目录。越具体的放越前面。+ */+export function shadowAliases(+ started: { shadowDir: string; mirrorRoot?: string },+ workingDir: string,+ personalRoots: ReadonlyArray<{ relative: string; local: string }>,+): Array<{ from: string; to: string }> {+ if (!started.shadowDir) return [];+ const aliases: Array<{ from: string; to: string }> = personalRoots.map((root) => ({+ from: `${started.shadowDir.replace(/[\\/]+$/, '')}/${root.relative}`,+ to: root.local,+ }));+ const mirrorRoot = started.mirrorRoot?.replace(/\\/g, '/').replace(/\/+$/, '');+ let shadow = started.shadowDir;+ let real = workingDir;+ aliases.push({ from: shadow, to: real });+ if (!mirrorRoot) return aliases;+ for (;;) {+ const nextShadow = parentOf(shadow);+ const nextReal = path.dirname(real);+ if (!nextShadow || nextReal === real || !nextShadow.startsWith(`${mirrorRoot}/`)) break;+ shadow = nextShadow;+ real = nextReal;+ aliases.push({ from: shadow, to: real });+ }+ return aliases;+}++function shellName(): string {+ if (process.platform === 'win32') return 'bash';+ return (process.env.SHELL ?? '/bin/bash').split('/').pop() || 'bash';+}++export async function startRemoteAgentSession(+ kind: RemoteAgentKind,+ opts: StartSessionOptions,+ deps: StartRemoteAgentDeps,+): Promise<AgentSessionHandle> {+ if (!opts.sessionId) throw new Error('remote agent sessions require a session id');+ const extraDirs = [...new Set([...(opts.extraDirs ?? []), ...(opts.writableDirs ?? [])])];+ const workspace = new ExecutorWorkspace({ workingDir: opts.workingDir, extraDirs });+ const gate = new ExecutorGate(workspace, executorGateModeFor(opts.permissionMode, opts.planMode === true));+ const executor = new RemoteExecutor({+ workspace,+ gate,+ rgPath: deps.rgPath,+ capture: deps.capture?.({ kind, opts }),+ ...(deps.extractPdfText ? { extractPdfText: deps.extractPdfText } : {}),+ });+ let permissionMode = opts.permissionMode;+ let planMode = opts.planMode === true;+ const vendorOptions: Record<string, unknown> = { ...(opts.vendorOptions ?? {}) };+ const mcp = await deps.prepareMcp({ kind, opts, vendorOptions }).catch((error) => {+ void executor.close();+ throw error;+ });+ const router = createReverseHttpRouter({ executor, mcpTarget: (name) => mcp.servers.get(name) });++ let controller: RemoteAgentHandleController | null = null;+ const early: Array<{ type: 'event' | 'state'; value: unknown }> = [];+ let closedEarly: { reason: string; message?: string } | null = null;+ // Codex:对方的 Codex 把本机当作 exec-server 执行环境。客户端在下面创建,帧推送时再取。+ let pushFrames: ((frames: Parameters<RemoteAgentRunClient['push']>[0]) => Promise<void>) | null = null;+ const codexPath = kind === 'codex' ? deps.codexPath?.() : undefined;+ const relay = codexPath+ ? new ExecServerRelay({+ codexPath,+ cwd: workspace.workingDir,+ authorize: (action) => executor.check(action),+ push: async (frames) => {+ await pushFrames?.(frames);+ },+ log: deps.log,+ })+ : null;++ const disposeLocal = async () => {+ relay?.close();+ try {+ mcp.dispose();+ } catch (error) {+ deps.log?.warn('remote agent: MCP dispose failed', { error: String(error) });+ }+ await executor.close();+ };++ const poller = deps.poller ?? new RemoteAgentPoller(deps.invoke, deps.log);+ const client = new RemoteAgentRunClient(deps.newId(), poller, {+ onEvent: (event) => {+ if (controller) controller.onEvent(event);+ else early.push({ type: 'event', value: event });+ },+ onState: (state) => {+ if (controller) controller.onState(state);+ else early.push({ type: 'state', value: state });+ },+ onRequest: async (request: RemoteAgentReverseRequest, signal): Promise<RemoteAgentReply> => {+ if (request.type === 'http') return router(request, signal);+ if (request.type === 'callback' && request.name === 'onInvalidResumeSession' && !controller) {+ const expected = request.args[0];+ const value = typeof expected === 'string' && opts.onInvalidResumeSession+ ? await opts.onInvalidResumeSession(expected)+ : false;+ return { type: 'callback', value };+ }+ const answered = controller?.onRequest(request);+ if (answered) return answered;+ return { type: 'error', error: { code: 'REMOTE_AGENT_UNAVAILABLE', message: 'This computer is not ready to answer yet.' } };+ },+ onWs: (item: Extract<RemoteAgentStreamItem, { t: 'ws' }>) => {+ if (relay) relay.handle(item);+ else if (item.kind === 'open') void pushFrames?.([{ connId: item.connId, kind: 'close' }]);+ },+ onClosed: (reason, error) => {+ if (controller) controller.onClosed(reason, error?.message);+ else {+ closedEarly = { reason, message: error?.message };+ void disposeLocal();+ }+ },+ }, deps.newId, deps.log);+ pushFrames = (frames) => client.push(frames);++ const projectFiles = await deps.collectProjectFiles(opts.workingDir).catch(() => []);+ const ancestorFiles = await (deps.collectAncestorFiles?.(opts.workingDir) ?? Promise.resolve([])).catch(() => []);+ const collectedPersonal = await (deps.collectPersonal?.(kind, projectFiles) ?? Promise.resolve(null))+ .catch(() => null);+ const payload: RemoteAgentOpenPayload = {+ sessionId: opts.sessionId,+ options: encodeStartOptions(opts),+ workspace: {+ workingDir: opts.workingDir,+ extraDirs: opts.extraDirs ?? [],+ writableDirs: opts.writableDirs ?? [],+ platform: process.platform,+ shell: shellName(),+ osVersion: `${os.type()} ${os.release()}`,+ homeDir: os.homedir(),+ isGitRepo: await deps.isGitRepo(opts.workingDir).catch(() => false),+ },+ projectFiles,+ ancestorFiles,+ personal: collectedPersonal?.personal ?? { files: [] },+ mcpServers: [...mcp.servers.keys()],+ };++ let startedRaw: Record<string, unknown>;+ try {+ startedRaw = await client.open(kind, payload);+ } catch (error) {+ client.abandon('start-failed');+ await disposeLocal();+ throw localizeRemoteError(error);+ }+ if (closedEarly) throw new Error((closedEarly as { message?: string }).message ?? '[REMOTE_AGENT_UNAVAILABLE] The agent stopped right after starting.');+ const started = parseStartedInfo(startedRaw, kind);+ workspace.setAliases(shadowAliases(started, workspace.workingDir, collectedPersonal?.roots ?? []));++ controller = createRemoteAgentHandle({+ client,+ started,+ workspace,+ recordApproval: (action) => executor.recordApproval(action),+ onInvalidResumeSession: opts.onInvalidResumeSession,+ mapEvent: deps.mapEvent?.(kind),+ newId: deps.newId,+ onPermissionMode: (mode) => {+ permissionMode = mode as typeof permissionMode;+ executor.setGateMode(executorGateModeFor(permissionMode, planMode));+ },+ onPlanMode: (enabled) => {+ planMode = enabled;+ executor.setGateMode(executorGateModeFor(permissionMode, planMode));+ },+ onExtraDirs: (dirs) => workspace.setExtraDirs([...new Set([...dirs, ...(opts.writableDirs ?? [])])]),+ onVendorOptions: (patch) => {+ Object.assign(vendorOptions, patch);+ },+ dispose: disposeLocal,+ });+ for (const item of early.splice(0)) {+ if (item.type === 'event') controller.onEvent(item.value);+ else controller.onState(item.value as Record<string, unknown>);+ }+ deps.log?.info('remote agent session started', { kind, runId: client.runId });+ return controller.handle;+}diff --git a/apps/desktop/src/main/remote-agent/eventLog.ts b/apps/desktop/src/main/remote-agent/eventLog.tsnew file mode 100644index 0000000000..e4bd775c51--- /dev/null+++ b/apps/desktop/src/main/remote-agent/eventLog.ts@@ -0,0 +1,169 @@+/**+ * 远程 Agent 事件流的有界字节日志(被控端)。+ *+ * 每条记录是一行 JSON。控制端按游标(字节偏移)拉取:一次 poll 带的游标就是它已经完整收到的位置,+ * 之前的字节随即丢弃;回包丢失时控制端用同一游标重读,拿到的是同一段数据(幂等)。+ * 未读字节超过上限说明控制端已经跟不上或离开,由调用方结束任务。+ */+export interface EventLogRead {+ /** 数据的起始偏移(游标早于已丢弃的位置时,从仍保留的最早位置开始)。 */+ from: number;+ cursor: number;+ data?: Buffer;+ done?: true;+}++export class EventLog {+ private chunks: Buffer[] = [];+ /** chunks[0] 的起始偏移。 */+ private baseOffset = 0;+ private endOffset = 0;+ private ended = false;+ private readonly waiters = new Set<() => void>();++ constructor(private readonly maxUnreadBytes: number) {}++ get unreadBytes(): number {+ return this.endOffset - this.baseOffset;+ }++ get isEnded(): boolean {+ return this.ended;+ }++ /** 追加一条记录;超出未读上限返回 false(记录不追加)。 */+ append(item: unknown): boolean {+ if (this.ended) return false;+ const line = Buffer.from(`${JSON.stringify(item)}\n`, 'utf8');+ if (this.unreadBytes + line.length > this.maxUnreadBytes) return false;+ this.chunks.push(line);+ this.endOffset += line.length;+ this.wake();+ return true;+ }++ /** 结束日志:已有数据仍可读完。 */+ end(): void {+ if (this.ended) return;+ this.ended = true;+ this.wake();+ }++ /** cursor 超出已写范围时为 false(调用方按无效处理)。 */+ isValidCursor(cursor: number): boolean {+ return cursor >= 0 && cursor <= this.endOffset;+ }++ /** cursor 之后有新数据,或日志已结束。 */+ isReady(cursor: number): boolean {+ return cursor < this.endOffset || this.ended;+ }++ /** 订阅「有新数据或结束」。 */+ onChange(listener: () => void): () => void {+ this.waiters.add(listener);+ return () => this.waiters.delete(listener);+ }++ /**+ * 立即从 cursor 读取最多 maxBytes。cursor 之前的数据视为已确认并丢弃;cursor 早于已丢弃的+ * 位置(并发 poll 中较旧的那个)时从仍保留的最早位置开始,起点由 from 标明。+ */+ readNow(cursor: number, maxBytes: number): EventLogRead {+ if (!this.isValidCursor(cursor)) throw new Error('REMOTE_AGENT_INVALID');+ this.acknowledge(cursor);+ const from = Math.max(cursor, this.baseOffset);+ if (from === this.endOffset || maxBytes <= 0) {+ return this.ended && from === this.endOffset ? { from, cursor: from, done: true } : { from, cursor: from };+ }+ const parts: Buffer[] = [];+ let size = 0;+ for (const chunk of this.chunks) {+ if (size >= maxBytes) break;+ const take = Math.min(chunk.length, maxBytes - size);+ parts.push(take === chunk.length ? chunk : chunk.subarray(0, take));+ size += take;+ }+ const next = from + size;+ return {+ from,+ cursor: next,+ data: Buffer.concat(parts, size),+ ...(this.ended && next === this.endOffset ? { done: true as const } : {}),+ };+ }++ /** 读取;没有新数据时最多等 waitMs。 */+ async read(cursor: number, maxBytes: number, waitMs: number, signal?: AbortSignal): Promise<EventLogRead> {+ if (!this.isValidCursor(cursor)) throw new Error('REMOTE_AGENT_INVALID');+ if (!this.isReady(cursor) && waitMs > 0) await waitForAny([this], waitMs, signal);+ return this.readNow(cursor, maxBytes);+ }++ private acknowledge(cursor: number): void {+ if (cursor <= this.baseOffset) return;+ let drop = cursor - this.baseOffset;+ while (drop > 0 && this.chunks.length > 0) {+ const first = this.chunks[0];+ if (first.length <= drop) {+ this.chunks.shift();+ drop -= first.length;+ this.baseOffset += first.length;+ } else {+ this.chunks[0] = first.subarray(drop);+ this.baseOffset += drop;+ drop = 0;+ }+ }+ }++ private wake(): void {+ for (const wake of [...this.waiters]) wake();+ }+}++/** 等任意一个日志有新数据(或结束),最多 waitMs。 */+export function waitForAny(logs: readonly EventLog[], waitMs: number, signal?: AbortSignal): Promise<void> {+ return new Promise<void>((resolve) => {+ const unsubscribes: Array<() => void> = [];+ const done = () => {+ clearTimeout(timer);+ for (const unsubscribe of unsubscribes) unsubscribe();+ signal?.removeEventListener('abort', done);+ resolve();+ };+ const timer = setTimeout(done, waitMs);+ for (const log of logs) unsubscribes.push(log.onChange(done));+ signal?.addEventListener('abort', done, { once: true });+ });+}++/** 控制端:把按字节到达的事件流切成行(行可能被截在两次 read 之间)。 */+export class LineSplitter {+ private pending: Buffer[] = [];+ private pendingBytes = 0;++ constructor(private readonly maxLineBytes: number) {}++ push(data: Buffer): string[] {+ const lines: string[] = [];+ let start = 0;+ for (;;) {+ const index = data.indexOf(0x0a, start);+ if (index < 0) break;+ const piece = data.subarray(start, index);+ const line = this.pending.length ? Buffer.concat([...this.pending, piece]) : piece;+ this.pending = [];+ this.pendingBytes = 0;+ lines.push(line.toString('utf8'));+ start = index + 1;+ }+ if (start < data.length) {+ const rest = data.subarray(start);+ this.pendingBytes += rest.length;+ if (this.pendingBytes > this.maxLineBytes) throw new Error('REMOTE_AGENT_INVALID');+ this.pending.push(Buffer.from(rest));+ }+ return lines;+ }+}diff --git a/apps/desktop/src/main/remote-agent/executor/__tests__/executor.test.ts b/apps/desktop/src/main/remote-agent/executor/__tests__/executor.test.tsnew file mode 100644index 0000000000..7912f9c54d--- /dev/null+++ b/apps/desktop/src/main/remote-agent/executor/__tests__/executor.test.ts@@ -0,0 +1,449 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';++import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { handleExecMcpRequest } from '../ccMcp';+import { RemoteExecutor } from '../executor';+import { EXECUTOR_APPROVAL_TTL_MS, ExecutorGate, executorGateModeFor } from '../gate';+import type { PdfTextExtractor } from '../files';+import { findWindowsGitBash, truncateOutput } from '../shell';+import { ExecutorWorkspace } from '../workspace';++const RG = path.resolve(__dirname, '../../../../../../ripgrep-bin', `${process.platform}-${process.arch}`, process.platform === 'win32' ? 'rg.exe' : 'rg');+const posix = process.platform !== 'win32';++let root: string;+let project: string;+let outside: string;+let captured: string[];+let opaque: number;++function makeExecutor(+ mode: ReturnType<typeof executorGateModeFor> = 'normal',+ extra: { aliases?: Array<{ from: string; to: string }>; now?: () => number; extractPdfText?: PdfTextExtractor } = {},+) {+ const workspace = new ExecutorWorkspace({ workingDir: project, aliases: extra.aliases });+ const gate = new ExecutorGate(workspace, mode, extra.now);+ const executor = new RemoteExecutor({+ workspace,+ gate,+ rgPath: RG,+ tempDir: path.join(root, 'tmp'),+ ...(extra.extractPdfText ? { extractPdfText: extra.extractPdfText } : {}),+ capture: {+ beforeWrite: async (p) => {+ captured.push(p);+ },+ noteOpaqueWrite: () => {+ opaque += 1;+ },+ },+ });+ return { executor, gate, workspace };+}++function text(result: { content: Array<{ type: string; text?: string }> }): string {+ return result.content.map((item) => item.text ?? '').join('');+}++beforeEach(() => {+ root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-exec-')));+ project = path.join(root, 'project');+ outside = path.join(root, 'outside');+ fs.mkdirSync(project);+ fs.mkdirSync(outside);+ captured = [];+ opaque = 0;+});++afterEach(() => {+ fs.rmSync(root, { recursive: true, force: true });+});++describe('workspace', () => {+ it('resolves relative paths against the working directory and maps shadow paths back', () => {+ const workspace = new ExecutorWorkspace({ workingDir: project, aliases: [{ from: '/remote/shadow/proj', to: project }] });+ expect(workspace.resolve('a/b.txt')).toBe(path.join(project, 'a/b.txt'));+ expect(workspace.resolve('/remote/shadow/proj/src/x.ts')).toBe(path.join(project, 'src/x.ts'));+ expect(workspace.resolve('/remote/shadow/proj')).toBe(project);+ // 同前缀但不是同一目录的不映射。+ expect(workspace.resolve('/remote/shadow/projX/y')).toBe(path.resolve('/remote/shadow/projX/y'));+ expect(workspace.mapCommand('cat /remote/shadow/proj/a.txt && ls /remote/shadow/projX'))+ .toBe(`cat ${project}/a.txt && ls /remote/shadow/projX`);+ expect(() => workspace.resolve('')).toThrow();+ expect(() => workspace.resolve('a\0b')).toThrow();+ });++ it('judges containment by real path so symlinks cannot borrow their way out', () => {+ const workspace = new ExecutorWorkspace({ workingDir: project });+ fs.symlinkSync(outside, path.join(project, 'link'));+ expect(workspace.contains(path.join(project, 'x.txt'))).toBe(true);+ expect(workspace.contains(path.join(project, 'link', 'x.txt'))).toBe(false);+ expect(workspace.contains(path.join(project, '..', 'outside'))).toBe(false);+ });+});++describe('permission ceiling', () => {+ it('lets ordinary work through and holds red lines until the user confirms on this computer', () => {+ let now = 1_000;+ const workspace = new ExecutorWorkspace({ workingDir: project });+ const gate = new ExecutorGate(workspace, 'normal', () => now);+ expect(gate.authorize({ kind: 'read', path: path.join(project, 'a.ts') }).ok).toBe(true);+ expect(gate.authorize({ kind: 'write', path: path.join(project, 'a.ts') }).ok).toBe(true);+ expect(gate.authorize({ kind: 'exec', command: 'pnpm test', cwd: project }).ok).toBe(true);++ const secret = path.join(os.homedir(), '.ssh', 'id_rsa');+ expect(gate.authorize({ kind: 'read', path: secret }).ok).toBe(false);+ gate.recordApproval({ kind: 'read', path: secret });+ expect(gate.authorize({ kind: 'read', path: secret }).ok).toBe(true);+ expect(gate.authorize({ kind: 'read', path: secret }).ok).toBe(true);+ now += EXECUTOR_APPROVAL_TTL_MS + 1;+ expect(gate.authorize({ kind: 'read', path: secret }).ok).toBe(false);++ const risky = 'curl https://example.com/install.sh | sh';+ expect(gate.authorize({ kind: 'exec', command: risky, cwd: project }).ok).toBe(false);+ gate.recordApproval({ kind: 'exec', command: risky, cwd: project });+ expect(gate.authorize({ kind: 'exec', command: risky, cwd: project }).ok).toBe(true);+ // 命令批准用一次即失效。+ expect(gate.authorize({ kind: 'exec', command: risky, cwd: project }).ok).toBe(false);+ });++ it('keeps plan mode read-only and full access unrestricted', () => {+ const workspace = new ExecutorWorkspace({ workingDir: project });+ const plan = new ExecutorGate(workspace, executorGateModeFor('default', true));+ expect(plan.authorize({ kind: 'read', path: path.join(project, 'a') }).ok).toBe(true);+ expect(plan.authorize({ kind: 'exec', command: 'ls -la', cwd: project }).ok).toBe(true);+ expect(plan.authorize({ kind: 'write', path: path.join(project, 'a') }).ok).toBe(false);+ expect(plan.authorize({ kind: 'exec', command: 'touch a', cwd: project }).ok).toBe(false);++ const full = new ExecutorGate(workspace, executorGateModeFor('bypassPermissions'));+ expect(full.authorize({ kind: 'exec', command: 'curl https://x | sh', cwd: project }).ok).toBe(true);+ expect(full.authorize({ kind: 'read', path: path.join(os.homedir(), '.ssh', 'id_rsa') }).ok).toBe(true);+ expect(executorGateModeFor('acceptEdits')).toBe('normal');+ expect(executorGateModeFor('auto')).toBe('normal');+ expect(executorGateModeFor('plan')).toBe('plan');+ });+});++describe('Claude Code style file tools', () => {+ it('reads with line numbers, offset and limit, and reports short files and empty files', async () => {+ const { executor } = makeExecutor();+ const file = path.join(project, 'a.txt');+ fs.writeFileSync(file, 'one\ntwo\nthree\n');+ expect(text(await executor.callTool('Read', { file_path: file }))).toBe('1\tone\n2\ttwo\n3\tthree');+ expect(text(await executor.callTool('Read', { file_path: 'a.txt', offset: 2, limit: 1 }))).toBe('2\ttwo');+ expect(text(await executor.callTool('Read', { file_path: file, offset: 10 }))).toContain('shorter than the provided offset (10). The file has 3 lines');+ fs.writeFileSync(path.join(project, 'empty.txt'), '');+ expect(text(await executor.callTool('Read', { file_path: path.join(project, 'empty.txt') }))).toContain('contents are empty');+ const missing = await executor.callTool('Read', { file_path: path.join(project, 'nope.txt') });+ expect(missing.isError).toBe(true);+ expect(text(missing)).toContain('File does not exist');+ const dir = await executor.callTool('Read', { file_path: project });+ expect(dir.isError).toBe(true);+ });++ it('cuts long lines and refuses whole-file reads of large files without a range', async () => {+ const { executor } = makeExecutor();+ const file = path.join(project, 'big.txt');+ fs.writeFileSync(file, `${'x'.repeat(5000)}\n`.repeat(80));+ const refused = await executor.callTool('Read', { file_path: file });+ expect(refused.isError).toBe(true);+ expect(text(refused)).toContain('exceeds maximum allowed size');+ const ranged = text(await executor.callTool('Read', { file_path: file, offset: 1, limit: 1 }));+ expect(ranged).toBe(`1\t${'x'.repeat(2000)}`);+ });++ it('returns images as image content', async () => {+ const { executor } = makeExecutor();+ const png = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==', 'base64');+ fs.writeFileSync(path.join(project, 'dot.png'), png);+ const result = await executor.callTool('Read', { file_path: path.join(project, 'dot.png') });+ expect(result.content[0]).toMatchObject({ type: 'image', mimeType: 'image/png' });+ });++ it('returns PDF pages as text, 20 pages at a time, because tool results cannot carry documents', async () => {+ const calls: number[] = [];+ const extractPdfText: PdfTextExtractor = async (_data, lastPage) => {+ calls.push(lastPage);+ const pages = Math.min(lastPage, 30);+ return {+ sections: Array.from({ length: pages }, (_, index) => `--- 第 ${index + 1} 页 ---\npage ${index + 1} text`),+ numPages: 30,+ pagesInspected: pages,+ clipped: false,+ };+ };+ const { executor } = makeExecutor('normal', { extractPdfText });+ const pdf = path.join(project, 'doc.pdf');+ fs.writeFileSync(pdf, '%PDF-1.4 fake');++ const first = await executor.callTool('Read', { file_path: pdf });+ expect(first.isError).toBeUndefined();+ expect(text(first)).toContain('30 page(s). Text of pages 1-20 follows');+ expect(text(first)).toContain('--- Page 20 ---\npage 20 text');+ expect(text(first)).not.toContain('page 21 text');+ expect(text(first)).toContain('"21-30"');+ expect(calls).toEqual([20]);++ const ranged = text(await executor.callTool('Read', { file_path: pdf, pages: '3-4' }));+ expect(ranged).toContain('Text of pages 3-4 follows');+ expect(ranged).toContain('--- Page 3 ---\npage 3 text\n\n--- Page 4 ---\npage 4 text');+ expect(ranged).not.toContain('page 2 text');+ expect(ranged).not.toContain('Use the pages parameter');++ expect(text(await executor.callTool('Read', { file_path: pdf, pages: '1-25' }))).toMatch(/exceeds the maximum of 20 pages/);+ expect(text(await executor.callTool('Read', { file_path: pdf, pages: 'abc' }))).toMatch(/Invalid pages parameter/);+ expect(text(await executor.callTool('Read', { file_path: pdf, pages: '40' }))).toMatch(/page 40 does not exist/);+ });++ it('says so when a PDF has no text or cannot be read here', async () => {+ const pdf = path.join(project, 'scan.pdf');+ fs.writeFileSync(pdf, '%PDF-1.4 fake');+ const scanned = makeExecutor('normal', {+ extractPdfText: async () => ({ sections: [], numPages: 2, pagesInspected: 2, clipped: false }),+ }).executor;+ expect(text(await scanned.callTool('Read', { file_path: pdf }))).toMatch(/no extractable text/);+ const unavailable = await makeExecutor().executor.callTool('Read', { file_path: pdf });+ expect(unavailable.isError).toBe(true);+ expect(text(unavailable)).toMatch(/Reading PDF files is not available here/);+ });++ it('requires a read before writing an existing file and notices outside changes', async () => {+ const { executor } = makeExecutor();+ const file = path.join(project, 'w.txt');+ fs.writeFileSync(file, 'old');+ const blocked = await executor.callTool('Write', { file_path: file, content: 'new' });+ expect(blocked.isError).toBe(true);+ expect(text(blocked)).toContain('has not been read yet');+ await executor.callTool('Read', { file_path: file });+ const future = new Date(Date.now() + 5_000);+ fs.utimesSync(file, future, future);+ expect(text(await executor.callTool('Write', { file_path: file, content: 'new' }))).toContain('modified since read');+ await executor.callTool('Read', { file_path: file });+ expect((await executor.callTool('Write', { file_path: file, content: 'new' })).isError).toBeUndefined();+ expect(fs.readFileSync(file, 'utf8')).toBe('new');+ // 新文件不用先读,父目录自动创建。+ const created = path.join(project, 'deep', 'dir', 'n.txt');+ expect(text(await executor.callTool('Write', { file_path: created, content: 'hi' }))).toContain('File created successfully');+ expect(fs.readFileSync(created, 'utf8')).toBe('hi');+ expect(captured).toEqual([file, created]);+ });++ it('edits exact unique text, honours replace_all, keeps CRLF and creates files from an empty old_string', async () => {+ const { executor } = makeExecutor();+ const file = path.join(project, 'e.txt');+ fs.writeFileSync(file, 'a\r\nfoo\r\nfoo\r\n');+ await executor.callTool('Read', { file_path: file });+ expect(text(await executor.callTool('Edit', { file_path: file, old_string: 'foo', new_string: 'bar' }))).toContain('Found 2 matches');+ expect(text(await executor.callTool('Edit', { file_path: file, old_string: 'zzz', new_string: 'bar' }))).toContain('String to replace not found');+ expect(text(await executor.callTool('Edit', { file_path: file, old_string: 'foo', new_string: 'foo' }))).toContain('No changes to make');+ expect((await executor.callTool('Edit', { file_path: file, old_string: 'a\nfoo', new_string: 'A\nbar' })).isError).toBeUndefined();+ expect(fs.readFileSync(file, 'utf8')).toBe('A\r\nbar\r\nfoo\r\n');+ expect((await executor.callTool('Edit', { file_path: file, old_string: 'o', new_string: '0', replace_all: true })).isError).toBeUndefined();+ expect(fs.readFileSync(file, 'utf8')).toBe('A\r\nbar\r\nf00\r\n');+ const created = path.join(project, 'c.txt');+ expect(text(await executor.callTool('Edit', { file_path: created, old_string: '', new_string: 'x' }))).toContain('created');+ expect(fs.readFileSync(created, 'utf8')).toBe('x');+ expect(text(await executor.callTool('Edit', { file_path: path.join(project, 'none.txt'), old_string: 'a', new_string: 'b' }))).toContain('does not exist');+ });++ it('edits notebook cells by id', async () => {+ const { executor } = makeExecutor();+ const file = path.join(project, 'n.ipynb');+ fs.writeFileSync(file, JSON.stringify({+ nbformat: 4,+ nbformat_minor: 5,+ metadata: {},+ cells: [{ id: 'c1', cell_type: 'code', source: 'print(1)', outputs: [{ output_type: 'stream', text: '1\n' }], execution_count: 1, metadata: {} }],+ }, null, 1));+ const shown = text(await executor.callTool('Read', { file_path: file }));+ expect(shown).toContain('<cell id="c1">');+ expect(shown).toContain('print(1)');+ expect((await executor.callTool('NotebookEdit', { notebook_path: file, cell_id: 'c1', new_source: 'print(2)' })).isError).toBeUndefined();+ await executor.callTool('Read', { file_path: file });+ expect((await executor.callTool('NotebookEdit', { notebook_path: file, cell_id: 'c1', new_source: '# hi', cell_type: 'markdown', edit_mode: 'insert' })).isError).toBeUndefined();+ const notebook = JSON.parse(fs.readFileSync(file, 'utf8'));+ expect(notebook.cells.map((cell: { source: string }) => cell.source)).toEqual(['print(2)', '# hi']);+ expect(notebook.cells[0].outputs).toEqual([]);+ });++ it('refuses credential files until confirmed on this computer', async () => {+ const { executor, gate } = makeExecutor();+ const env = path.join(project, '.env');+ fs.writeFileSync(env, 'TOKEN=1');+ const denied = await executor.callTool('Read', { file_path: env });+ expect(denied.isError).toBe(true);+ expect(text(denied)).toContain('needs the user\'s confirmation');+ gate.recordApproval({ kind: 'read', path: env });+ expect(text(await executor.callTool('Read', { file_path: env }))).toBe('1\tTOKEN=1');+ });+});++describe.runIf(posix)('Claude Code style Bash', () => {+ it('keeps the working directory between calls, but resets it when it leaves the project', async () => {+ const { executor } = makeExecutor();+ fs.mkdirSync(path.join(project, 'sub'));+ expect(text(await executor.callTool('Bash', { command: 'cd sub && pwd' }))).toBe(path.join(project, 'sub'));+ expect(text(await executor.callTool('Bash', { command: 'pwd' }))).toBe(path.join(project, 'sub'));+ const reset = text(await executor.callTool('Bash', { command: `cd ${outside}` }));+ expect(reset).toContain(`Shell cwd was reset to ${project}`);+ expect(text(await executor.callTool('Bash', { command: 'pwd' }))).toBe(project);+ expect(opaque).toBe(4);+ });++ it('reports exit codes, timeouts and keeps the start and end of long output', async () => {+ const { executor } = makeExecutor();+ const failed = await executor.callTool('Bash', { command: 'echo out; echo err >&2; exit 3' });+ expect(failed.isError).toBe(true);+ expect(text(failed)).toContain('out');+ expect(text(failed)).toContain('err');+ expect(text(failed)).toContain('Exit code 3');+ const started = Date.now();+ const slow = await executor.callTool('Bash', { command: 'sleep 30', timeout: 300 });+ expect(Date.now() - started).toBeLessThan(10_000);+ expect(slow.isError).toBe(true);+ expect(text(slow)).toContain('Command timed out');+ const long = truncateOutput(`${'a\n'.repeat(20_000)}END`);+ expect(long.length).toBeLessThan(31_000);+ expect(long).toContain('lines truncated');+ expect(long.endsWith('END')).toBe(true);+ });++ it('stops the whole process group when a command is interrupted', async () => {+ const { executor } = makeExecutor();+ const marker = path.join(project, 'child-alive');+ const controller = new AbortController();+ const running = executor.callTool('Bash', { command: `(sleep 2; touch ${marker}) & wait` }, controller.signal);+ setTimeout(() => controller.abort(), 300);+ const result = await running;+ expect(text(result)).toContain('interrupted');+ await new Promise((resolve) => setTimeout(resolve, 2_500));+ expect(fs.existsSync(marker)).toBe(false);+ });++ it('runs background commands, reads their output incrementally and stops them', async () => {+ const { executor } = makeExecutor();+ const started = text(await executor.callTool('Bash', { command: 'echo first; sleep 0.3; echo second; sleep 30', run_in_background: true }));+ const id = /ID: (bash_[0-9a-f]+)/.exec(started)?.[1];+ expect(id).toBeTruthy();+ await new Promise((resolve) => setTimeout(resolve, 800));+ const first = text(await executor.callTool('BashOutput', { bash_id: id }));+ expect(first).toContain('<status>running</status>');+ expect(first).toContain('first');+ expect(first).toContain('second');+ expect(text(await executor.callTool('BashOutput', { bash_id: id }))).toContain('(No new output)');+ expect(text(await executor.callTool('KillShell', { shell_id: id }))).toContain('Successfully killed');+ await new Promise((resolve) => setTimeout(resolve, 300));+ expect(text(await executor.callTool('BashOutput', { bash_id: id }))).toContain('<status>killed</status>');+ await executor.close();+ });++ it('holds high-impact commands until confirmed', async () => {+ const { executor, gate } = makeExecutor();+ const command = `rm -rf ${outside}`;+ const denied = await executor.callTool('Bash', { command });+ expect(denied.isError).toBe(true);+ expect(fs.existsSync(outside)).toBe(true);+ gate.recordApproval({ kind: 'exec', command, cwd: project });+ expect((await executor.callTool('Bash', { command })).isError).toBeUndefined();+ expect(fs.existsSync(outside)).toBe(false);+ });+});++describe('raw operations for Pi', () => {+ it('reads, writes, lists, stats and detects image types', async () => {+ const { executor } = makeExecutor();+ await executor.handle('fs.mkdir', { path: 'src' });+ await executor.handle('fs.write', { path: 'src/a.ts', data: Buffer.from('export const a = 1;\n').toString('base64') });+ await executor.handle('fs.write', { path: 'empty.txt', data: '' });+ expect(fs.readFileSync(path.join(project, 'empty.txt'), 'utf8')).toBe('');+ expect(Buffer.from(((await executor.handle('fs.read', { path: 'src/a.ts' })) as { data: string }).data, 'base64').toString()).toContain('a = 1');+ expect(await executor.handle('fs.readdir', { path: 'src' })).toEqual({ entries: ['a.ts'] });+ expect(await executor.handle('fs.stat', { path: 'src' })).toMatchObject({ type: 'directory' });+ await expect(executor.handle('fs.access', { path: 'missing.txt' })).rejects.toMatchObject({ code: 'ENOENT' });+ fs.writeFileSync(path.join(project, 'img.bin'), Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0]));+ expect(await executor.handle('fs.mime', { path: 'img.bin' })).toEqual({ mime: 'image/png' });+ expect(captured).toEqual([path.join(project, 'src/a.ts'), path.join(project, 'empty.txt')]);+ await expect(executor.handle('fs.nope', {})).rejects.toMatchObject({ code: 'UNSUPPORTED' });+ });++ it('finds files and searches content with the bundled ripgrep in Pi format', async () => {+ const { executor } = makeExecutor();+ fs.mkdirSync(path.join(project, 'src'));+ fs.writeFileSync(path.join(project, 'src', 'a.ts'), 'const alpha = 1;\nconst beta = 2;\nconst alphabet = 3;\n');+ fs.writeFileSync(path.join(project, 'b.md'), 'alpha\n');+ const glob = (await executor.handle('fs.glob', { pattern: '*.ts', cwd: '.', limit: 10 })) as { paths: string[] };+ expect(glob.paths).toEqual([path.join(project, 'src', 'a.ts')]);+ const grep = (await executor.handle('pi.grep', { params: { pattern: 'alpha', glob: '*.ts' } })) as { text: string };+ expect(grep.text).toBe('src/a.ts:1: const alpha = 1;\nsrc/a.ts:3: const alphabet = 3;');+ const limited = (await executor.handle('pi.grep', { params: { pattern: 'alpha', limit: 1, path: 'src' } })) as { text: string };+ expect(limited.text).toContain('1 matches limit reached');+ const context = (await executor.handle('pi.grep', { params: { pattern: 'beta', context: 1, path: 'src/a.ts' } })) as { text: string };+ expect(context.text).toBe('a.ts-1- const alpha = 1;\na.ts:2: const beta = 2;\na.ts-3- const alphabet = 3;');+ expect(await executor.handle('pi.grep', { params: { pattern: 'zzz' } })).toEqual({ text: 'No matches found' });+ });++ it.runIf(posix)('runs commands once with timeout and abort semantics', async () => {+ const { executor } = makeExecutor();+ const ok = (await executor.handle('exec.run', { command: 'echo hi; pwd', cwd: project })) as { output: string; exitCode: number };+ expect(Buffer.from(ok.output, 'base64').toString()).toBe(`hi\n${project}\n`);+ expect(ok.exitCode).toBe(0);+ const timedOut = (await executor.handle('exec.run', { command: 'sleep 20', timeout: 0.2 })) as { timedOut?: boolean };+ expect(timedOut.timedOut).toBe(true);+ const controller = new AbortController();+ const pending = executor.handle('exec.run', { command: 'sleep 20' }, controller.signal);+ setTimeout(() => controller.abort(), 100);+ expect(await pending).toMatchObject({ aborted: true });+ });++ it('refuses everything after the task has ended', async () => {+ const { executor } = makeExecutor();+ await executor.close();+ await expect(executor.handle('fs.read', { path: 'a' })).rejects.toMatchObject({ code: 'CLOSED' });+ expect((await executor.callTool('Read', { file_path: 'a' })).isError).toBe(true);+ });+});++describe('cindy_exec MCP endpoint', () => {+ it('initializes, lists the Claude Code style tools and calls them', async () => {+ const { executor } = makeExecutor();+ const post = async (body: unknown) => {+ const response = await handleExecMcpRequest(executor, 'POST', Buffer.from(JSON.stringify(body)));+ return { status: response.status, json: response.body ? JSON.parse(response.body.toString()) : undefined };+ };+ const init = await post({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-03-26', capabilities: {}, clientInfo: { name: 't', version: '1' } } });+ expect(init.json.result.protocolVersion).toBe('2025-03-26');+ expect((await post({ jsonrpc: '2.0', method: 'notifications/initialized' })).status).toBe(202);+ const tools = await post({ jsonrpc: '2.0', id: 2, method: 'tools/list' });+ expect(tools.json.result.tools.map((tool: { name: string }) => tool.name))+ .toEqual(['Bash', 'BashOutput', 'KillShell', 'Read', 'Write', 'Edit', 'NotebookEdit']);+ fs.writeFileSync(path.join(project, 'm.txt'), 'hello');+ const call = await post({ jsonrpc: '2.0', id: 3, method: 'tools/call', params: { name: 'Read', arguments: { file_path: path.join(project, 'm.txt') } } });+ expect(call.json.result.content[0].text).toBe('1\thello');+ expect((await post({ jsonrpc: '2.0', id: 4, method: 'nope' })).json.error.code).toBe(-32601);+ expect((await handleExecMcpRequest(executor, 'GET', undefined)).status).toBe(405);+ expect((await handleExecMcpRequest(executor, 'POST', Buffer.from('{bad'))).status).toBe(400);+ });+});++describe('findWindowsGitBash', () => {+ it('uses the configured Git Bash and reports none when nothing is installed', () => {+ const bash = path.join(root, 'bash.exe');+ fs.writeFileSync(bash, '');+ expect(findWindowsGitBash({ CLAUDE_CODE_GIT_BASH_PATH: bash })).toBe(bash);+ expect(findWindowsGitBash({ CLAUDE_CODE_GIT_BASH_PATH: path.join(root, 'missing.exe') })).toBeNull();+ expect(findWindowsGitBash({})).toBeNull();+ });++ it.runIf(process.platform === 'win32')('finds bash next to git on PATH and in the usual install folders', () => {+ const install = path.join(root, 'Git');+ fs.mkdirSync(path.join(install, 'cmd'), { recursive: true });+ fs.mkdirSync(path.join(install, 'bin'), { recursive: true });+ fs.writeFileSync(path.join(install, 'cmd', 'git.exe'), '');+ fs.writeFileSync(path.join(install, 'bin', 'bash.exe'), '');+ expect(findWindowsGitBash({ PATH: path.join(install, 'cmd') })).toBe(path.join(install, 'bin', 'bash.exe'));+ expect(findWindowsGitBash({ ProgramFiles: root })).toBe(path.join(install, 'bin', 'bash.exe'));+ });+});diff --git a/apps/desktop/src/main/remote-agent/executor/ccMcp.ts b/apps/desktop/src/main/remote-agent/executor/ccMcp.tsnew file mode 100644index 0000000000..7c26aef8da--- /dev/null+++ b/apps/desktop/src/main/remote-agent/executor/ccMcp.ts@@ -0,0 +1,112 @@+/**+ * `cindy_exec` MCP 服务(控制端):把执行器的 Claude Code 风格工具以 MCP(Streamable HTTP,+ * 无状态、请求-响应)提供给另一台电脑上的 Claude Code。请求经设备互联隧道到达这里。+ */+import { executorCcToolDefinitions, type RemoteExecutor } from './executor';++export const CINDY_EXEC_MCP_SERVER = 'cindy_exec';+const PROTOCOL_VERSIONS = ['2025-06-18', '2025-03-26', '2024-11-05'];+const MAX_BATCH = 32;++export interface McpHttpResponse {+ status: number;+ headers: Array<[string, string]>;+ body?: Buffer;+}++interface JsonRpcRequest {+ jsonrpc?: string;+ id?: string | number | null;+ method?: string;+ params?: Record<string, unknown>;+}++function json(status: number, value: unknown): McpHttpResponse {+ return {+ status,+ headers: [['content-type', 'application/json']],+ body: Buffer.from(JSON.stringify(value)),+ };+}++function rpcError(id: JsonRpcRequest['id'], code: number, message: string): Record<string, unknown> {+ return { jsonrpc: '2.0', id: id ?? null, error: { code, message } };+}++async function handleOne(+ executor: RemoteExecutor,+ request: JsonRpcRequest,+ signal?: AbortSignal,+): Promise<Record<string, unknown> | null> {+ const isNotification = request.id === undefined;+ if (request.jsonrpc !== '2.0' || typeof request.method !== 'string') {+ return isNotification ? null : rpcError(request.id, -32600, 'Invalid Request');+ }+ if (isNotification) return null;+ switch (request.method) {+ case 'initialize': {+ const requested = request.params?.protocolVersion;+ const protocolVersion = typeof requested === 'string' && PROTOCOL_VERSIONS.includes(requested)+ ? requested+ : PROTOCOL_VERSIONS[0];+ return {+ jsonrpc: '2.0',+ id: request.id,+ result: {+ protocolVersion,+ capabilities: { tools: { listChanged: false } },+ serverInfo: { name: CINDY_EXEC_MCP_SERVER, version: '1.0.0' },+ },+ };+ }+ case 'ping':+ return { jsonrpc: '2.0', id: request.id, result: {} };+ case 'tools/list':+ return {+ jsonrpc: '2.0',+ id: request.id,+ result: {+ tools: executorCcToolDefinitions().map((tool) => ({+ name: tool.name,+ description: tool.description,+ inputSchema: tool.inputSchema,+ })),+ },+ };+ case 'tools/call': {+ const name = request.params?.name;+ if (typeof name !== 'string') return rpcError(request.id, -32602, 'tool name is required');+ const result = await executor.callTool(name, request.params?.arguments ?? {}, signal);+ return { jsonrpc: '2.0', id: request.id, result };+ }+ default:+ return rpcError(request.id, -32601, `Method not found: ${request.method}`);+ }+}++/** 处理一次 MCP HTTP 请求。只支持 POST(无状态,不开 SSE 推送流)。 */+export async function handleExecMcpRequest(+ executor: RemoteExecutor,+ method: string,+ body: Buffer | undefined,+ signal?: AbortSignal,+): Promise<McpHttpResponse> {+ if (method === 'GET') return { status: 405, headers: [['allow', 'POST']] };+ if (method === 'DELETE') return { status: 200, headers: [] };+ if (method !== 'POST') return { status: 405, headers: [['allow', 'POST']] };+ let parsed: unknown;+ try {+ parsed = JSON.parse(body?.toString('utf8') ?? '');+ } catch {+ return json(400, rpcError(null, -32700, 'Parse error'));+ }+ if (Array.isArray(parsed)) {+ if (parsed.length === 0 || parsed.length > MAX_BATCH) return json(400, rpcError(null, -32600, 'Invalid Request'));+ const responses = (await Promise.all(parsed.map((item) =>+ handleOne(executor, (item ?? {}) as JsonRpcRequest, signal)))).filter((item) => item !== null);+ return responses.length ? json(200, responses) : { status: 202, headers: [] };+ }+ if (!parsed || typeof parsed !== 'object') return json(400, rpcError(null, -32600, 'Invalid Request'));+ const response = await handleOne(executor, parsed as JsonRpcRequest, signal);+ return response ? json(200, response) : { status: 202, headers: [] };+}diff --git a/apps/desktop/src/main/remote-agent/executor/executor.ts b/apps/desktop/src/main/remote-agent/executor/executor.tsnew file mode 100644index 0000000000..5bc9fed36c--- /dev/null+++ b/apps/desktop/src/main/remote-agent/executor/executor.ts@@ -0,0 +1,490 @@+/**+ * 远程 Agent 执行器(控制端):一个任务一份,任务结束即关闭。+ *+ * Agent 所在电脑发来的每个文件 / 命令请求都在这里先过权限上限,再在本机执行:+ * - `handle(op, body)`:原始操作(Pi 的工具后端);+ * - `callTool(name, args)`:Claude Code 风格的 Bash / BashOutput / KillShell / Read / Write / Edit /+ * NotebookEdit(Claude Code 的自带文件与命令工具关掉后由它顶替)。+ * 写文件前通知「每轮改动对比」抓取改前内容;命令执行后登记一次无法预知范围的改动。+ */+import path from 'node:path';++import {+ ccEdit,+ ccNotebookEdit,+ ccRead,+ ccWrite,+ createRipgrepRunner,+ detectImageMime,+ rawAccess,+ rawGlob,+ rawMkdir,+ rawReadFile,+ rawReaddir,+ rawStat,+ rawWriteFile,+ ReadStateTracker,+ textResult,+ type FileWriteHooks,+ type PdfTextExtractor,+ type RipgrepRunner,+ type ToolResult,+} from './files';+import type { ExecutorAction, ExecutorGate, ExecutorGateDecision, ExecutorGateMode } from './gate';+import { piGrep, type PiGrepInput } from './search';+import { runOnce, ShellSession } from './shell';+import { ExecutorPathError, type ExecutorWorkspace } from './workspace';++/** Pi bash 的超时(秒)上限,与 Pi 侧 Cindy 桥的上限一致。 */+const PI_BASH_MAX_TIMEOUT_SECONDS = 1800;++export interface ExecutorCaptureHooks {+ beforeWrite(absPath: string): Promise<void>;+ noteOpaqueWrite(): void;+}++export interface RemoteExecutorOptions {+ workspace: ExecutorWorkspace;+ gate: ExecutorGate;+ rgPath: string;+ capture?: ExecutorCaptureHooks;+ /** 后台命令输出文件所在目录。 */+ tempDir?: string;+ /** Read 读 PDF 时取文字;缺省时 PDF 不能用 Read 读取。 */+ extractPdfText?: PdfTextExtractor;+}++export class ExecutorRequestError extends Error {+ constructor(readonly code: string, message: string) {+ super(message);+ this.name = 'ExecutorRequestError';+ }+}++function errorCode(error: unknown): string {+ const code = (error as NodeJS.ErrnoException | undefined)?.code;+ return typeof code === 'string' && /^[A-Z][A-Z0-9_]{1,31}$/.test(code) ? code : 'EXECUTOR_ERROR';+}++function record(value: unknown): Record<string, unknown> {+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new ExecutorRequestError('INVALID', 'request body must be an object');+ return value as Record<string, unknown>;+}++function str(body: Record<string, unknown>, key: string): string {+ const value = body[key];+ if (typeof value !== 'string' || value.length === 0) throw new ExecutorRequestError('INVALID', `${key} must be a non-empty string`);+ return value;+}++function optionalNumber(body: Record<string, unknown>, key: string): number | undefined {+ const value = body[key];+ if (value === undefined || value === null) return undefined;+ if (typeof value !== 'number' || !Number.isFinite(value)) throw new ExecutorRequestError('INVALID', `${key} must be a number`);+ return value;+}++function optionalString(body: Record<string, unknown>, key: string): string | undefined {+ const value = body[key];+ if (value === undefined || value === null) return undefined;+ if (typeof value !== 'string') throw new ExecutorRequestError('INVALID', `${key} must be a string`);+ return value;+}++/** Claude Code 风格工具名(与自带工具同名,模型和界面看到的都是这些名字)。 */+export const EXECUTOR_CC_TOOL_NAMES = ['Bash', 'BashOutput', 'KillShell', 'Read', 'Write', 'Edit', 'NotebookEdit'] as const;+export type ExecutorCcToolName = (typeof EXECUTOR_CC_TOOL_NAMES)[number];++export class RemoteExecutor {+ readonly workspace: ExecutorWorkspace;+ private readonly gate: ExecutorGate;+ private readonly rg: RipgrepRunner;+ private readonly readState = new ReadStateTracker();+ private readonly shell: ShellSession;+ private readonly writeHooks: FileWriteHooks;+ private closed = false;++ constructor(private readonly opts: RemoteExecutorOptions) {+ this.workspace = opts.workspace;+ this.gate = opts.gate;+ this.rg = createRipgrepRunner(opts.rgPath);+ this.shell = new ShellSession({+ workingDir: opts.workspace.workingDir,+ isAllowedCwd: (cwd) => opts.workspace.contains(cwd),+ tempDir: opts.tempDir,+ });+ this.writeHooks = {+ beforeWrite: async (absPath) => {+ await opts.capture?.beforeWrite(absPath);+ },+ };+ }++ /** 本机任务的权限档变化时更新上限档位。 */+ setGateMode(mode: ExecutorGateMode): void {+ this.gate.setMode(mode);+ }++ /** 本机用户在确认卡上允许了一个操作。 */+ recordApproval(action: ExecutorAction): void {+ this.gate.recordApproval(action);+ }++ /** 权限上限检查(Codex exec-server 中继用;本执行器自己的操作在内部检查)。 */+ check(action: ExecutorAction): ExecutorGateDecision {+ if (this.closed) return { ok: false, reason: 'The task has ended on the computer where it runs.' };+ return this.gate.authorize(action);+ }++ async close(): Promise<void> {+ if (this.closed) return;+ this.closed = true;+ await this.shell.close();+ }++ private ensureOpen(): void {+ if (this.closed) throw new ExecutorRequestError('CLOSED', 'The task has ended on the computer where it runs.');+ }++ private resolvePath(input: string, baseDir?: string): string {+ try {+ return this.workspace.resolve(input, baseDir ? this.workspace.resolve(baseDir) : undefined);+ } catch (error) {+ if (error instanceof ExecutorPathError) throw new ExecutorRequestError('INVALID', error.message);+ throw error;+ }+ }++ private authorize(action: ExecutorAction): void {+ const decision = this.gate.authorize(action);+ if (!decision.ok) throw new ExecutorRequestError('EACCES', decision.reason ?? 'Not allowed.');+ }++ // ─── 原始操作 ──────────────────────────────────────────────────++ async handle(op: string, rawBody: unknown, signal?: AbortSignal): Promise<unknown> {+ this.ensureOpen();+ const body = record(rawBody);+ try {+ switch (op) {+ case 'fs.read': {+ const target = this.resolvePath(str(body, 'path'));+ this.authorize({ kind: 'read', path: target });+ return { data: (await rawReadFile(target)).toString('base64') };+ }+ case 'fs.access': {+ const target = this.resolvePath(str(body, 'path'));+ const mode = body.mode === 'write' ? 'write' : 'read';+ this.authorize({ kind: mode, path: target });+ await rawAccess(target, mode);+ return {};+ }+ case 'fs.write': {+ const target = this.resolvePath(str(body, 'path'));+ this.authorize({ kind: 'write', path: target });+ if (typeof body.data !== 'string') throw new ExecutorRequestError('INVALID', 'data must be a base64 string');+ const data = Buffer.from(body.data, 'base64');+ await this.writeHooks.beforeWrite(target);+ await rawWriteFile(target, data);+ return {};+ }+ case 'fs.mkdir': {+ const target = this.resolvePath(str(body, 'path'));+ this.authorize({ kind: 'write', path: target });+ await rawMkdir(target);+ return {};+ }+ case 'fs.stat': {+ const target = this.resolvePath(str(body, 'path'));+ this.authorize({ kind: 'read', path: target });+ return await rawStat(target);+ }+ case 'fs.readdir': {+ const target = this.resolvePath(str(body, 'path'));+ this.authorize({ kind: 'read', path: target });+ return { entries: await rawReaddir(target) };+ }+ case 'fs.glob': {+ const cwd = this.resolvePath(str(body, 'cwd'));+ this.authorize({ kind: 'read', path: cwd });+ const limit = Math.max(1, Math.floor(optionalNumber(body, 'limit') ?? 1000));+ return { paths: await rawGlob(this.rg, str(body, 'pattern'), cwd, limit, signal) };+ }+ case 'fs.mime': {+ const target = this.resolvePath(str(body, 'path'));+ this.authorize({ kind: 'read', path: target });+ return { mime: await detectImageMime(target) };+ }+ case 'pi.grep': {+ const params = record(body.params) as unknown as PiGrepInput;+ if (typeof params.pattern !== 'string' || !params.pattern) throw new ExecutorRequestError('INVALID', 'pattern is required');+ const root = this.resolvePath(typeof params.path === 'string' && params.path ? params.path : '.');+ this.authorize({ kind: 'read', path: root });+ return await piGrep(this.opts.rgPath, root, params, signal);+ }+ case 'exec.run': {+ const command = this.workspace.mapCommand(str(body, 'command'));+ const cwd = this.resolvePath(optionalString(body, 'cwd') ?? this.workspace.workingDir);+ this.authorize({ kind: 'exec', command, cwd });+ const timeoutSeconds = optionalNumber(body, 'timeout');+ const timeoutMs = timeoutSeconds && timeoutSeconds > 0+ ? Math.min(timeoutSeconds, PI_BASH_MAX_TIMEOUT_SECONDS) * 1000+ : undefined;+ try {+ const result = await runOnce(command, { cwd, timeoutMs, signal });+ return {+ output: result.output.toString('base64'),+ exitCode: result.exitCode,+ ...(result.timedOut ? { timedOut: true } : {}),+ ...(result.aborted ? { aborted: true } : {}),+ };+ } finally {+ this.opts.capture?.noteOpaqueWrite();+ }+ }+ default:+ throw new ExecutorRequestError('UNSUPPORTED', `unknown operation ${op}`);+ }+ } catch (error) {+ if (error instanceof ExecutorRequestError) throw error;+ throw new ExecutorRequestError(errorCode(error), (error as Error)?.message ?? String(error));+ }+ }++ // ─── Claude Code 风格工具 ──────────────────────────────────────++ async callTool(name: string, rawArgs: unknown, signal?: AbortSignal): Promise<ToolResult> {+ if (this.closed) return textResult('The task has ended on the computer where it runs.', true);+ let args: Record<string, unknown>;+ try {+ args = record(rawArgs ?? {});+ } catch {+ return textResult('Tool arguments must be an object.', true);+ }+ try {+ switch (name as ExecutorCcToolName) {+ case 'Bash':+ return await this.bash(args, signal);+ case 'BashOutput': {+ const id = optionalString(args, 'bash_id') ?? optionalString(args, 'task_id') ?? optionalString(args, 'shell_id');+ if (!id) return textResult('bash_id is required.', true);+ const result = await this.shell.readBackground(id, optionalString(args, 'filter'));+ return textResult(result.text, result.isError);+ }+ case 'KillShell': {+ const id = optionalString(args, 'shell_id') ?? optionalString(args, 'task_id') ?? optionalString(args, 'bash_id');+ if (!id) return textResult('shell_id is required.', true);+ const result = this.shell.killBackground(id);+ return textResult(result.text, result.isError);+ }+ case 'Read': {+ const target = this.resolvePath(str(args, 'file_path'), this.shell.getCwd());+ this.authorizeTool({ kind: 'read', path: target });+ return await ccRead(target, {+ file_path: target,+ offset: optionalNumber(args, 'offset'),+ limit: optionalNumber(args, 'limit'),+ pages: optionalString(args, 'pages'),+ }, this.readState, this.workspace.workingDir, this.opts.extractPdfText);+ }+ case 'Write': {+ const target = this.resolvePath(str(args, 'file_path'), this.shell.getCwd());+ const content = args.content;+ if (typeof content !== 'string') return textResult('content must be a string.', true);+ this.authorizeTool({ kind: 'write', path: target });+ return await ccWrite(target, content, this.readState, this.writeHooks);+ }+ case 'Edit': {+ const target = this.resolvePath(str(args, 'file_path'), this.shell.getCwd());+ if (typeof args.old_string !== 'string' || typeof args.new_string !== 'string') {+ return textResult('old_string and new_string must be strings.', true);+ }+ this.authorizeTool({ kind: 'write', path: target });+ return await ccEdit(target, {+ old_string: args.old_string,+ new_string: args.new_string,+ replace_all: args.replace_all === true,+ }, this.readState, this.writeHooks);+ }+ case 'NotebookEdit': {+ const target = this.resolvePath(str(args, 'notebook_path'), this.shell.getCwd());+ if (typeof args.new_source !== 'string') return textResult('new_source must be a string.', true);+ const cellType = args.cell_type === 'markdown' || args.cell_type === 'code' ? args.cell_type : undefined;+ const editMode = args.edit_mode === 'insert' || args.edit_mode === 'delete' || args.edit_mode === 'replace'+ ? args.edit_mode : undefined;+ this.authorizeTool({ kind: 'write', path: target });+ return await ccNotebookEdit(target, {+ cell_id: optionalString(args, 'cell_id'),+ new_source: args.new_source,+ cell_type: cellType,+ edit_mode: editMode,+ }, this.readState, this.writeHooks);+ }+ default:+ return textResult(`Unknown tool: ${name}`, true);+ }+ } catch (error) {+ if (error instanceof ExecutorDenied) return textResult(error.message, true);+ if (error instanceof ExecutorRequestError) return textResult(error.message, true);+ const code = (error as NodeJS.ErrnoException)?.code;+ if (code === 'EACCES' || code === 'EPERM') return textResult(`Permission denied: ${(error as Error).message}`, true);+ return textResult((error as Error)?.message ?? String(error), true);+ }+ }++ private authorizeTool(action: ExecutorAction): void {+ const decision = this.gate.authorize(action);+ if (!decision.ok) throw new ExecutorDenied(decision.reason ?? 'Not allowed.');+ }++ private async bash(args: Record<string, unknown>, signal?: AbortSignal): Promise<ToolResult> {+ const rawCommand = args.command;+ if (typeof rawCommand !== 'string' || !rawCommand.trim()) return textResult('command is required.', true);+ const command = this.workspace.mapCommand(rawCommand);+ this.authorizeTool({ kind: 'exec', command, cwd: this.shell.getCwd() });+ const timeout = optionalNumber(args, 'timeout');+ try {+ const result = args.run_in_background === true+ ? await this.shell.startBackground(command)+ : await this.shell.run(command, timeout, signal);+ return textResult(result.text, result.isError);+ } finally {+ this.opts.capture?.noteOpaqueWrite();+ }+ }+}++class ExecutorDenied extends Error {+ constructor(message: string) {+ super(message);+ this.name = 'ExecutorDenied';+ }+}++/** 给 Claude Code 的工具定义(参数名与自带工具一致;说明是 Cindy 自己写的)。 */+export function executorCcToolDefinitions(platform: NodeJS.Platform = process.platform): Array<{+ name: ExecutorCcToolName;+ description: string;+ inputSchema: Record<string, unknown>;+}> {+ const where = 'on the user\'s computer, where the project lives';+ const shellNote = platform === 'win32'+ ? 'Commands run in Git Bash when available, otherwise cmd.exe.'+ : `Commands run with ${path.basename(process.env.SHELL || 'bash')}.`;+ return [+ {+ name: 'Bash',+ description: [+ `Run a shell command ${where}. ${shellNote}`,+ 'The working directory persists between calls; environment variables do not. Prefer absolute paths.',+ 'Default timeout is 120000 ms (max 600000). Output longer than 30000 characters is shortened in the middle.',+ 'Set run_in_background to true for long-running processes such as dev servers, then read their output with BashOutput and stop them with KillShell.',+ 'Use the dedicated Read, Edit and Write tools for file contents instead of cat, sed or echo redirection.',+ ].join(' '),+ inputSchema: {+ type: 'object',+ properties: {+ command: { type: 'string', description: 'The command to execute' },+ timeout: { type: 'number', description: 'Optional timeout in milliseconds (max 600000)' },+ description: { type: 'string', description: 'A short description of what the command does, in plain words' },+ run_in_background: { type: 'boolean', description: 'Run the command in the background' },+ },+ required: ['command'],+ additionalProperties: false,+ },+ },+ {+ name: 'BashOutput',+ description: 'Read new output from a background command started with Bash run_in_background, plus whether it is still running. Each call returns only output produced since the previous call.',+ inputSchema: {+ type: 'object',+ properties: {+ bash_id: { type: 'string', description: 'The ID returned when the background command started' },+ filter: { type: 'string', description: 'Optional regular expression; only matching lines are returned' },+ },+ required: ['bash_id'],+ additionalProperties: false,+ },+ },+ {+ name: 'KillShell',+ description: 'Stop a background command started with Bash run_in_background.',+ inputSchema: {+ type: 'object',+ properties: {+ shell_id: { type: 'string', description: 'The ID of the background command to stop' },+ },+ required: ['shell_id'],+ additionalProperties: false,+ },+ },+ {+ name: 'Read',+ description: [+ `Read a file ${where}. file_path should be absolute.`,+ 'Returns up to 2000 lines starting at offset, each prefixed with its line number and a tab; lines longer than 2000 characters are cut.',+ 'Images (PNG, JPEG, GIF, WebP and other common formats) are returned as images; PDFs as the text of each page (at most 20 pages per call, use pages); Jupyter notebooks with their cells and outputs.',+ 'Read a file before editing or overwriting it. Reading a directory fails; use Bash with ls instead.',+ ].join(' '),+ inputSchema: {+ type: 'object',+ properties: {+ file_path: { type: 'string', description: 'The absolute path to the file to read' },+ offset: { type: 'integer', minimum: 0, description: 'The line number to start reading from. Only provide if the file is too large to read at once' },+ limit: { type: 'integer', exclusiveMinimum: 0, description: 'The number of lines to read. Only provide if the file is too large to read at once' },+ pages: { type: 'string', description: 'Page range for PDF files (e.g. "1-5"). Defaults to the first 20 pages' },+ },+ required: ['file_path'],+ additionalProperties: false,+ },+ },+ {+ name: 'Write',+ description: `Write a file ${where}, creating parent directories as needed and replacing any existing content. An existing file must have been read first in this task. Prefer Edit for changes to existing files.`,+ inputSchema: {+ type: 'object',+ properties: {+ file_path: { type: 'string', description: 'The absolute path to the file to write (must be absolute, not relative)' },+ content: { type: 'string', description: 'The content to write to the file' },+ },+ required: ['file_path', 'content'],+ additionalProperties: false,+ },+ },+ {+ name: 'Edit',+ description: [+ `Replace exact text in a file ${where}. The file must have been read first in this task.`,+ 'old_string must match the file exactly (do not include the line-number prefix from Read) and be unique unless replace_all is true; add surrounding context to make it unique.',+ 'An empty old_string creates a new file with new_string as its content.',+ ].join(' '),+ inputSchema: {+ type: 'object',+ properties: {+ file_path: { type: 'string', description: 'The absolute path to the file to modify' },+ old_string: { type: 'string', description: 'The text to replace' },+ new_string: { type: 'string', description: 'The text to replace it with (must be different from old_string)' },+ replace_all: { type: 'boolean', default: false, description: 'Replace all occurrences of old_string (default false)' },+ },+ required: ['file_path', 'old_string', 'new_string'],+ additionalProperties: false,+ },+ },+ {+ name: 'NotebookEdit',+ description: `Replace, insert or delete one cell of a Jupyter notebook ${where}. Read the notebook first to get cell IDs.`,+ inputSchema: {+ type: 'object',+ properties: {+ notebook_path: { type: 'string', description: 'The absolute path to the Jupyter notebook file to edit' },+ cell_id: { type: 'string', description: 'The ID of the cell to edit. When inserting, the new cell goes after this cell, or at the beginning if omitted' },+ new_source: { type: 'string', description: 'The new source for the cell' },+ cell_type: { type: 'string', enum: ['code', 'markdown'], description: 'The cell type. Required for insert' },+ edit_mode: { type: 'string', enum: ['replace', 'insert', 'delete'], description: 'The type of edit (default replace)' },+ },+ required: ['notebook_path', 'new_source'],+ additionalProperties: false,+ },+ },+ ];+}diff --git a/apps/desktop/src/main/remote-agent/executor/files.ts b/apps/desktop/src/main/remote-agent/executor/files.tsnew file mode 100644index 0000000000..2a56ca2bc6--- /dev/null+++ b/apps/desktop/src/main/remote-agent/executor/files.ts@@ -0,0 +1,628 @@+/**+ * 远程 Agent 执行器的文件操作(控制端)。+ *+ * 两层:+ * - 原始操作(读字节、写字节、建目录、查信息、列目录、找文件、搜内容):给 Pi 用。Pi 的+ * read / write / edit / ls / find / grep 工具逻辑原样跑在 Agent 所在电脑上,只把落盘动作换成这里;+ * - Claude Code 风格的 Read / Write / Edit / NotebookEdit:Claude Code 的自带文件工具关掉后由+ * Cindy 工具顶替,行为对齐自带工具(行号、偏移、先读后改、精确替换、唯一性、换行风格)。+ *+ * 路径均已由调用方解析为本机绝对路径并通过权限上限检查。+ */+import { spawn } from 'node:child_process';+import fs from 'node:fs';+import fsp from 'node:fs/promises';+import path from 'node:path';+import readline from 'node:readline';++import { getDefaultImageResizer } from '@cindy/maker-core';++/** 原始读取上限:Pi 的 read 先整读再截断,过大的文件在本机这一侧就拒绝。 */+export const EXECUTOR_RAW_READ_MAX_BYTES = 16 * 1024 * 1024;+/** Read 不带 offset / limit 时允许整读的最大文件。 */+export const CC_READ_MAX_FULL_BYTES = 256 * 1024;+export const CC_READ_DEFAULT_LIMIT = 2000;+export const CC_READ_MAX_LINE_CHARS = 2000;+/** 单张图片给模型的上限(base64 前)。 */+const CC_IMAGE_MAX_BYTES = 5 * 1024 * 1024;+const CC_PDF_MAX_BYTES = 32 * 1024 * 1024;+/** 一次 Read 最多读的 PDF 页数(与自带 Read 的页数上限一致)。 */+export const CC_PDF_MAX_PAGES_PER_READ = 20;+/** 一次 Read 返回的 PDF 文字上限。 */+export const CC_PDF_MAX_CHARS = 100_000;++const IMAGE_MIME: Record<string, string> = {+ '.png': 'image/png',+ '.jpg': 'image/jpeg',+ '.jpeg': 'image/jpeg',+ '.jfif': 'image/jpeg',+ '.gif': 'image/gif',+ '.webp': 'image/webp',+};+/** 需要先压缩/转码才能给模型的图片格式。 */+const CONVERTIBLE_IMAGE_EXTENSIONS = new Set(['.bmp', '.avif', '.ico', '.tiff', '.tif', '.heic', '.heif']);++export type ToolContent =+ | { type: 'text'; text: string }+ | { type: 'image'; data: string; mimeType: string };++export interface ToolResult {+ content: ToolContent[];+ isError?: boolean;+}++export class ExecutorToolError extends Error {+ constructor(message: string) {+ super(message);+ this.name = 'ExecutorToolError';+ }+}++export function textResult(text: string, isError = false): ToolResult {+ return { content: [{ type: 'text', text }], ...(isError ? { isError: true } : {}) };+}++// ─── 原始操作(Pi)─────────────────────────────────────────────────++export async function rawReadFile(absPath: string): Promise<Buffer> {+ const stat = await fsp.stat(absPath);+ if (stat.isDirectory()) throw Object.assign(new Error(`EISDIR: illegal operation on a directory, read '${absPath}'`), { code: 'EISDIR' });+ if (stat.size > EXECUTOR_RAW_READ_MAX_BYTES) {+ throw new ExecutorToolError(`File is too large to read through the remote connection (${stat.size} bytes, limit ${EXECUTOR_RAW_READ_MAX_BYTES}).`);+ }+ return fsp.readFile(absPath);+}++export async function rawAccess(absPath: string, mode: 'read' | 'write'): Promise<void> {+ await fsp.access(absPath, mode === 'write' ? fs.constants.R_OK | fs.constants.W_OK : fs.constants.R_OK);+}++export async function rawWriteFile(absPath: string, data: Buffer): Promise<void> {+ await fsp.mkdir(path.dirname(absPath), { recursive: true });+ await fsp.writeFile(absPath, data);+}++export async function rawMkdir(absPath: string): Promise<void> {+ await fsp.mkdir(absPath, { recursive: true });+}++export interface RawStat {+ type: 'file' | 'directory' | 'symlink' | 'other';+ size: number;+ mtimeMs: number;+}++export async function rawStat(absPath: string): Promise<RawStat> {+ const stat = await fsp.stat(absPath);+ return {+ type: stat.isFile() ? 'file' : stat.isDirectory() ? 'directory' : stat.isSymbolicLink() ? 'symlink' : 'other',+ size: stat.size,+ mtimeMs: stat.mtimeMs,+ };+}++export async function rawReaddir(absPath: string): Promise<string[]> {+ return fsp.readdir(absPath);+}++/** 按魔数识别图片类型(与 Pi 内置 detectImageMimeType 同一组格式)。 */+export async function detectImageMime(absPath: string): Promise<string | null> {+ let handle: fsp.FileHandle | undefined;+ try {+ handle = await fsp.open(absPath, 'r');+ const header = Buffer.alloc(16);+ const { bytesRead } = await handle.read(header, 0, 16, 0);+ const b = header.subarray(0, bytesRead);+ if (b.length >= 8 && b.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return 'image/png';+ if (b.length >= 3 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff) return 'image/jpeg';+ if (b.length >= 6 && (b.subarray(0, 6).toString('latin1') === 'GIF87a' || b.subarray(0, 6).toString('latin1') === 'GIF89a')) return 'image/gif';+ if (b.length >= 12 && b.subarray(0, 4).toString('latin1') === 'RIFF' && b.subarray(8, 12).toString('latin1') === 'WEBP') return 'image/webp';+ return null;+ } catch {+ return null;+ } finally {+ await handle?.close().catch(() => undefined);+ }+}++export interface RipgrepRunner {+ /** 返回 rg 的 stdout 行;达到 maxLines 时提前结束。退出码 1(无匹配)视为正常。 */+ (args: string[], cwd: string, opts: { maxLines: number; signal?: AbortSignal }): Promise<string[]>;+}++export function createRipgrepRunner(rgPath: string): RipgrepRunner {+ return (args, cwd, { maxLines, signal }) => new Promise((resolve, reject) => {+ const child = spawn(rgPath, args, { cwd, stdio: ['ignore', 'pipe', 'pipe'], signal });+ const lines: string[] = [];+ let stderr = '';+ let stopped = false;+ const reader = readline.createInterface({ input: child.stdout });+ reader.on('line', (line) => {+ if (stopped) return;+ lines.push(line);+ if (lines.length >= maxLines) {+ stopped = true;+ child.kill();+ }+ });+ child.stderr.on('data', (chunk: Buffer) => {+ if (stderr.length < 8192) stderr += chunk.toString();+ });+ child.on('error', (error) => {+ reader.close();+ reject(error);+ });+ child.on('close', (code) => {+ reader.close();+ if (!stopped && code !== 0 && code !== 1) {+ reject(new ExecutorToolError(stderr.trim() || `ripgrep exited with code ${String(code)}`));+ return;+ }+ resolve(lines);+ });+ });+}++/** Pi find 的后端:按 glob 列文件(遵守 .gitignore),返回绝对路径。 */+export async function rawGlob(+ rg: RipgrepRunner,+ pattern: string,+ cwd: string,+ limit: number,+ signal?: AbortSignal,+): Promise<string[]> {+ const lines = await rg(['--files', '--hidden', '--glob', '!.git', '--glob', pattern], cwd, {+ maxLines: Math.max(1, Math.min(limit, 10_000)),+ signal,+ });+ return lines.map((line) => path.resolve(cwd, line));+}++// ─── Claude Code 风格工具 ─────────────────────────────────────────++/** 每个任务一份:记录读过哪些文件,写入/编辑前校验「先读过且之后没被改过」。 */+export class ReadStateTracker {+ private readonly state = new Map<string, number>();++ record(absPath: string, mtimeMs: number): void {+ this.state.set(path.resolve(absPath), mtimeMs);+ if (this.state.size > 4096) {+ const oldest = this.state.keys().next().value;+ if (oldest !== undefined) this.state.delete(oldest);+ }+ }++ /** 已存在文件写入前的检查;返回错误信息或 null。 */+ async check(absPath: string): Promise<string | null> {+ const recorded = this.state.get(path.resolve(absPath));+ if (recorded === undefined) return 'File has not been read yet. Read it first before writing to it.';+ const stat = await fsp.stat(absPath);+ if (Math.floor(stat.mtimeMs) > Math.floor(recorded)) {+ return 'File has been modified since read, either by the user or by a linter. Read it again before attempting to write it.';+ }+ return null;+ }+}++async function statOrNull(absPath: string): Promise<fs.Stats | null> {+ try {+ return await fsp.stat(absPath);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT' || (error as NodeJS.ErrnoException).code === 'ENOTDIR') return null;+ throw error;+ }+}++function truncateLine(line: string): string {+ return line.length > CC_READ_MAX_LINE_CHARS ? line.slice(0, CC_READ_MAX_LINE_CHARS) : line;+}++function formatNumberedLines(lines: string[], firstLine: number): string {+ return lines.map((line, index) => `${firstLine + index}\t${truncateLine(line)}`).join('\n');+}++export interface CcReadInput {+ file_path: string;+ offset?: number;+ limit?: number;+ pages?: string;+}++/**+ * 取 PDF 第 1..lastPage 页的文字。sections 每段以 `--- 第 N 页 ---` 开头(只含有文字的页)。+ * 与审查读 PDF 交付物是同一个抽取进程。+ */+export type PdfTextExtractor = (data: Uint8Array, lastPage: number, maxChars: number) => Promise<{+ sections: string[];+ numPages: number;+ pagesInspected: number;+ clipped: boolean;+}>;++/** `"3"` / `"1-5"` → 页码范围;格式不对返回 null。 */+export function parsePdfPageRange(pages: string): { first: number; last: number } | null {+ const match = /^\s*(\d+)\s*(?:-\s*(\d+)\s*)?$/.exec(pages);+ if (!match) return null;+ const first = Number(match[1]);+ const last = match[2] === undefined ? first : Number(match[2]);+ if (!Number.isSafeInteger(first) || !Number.isSafeInteger(last) || first < 1 || last < first) return null;+ return { first, last };+}++/**+ * PDF 的 Read:自带 Read 把 PDF 整份交给模型,Cindy 工具的结果只能是文字和图片(其他二进制会被+ * Agent 存到它自己那台电脑的临时文件里,模型读不到),所以这里给出逐页文字。+ */+async function readPdfText(+ absPath: string,+ pages: string | undefined,+ extract: PdfTextExtractor | undefined,+): Promise<ToolResult> {+ if (!extract) {+ return textResult('Reading PDF files is not available here. Extract the text with Bash (for example pdftotext) instead.', true);+ }+ const requested = pages === undefined || pages.trim() === '' ? null : parsePdfPageRange(pages);+ if (pages !== undefined && pages.trim() !== '' && !requested) {+ return textResult(`Invalid pages parameter: "${pages}". Use formats like "1-5", "3", or "10-20". Pages are 1-indexed.`, true);+ }+ const range = requested ?? { first: 1, last: CC_PDF_MAX_PAGES_PER_READ };+ if (range.last - range.first + 1 > CC_PDF_MAX_PAGES_PER_READ) {+ return textResult(`Page range "${pages}" exceeds the maximum of ${CC_PDF_MAX_PAGES_PER_READ} pages per request. Please use a smaller range.`, true);+ }+ const data = await fsp.readFile(absPath);+ const extracted = await extract(new Uint8Array(data), range.last, CC_PDF_MAX_CHARS);+ if (range.first > extracted.numPages) {+ return textResult(`The PDF has ${extracted.numPages} page(s); page ${range.first} does not exist.`, true);+ }+ const lastRead = Math.min(range.last, extracted.pagesInspected);+ const sections = extracted.sections.flatMap((section) => {+ const match = /^--- 第 (\d+) 页 ---\n/.exec(section);+ if (!match || Number(match[1]) < range.first) return [];+ return [`--- Page ${match[1]} ---\n${section.slice(match[0].length)}`];+ });+ const notes = [+ `PDF ${absPath}: ${extracted.numPages} page(s). Text of pages ${range.first}-${lastRead} follows; images, layout and scanned pages are not included.`,+ ];+ if (!requested && extracted.numPages > lastRead) {+ notes.push(`Use the pages parameter (for example "${lastRead + 1}-${Math.min(extracted.numPages, lastRead + CC_PDF_MAX_PAGES_PER_READ)}") to read more.`);+ }+ if (extracted.clipped) notes.push('The text was cut off at the size limit; read a smaller page range to see the rest.');+ if (!sections.length) notes.push('These pages have no extractable text (they may be scanned images).');+ return textResult([notes.join(' '), ...sections].join('\n\n'));+}++export async function ccRead(+ absPath: string,+ input: CcReadInput,+ readState: ReadStateTracker,+ cwd: string,+ extractPdfText?: PdfTextExtractor,+): Promise<ToolResult> {+ const stat = await statOrNull(absPath);+ if (!stat) {+ return textResult(`File does not exist. Note: your current working directory is ${cwd}.`, true);+ }+ if (stat.isDirectory()) {+ return textResult(`EISDIR: illegal operation on a directory, read '${absPath}'. Use Bash with ls to list a directory.`, true);+ }+ const ext = path.extname(absPath).toLowerCase();+ if (IMAGE_MIME[ext] || CONVERTIBLE_IMAGE_EXTENSIONS.has(ext)) {+ const result = await readImage(absPath);+ readState.record(absPath, stat.mtimeMs);+ return result;+ }+ if (ext === '.pdf') {+ if (stat.size > CC_PDF_MAX_BYTES) return textResult(`PDF is too large to read (${stat.size} bytes).`, true);+ const result = await readPdfText(absPath, input.pages, extractPdfText);+ if (!result.isError) readState.record(absPath, stat.mtimeMs);+ return result;+ }+ if (ext === '.ipynb') {+ const raw = await fsp.readFile(absPath, 'utf8');+ readState.record(absPath, stat.mtimeMs);+ return textResult(renderNotebook(raw));+ }+ const hasRange = input.offset !== undefined || input.limit !== undefined;+ if (!hasRange && stat.size > CC_READ_MAX_FULL_BYTES) {+ return textResult(+ `File content (${Math.round(stat.size / 1024)}KB) exceeds maximum allowed size (${CC_READ_MAX_FULL_BYTES / 1024}KB). Please use offset and limit parameters to read specific portions of the file, or search for specific content instead of reading the whole file.`,+ true,+ );+ }+ if (stat.size === 0) {+ readState.record(absPath, stat.mtimeMs);+ return textResult('<system-reminder>Warning: the file exists but the contents are empty.</system-reminder>');+ }+ const start = Math.max(1, Math.floor(input.offset ?? 1) || 1);+ const limit = Math.max(1, Math.floor(input.limit ?? CC_READ_DEFAULT_LIMIT) || CC_READ_DEFAULT_LIMIT);+ const { lines, total } = await readLineRange(absPath, start, limit);+ readState.record(absPath, stat.mtimeMs);+ if (lines.length === 0) {+ return textResult(+ `<system-reminder>Warning: the file exists but is shorter than the provided offset (${start}). The file has ${total} lines.</system-reminder>`,+ );+ }+ return textResult(formatNumberedLines(lines, start));+}++/** 逐行读取 [start, start+limit) 行(1 起),同时数出总行数;大文件不整读进内存。 */+async function readLineRange(absPath: string, start: number, limit: number): Promise<{ lines: string[]; total: number }> {+ const stream = fs.createReadStream(absPath, { encoding: 'utf8' });+ const reader = readline.createInterface({ input: stream, crlfDelay: Infinity });+ const lines: string[] = [];+ let total = 0;+ try {+ for await (const line of reader) {+ total += 1;+ if (total >= start && lines.length < limit) lines.push(line);+ }+ } finally {+ reader.close();+ stream.destroy();+ }+ return { lines, total };+}++async function readImage(absPath: string): Promise<ToolResult> {+ let target = absPath;+ try {+ target = await getDefaultImageResizer().process(absPath);+ } catch {+ target = absPath;+ }+ const mime = IMAGE_MIME[path.extname(target).toLowerCase()] ?? (await detectImageMime(target));+ if (!mime) return textResult(`Unsupported image format: ${path.extname(absPath) || 'unknown'}.`, true);+ const data = await fsp.readFile(target);+ if (data.length > CC_IMAGE_MAX_BYTES) {+ return textResult(`Image is too large to send to the model (${data.length} bytes).`, true);+ }+ return { content: [{ type: 'image', data: data.toString('base64'), mimeType: mime }] };+}++interface NotebookCell {+ id?: string;+ cell_type?: string;+ source?: string | string[];+ outputs?: Array<Record<string, unknown>>;+ metadata?: Record<string, unknown>;+ execution_count?: number | null;+}++interface Notebook {+ cells?: NotebookCell[];+ metadata?: { language_info?: { name?: string } };+ nbformat?: number;+ nbformat_minor?: number;+}++function cellSource(cell: NotebookCell): string {+ return Array.isArray(cell.source) ? cell.source.join('') : (cell.source ?? '');+}++function cellId(cell: NotebookCell, index: number): string {+ return typeof cell.id === 'string' && cell.id ? cell.id : `cell-${index}`;+}++function outputText(output: Record<string, unknown>): string {+ const text = output.text;+ if (typeof text === 'string') return text;+ if (Array.isArray(text)) return text.join('');+ const data = output.data as Record<string, unknown> | undefined;+ const plain = data?.['text/plain'];+ if (typeof plain === 'string') return plain;+ if (Array.isArray(plain)) return plain.join('');+ if (data && Object.keys(data).some((key) => key.startsWith('image/'))) return '[image output]';+ if (typeof output.ename === 'string') return `${output.ename}: ${String(output.evalue ?? '')}`;+ return '';+}++function renderNotebook(raw: string): string {+ let notebook: Notebook;+ try {+ notebook = JSON.parse(raw) as Notebook;+ } catch {+ return raw;+ }+ const cells = Array.isArray(notebook.cells) ? notebook.cells : [];+ if (cells.length === 0) return '<system-reminder>Warning: the notebook has no cells.</system-reminder>';+ return cells.map((cell, index) => {+ const outputs = (cell.outputs ?? []).map(outputText).filter(Boolean).join('\n');+ return [+ `<cell id="${cellId(cell, index)}"><cell_type>${cell.cell_type ?? 'code'}</cell_type>`,+ cellSource(cell),+ outputs ? `<outputs>\n${outputs}\n</outputs>` : '',+ '</cell>',+ ].filter(Boolean).join('\n');+ }).join('\n');+}++export interface FileWriteHooks {+ /** 写入已知文件前调用(每轮改动对比抓取改前内容)。 */+ beforeWrite(absPath: string): Promise<void>;+}++export async function ccWrite(+ absPath: string,+ content: string,+ readState: ReadStateTracker,+ hooks: FileWriteHooks,+): Promise<ToolResult> {+ const stat = await statOrNull(absPath);+ if (stat?.isDirectory()) return textResult(`EISDIR: illegal operation on a directory, write '${absPath}'`, true);+ if (stat) {+ const problem = await readState.check(absPath);+ if (problem) return textResult(problem, true);+ }+ await hooks.beforeWrite(absPath);+ await fsp.mkdir(path.dirname(absPath), { recursive: true });+ await fsp.writeFile(absPath, content, 'utf8');+ const after = await fsp.stat(absPath);+ readState.record(absPath, after.mtimeMs);+ return textResult(stat ? `The file ${absPath} has been updated successfully.` : `File created successfully at: ${absPath}`);+}++export interface CcEditInput {+ old_string: string;+ new_string: string;+ replace_all?: boolean;+}++function countOccurrences(haystack: string, needle: string): number {+ let count = 0;+ let index = haystack.indexOf(needle);+ while (index !== -1) {+ count += 1;+ index = haystack.indexOf(needle, index + needle.length);+ }+ return count;+}++export async function ccEdit(+ absPath: string,+ input: CcEditInput,+ readState: ReadStateTracker,+ hooks: FileWriteHooks,+): Promise<ToolResult> {+ const { old_string: oldString, new_string: newString } = input;+ if (oldString === newString) {+ return textResult('No changes to make: old_string and new_string are exactly the same.', true);+ }+ const stat = await statOrNull(absPath);+ if (stat?.isDirectory()) return textResult(`EISDIR: illegal operation on a directory, edit '${absPath}'`, true);+ if (!stat) {+ if (oldString !== '') return textResult(`File does not exist: ${absPath}`, true);+ await hooks.beforeWrite(absPath);+ await fsp.mkdir(path.dirname(absPath), { recursive: true });+ await fsp.writeFile(absPath, newString, 'utf8');+ readState.record(absPath, (await fsp.stat(absPath)).mtimeMs);+ return textResult(`File created successfully at: ${absPath}`);+ }+ const problem = await readState.check(absPath);+ if (problem) return textResult(problem, true);+ const original = await fsp.readFile(absPath, 'utf8');+ if (oldString === '') {+ if (original.trim() !== '') return textResult('Cannot create new file - file already exists.', true);+ await hooks.beforeWrite(absPath);+ await fsp.writeFile(absPath, newString, 'utf8');+ readState.record(absPath, (await fsp.stat(absPath)).mtimeMs);+ return textResult(`The file ${absPath} has been updated successfully.`);+ }+ // 文件用 CRLF 时按 LF 匹配,写回时恢复原换行风格。+ const crlf = original.includes('\r\n');+ const text = crlf ? original.replace(/\r\n/g, '\n') : original;+ const needle = crlf ? oldString.replace(/\r\n/g, '\n') : oldString;+ const replacement = crlf ? newString.replace(/\r\n/g, '\n') : newString;+ const matches = countOccurrences(text, needle);+ if (matches === 0) {+ return textResult(`String to replace not found in file.\nString: ${oldString}`, true);+ }+ if (matches > 1 && !input.replace_all) {+ return textResult(+ `Found ${matches} matches of the string to replace, but replace_all is false. To replace all occurrences, set replace_all to true. To replace only one occurrence, please provide more context to uniquely identify the instance.\nString: ${oldString}`,+ true,+ );+ }+ const updated = input.replace_all ? text.split(needle).join(replacement) : text.replace(needle, () => replacement);+ await hooks.beforeWrite(absPath);+ await fsp.writeFile(absPath, crlf ? updated.replace(/\n/g, '\r\n') : updated, 'utf8');+ readState.record(absPath, (await fsp.stat(absPath)).mtimeMs);+ return textResult(`The file ${absPath} has been updated successfully.`);+}++export interface CcNotebookEditInput {+ cell_id?: string;+ new_source: string;+ cell_type?: 'code' | 'markdown';+ edit_mode?: 'replace' | 'insert' | 'delete';+}++function findCellIndex(cells: NotebookCell[], id: string): number {+ const exact = cells.findIndex((cell) => cell.id === id);+ if (exact >= 0) return exact;+ const numbered = /^cell-(\d+)$/.exec(id);+ if (numbered) {+ const index = Number(numbered[1]);+ if (index < cells.length) return index;+ }+ return -1;+}++function detectIndent(raw: string): number {+ const match = /^\{\s*\n( +)"/.exec(raw);+ return match ? match[1].length : 1;+}++function newCellId(): string {+ return Math.random().toString(16).slice(2, 10).padEnd(8, '0');+}++export async function ccNotebookEdit(+ absPath: string,+ input: CcNotebookEditInput,+ readState: ReadStateTracker,+ hooks: FileWriteHooks,+): Promise<ToolResult> {+ if (path.extname(absPath).toLowerCase() !== '.ipynb') {+ return textResult('File must be a Jupyter notebook (.ipynb file). For editing other file types, use the Edit tool.', true);+ }+ const stat = await statOrNull(absPath);+ if (!stat) return textResult('Notebook file does not exist.', true);+ const problem = await readState.check(absPath);+ if (problem) return textResult(problem, true);+ const raw = await fsp.readFile(absPath, 'utf8');+ let notebook: Notebook;+ try {+ notebook = JSON.parse(raw) as Notebook;+ } catch {+ return textResult('Notebook is not valid JSON.', true);+ }+ const cells = Array.isArray(notebook.cells) ? notebook.cells : [];+ notebook.cells = cells;+ const mode = input.edit_mode ?? 'replace';+ const index = input.cell_id ? findCellIndex(cells, input.cell_id) : -1;+ if (mode !== 'insert' && index < 0) {+ return textResult(input.cell_id ? `Cell with ID "${input.cell_id}" not found in notebook.` : 'cell_id is required for replace and delete.', true);+ }+ if (mode === 'insert' && input.cell_id && index < 0) {+ return textResult(`Cell with ID "${input.cell_id}" not found in notebook.`, true);+ }+ if (mode === 'insert' && !input.cell_type) {+ return textResult('cell_type is required when using edit_mode=insert.', true);+ }+ const supportsIds = (notebook.nbformat ?? 4) > 4 || ((notebook.nbformat ?? 4) === 4 && (notebook.nbformat_minor ?? 0) >= 5);+ let resultId = input.cell_id ?? '';+ if (mode === 'delete') {+ cells.splice(index, 1);+ } else if (mode === 'insert') {+ const cellType = input.cell_type ?? 'code';+ const cell: NotebookCell = cellType === 'markdown'+ ? { cell_type: 'markdown', metadata: {}, source: input.new_source }+ : { cell_type: 'code', metadata: {}, source: input.new_source, outputs: [], execution_count: null };+ if (supportsIds) {+ cell.id = newCellId();+ resultId = cell.id;+ }+ cells.splice(index + 1, 0, cell);+ } else {+ const cell = cells[index];+ cell.source = input.new_source;+ if (input.cell_type && input.cell_type !== cell.cell_type) {+ cell.cell_type = input.cell_type;+ if (input.cell_type === 'markdown') {+ delete cell.outputs;+ delete cell.execution_count;+ } else {+ cell.outputs = [];+ cell.execution_count = null;+ }+ } else if (cell.cell_type === 'code') {+ cell.outputs = [];+ cell.execution_count = null;+ }+ }+ await hooks.beforeWrite(absPath);+ await fsp.writeFile(absPath, `${JSON.stringify(notebook, null, detectIndent(raw))}\n`, 'utf8');+ readState.record(absPath, (await fsp.stat(absPath)).mtimeMs);+ const verb = mode === 'delete' ? 'Deleted cell' : mode === 'insert' ? 'Inserted cell' : 'Updated cell';+ return textResult(`${verb} ${resultId}`.trim());+}diff --git a/apps/desktop/src/main/remote-agent/executor/gate.ts b/apps/desktop/src/main/remote-agent/executor/gate.tsnew file mode 100644index 0000000000..18bbb8f746--- /dev/null+++ b/apps/desktop/src/main/remote-agent/executor/gate.ts@@ -0,0 +1,127 @@+/**+ * 远程 Agent 执行器的权限上限(控制端)。+ *+ * 分工:Agent 所在电脑上的 Cindy 用与本机任务完全相同的权限逻辑决定「问不问」(权限档、+ * 自动审查、会话内允许规则),需要问的都弹到本机界面上让用户点。执行器在本机这一侧再守一道+ * 上限,保证另一台电脑无论如何不能越过本机用户:+ * - 全权:一律放行(用户在本机为这个任务选了全权);+ * - 凭证类路径、静态可证的高危命令:本机任务这类操作总是逐次问用户,执行器只认本机用户+ * 刚批准过的同一操作;+ * - 计划模式:只允许读取和静态可证只读的命令,其余同样要本机用户批准过。+ * 批准记录只在短时间内有效;命令批准用一次即失效,路径批准在有效期内覆盖同一路径的读写+ * (编辑会先读后写)。+ */+import path from 'node:path';++import { classifyShellCommand } from '@cindy/maker-core';++import type { ExecutorWorkspace } from './workspace';++/**+ * 与本机任务权限对应的上限档位:`full` = 全权;`plan` = 计划模式;其余权限档统一为 `normal`+ * (问不问由 Agent 侧的权限逻辑决定,这里只守高危上限)。+ */+export type ExecutorGateMode = 'full' | 'plan' | 'normal';++export type ExecutorAction =+ | { kind: 'read'; path: string }+ | { kind: 'write'; path: string }+ | { kind: 'exec'; command: string; cwd: string };++export interface ExecutorGateDecision {+ ok: boolean;+ /** 拒绝时给 Agent 看的原因。 */+ reason?: string;+}++/** 批准记录的有效期:覆盖「确认后到真正执行」之间的间隔,过期须重新确认。 */+export const EXECUTOR_APPROVAL_TTL_MS = 2 * 60_000;+const MAX_APPROVALS = 256;++interface Approval {+ kind: 'path' | 'exec';+ key: string;+ expiresAt: number;+}++export function executorGateModeFor(+ permissionMode: string | null | undefined,+ planMode = false,+): ExecutorGateMode {+ if (planMode || permissionMode === 'plan') return 'plan';+ return permissionMode === 'bypassPermissions' ? 'full' : 'normal';+}++function pathKey(target: string): string {+ return path.resolve(target);+}++export class ExecutorGate {+ private mode: ExecutorGateMode;+ private approvals: Approval[] = [];++ constructor(+ private readonly workspace: ExecutorWorkspace,+ mode: ExecutorGateMode = 'normal',+ private readonly now: () => number = Date.now,+ ) {+ this.mode = mode;+ }++ setMode(mode: ExecutorGateMode): void {+ this.mode = mode;+ }++ getMode(): ExecutorGateMode {+ return this.mode;+ }++ /** 本机用户在确认卡上允许了一个操作后调用。 */+ recordApproval(action: ExecutorAction): void {+ this.prune();+ this.approvals.push(action.kind === 'exec'+ ? { kind: 'exec', key: action.command, expiresAt: this.now() + EXECUTOR_APPROVAL_TTL_MS }+ : { kind: 'path', key: pathKey(action.path), expiresAt: this.now() + EXECUTOR_APPROVAL_TTL_MS });+ if (this.approvals.length > MAX_APPROVALS) this.approvals.splice(0, this.approvals.length - MAX_APPROVALS);+ }++ authorize(action: ExecutorAction): ExecutorGateDecision {+ if (this.mode === 'full') return { ok: true };+ if (!this.requiresApproval(action)) return { ok: true };+ if (this.consume(action)) return { ok: true };+ return {+ ok: false,+ reason: action.kind === 'exec'+ ? 'This command needs the user\'s confirmation on the computer where the task runs, and it was not confirmed.'+ : `Access to ${action.path} needs the user's confirmation on the computer where the task runs, and it was not confirmed.`,+ };+ }++ private requiresApproval(action: ExecutorAction): boolean {+ if (action.kind === 'exec') {+ const verdict = classifyShellCommand(action.command, this.workspace.allRoots(), {+ cwd: action.cwd,+ platform: process.platform,+ });+ if (verdict === 'prompt-each-time') return true;+ return this.mode === 'plan' && verdict !== 'auto-approve';+ }+ if (this.workspace.isSensitive(action.path)) return true;+ return action.kind === 'write' && this.mode === 'plan';+ }++ private consume(action: ExecutorAction): boolean {+ this.prune();+ const kind = action.kind === 'exec' ? 'exec' : 'path';+ const key = action.kind === 'exec' ? action.command : pathKey(action.path);+ const index = this.approvals.findIndex((approval) => approval.kind === kind && approval.key === key);+ if (index < 0) return false;+ if (kind === 'exec') this.approvals.splice(index, 1);+ return true;+ }++ private prune(): void {+ const t = this.now();+ this.approvals = this.approvals.filter((approval) => approval.expiresAt > t);+ }+}diff --git a/apps/desktop/src/main/remote-agent/executor/search.ts b/apps/desktop/src/main/remote-agent/executor/search.tsnew file mode 100644index 0000000000..c176dcaf6c--- /dev/null+++ b/apps/desktop/src/main/remote-agent/executor/search.ts@@ -0,0 +1,164 @@+/**+ * Pi grep 的本机后端:用 Cindy 自带的 ripgrep 在本机项目里搜索,输出格式与 Pi 自带 grep 一致+ * (`路径:行号: 内容`,上下文行用 `-`),命中上限、长行截断、总量截断的提示也一致。+ */+import { spawn } from 'node:child_process';+import fsp from 'node:fs/promises';+import path from 'node:path';+import readline from 'node:readline';++/** 与 Pi 自带 grep 相同的默认值。 */+const DEFAULT_LIMIT = 100;+const MAX_LINE_CHARS = 500;+const MAX_OUTPUT_BYTES = 50 * 1024;++export interface PiGrepInput {+ pattern: string;+ path?: string;+ glob?: string;+ ignoreCase?: boolean;+ literal?: boolean;+ context?: number;+ limit?: number;+}++export interface PiGrepResult {+ text: string;+ details?: {+ matchLimitReached?: number;+ linesTruncated?: true;+ truncated?: true;+ };+}++function truncateLine(line: string): { text: string; truncated: boolean } {+ return line.length > MAX_LINE_CHARS+ ? { text: `${line.slice(0, MAX_LINE_CHARS)}... [truncated]`, truncated: true }+ : { text: line, truncated: false };+}++function formatSize(bytes: number): string {+ return bytes >= 1024 ? `${Math.round(bytes / 1024)}KB` : `${bytes}B`;+}++interface RgEvent {+ type: string;+ data?: {+ path?: { text?: string };+ lines?: { text?: string };+ line_number?: number;+ };+}++export async function piGrep(+ rgPath: string,+ root: string,+ input: PiGrepInput,+ signal?: AbortSignal,+): Promise<PiGrepResult> {+ const stat = await fsp.stat(root);+ const rootIsDirectory = stat.isDirectory();+ const limit = Math.max(1, Math.floor(input.limit ?? DEFAULT_LIMIT) || DEFAULT_LIMIT);+ const context = input.context && input.context > 0 ? Math.floor(input.context) : 0;+ const args = ['--json', '--hidden', '--glob', '!.git'];+ if (input.ignoreCase) args.push('--ignore-case');+ if (input.literal) args.push('--fixed-strings');+ if (context > 0) args.push('--context', String(context));+ if (input.glob) args.push('--glob', input.glob);+ args.push('--regexp', input.pattern, '--', rootIsDirectory ? '.' : path.basename(root));+ const cwd = rootIsDirectory ? root : path.dirname(root);++ const outputLines: string[] = [];+ let matches = 0;+ let limitReached = false;+ let linesTruncated = false;+ let stderr = '';+ let lastPath: string | undefined;+ let lastLine = -1;++ await new Promise<void>((resolve, reject) => {+ const child = spawn(rgPath, args, { cwd, stdio: ['ignore', 'pipe', 'pipe'], signal });+ const reader = readline.createInterface({ input: child.stdout });+ let stopped = false;+ reader.on('line', (raw) => {+ if (stopped) return;+ let event: RgEvent;+ try {+ event = JSON.parse(raw) as RgEvent;+ } catch {+ return;+ }+ if (event.type !== 'match' && event.type !== 'context') return;+ const file = event.data?.path?.text;+ const lineNumber = event.data?.line_number;+ if (!file || typeof lineNumber !== 'number') return;+ const display = rootIsDirectory ? file.replace(/^\.\//, '').split(path.sep).join('/') : path.basename(root);+ if (lastPath !== undefined && (display !== lastPath || lineNumber > lastLine + 1) && context > 0) {+ outputLines.push('--');+ }+ lastPath = display;+ lastLine = lineNumber;+ const text = (event.data?.lines?.text ?? '').replace(/\r?\n$/, '').replace(/\r/g, '');+ const { text: shown, truncated } = truncateLine(text);+ if (truncated) linesTruncated = true;+ const separator = event.type === 'match' ? ':' : '-';+ outputLines.push(`${display}${separator}${lineNumber}${separator} ${shown}`);+ if (event.type === 'match') {+ matches += 1;+ if (matches >= limit) {+ limitReached = true;+ stopped = true;+ child.kill();+ }+ }+ });+ child.stderr.on('data', (chunk: Buffer) => {+ if (stderr.length < 8192) stderr += chunk.toString();+ });+ child.on('error', (error) => {+ reader.close();+ reject(error);+ });+ child.on('close', (code) => {+ reader.close();+ if (!limitReached && code !== 0 && code !== 1) {+ reject(new Error(stderr.trim() || `ripgrep exited with code ${String(code)}`));+ return;+ }+ resolve();+ });+ });++ if (matches === 0) return { text: 'No matches found' };+ // 上下文模式下最后一条可能是命中后的上下文,按出现顺序保留。+ let output = outputLines.join('\n');+ let truncated = false;+ if (Buffer.byteLength(output) > MAX_OUTPUT_BYTES) {+ const kept: string[] = [];+ let size = 0;+ for (const line of outputLines) {+ const next = Buffer.byteLength(line) + 1;+ if (size + next > MAX_OUTPUT_BYTES) break;+ kept.push(line);+ size += next;+ }+ output = kept.join('\n');+ truncated = true;+ }+ const notices: string[] = [];+ const details: NonNullable<PiGrepResult['details']> = {};+ if (limitReached) {+ notices.push(`${limit} matches limit reached`);+ details.matchLimitReached = limit;+ }+ if (linesTruncated) {+ notices.push('long lines truncated');+ details.linesTruncated = true;+ }+ if (truncated) {+ notices.push(`${formatSize(MAX_OUTPUT_BYTES)} limit reached`);+ details.truncated = true;+ }+ if (notices.length > 0) output += `\n\n[${notices.join('. ')}]`;+ return { text: output, ...(Object.keys(details).length > 0 ? { details } : {}) };+}diff --git a/apps/desktop/src/main/remote-agent/executor/shell.ts b/apps/desktop/src/main/remote-agent/executor/shell.tsnew file mode 100644index 0000000000..4c0bf7463c--- /dev/null+++ b/apps/desktop/src/main/remote-agent/executor/shell.ts@@ -0,0 +1,419 @@+/**+ * 远程 Agent 执行器的命令执行(控制端)。+ *+ * 命令在本机执行,进程组可整体结束;输出合并 stdout/stderr(与终端里看到的顺序一致)。+ * - `runOnce`:一次性执行,给 Pi 的 bash 用(Pi 自己负责截断与超时提示);+ * - `ShellSession`:给 Claude Code 风格的 Bash 用,跨调用保留当前目录(环境变量不保留,+ * 与 Claude Code 一致),默认 2 分钟、最长 10 分钟超时,输出超过 30000 字符时保留首尾;+ * 支持后台命令,输出写到本机临时文件,可查看增量输出、可结束。+ */+import { spawn, type ChildProcess } from 'node:child_process';+import { randomUUID } from 'node:crypto';+import fs from 'node:fs';+import fsp from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';++export const CC_BASH_DEFAULT_TIMEOUT_MS = 120_000;+export const CC_BASH_MAX_TIMEOUT_MS = 600_000;+export const CC_BASH_MAX_OUTPUT_CHARS = 30_000;+/** 一次性执行的输出上限(超出部分丢弃头部,保留最新输出)。 */+const RUN_MAX_OUTPUT_BYTES = 8 * 1024 * 1024;+const KILL_GRACE_MS = 2_000;+const MAX_BACKGROUND_JOBS = 32;++function shellQuote(value: string): string {+ return `'${value.replace(/'/g, `'\\''`)}'`;+}++/** PATH 上的可执行文件(Windows)。 */+function findOnWindowsPath(name: string, env: NodeJS.ProcessEnv): string | null {+ for (const dir of (env.PATH ?? env.Path ?? '').split(';')) {+ if (!dir) continue;+ const candidate = path.win32.join(dir.replace(/^"|"$/g, ''), name);+ if (fs.existsSync(candidate)) return candidate;+ }+ return null;+}++/**+ * Windows 上的 Git Bash(Agent 的命令都是 bash 写法;与 Claude Code 在 Windows 上的要求一致):+ * CLAUDE_CODE_GIT_BASH_PATH → PATH 上 git.exe 旁的 bin\bash.exe → 常见安装位置。找不到返回 null。+ */+export function findWindowsGitBash(env: NodeJS.ProcessEnv = process.env): string | null {+ const explicit = env.CLAUDE_CODE_GIT_BASH_PATH;+ if (explicit && fs.existsSync(explicit)) return explicit;+ const git = findOnWindowsPath('git.exe', env);+ if (git) {+ const gitDir = path.win32.dirname(git);+ for (const candidate of [+ path.win32.join(path.win32.dirname(gitDir), 'bin', 'bash.exe'),+ path.win32.join(gitDir, 'bash.exe'),+ ]) {+ if (fs.existsSync(candidate)) return candidate;+ }+ }+ const roots = [env.ProgramFiles, env['ProgramFiles(x86)'], env.LOCALAPPDATA && path.win32.join(env.LOCALAPPDATA, 'Programs')]+ .filter((root): root is string => !!root);+ for (const root of roots) {+ const candidate = path.win32.join(root, 'Git', 'bin', 'bash.exe');+ if (fs.existsSync(candidate)) return candidate;+ }+ return null;+}++/** 本机用于执行命令的 shell。 */+export function resolveExecutorShell(): { file: string; args: (script: string) => string[] } {+ if (process.platform === 'win32') {+ const gitBash = findWindowsGitBash();+ if (gitBash) return { file: gitBash, args: (script) => ['-c', script] };+ return { file: process.env.ComSpec || 'cmd.exe', args: (script) => ['/d', '/s', '/c', script] };+ }+ const preferred = process.env.SHELL;+ const file = preferred && /\/(zsh|bash)$/.test(preferred) && fs.existsSync(preferred)+ ? preferred+ : fs.existsSync('/bin/bash') ? '/bin/bash' : '/bin/sh';+ return { file, args: (script) => ['-c', script] };+}++function killTree(child: ChildProcess, signal: NodeJS.Signals): void {+ if (child.pid === undefined || child.exitCode !== null || child.signalCode !== null) return;+ if (process.platform === 'win32') {+ spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore' }).on('error', () => undefined);+ return;+ }+ try {+ process.kill(-child.pid, signal);+ } catch {+ try {+ child.kill(signal);+ } catch {+ // 进程已退出。+ }+ }+}++function terminate(child: ChildProcess): void {+ killTree(child, 'SIGTERM');+ const timer = setTimeout(() => killTree(child, 'SIGKILL'), KILL_GRACE_MS);+ timer.unref?.();+ child.once('exit', () => clearTimeout(timer));+}++export interface RunResult {+ output: Buffer;+ exitCode: number | null;+ timedOut: boolean;+ aborted: boolean;+}++/** 有上限的输出缓冲:超过上限时丢弃最早的内容。 */+class OutputBuffer {+ private chunks: Buffer[] = [];+ private size = 0;+ dropped = 0;++ constructor(private readonly max: number) {}++ push(chunk: Buffer): void {+ this.chunks.push(chunk);+ this.size += chunk.length;+ while (this.size > this.max && this.chunks.length > 1) {+ const first = this.chunks.shift()!;+ this.size -= first.length;+ this.dropped += first.length;+ }+ }++ toBuffer(): Buffer {+ return Buffer.concat(this.chunks);+ }+}++export interface RunOptions {+ cwd: string;+ timeoutMs?: number;+ signal?: AbortSignal;+ env?: NodeJS.ProcessEnv;+ onData?: (chunk: Buffer) => void;+}++/** 执行一条 shell 命令直到结束;超时 / 取消时结束整个进程组。 */+export function runOnce(script: string, opts: RunOptions): Promise<RunResult> {+ return new Promise((resolve, reject) => {+ if (opts.signal?.aborted) {+ resolve({ output: Buffer.alloc(0), exitCode: null, timedOut: false, aborted: true });+ return;+ }+ const shell = resolveExecutorShell();+ let child: ChildProcess;+ try {+ child = spawn(shell.file, shell.args(script), {+ cwd: opts.cwd,+ env: opts.env ?? process.env,+ stdio: ['ignore', 'pipe', 'pipe'],+ detached: process.platform !== 'win32',+ windowsHide: true,+ });+ } catch (error) {+ reject(error);+ return;+ }+ const buffer = new OutputBuffer(RUN_MAX_OUTPUT_BYTES);+ let timedOut = false;+ let aborted = false;+ const onChunk = (chunk: Buffer) => {+ buffer.push(chunk);+ opts.onData?.(chunk);+ };+ child.stdout?.on('data', onChunk);+ child.stderr?.on('data', onChunk);+ const timer = opts.timeoutMs && opts.timeoutMs > 0+ ? setTimeout(() => {+ timedOut = true;+ terminate(child);+ }, opts.timeoutMs)+ : undefined;+ const onAbort = () => {+ aborted = true;+ terminate(child);+ };+ opts.signal?.addEventListener('abort', onAbort, { once: true });+ child.once('error', (error) => {+ if (timer) clearTimeout(timer);+ opts.signal?.removeEventListener('abort', onAbort);+ reject(error);+ });+ child.once('close', (code) => {+ if (timer) clearTimeout(timer);+ opts.signal?.removeEventListener('abort', onAbort);+ resolve({ output: buffer.toBuffer(), exitCode: code, timedOut, aborted });+ });+ });+}++/** 超过上限时保留首尾,中间注明省略了多少行。 */+export function truncateOutput(text: string, max = CC_BASH_MAX_OUTPUT_CHARS): string {+ if (text.length <= max) return text;+ const half = Math.floor(max / 2);+ const head = text.slice(0, half);+ const tail = text.slice(text.length - half);+ const omitted = text.slice(half, text.length - half);+ const omittedLines = omitted.split('\n').length - 1;+ return `${head}\n\n... [${omittedLines} lines truncated] ...\n\n${tail}`;+}++function formatDuration(ms: number): string {+ const seconds = Math.round(ms / 1000);+ const minutes = Math.floor(seconds / 60);+ const rest = seconds % 60;+ return minutes > 0 ? `${minutes}m ${rest}s` : `${rest}s`;+}++export interface ShellCommandResult {+ text: string;+ isError: boolean;+}++interface BackgroundJob {+ id: string;+ command: string;+ outputPath: string;+ child: ChildProcess;+ exitCode: number | null;+ done: boolean;+ killed: boolean;+ readOffset: number;+}++export interface ShellSessionOptions {+ workingDir: string;+ /** 当前目录离开这些目录时重置回工作目录(与 Claude Code 一致)。 */+ isAllowedCwd: (cwd: string) => boolean;+ /** 后台命令输出文件所在目录(本机)。 */+ tempDir?: string;+}++export class ShellSession {+ private cwd: string;+ private readonly jobs = new Map<string, BackgroundJob>();+ private readonly tempDir: string;+ private closed = false;++ constructor(private readonly opts: ShellSessionOptions) {+ this.cwd = opts.workingDir;+ this.tempDir = opts.tempDir ?? path.join(os.tmpdir(), 'cindy-remote-agent');+ }++ getCwd(): string {+ return this.cwd;+ }++ /** 执行一条命令;命令结束后记下它所在的目录,下一条命令从那里开始。 */+ async run(command: string, timeoutMs: number | undefined, signal?: AbortSignal): Promise<ShellCommandResult> {+ if (this.closed) return { text: 'The shell session has ended.', isError: true };+ const timeout = Math.min(Math.max(1, Math.floor(timeoutMs ?? CC_BASH_DEFAULT_TIMEOUT_MS)), CC_BASH_MAX_TIMEOUT_MS);+ await fsp.mkdir(this.tempDir, { recursive: true });+ const cwdFile = path.join(this.tempDir, `cwd-${randomUUID()}`);+ const startCwd = await this.validCwd();+ const script = process.platform === 'win32' && !/bash\.exe$/i.test(resolveExecutorShell().file)+ ? command+ : `cd -- ${shellQuote(startCwd)} && eval ${shellQuote(command)} < /dev/null; __cindy_status=$?; pwd -P >| ${shellQuote(cwdFile)}; exit $__cindy_status`;+ const started = Date.now();+ let result: RunResult;+ try {+ result = await runOnce(script, { cwd: startCwd, timeoutMs: timeout, signal });+ } catch (error) {+ await fsp.rm(cwdFile, { force: true });+ return { text: `Failed to run command: ${(error as Error).message}`, isError: true };+ }+ let resetNote = '';+ try {+ const next = (await fsp.readFile(cwdFile, 'utf8')).trim();+ if (next) {+ if (this.opts.isAllowedCwd(next)) this.cwd = next;+ else {+ this.cwd = this.opts.workingDir;+ resetNote = `\nShell cwd was reset to ${this.opts.workingDir}`;+ }+ }+ } catch {+ // 命令中途退出(exit / 超时 / 取消)时没有写出目录,保持原目录。+ } finally {+ await fsp.rm(cwdFile, { force: true });+ }+ const output = truncateOutput(result.output.toString('utf8').replace(/\s+$/, ''));+ if (result.aborted) {+ return { text: `${output}\n[Command was interrupted]`.trim(), isError: true };+ }+ if (result.timedOut) {+ return { text: `${output}\nCommand timed out after ${formatDuration(Date.now() - started)}`.trim(), isError: true };+ }+ if (result.exitCode !== 0) {+ return { text: `${output}${resetNote}\nExit code ${String(result.exitCode)}`.trim(), isError: true };+ }+ return { text: `${output}${resetNote}`.trim() || '(No output)', isError: false };+ }++ /** 后台执行:立即返回编号与输出文件位置。 */+ async startBackground(command: string): Promise<ShellCommandResult> {+ if (this.closed) return { text: 'The shell session has ended.', isError: true };+ this.pruneJobs();+ if ([...this.jobs.values()].filter((job) => !job.done).length >= MAX_BACKGROUND_JOBS) {+ return { text: `Too many background commands are running (limit ${MAX_BACKGROUND_JOBS}). Stop one with KillShell first.`, isError: true };+ }+ await fsp.mkdir(this.tempDir, { recursive: true });+ const id = `bash_${randomUUID().slice(0, 8)}`;+ const outputPath = path.join(this.tempDir, `${id}.output`);+ const out = fs.openSync(outputPath, 'w');+ const startCwd = await this.validCwd();+ const shell = resolveExecutorShell();+ let child: ChildProcess;+ try {+ child = spawn(shell.file, shell.args(`cd -- ${shellQuote(startCwd)} && eval ${shellQuote(command)} < /dev/null`), {+ cwd: startCwd,+ env: process.env,+ stdio: ['ignore', out, out],+ detached: process.platform !== 'win32',+ windowsHide: true,+ });+ } catch (error) {+ fs.closeSync(out);+ return { text: `Failed to start command: ${(error as Error).message}`, isError: true };+ }+ fs.closeSync(out);+ const job: BackgroundJob = { id, command, outputPath, child, exitCode: null, done: false, killed: false, readOffset: 0 };+ child.once('exit', (code) => {+ job.exitCode = code;+ job.done = true;+ });+ child.once('error', () => {+ job.done = true;+ });+ this.jobs.set(id, job);+ return {+ text: `Command running in background with ID: ${id}. Output is being written to: ${outputPath}. Use BashOutput with this ID to read new output, and KillShell to stop it.`,+ isError: false,+ };+ }++ /** 读取后台命令自上次读取以来的新输出。 */+ async readBackground(id: string, filter?: string): Promise<ShellCommandResult> {+ const job = this.jobs.get(id);+ if (!job) return { text: `No background command found with ID: ${id}`, isError: true };+ let text = '';+ try {+ const handle = await fsp.open(job.outputPath, 'r');+ try {+ const stat = await handle.stat();+ const length = Math.max(0, stat.size - job.readOffset);+ if (length > 0) {+ const buffer = Buffer.alloc(Math.min(length, 4 * 1024 * 1024));+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, job.readOffset);+ job.readOffset += bytesRead;+ text = buffer.subarray(0, bytesRead).toString('utf8');+ }+ } finally {+ await handle.close();+ }+ } catch {+ text = '';+ }+ if (filter) {+ try {+ const pattern = new RegExp(filter);+ text = text.split('\n').filter((line) => pattern.test(line)).join('\n');+ } catch {+ return { text: `Invalid filter regular expression: ${filter}`, isError: true };+ }+ }+ const status = job.killed ? 'killed' : job.done ? 'completed' : 'running';+ const lines = [+ `<status>${status}</status>`,+ ...(job.done && job.exitCode !== null ? [`<exit_code>${job.exitCode}</exit_code>`] : []),+ text ? `<output>\n${truncateOutput(text.replace(/\s+$/, ''))}\n</output>` : '<output>(No new output)</output>',+ ];+ return { text: lines.join('\n'), isError: false };+ }++ killBackground(id: string): ShellCommandResult {+ const job = this.jobs.get(id);+ if (!job) return { text: `No background command found with ID: ${id}`, isError: true };+ if (job.done) return { text: `Background command ${id} has already finished.`, isError: false };+ job.killed = true;+ terminate(job.child);+ return { text: `Successfully killed background command ${id} (${job.command})`, isError: false };+ }++ /** 任务结束:结束所有后台命令并清理输出文件。 */+ async close(): Promise<void> {+ if (this.closed) return;+ this.closed = true;+ for (const job of this.jobs.values()) {+ if (!job.done) terminate(job.child);+ await fsp.rm(job.outputPath, { force: true });+ }+ this.jobs.clear();+ }++ private pruneJobs(): void {+ if (this.jobs.size < MAX_BACKGROUND_JOBS * 2) return;+ for (const [id, job] of this.jobs) {+ if (job.done) {+ void fsp.rm(job.outputPath, { force: true });+ this.jobs.delete(id);+ }+ }+ }++ private async validCwd(): Promise<string> {+ try {+ const stat = await fsp.stat(this.cwd);+ if (stat.isDirectory()) return this.cwd;+ } catch {+ // 目录被删时退回工作目录。+ }+ this.cwd = this.opts.workingDir;+ return this.cwd;+ }+}diff --git a/apps/desktop/src/main/remote-agent/executor/workspace.ts b/apps/desktop/src/main/remote-agent/executor/workspace.tsnew file mode 100644index 0000000000..9944050a0a--- /dev/null+++ b/apps/desktop/src/main/remote-agent/executor/workspace.ts@@ -0,0 +1,148 @@+/**+ * 远程 Agent 执行器的工作区(控制端)。+ *+ * Agent 跑在另一台电脑上,它对本机文件和命令的每个请求都在这里落地。路径一律按本机路径+ * 解析:相对路径以任务工作目录为基准。Agent 所在电脑上的影子目录(只放项目说明类小文件,+ * 让 Agent 照常加载项目说明与 Skill)在这里映射回本机真实目录,模型即使用了影子路径也落在+ * 本机项目里。+ */+import fs from 'node:fs';+import path from 'node:path';++import { isSensitiveCredentialPath } from '@cindy/maker-core';++export interface ExecutorPathAlias {+ /** Agent 所在电脑上的影子目录(绝对路径,按该电脑的路径写法)。 */+ from: string;+ /** 对应的本机真实目录。 */+ to: string;+}++export interface ExecutorWorkspaceRoots {+ /** 任务工作目录(本机绝对路径)。 */+ workingDir: string;+ /** 额外允许的目录(任务的附加目录)。 */+ extraDirs?: readonly string[];+ /** 影子目录映射。 */+ aliases?: readonly ExecutorPathAlias[];+}++export class ExecutorPathError extends Error {+ constructor(message: string) {+ super(message);+ this.name = 'ExecutorPathError';+ }+}++/** 取一个路径的真实路径;不存在时按最近的已存在祖先解析,再拼回剩余部分。 */+export function realPathOrAncestor(target: string): string {+ let current = path.resolve(target);+ const rest: string[] = [];+ for (;;) {+ try {+ const real = fs.realpathSync.native(current);+ return rest.length ? path.join(real, ...rest.reverse()) : real;+ } catch {+ const parent = path.dirname(current);+ if (parent === current) return path.resolve(target);+ rest.push(path.basename(current));+ current = parent;+ }+ }+}++function isInside(child: string, parent: string): boolean {+ const relative = path.relative(parent, child);+ return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative));+}++/** 影子目录前缀匹配:只认完整路径段(`/a/b` 不匹配 `/a/bc`),不区分分隔符写法。 */+function stripAliasPrefix(input: string, from: string): string | null {+ const normalizedInput = input.replace(/\\/g, '/');+ const normalizedFrom = from.replace(/\\/g, '/').replace(/\/+$/, '');+ if (!normalizedFrom) return null;+ if (normalizedInput === normalizedFrom) return '';+ if (normalizedInput.startsWith(`${normalizedFrom}/`)) return normalizedInput.slice(normalizedFrom.length + 1);+ return null;+}++export class ExecutorWorkspace {+ readonly workingDir: string;+ private roots: string[];+ private extraDirs: string[];+ private aliases: ExecutorPathAlias[];++ constructor(roots: ExecutorWorkspaceRoots) {+ if (!path.isAbsolute(roots.workingDir)) throw new ExecutorPathError('working directory must be absolute');+ this.workingDir = path.resolve(roots.workingDir);+ this.extraDirs = [];+ this.roots = [];+ this.aliases = [];+ this.setAliases(roots.aliases ?? []);+ this.setExtraDirs(roots.extraDirs ?? []);+ }++ /** Agent 启动后才知道它那边的影子目录,届时设置。 */+ setAliases(aliases: readonly ExecutorPathAlias[]): void {+ this.aliases = aliases.filter((alias) => alias.from && path.isAbsolute(alias.to));+ }++ /** 任务运行中附加目录变化时更新。 */+ setExtraDirs(extraDirs: readonly string[]): void {+ this.extraDirs = extraDirs.filter((dir) => path.isAbsolute(dir)).map((dir) => path.resolve(dir));+ this.roots = [this.workingDir, ...this.extraDirs].map((dir) => realPathOrAncestor(dir));+ }++ /** 工作目录与附加目录(本机路径,未解析符号链接)。 */+ allRoots(): string[] {+ return [this.workingDir, ...this.extraDirs];+ }++ /** 影子路径映射回本机路径;不是影子路径时原样返回。 */+ mapAlias(input: string): string {+ for (const alias of this.aliases) {+ const rest = stripAliasPrefix(input, alias.from);+ if (rest !== null) return rest ? path.join(alias.to, ...rest.split('/')) : alias.to;+ }+ return input;+ }++ /** 命令文本里出现的影子目录前缀替换成本机目录(按完整路径段)。 */+ mapCommand(command: string): string {+ let next = command;+ for (const alias of this.aliases) {+ const from = alias.from.replace(/\/+$/, '');+ if (!from) continue;+ // 只在后面是路径边界时替换,避免误伤更长的同前缀路径。+ const pattern = new RegExp(`${from.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?=$|[/\\s'"\`;:|&)<>])`, 'g');+ next = next.replace(pattern, () => alias.to);+ }+ return next;+ }++ /** 把 Agent 给的路径解析成本机绝对路径(相对路径以 baseDir / 工作目录为基准)。 */+ resolve(input: string, baseDir = this.workingDir): string {+ if (typeof input !== 'string' || input.length === 0 || input.includes('\0')) {+ throw new ExecutorPathError('path is empty or invalid');+ }+ const trimmed = input.startsWith('@') ? input.slice(1) : input;+ const expanded = trimmed === '~' || trimmed.startsWith('~/')+ ? path.join(process.env.HOME ?? '', trimmed.slice(1))+ : trimmed;+ return path.resolve(this.mapAlias(baseDir), this.mapAlias(expanded));+ }++ /** 真实路径是否落在工作目录或附加目录内(防符号链接与 `..` 借道)。 */+ contains(absolutePath: string): boolean {+ const real = realPathOrAncestor(absolutePath);+ return this.roots.some((root) => isInside(real, root));+ }++ /**+ * 凭证类路径(与本机 harness 权限适配器同一份规则)。本机任务对这类路径是「每次都问」,+ * 执行器同样要求本机确认过才放行。+ */+ isSensitive(absolutePath: string): boolean {+ return isSensitiveCredentialPath(absolutePath) || isSensitiveCredentialPath(realPathOrAncestor(absolutePath));+ }+}diff --git a/apps/desktop/src/main/remote-agent/host/runHost.ts b/apps/desktop/src/main/remote-agent/host/runHost.tsnew file mode 100644index 0000000000..b39fd7c25f--- /dev/null+++ b/apps/desktop/src/main/remote-agent/host/runHost.ts@@ -0,0 +1,758 @@+/**+ * 远程 Agent 运行服务(被控端:提供 Agent 登录、订阅与供应商的电脑)。+ *+ * 同账号另一台电脑(控制端)上的任务选择「Agent 在这台电脑上运行」时,经 `maker:remote-agent:v1`+ * 打到这里:本机用自己的 Agent 程序、登录与供应商启动 Agent,Agent 的文件、命令与 Cindy 工具+ * 请求经本次任务的隧道变成反向请求,等控制端在它那台电脑上执行后回包。+ *+ * 不变量:+ * - 只为通过准入的同账号控制端服务(远程控制打开、未撤销、账号未切换),关闭或撤销后最迟一个+ * 巡检周期内结束全部任务;+ * - 本机从不主动向控制端发起请求,一切经控制端拉取的事件流交付;控制端长时间不拉取视为离开;+ * - 本机的地址、凭证与供应商配置不进事件流:事件只含 Agent 输出与反向请求;+ * - open / call / reply / push / close 都按各自的 id 去重,poll 按游标幂等;+ * - 同一控制端的全部任务共用一个 poll,任务再多也只占设备互联的一个在途请求。+ */+import { createHash, randomUUID } from 'node:crypto';+import fsp from 'node:fs/promises';+import path from 'node:path';+import { promisify } from 'node:util';+import { gunzip } from 'node:zlib';++import {+ REMOTE_AGENT_MAX_PAYLOAD_BYTES,+ REMOTE_AGENT_MAX_RUNS_PER_CONTROLLER,+ REMOTE_AGENT_METHODS,+ REMOTE_AGENT_POLL_MAX_BYTES,+ REMOTE_AGENT_READ_MAX_BYTES,+ REMOTE_AGENT_READ_WAIT_MS,+ REMOTE_AGENT_UPLOAD_CHUNK_BYTES,+ REMOTE_AGENT_VERSION,+ parseRemoteAgentReply,+ parseRemoteAgentRequest,+ type RemoteAgentCaps,+ type RemoteAgentErrorInfo,+ type RemoteAgentKind,+ type RemoteAgentMethod,+ type RemoteAgentPayload,+ type RemoteAgentPollResult,+ type RemoteAgentReply,+ type RemoteAgentReverseRequest,+ type RemoteAgentTeardownReason,+} from '@cindy/device-link';+import type { AgentSessionHandle, InteractionRequest } from '@cindy/maker-core';++import { EventLog, waitForAny } from '../eventLog';+import {+ MAX_ANCESTOR_LEVELS,+ decodeOpenPayload,+ decodeSendOptions,+ decodeUserMessage,+ type RemoteAgentOpenPayload,+ type RemoteAgentWireStartOptions,+ type RemoteAgentWireWorkspace,+} from '../wire';+import { createRunTunnel, type RunTunnel, type TunnelHttpRequest, type TunnelHttpResponse } from './tunnel';++const gunzipAsync = promisify(gunzip);++/** 控制端不读时最多替它缓存的未读事件字节;超出说明它已跟不上或离开,结束任务。 */+export const REMOTE_AGENT_HOST_UNREAD_BYTES = 64 * 1024 * 1024;+/** 运行中的任务超过这么久没有被读取,视为控制端已离开。 */+export const REMOTE_AGENT_HOST_IDLE_MS = 3 * 60_000;+/** 结束后保留一段时间供控制端读完收尾事件。 */+export const REMOTE_AGENT_HOST_RETAIN_MS = 60_000;+const UPLOAD_IDLE_MS = 2 * 60_000;+const MAX_STAGED_BYTES_PER_CONTROLLER = REMOTE_AGENT_MAX_PAYLOAD_BYTES * 2;+const MAX_DECOMPRESSED_BYTES = 128 * 1024 * 1024;+const SWEEP_INTERVAL_MS = 5_000;+const STATE_INTERVAL_MS = 2_000;+const MAX_REMEMBERED_CALLS = 256;++export interface HostedStartInput {+ kind: RemoteAgentKind;+ /** 本机侧的任务 id(由控制端与任务 id 派生,恢复同一任务时不变)。 */+ hostSessionId: string;+ /** 影子目录:只放项目说明类文件,作为 Agent 进程的工作目录。 */+ shadowDir: string;+ /** 影子目录按控制端真实路径逐级镜像的根(上级目录里的说明文件放在对应的上级)。 */+ mirrorRoot: string;+ /** 控制端的个人说明(写进给 Agent 的环境说明)。 */+ personalInstructions?: string;+ options: RemoteAgentWireStartOptions;+ workspace: RemoteAgentWireWorkspace;+ tunnel: { url: string; token: string };+ mcpServers: string[];+ onInvalidResumeSession?: (expectedSdkSessionId: string) => Promise<boolean>;+}++export interface RemoteAgentHostDeps {+ isAgentAvailable(kind: RemoteAgentKind): boolean;+ startHosted(input: HostedStartInput): Promise<AgentSessionHandle>;+ /** 本机仍允许该控制端远程控制(总开关打开且未撤销)。 */+ isControllerAuthorized(controller: string): boolean;+ captureOwner(): unknown;+ isOwnerCurrent(owner: unknown): boolean;+ /** 本机存放影子目录与附件的根目录。 */+ runsRoot: string;+ now?: () => number;+ log?: {+ info(message: string, meta?: Record<string, unknown>): void;+ warn(message: string, meta?: Record<string, unknown>): void;+ };+}++interface Upload {+ controller: string;+ chunks: Array<Buffer | undefined>;+ bytes: number;+ touchedAt: number;+}++interface PendingReverse {+ resolve(reply: RemoteAgentReply): void;+ reject(error: Error): void;+}++interface Run {+ id: string;+ controller: string;+ owner: unknown;+ kind: RemoteAgentKind;+ log: EventLog;+ lastReadAt: number;+ closedAt?: number;+ closing: boolean;+ handle?: AgentSessionHandle;+ tunnel?: RunTunnel;+ attachmentsDir: string;+ pending: Map<string, PendingReverse>;+ calls: Map<string, 'running' | 'done'>;+ pushSeq: Set<number>;+ /** 拼接中的分段 WebSocket 消息(按连接)。 */+ pushParts: Map<string, string>;+ lastState?: string;+ stateTimer?: ReturnType<typeof setInterval>;+}++/** 控制端真实路径 → 影子目录里逐级镜像的目录名(去掉本机文件系统不允许的字符)。 */+export function mirrorSegments(realPath: string): string[] {+ const parts = realPath.split(/[\\/]+/).filter(Boolean);+ return parts.slice(-(MAX_ANCESTOR_LEVELS + 1)).map((part) => {+ const cleaned = part+ .replace(/^([A-Za-z]):$/, '$1')+ // eslint-disable-next-line no-control-regex -- 控制字符是显式清洗目标+ .replace(/[<>:"|?*\u0000-\u001f]/g, '_')+ .replace(/[. ]+$/, '')+ .slice(0, 64);+ return cleaned && cleaned !== '.' && cleaned !== '..' ? cleaned : '_';+ });+}++/** 个人权限规则并入项目 local 设置(保留项目里已有的规则)。 */+async function mergeLocalPermissions(+ file: string,+ personal: { allow?: string[]; deny?: string[]; ask?: string[] },+): Promise<void> {+ let current: { permissions?: Record<string, unknown> } = {};+ try {+ current = JSON.parse(await fsp.readFile(file, 'utf8')) as typeof current;+ } catch {+ current = {};+ }+ const merged: Record<string, string[]> = {};+ for (const key of ['allow', 'deny', 'ask'] as const) {+ const existing = Array.isArray(current.permissions?.[key])+ ? (current.permissions![key] as unknown[]).filter((item): item is string => typeof item === 'string')+ : [];+ const rules = [...new Set([...existing, ...(personal[key] ?? [])])];+ if (rules.length) merged[key] = rules;+ }+ await fsp.mkdir(path.dirname(file), { recursive: true });+ await fsp.writeFile(file, JSON.stringify({ permissions: merged }, null, 2));+}++function fail(code: string, message: string): never {+ throw new Error(`[${code}] ${message}`);+}++export function remoteAgentErrorInfo(error: unknown): RemoteAgentErrorInfo {+ const err = error instanceof Error ? error : new Error(String(error));+ const rawCode = (err as unknown as { code?: unknown }).code;+ const code = /^\[([A-Z][A-Z0-9_]+)\]/.exec(err.message)?.[1]+ ?? (typeof rawCode === 'string' && rawCode ? rawCode : 'AGENT_ERROR');+ return { code: code.slice(0, 128), message: err.message.slice(0, 2048), name: err.name };+}++/** 本机侧的任务 id:控制端设备 + 控制端任务 id 派生,避免与本机自己的任务撞 id。 */+export function hostSessionIdFor(controller: string, sessionId: string): string {+ const hex = createHash('sha256').update(`${controller}\0${sessionId}`).digest('hex');+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-4${hex.slice(13, 16)}-a${hex.slice(17, 20)}-${hex.slice(20, 32)}`;+}++function safeCall<T>(fn: (() => T) | undefined): T | undefined {+ if (!fn) return undefined;+ try {+ return fn();+ } catch {+ return undefined;+ }+}++/** 控制端镜像同步读取的会话状态。 */+export function snapshotHandleState(handle: AgentSessionHandle): Record<string, unknown> {+ const state: Record<string, unknown> = {+ id: handle.id,+ model: handle.model,+ usage: safeCall(() => handle.getUsageSnapshot()),+ turnRunning: safeCall(handle.isTurnRunning?.bind(handle)),+ preparing: safeCall(handle.isPreparingUserTurn?.bind(handle)),+ currentTurnId: safeCall(handle.getCurrentTurnId?.bind(handle)),+ planMode: safeCall(handle.getPlanMode?.bind(handle)),+ executionPlanMode: safeCall(handle.getExecutionPlanMode?.bind(handle)),+ fastMode: safeCall(handle.getFastMode?.bind(handle)),+ effort: safeCall(handle.getEffort?.bind(handle)),+ backgroundTasks: safeCall(handle.listBackgroundTasks?.bind(handle)),+ pendingWake: safeCall(handle.countPendingWakeContinuations?.bind(handle)),+ requestSessionId: handle.requestSessionId,+ codexThreadModelProviderId: handle.codexThreadModelProviderId,+ codexThreadMayHaveRollout: handle.codexThreadMayHaveRollout,+ disabledSkillPaths: handle.disabledSkillPaths,+ };+ for (const key of Object.keys(state)) if (state[key] === undefined) delete state[key];+ return JSON.parse(JSON.stringify(state)) as Record<string, unknown>;+}++/** 启动结果里给控制端的会话描述(静态部分 + 支持哪些可选方法)。 */+function describeHandle(handle: AgentSessionHandle, shadowDir: string, mirrorRoot: string): Record<string, unknown> {+ const methods = REMOTE_AGENT_METHODS.filter((method) => typeof (handle as unknown as Record<string, unknown>)[method] === 'function');+ return {+ id: handle.id,+ agentKind: handle.agentKind,+ model: handle.model,+ shadowDir,+ mirrorRoot,+ methods,+ ...(handle.requestSessionId ? { requestSessionId: handle.requestSessionId } : {}),+ ...(handle.codexProxyActive !== undefined ? { codexProxyActive: handle.codexProxyActive } : {}),+ ...(handle.codexHostKey ? { codexHostKey: handle.codexHostKey } : {}),+ ...(handle.codexCindyRemoteCompactionCompatible !== undefined+ ? { codexCindyRemoteCompactionCompatible: handle.codexCindyRemoteCompactionCompatible }+ : {}),+ ...(handle.codexProductPromptDelivery ? { codexProductPromptDelivery: handle.codexProductPromptDelivery } : {}),+ state: snapshotHandleState(handle),+ };+}++export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {+ const now = deps.now ?? Date.now;+ const runs = new Map<string, Run>();+ const uploads = new Map<string, Upload>();+ let sweepTimer: ReturnType<typeof setInterval> | null = null;+ const key = (controller: string, id: string) => `${controller}\0${id}`;++ function ensureSweep(): void {+ if (sweepTimer) return;+ sweepTimer = setInterval(sweep, SWEEP_INTERVAL_MS);+ (sweepTimer as { unref?: () => void }).unref?.();+ }++ function stopSweepIfIdle(): void {+ if (sweepTimer && runs.size === 0 && uploads.size === 0) {+ clearInterval(sweepTimer);+ sweepTimer = null;+ }+ }++ function sweep(): void {+ const t = now();+ for (const [uploadKey, upload] of uploads) {+ if (t - upload.touchedAt > UPLOAD_IDLE_MS) uploads.delete(uploadKey);+ }+ for (const run of runs.values()) {+ if (run.closedAt !== undefined) {+ if (t - run.closedAt > REMOTE_AGENT_HOST_RETAIN_MS) void disposeRun(run);+ continue;+ }+ if (!deps.isControllerAuthorized(run.controller)) {+ void finishRun(run, 'access-revoked', 'navigation');+ } else if (!deps.isOwnerCurrent(run.owner)) {+ void finishRun(run, 'account-changed', 'account-boundary');+ } else if (t - run.lastReadAt > REMOTE_AGENT_HOST_IDLE_MS) {+ void finishRun(run, 'controller-gone', 'navigation');+ }+ }+ stopSweepIfIdle();+ }++ function stagedBytes(controller: string): number {+ let total = 0;+ for (const upload of uploads.values()) if (upload.controller === controller) total += upload.bytes;+ return total;+ }++ async function resolvePayload(controller: string, payload: RemoteAgentPayload): Promise<unknown> {+ if ('json' in payload) return payload.json;+ const uploadKey = key(controller, payload.uploadId);+ const upload = uploads.get(uploadKey);+ if (!upload || upload.chunks.length !== payload.chunks) fail('REMOTE_AGENT_EXPIRED', 'upload is missing or expired');+ for (let index = 0; index < payload.chunks; index += 1) {+ if (!upload.chunks[index]) fail('REMOTE_AGENT_EXPIRED', 'upload is incomplete');+ }+ const gz = Buffer.concat(upload.chunks as Buffer[]);+ if (gz.length !== payload.bytes) fail('REMOTE_AGENT_INVALID', 'upload size mismatch');+ uploads.delete(uploadKey);+ const raw = await gunzipAsync(gz, { maxOutputLength: MAX_DECOMPRESSED_BYTES });+ return JSON.parse(raw.toString('utf8')) as unknown;+ }++ function append(run: Run, item: unknown): void {+ if (run.log.append(item)) return;+ if (!run.closing) {+ deps.log?.warn('remote agent event log overflow; ending run', { runId: run.id });+ void finishRun(run, 'overflow', 'navigation');+ }+ }++ function emitState(run: Run): void {+ if (!run.handle || run.closing) return;+ const state = snapshotHandleState(run.handle);+ const serialized = JSON.stringify(state);+ if (serialized === run.lastState) return;+ run.lastState = serialized;+ append(run, { t: 'state', state });+ }++ /** 经事件流向控制端发一个反向请求,等它回包;signal 中止时通知控制端放弃执行。 */+ function reverse(run: Run, request: RemoteAgentReverseRequest, signal?: AbortSignal): Promise<RemoteAgentReply> {+ if (run.closing) return Promise.reject(new Error('[REMOTE_AGENT_EXPIRED] task has ended'));+ if (signal?.aborted) return Promise.reject(new Error('aborted'));+ const requestId = randomUUID();+ return new Promise<RemoteAgentReply>((resolve, reject) => {+ const onAbort = () => {+ if (!run.pending.delete(requestId)) return;+ append(run, { t: 'cancel', requestId });+ reject(new Error('aborted'));+ };+ run.pending.set(requestId, {+ resolve: (reply) => {+ signal?.removeEventListener('abort', onAbort);+ resolve(reply);+ },+ reject: (error) => {+ signal?.removeEventListener('abort', onAbort);+ reject(error);+ },+ });+ signal?.addEventListener('abort', onAbort, { once: true });+ append(run, { t: 'request', requestId, request });+ });+ }++ async function reverseHttp(run: Run, request: TunnelHttpRequest, signal: AbortSignal): Promise<TunnelHttpResponse> {+ const reply = await reverse(run, {+ type: 'http',+ method: request.method,+ path: request.path,+ headers: request.headers,+ ...(request.body ? { body: request.body.toString('base64') } : {}),+ }, signal);+ if (reply.type === 'http') {+ return {+ status: reply.status,+ headers: reply.headers,+ ...(reply.body ? { body: Buffer.from(reply.body, 'base64') } : {}),+ };+ }+ if (reply.type === 'error') {+ return {+ status: 502,+ headers: [['content-type', 'application/json']],+ body: Buffer.from(JSON.stringify({ error: reply.error })),+ };+ }+ return { status: 502, headers: [] };+ }++ async function writeAttachment(run: Run, data: Buffer, ext: string): Promise<string> {+ await fsp.mkdir(run.attachmentsDir, { recursive: true });+ const file = path.join(run.attachmentsDir, `${createHash('sha256').update(data).digest('hex').slice(0, 24)}.${ext}`);+ await fsp.writeFile(file, data);+ return file;+ }++ /**+ * 影子目录:`<会话根>/fs/<控制端真实路径逐级镜像>`。逐级镜像让上级目录里的说明文件落在对应的+ * 上级目录,Agent 照本机方式沿目录向上加载;路径对同一任务固定(恢复会话依赖工作目录不变)。+ * 个人说明放在会话根(最外层,最先加载、优先级最低)。每次打开都按控制端当前内容重建。+ */+ async function prepareShadow(+ controller: string,+ payload: RemoteAgentOpenPayload,+ hostSessionId: string,+ ): Promise<{ shadowDir: string; mirrorRoot: string }> {+ const controllerDir = createHash('sha256').update(controller).digest('hex').slice(0, 16);+ const sessionRoot = path.join(deps.runsRoot, 'workspaces', controllerDir, hostSessionId);+ const mirrorRoot = path.join(sessionRoot, 'fs');+ const segments = mirrorSegments(payload.workspace.workingDir);+ const shadowDir = path.join(mirrorRoot, ...segments);+ await fsp.rm(sessionRoot, { recursive: true, force: true });+ await fsp.mkdir(shadowDir, { recursive: true });+ const inside = (target: string, root: string) => target.startsWith(`${root}${path.sep}`);+ const writeNew = async (target: string, data: Buffer) => {+ await fsp.mkdir(path.dirname(target), { recursive: true });+ await fsp.writeFile(target, data, { flag: 'wx' }).catch((error: NodeJS.ErrnoException) => {+ if (error.code !== 'EEXIST') throw error;+ });+ };+ for (const file of payload.projectFiles) {+ const target = path.join(shadowDir, ...file.path.split('/'));+ if (!inside(target, shadowDir)) continue;+ await fsp.mkdir(path.dirname(target), { recursive: true });+ await fsp.writeFile(target, Buffer.from(file.data, 'base64'));+ }+ for (const file of payload.ancestorFiles) {+ if (file.up > segments.length - 1) continue;+ let dir = shadowDir;+ for (let level = 0; level < file.up; level += 1) dir = path.dirname(dir);+ if (!inside(dir, mirrorRoot)) continue;+ await writeNew(path.join(dir, file.name), Buffer.from(file.data, 'base64'));+ }+ const { personal } = payload;+ if (personal.memory) await writeNew(path.join(sessionRoot, 'CLAUDE.md'), Buffer.from(personal.memory, 'utf8'));+ // 项目里已有同名文件时以项目为准(只写不存在的)。+ for (const file of personal.files) {+ const target = path.join(shadowDir, ...file.path.split('/'));+ if (!inside(target, shadowDir)) continue;+ await writeNew(target, Buffer.from(file.data, 'base64'));+ }+ if (personal.permissions) await mergeLocalPermissions(path.join(shadowDir, '.claude', 'settings.local.json'), personal.permissions);+ return { shadowDir, mirrorRoot };+ }++ async function startRun(run: Run, payload: RemoteAgentOpenPayload): Promise<void> {+ try {+ const hostSessionId = hostSessionIdFor(run.controller, payload.sessionId);+ const { shadowDir, mirrorRoot } = await prepareShadow(run.controller, payload, hostSessionId);+ const tunnel = await createRunTunnel({+ http: (request, signal) => reverseHttp(run, request, signal),+ wsOpen: (connId, wsPath) => append(run, { t: 'ws', connId, kind: 'open', path: wsPath }),+ wsMessage: (connId, data) => append(run, { t: 'ws', connId, kind: 'message', data }),+ wsClose: (connId) => append(run, { t: 'ws', connId, kind: 'close' }),+ });+ run.tunnel = tunnel;+ if (run.closing) return;+ const handle = await deps.startHosted({+ kind: run.kind,+ hostSessionId,+ shadowDir,+ mirrorRoot,+ ...(payload.personal.instructions ? { personalInstructions: payload.personal.instructions } : {}),+ options: payload.options,+ workspace: payload.workspace,+ tunnel: { url: tunnel.url, token: tunnel.token },+ mcpServers: payload.mcpServers,+ ...(payload.options.invalidResumeCallback+ ? {+ onInvalidResumeSession: async (expected: string) => {+ const reply = await reverse(run, { type: 'callback', name: 'onInvalidResumeSession', args: [expected] });+ return reply.type === 'callback' && reply.value === true;+ },+ }+ : {}),+ });+ if (run.closing) {+ await handle.close({ reason: 'navigation' }).catch(() => undefined);+ return;+ }+ run.handle = handle;+ handle.setInteractionResolver(async (request: InteractionRequest) => {+ const reply = await reverse(run, { type: 'interaction', request });+ if (reply.type === 'interaction') return reply.result as Awaited<ReturnType<Parameters<AgentSessionHandle['setInteractionResolver']>[0]>>;+ throw new Error(reply.type === 'error' ? reply.error.message : 'interaction failed');+ });+ append(run, { t: 'started', handle: describeHandle(handle, shadowDir, mirrorRoot) });+ run.lastState = JSON.stringify(snapshotHandleState(handle));+ run.stateTimer = setInterval(() => emitState(run), STATE_INTERVAL_MS);+ (run.stateTimer as { unref?: () => void }).unref?.();+ void pumpEvents(run, handle);+ } catch (error) {+ append(run, { t: 'start-failed', error: remoteAgentErrorInfo(error) });+ await finishRun(run, 'start-failed', 'navigation', false);+ }+ }++ async function pumpEvents(run: Run, handle: AgentSessionHandle): Promise<void> {+ try {+ for await (const event of handle.events()) {+ if (run.closing) break;+ append(run, { t: 'event', event });+ emitState(run);+ }+ await finishRun(run, 'ended', 'navigation', false);+ } catch (error) {+ append(run, { t: 'closed', reason: 'error', error: remoteAgentErrorInfo(error) });+ await finishRun(run, 'error', 'navigation', false, true);+ }+ }++ /** 结束任务:关掉 Agent 与隧道,拒掉未完成的反向请求,写收尾事件。 */+ async function finishRun(+ run: Run,+ reason: string,+ teardown: RemoteAgentTeardownReason,+ closeHandle = true,+ skipClosedEvent = false,+ mode: 'close' | 'detach' = 'close',+ ): Promise<void> {+ if (run.closing) return;+ run.closing = true;+ if (run.stateTimer) clearInterval(run.stateTimer);+ for (const pending of run.pending.values()) pending.reject(new Error('[REMOTE_AGENT_EXPIRED] task has ended'));+ run.pending.clear();+ if (closeHandle && run.handle) {+ try {+ if (mode === 'detach' && run.handle.detach) await run.handle.detach({ reason: teardown });+ else await run.handle.close({ reason: teardown });+ } catch (error) {+ deps.log?.warn('remote agent close failed', { runId: run.id, error: String(error) });+ }+ }+ await run.tunnel?.close().catch(() => undefined);+ // 收尾事件绕过 closing 判断直接写入。+ if (!skipClosedEvent) run.log.append({ t: 'closed', reason });+ run.log.end();+ run.closedAt = now();+ deps.log?.info('remote agent run finished', { runId: run.id, reason });+ }++ async function disposeRun(run: Run): Promise<void> {+ runs.delete(key(run.controller, run.id));+ await fsp.rm(run.attachmentsDir, { recursive: true, force: true }).catch(() => undefined);+ stopSweepIfIdle();+ }++ function requireRun(controller: string, runId: string): Run {+ const run = runs.get(key(controller, runId));+ if (!run) fail('REMOTE_AGENT_NOT_FOUND', 'task is not running on this computer');+ return run;+ }++ async function call(run: Run, callId: string, method: RemoteAgentMethod, payload: RemoteAgentPayload): Promise<void> {+ const handle = run.handle;+ try {+ if (!handle) fail('REMOTE_AGENT_UNAVAILABLE', 'agent has not started');+ const raw = await resolvePayload(run.controller, payload);+ const args = Array.isArray(raw) ? raw : [];+ const target = (handle as unknown as Record<string, unknown>)[method];+ if (typeof target !== 'function') fail('REMOTE_AGENT_UNSUPPORTED', `${method} is not supported by this agent`);+ let callArgs: unknown[] = args;+ if (method === 'send' || method === 'steer') {+ const message = await decodeUserMessage(args[0], (data, ext) => writeAttachment(run, data, ext));+ const opts = await decodeSendOptions(args[1], {+ onTranscriptUserEntry: async (entryId) => {+ await reverse(run, { type: 'callback', name: 'onTranscriptUserEntry', args: [callId, entryId] }).catch(() => undefined);+ },+ onInteractionStateChange: (state) => {+ void reverse(run, { type: 'callback', name: 'onInteractionStateChange', args: [callId, state] }).catch(() => undefined);+ },+ writeAttachment: (data, ext) => writeAttachment(run, data, ext),+ });+ callArgs = [message, opts];+ }+ const value = await (target as (...a: unknown[]) => unknown).apply(handle, callArgs);+ append(run, { t: 'result', callId, ok: true, ...(value !== undefined ? { value: JSON.parse(JSON.stringify(value)) } : {}) });+ } catch (error) {+ append(run, { t: 'result', callId, ok: false, error: remoteAgentErrorInfo(error) });+ } finally {+ run.calls.set(callId, 'done');+ if (run.calls.size > MAX_REMEMBERED_CALLS) {+ for (const [id, status] of run.calls) {+ if (run.calls.size <= MAX_REMEMBERED_CALLS) break;+ if (status === 'done') run.calls.delete(id);+ }+ }+ emitState(run);+ }+ }++ /** 轮流决定 poll 从哪个任务开始取数据,避免积压多的任务一直挤占前面的额度。 */+ let pollRotation = 0;++ async function poll(+ controller: string,+ wanted: ReadonlyArray<{ runId: string; cursor: number }>,+ waitMs: number,+ signal?: AbortSignal,+ ): Promise<RemoteAgentPollResult> {+ const touch = () => {+ const t = now();+ for (const { runId } of wanted) {+ const run = runs.get(key(controller, runId));+ if (run) run.lastReadAt = t;+ }+ };+ const live = () => wanted.flatMap(({ runId, cursor }) => {+ const run = runs.get(key(controller, runId));+ return run && run.log.isValidCursor(cursor) ? [{ run, cursor }] : [];+ });+ touch();+ const initial = live();+ const anyReady = initial.length < wanted.length || initial.some(({ run, cursor }) => run.log.isReady(cursor));+ if (!anyReady && waitMs > 0) await waitForAny(initial.map(({ run }) => run.log), waitMs, signal);+ touch();+ const out: RemoteAgentPollResult = { runs: [] };+ let budget = REMOTE_AGENT_POLL_MAX_BYTES;+ const start = wanted.length ? pollRotation++ % wanted.length : 0;+ for (let index = 0; index < wanted.length; index += 1) {+ const { runId, cursor } = wanted[(start + index) % wanted.length];+ const run = runs.get(key(controller, runId));+ // 不存在或游标超出已写范围(对端状态与本机不一致):控制端按任务丢失处理。+ if (!run || !run.log.isValidCursor(cursor)) {+ out.runs.push({ runId, cursor, missing: true });+ continue;+ }+ const result = run.log.readNow(cursor, Math.min(REMOTE_AGENT_READ_MAX_BYTES, budget));+ if (!result.data?.length && !result.done) continue;+ budget -= result.data?.length ?? 0;+ out.runs.push({+ runId,+ ...(result.from !== cursor ? { from: result.from } : {}),+ cursor: result.cursor,+ ...(result.data?.length ? { data: result.data.toString('base64') } : {}),+ ...(result.done ? { done: true as const } : {}),+ });+ }+ return out;+ }++ async function handle(controller: string, raw: unknown, signal?: AbortSignal): Promise<unknown> {+ const request = parseRemoteAgentRequest(raw);+ if (!deps.isControllerAuthorized(controller)) fail('REMOTE_AGENT_UNAVAILABLE', 'remote control is not allowed');+ switch (request.op) {+ case 'caps': {+ const caps: RemoteAgentCaps = {+ version: REMOTE_AGENT_VERSION,+ agents: (['claude-code', 'codex', 'pi'] as const).map((kind) => ({ kind, available: deps.isAgentAvailable(kind) })),+ maxRuns: REMOTE_AGENT_MAX_RUNS_PER_CONTROLLER,+ uploadChunkBytes: REMOTE_AGENT_UPLOAD_CHUNK_BYTES,+ maxPayloadBytes: REMOTE_AGENT_MAX_PAYLOAD_BYTES,+ };+ return caps;+ }+ case 'upload': {+ const uploadKey = key(controller, request.uploadId);+ let upload = uploads.get(uploadKey);+ const chunk = Buffer.from(request.data, 'base64');+ if (!upload) {+ if (stagedBytes(controller) + chunk.length > MAX_STAGED_BYTES_PER_CONTROLLER) fail('REMOTE_AGENT_BUSY', 'too much staged data');+ upload = { controller, chunks: [], bytes: 0, touchedAt: now() };+ uploads.set(uploadKey, upload);+ ensureSweep();+ }+ if (!upload.chunks[request.index]) {+ upload.chunks[request.index] = chunk;+ upload.bytes += chunk.length;+ }+ upload.touchedAt = now();+ return {};+ }+ case 'open': {+ const existing = runs.get(key(controller, request.runId));+ if (existing) return {};+ if (!deps.isAgentAvailable(request.agentKind)) fail('REMOTE_AGENT_UNSUPPORTED', `${request.agentKind} is not available on this computer`);+ const active = [...runs.values()].filter((run) => run.controller === controller && run.closedAt === undefined).length;+ if (active >= REMOTE_AGENT_MAX_RUNS_PER_CONTROLLER) fail('REMOTE_AGENT_BUSY', 'too many tasks are running from this computer');+ const payload = decodeOpenPayload(await resolvePayload(controller, request.payload));+ const run: Run = {+ id: request.runId,+ controller,+ owner: deps.captureOwner(),+ kind: request.agentKind,+ log: new EventLog(REMOTE_AGENT_HOST_UNREAD_BYTES),+ lastReadAt: now(),+ closing: false,+ attachmentsDir: path.join(deps.runsRoot, 'attachments', request.runId),+ pending: new Map(),+ calls: new Map(),+ pushSeq: new Set(),+ pushParts: new Map(),+ };+ runs.set(key(controller, request.runId), run);+ ensureSweep();+ deps.log?.info('remote agent run opened', { runId: run.id, agent: run.kind });+ void startRun(run, payload);+ return {};+ }+ case 'call': {+ const run = requireRun(controller, request.runId);+ if (run.closing) fail('REMOTE_AGENT_EXPIRED', 'task has ended');+ if (run.calls.has(request.callId)) return {};+ run.calls.set(request.callId, 'running');+ void call(run, request.callId, request.method, request.payload);+ return {};+ }+ case 'poll':+ return poll(controller, request.runs, request.waitMs ?? REMOTE_AGENT_READ_WAIT_MS, signal);+ case 'reply': {+ const run = requireRun(controller, request.runId);+ const pending = run.pending.get(request.requestId);+ if (!pending) return {};+ const reply = parseRemoteAgentReply(await resolvePayload(controller, request.payload));+ run.pending.delete(request.requestId);+ pending.resolve(reply);+ return {};+ }+ case 'push': {+ const run = requireRun(controller, request.runId);+ if (run.pushSeq.has(request.seq)) return {};+ run.pushSeq.add(request.seq);+ if (run.pushSeq.size > 1024) run.pushSeq.delete(run.pushSeq.values().next().value as number);+ for (const frame of request.frames) {+ if (frame.kind === 'message' && frame.data !== undefined) {+ const joined = (run.pushParts.get(frame.connId) ?? '') + frame.data;+ if (frame.more) {+ // 单条消息拼接上限与反向请求载荷一致,防止无限累积。+ if (joined.length > REMOTE_AGENT_MAX_PAYLOAD_BYTES) {+ run.pushParts.delete(frame.connId);+ run.tunnel?.closeWs(frame.connId);+ } else run.pushParts.set(frame.connId, joined);+ continue;+ }+ run.pushParts.delete(frame.connId);+ run.tunnel?.sendWs(frame.connId, joined);+ } else {+ run.pushParts.delete(frame.connId);+ run.tunnel?.closeWs(frame.connId);+ }+ }+ return {};+ }+ case 'close': {+ const run = runs.get(key(controller, request.runId));+ if (!run) return {};+ await finishRun(run, request.mode === 'detach' ? 'detached' : 'closed', request.reason, true, false, request.mode);+ return {};+ }+ }+ }++ return {+ handle,+ /** 远程控制关闭 / 退出时结束全部任务。 */+ async abortAll(reason: RemoteAgentTeardownReason = 'navigation'): Promise<void> {+ await Promise.all([...runs.values()].map((run) => finishRun(run, 'aborted', reason)));+ },+ /** 测试与诊断用。 */+ runCount(): number {+ return [...runs.values()].filter((run) => run.closedAt === undefined).length;+ },+ dispose(): void {+ if (sweepTimer) clearInterval(sweepTimer);+ sweepTimer = null;+ for (const run of runs.values()) void finishRun(run, 'aborted', 'app-quit');+ },+ };+}++export type RemoteAgentHost = ReturnType<typeof createRemoteAgentHost>;diff --git a/apps/desktop/src/main/remote-agent/host/service.ts b/apps/desktop/src/main/remote-agent/host/service.tsnew file mode 100644index 0000000000..4c4d6d225e--- /dev/null+++ b/apps/desktop/src/main/remote-agent/host/service.ts@@ -0,0 +1,96 @@+/**+ * 远程 Agent 运行服务的被控端接线:把 `maker:remote-agent:v1` 接到本机 Maker 的 Agent。+ * 准入:本机打开了「允许远程控制」且没有撤销该控制端;账号切换后进行中的任务全部结束。+ */+import path from 'node:path';++import type { Maker, StartSessionOptions } from '@cindy/maker-core';++import { createLogger } from '../../logger.js';+import {+ captureDataOwnerBroadcastScope,+ isDataOwnerBroadcastScopeCurrent,+ type DataOwnerBroadcastScope,+} from '../../device-link/broadcast-tap.js';+import { setRemoteAgentHandler } from '../../device-link/dispatch.js';+import { readDeviceLinkSettings } from '../../device-link/settings-store.js';+import { createRemoteAgentHost, type HostedStartInput, type RemoteAgentHost } from './runHost';++const log = createLogger('remote-agent:host');++/** 对方任务的启动选项 → 本机 Agent 的启动选项(工作目录是影子目录,工具经隧道回到对方)。 */+export function hostedStartOptions(input: HostedStartInput): StartSessionOptions {+ const { options, workspace } = input;+ return {+ sessionId: input.hostSessionId,+ workingDir: input.shadowDir,+ model: options.model,+ ...(options.providerId !== undefined ? { providerId: options.providerId } : {}),+ ...(options.effort ? { effort: options.effort as StartSessionOptions['effort'] } : {}),+ ...(options.fastMode !== undefined ? { fastMode: options.fastMode } : {}),+ ...(options.thinkingEnabled !== undefined ? { thinkingEnabled: options.thinkingEnabled } : {}),+ ...(options.userPrompt ? { userPrompt: options.userPrompt } : {}),+ ...(options.botProfilePrompt ? { botProfilePrompt: options.botProfilePrompt } : {}),+ ...(options.botProfileContextPrompt ? { botProfileContextPrompt: options.botProfileContextPrompt } : {}),+ ...(options.botUserProfilePrompt ? { botUserProfilePrompt: options.botUserProfilePrompt } : {}),+ ...(options.makerMemoryEnabled !== undefined ? { makerMemoryEnabled: options.makerMemoryEnabled } : {}),+ ...(options.makerMemoryScopeKey ? { makerMemoryScopeKey: options.makerMemoryScopeKey } : {}),+ // 记忆在对方电脑上:没有快照时也给空快照,本机不读自己的记忆库。+ ...(options.makerMemoryEnabled ? { makerMemoryIndexSnapshot: options.makerMemoryIndexSnapshot ?? '' } : {}),+ ...(options.permissionMode ? { permissionMode: options.permissionMode as StartSessionOptions['permissionMode'] } : {}),+ ...(options.planMode !== undefined ? { planMode: options.planMode } : {}),+ ...(options.displayReasoning ? { displayReasoning: options.displayReasoning as StartSessionOptions['displayReasoning'] } : {}),+ ...(options.resumeSessionId ? { resumeSessionId: options.resumeSessionId } : {}),+ ...(options.codexHistoryHasProductPrompt !== undefined ? { codexHistoryHasProductPrompt: options.codexHistoryHasProductPrompt } : {}),+ ...(options.vendorOptions ? { vendorOptions: { ...options.vendorOptions } } : {}),+ extraDirs: [...workspace.extraDirs],+ writableDirs: [...workspace.writableDirs],+ deviceHosted: {+ ...workspace,+ tunnelUrl: input.tunnel.url,+ tunnelToken: input.tunnel.token,+ mcpServers: [...input.mcpServers],+ mirrorRoot: input.mirrorRoot,+ ...(input.personalInstructions ? { personalInstructions: input.personalInstructions } : {}),+ },+ ...(input.onInvalidResumeSession ? { onInvalidResumeSession: input.onInvalidResumeSession } : {}),+ };+}++let host: RemoteAgentHost | null = null;++export function installRemoteAgentHost(options: { getMaker: () => Maker; userDataDir: string }): void {+ if (host) return;+ host = createRemoteAgentHost({+ isAgentAvailable: (kind) => {+ try {+ return options.getMaker().listAvailableAgents().includes(kind);+ } catch {+ return false;+ }+ },+ startHosted: (input) => options.getMaker().startHostedAgentSession(input.kind, hostedStartOptions(input)),+ isControllerAuthorized: (controller) => {+ const settings = readDeviceLinkSettings();+ return settings.remoteControlEnabled && !settings.revokedControllers.includes(controller);+ },+ captureOwner: captureDataOwnerBroadcastScope,+ isOwnerCurrent: (owner) => isDataOwnerBroadcastScopeCurrent(owner as DataOwnerBroadcastScope),+ runsRoot: path.join(options.userDataDir, 'remote-agent'),+ log,+ });+ const current = host;+ setRemoteAgentHandler({+ handle: (controller, raw) => current.handle(controller, raw),+ abortAll: () => {+ void current.abortAll();+ },+ });+}++/** 退出时结束全部远程 Agent 任务。 */+export function disposeRemoteAgentHost(): void {+ setRemoteAgentHandler(null);+ host?.dispose();+ host = null;+}diff --git a/apps/desktop/src/main/remote-agent/host/tunnel.ts b/apps/desktop/src/main/remote-agent/host/tunnel.tsnew file mode 100644index 0000000000..35edcb6e20--- /dev/null+++ b/apps/desktop/src/main/remote-agent/host/tunnel.ts@@ -0,0 +1,215 @@+/**+ * 远程 Agent 的本机隧道(被控端):一个任务一个,只监听 127.0.0.1。+ *+ * 本机 Agent 访问 Cindy 工具(MCP)、执行器(Pi 的文件与命令后端)和 Codex exec-server 时连到这里;+ * 每个 HTTP 请求变成一条反向请求进入事件流,等控制端处理后回包;WebSocket 连接的帧同样经事件流+ * 送到控制端,控制端的帧经 push 送回。loopback 不是鉴权边界:每个请求都要带本任务随机生成的令牌。+ */+import { randomBytes, timingSafeEqual } from 'node:crypto';+import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';+import type { AddressInfo, Socket } from 'node:net';++import { WebSocketServer, type WebSocket } from 'ws';++/** 单个请求体上限(与反向请求载荷上限一致)。 */+export const TUNNEL_MAX_BODY_BYTES = 48 * 1024 * 1024;+const MAX_WS_CONNECTIONS = 16;+/** 单条 WebSocket 消息上限(Codex exec-server 读写大文件时整段 base64 在一条消息里)。 */+const MAX_WS_FRAME_BYTES = 48 * 1024 * 1024;++export interface TunnelHttpRequest {+ method: string;+ path: string;+ headers: Array<[string, string]>;+ body?: Buffer;+}++export interface TunnelHttpResponse {+ status: number;+ headers: Array<[string, string]>;+ body?: Buffer;+}++export interface TunnelHandlers {+ http(request: TunnelHttpRequest, signal: AbortSignal): Promise<TunnelHttpResponse>;+ wsOpen(connId: string, path: string): void;+ wsMessage(connId: string, data: string): void;+ wsClose(connId: string): void;+}++export interface RunTunnel {+ url: string;+ token: string;+ sendWs(connId: string, data: string): void;+ closeWs(connId: string): void;+ close(): Promise<void>;+}++/** 转发给控制端的请求头(其余如鉴权、Cookie、hop-by-hop 头不出本机)。 */+const FORWARDED_HEADERS = new Set([+ 'content-type',+ 'accept',+ 'mcp-session-id',+ 'mcp-protocol-version',+ 'last-event-id',+]);++function sameToken(given: string, token: string): boolean {+ const a = Buffer.from(given);+ const b = Buffer.from(token);+ return a.length === b.length && timingSafeEqual(a, b);+}++function tokenMatches(header: string | undefined, token: string): boolean {+ const match = /^Bearer (.+)$/.exec(header ?? '');+ return !!match && sameToken(match[1], token);+}++/**+ * 鉴权:请求头 `Authorization: Bearer <令牌>`,或路径前缀 `/t/<令牌>/`(给只能配置固定地址、+ * 自带另一份请求头的客户端,如 Codex 的 MCP 配置)。返回去掉前缀后的路径;未通过返回 null。+ */+function authorizedPath(url: string | undefined, header: string | undefined, token: string): string | null {+ const target = url ?? '/';+ const prefix = /^\/t\/([^/?#]+)(\/.*)$/.exec(target);+ if (prefix) {+ let given: string;+ try {+ given = decodeURIComponent(prefix[1]);+ } catch {+ return null;+ }+ return sameToken(given, token) ? prefix[2] : null;+ }+ return tokenMatches(header, token) ? target : null;+}++function readBody(req: IncomingMessage): Promise<Buffer> {+ return new Promise((resolve, reject) => {+ const chunks: Buffer[] = [];+ let size = 0;+ req.on('data', (chunk: Buffer) => {+ size += chunk.length;+ if (size > TUNNEL_MAX_BODY_BYTES) {+ reject(new Error('body too large'));+ req.destroy();+ return;+ }+ chunks.push(chunk);+ });+ req.on('end', () => resolve(Buffer.concat(chunks)));+ req.on('error', reject);+ });+}++export async function createRunTunnel(handlers: TunnelHandlers): Promise<RunTunnel> {+ const token = randomBytes(32).toString('base64url');+ const sockets = new Set<Socket>();+ const connections = new Map<string, WebSocket>();+ let nextConn = 0;+ let closed = false;++ const server: Server = createServer((req: IncomingMessage, res: ServerResponse) => {+ void (async () => {+ const requestPath = authorizedPath(req.url, req.headers.authorization, token);+ if (requestPath === null) {+ res.writeHead(401).end();+ req.resume();+ return;+ }+ const abort = new AbortController();+ res.on('close', () => {+ if (!res.writableFinished) abort.abort();+ });+ let body: Buffer;+ try {+ body = await readBody(req);+ } catch {+ if (!res.headersSent) res.writeHead(413).end();+ return;+ }+ const headers: Array<[string, string]> = [];+ for (const [name, value] of Object.entries(req.headers)) {+ if (!FORWARDED_HEADERS.has(name) || value === undefined) continue;+ headers.push([name, Array.isArray(value) ? value.join(', ') : value]);+ }+ try {+ const response = await handlers.http({+ method: req.method ?? 'GET',+ path: requestPath,+ headers,+ ...(body.length ? { body } : {}),+ }, abort.signal);+ if (res.destroyed) return;+ res.writeHead(response.status, Object.fromEntries(response.headers));+ res.end(response.body);+ } catch (error) {+ if (res.destroyed) return;+ const message = error instanceof Error ? error.message : String(error);+ res.writeHead(502, { 'content-type': 'application/json' });+ res.end(JSON.stringify({ error: { code: 'REMOTE_AGENT_TUNNEL', message } }));+ }+ })();+ });+ server.on('connection', (socket) => {+ sockets.add(socket);+ socket.on('close', () => sockets.delete(socket));+ });++ const wss = new WebSocketServer({ noServer: true, maxPayload: MAX_WS_FRAME_BYTES });+ server.on('upgrade', (req, socket, head) => {+ const wsPath = authorizedPath(req.url, req.headers.authorization, token);+ if (closed || wsPath === null || connections.size >= MAX_WS_CONNECTIONS) {+ socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');+ socket.destroy();+ return;+ }+ wss.handleUpgrade(req, socket, head, (ws) => {+ nextConn += 1;+ const connId = `c${nextConn}`;+ connections.set(connId, ws);+ handlers.wsOpen(connId, wsPath ?? '/');+ ws.on('message', (data, isBinary) => {+ if (isBinary) return;+ handlers.wsMessage(connId, data.toString());+ });+ ws.on('close', () => {+ if (connections.delete(connId)) handlers.wsClose(connId);+ });+ ws.on('error', () => ws.terminate());+ });+ });++ await new Promise<void>((resolve, reject) => {+ server.once('error', reject);+ server.listen(0, '127.0.0.1', () => {+ server.off('error', reject);+ resolve();+ });+ });+ const { port } = server.address() as AddressInfo;++ return {+ url: `http://127.0.0.1:${port}`,+ token,+ sendWs(connId, data) {+ const ws = connections.get(connId);+ if (ws && ws.readyState === ws.OPEN) ws.send(data);+ },+ closeWs(connId) {+ const ws = connections.get(connId);+ if (!ws) return;+ connections.delete(connId);+ ws.close();+ },+ async close() {+ if (closed) return;+ closed = true;+ for (const ws of connections.values()) ws.terminate();+ connections.clear();+ wss.close();+ for (const socket of sockets) socket.destroy();+ await new Promise<void>((resolve) => server.close(() => resolve()));+ },+ };+}diff --git a/apps/desktop/src/main/remote-agent/wire.ts b/apps/desktop/src/main/remote-agent/wire.tsnew file mode 100644index 0000000000..3fd3b87be1--- /dev/null+++ b/apps/desktop/src/main/remote-agent/wire.ts@@ -0,0 +1,585 @@+/**+ * 远程 Agent 的载荷编解码(两端共用)。+ *+ * maker-core 的启动选项与发送选项里有回调、AbortSignal 和 Symbol 键(只有本进程主线程能附上的+ * 证明),不能原样过设备互联。这里把它们换成可序列化的描述:+ * - 回调 → 标记位,被控端调用时作为反向请求回到控制端执行;+ * - Symbol 键 → `cindy` 子对象,被控端解码后重新附到 Symbol 键上(请求来自已鉴权的同账号+ * 控制端主进程,与本机主进程附上这些证明的前提一致);+ * - 每轮权限策略 → 已知策略按名字还原(两端同一份代码),认不出的一律按「全部确认」还原;+ * - 消息里的图片 → 字节随载荷带过去,被控端写到本次任务的附件目录再引用。+ * 被控端解码时按最小合同校验类型,不认识的字段丢弃。+ */+import {+ AUTO_REVIEW_DELEGATED_CONTINUATION,+ AUTO_REVIEW_SOURCE_CONTENT,+ AUTO_REVIEW_USER_INTENT,+ INHERITED_CAPABILITY_SELECTION,+ MAIN_OWNED_SEND_CONTEXT,+ type SendOptions,+ type StartSessionOptions,+ type TurnPermissionOrigin,+ type TurnPermissionPolicy,+ type UserContentBlock,+ type UserMessage,+} from '@cindy/maker-core';++import {+ channelForceConfirmMutatingToolCall,+ channelForceConfirmToolCall,+} from '../im/shared/channelToolPolicy';++export const REMOTE_AGENT_MAX_ATTACHMENT_BYTES = 20 * 1024 * 1024;+const MAX_PROJECT_FILES = 512;+const MAX_TEXT = 512 * 1024;++// ─── 通用校验 ────────────────────────────────────────────────────++function isRecord(value: unknown): value is Record<string, unknown> {+ return !!value && typeof value === 'object' && !Array.isArray(value);+}++function optString(value: unknown, max = MAX_TEXT): string | undefined {+ return typeof value === 'string' && value.length <= max ? value : undefined;+}++function optBool(value: unknown): boolean | undefined {+ return typeof value === 'boolean' ? value : undefined;+}++function optNumber(value: unknown): number | undefined {+ return typeof value === 'number' && Number.isFinite(value) ? value : undefined;+}++function stringArray(value: unknown, maxItems = 256): string[] | undefined {+ if (!Array.isArray(value) || value.length > maxItems) return undefined;+ const items = value.filter((item): item is string => typeof item === 'string' && item.length > 0 && item.length <= 4096);+ return items.length === value.length ? items : undefined;+}++/** JSON 往返:丢掉函数、Symbol 键与 undefined,保证能过设备互联。 */+function jsonSafe(value: unknown): unknown {+ if (value === undefined) return undefined;+ try {+ return JSON.parse(JSON.stringify(value));+ } catch {+ return undefined;+ }+}++function prune<T extends Record<string, unknown>>(value: T): T {+ for (const key of Object.keys(value)) {+ if (value[key] === undefined) delete value[key];+ }+ return value;+}++// ─── 打开任务 ────────────────────────────────────────────────────++/** 任务所在电脑的工作区描述(给 Agent 的提示与执行器边界用)。 */+export interface RemoteAgentWireWorkspace {+ workingDir: string;+ extraDirs: string[];+ writableDirs: string[];+ platform: NodeJS.Platform;+ shell: string;+ osVersion?: string;+ homeDir?: string;+ isGitRepo: boolean;+}++/** 同步到 Agent 所在电脑影子目录的项目说明类小文件(相对工作目录、`/` 分隔)。 */+export interface RemoteAgentWireFile {+ path: string;+ data: string;+}++export interface RemoteAgentWireStartOptions {+ model: string;+ providerId?: string | null;+ effort?: string;+ fastMode?: boolean;+ thinkingEnabled?: boolean;+ userPrompt?: string;+ botProfilePrompt?: string;+ botProfileContextPrompt?: string;+ botUserProfilePrompt?: string;+ makerMemoryEnabled?: boolean;+ makerMemoryScopeKey?: string;+ makerMemoryIndexSnapshot?: string;+ permissionMode?: string;+ planMode?: boolean;+ displayReasoning?: string;+ resumeSessionId?: string;+ codexHistoryHasProductPrompt?: boolean;+ vendorOptions?: Record<string, unknown>;+ /** 控制端注入了 invalid-resume CAS 回调。 */+ invalidResumeCallback?: boolean;+}++/** 项目上级目录里的说明文件(相对工作目录向上 up 级)。 */+export interface RemoteAgentWireAncestorFile {+ up: number;+ name: string;+ data: string;+}++/** 你这台的个人配置(用户级),在那台电脑上以项目级配置的形式提供给 Agent。 */+export interface RemoteAgentWirePersonal {+ /** 个人说明(Claude Code 的 ~/.claude/CLAUDE.md):放在影子目录最外层,最先加载、优先级最低。 */+ memory?: string;+ /** 个人 Skill / 子代理 / 命令(相对影子目录的路径,如 `.claude/skills/x/SKILL.md`);项目里有同名的以项目为准。 */+ files: RemoteAgentWireFile[];+ /** 个人权限规则(并入项目 local 设置)。 */+ permissions?: { allow?: string[]; deny?: string[]; ask?: string[] };+ /** 个人说明(Codex 的 AGENTS.md 等):写进给 Agent 的环境说明。 */+ instructions?: string;+}++export interface RemoteAgentOpenPayload {+ /** 控制端任务 id。 */+ sessionId: string;+ options: RemoteAgentWireStartOptions;+ workspace: RemoteAgentWireWorkspace;+ projectFiles: RemoteAgentWireFile[];+ /** 项目上级目录里的说明文件。 */+ ancestorFiles: RemoteAgentWireAncestorFile[];+ /** 你这台的个人配置。 */+ personal: RemoteAgentWirePersonal;+ /** 控制端经隧道提供的 Cindy MCP 服务名。 */+ mcpServers: string[];+}++/** 上级目录说明文件只认这几个名字,最多向上这么多级。 */+export const ANCESTOR_INSTRUCTION_FILES = ['CLAUDE.md', 'CLAUDE.local.md', 'AGENTS.md', 'AGENTS.override.md'] as const;+export const MAX_ANCESTOR_LEVELS = 24;+/** 个人配置只能落在这些子目录下。 */+const PERSONAL_PREFIXES = ['.claude/skills/', '.claude/agents/', '.claude/commands/'];++const START_STRING_FIELDS = [+ 'effort', 'userPrompt', 'botProfilePrompt', 'botProfileContextPrompt', 'botUserProfilePrompt',+ 'makerMemoryScopeKey', 'makerMemoryIndexSnapshot', 'permissionMode', 'displayReasoning', 'resumeSessionId',+] as const;+const START_BOOL_FIELDS = [+ 'fastMode', 'thinkingEnabled', 'makerMemoryEnabled', 'planMode', 'codexHistoryHasProductPrompt',+] as const;++/** vendorOptions 里只有这些是可序列化、对另一台电脑有意义的。 */+const VENDOR_OPTION_KEYS = new Set(['source', 'resumeSessionAt', 'forkSession']);++export function encodeStartOptions(opts: StartSessionOptions): RemoteAgentWireStartOptions {+ const record = opts as unknown as Record<string, unknown>;+ const wire: RemoteAgentWireStartOptions = { model: opts.model };+ if (opts.providerId !== undefined) wire.providerId = opts.providerId;+ for (const key of START_STRING_FIELDS) {+ const value = record[key];+ if (typeof value === 'string') (wire as unknown as Record<string, unknown>)[key] = value;+ }+ for (const key of START_BOOL_FIELDS) {+ const value = record[key];+ if (typeof value === 'boolean') (wire as unknown as Record<string, unknown>)[key] = value;+ }+ if (opts.vendorOptions) {+ const vendor: Record<string, unknown> = {};+ for (const [key, value] of Object.entries(opts.vendorOptions)) {+ if (VENDOR_OPTION_KEYS.has(key) && typeof value !== 'function') vendor[key] = jsonSafe(value);+ }+ if (Object.keys(vendor).length) wire.vendorOptions = vendor;+ }+ if (opts.onInvalidResumeSession) wire.invalidResumeCallback = true;+ return wire;+}++export function decodeStartOptions(value: unknown): RemoteAgentWireStartOptions {+ if (!isRecord(value) || typeof value.model !== 'string' || !value.model || value.model.length > 512) {+ throw new Error('REMOTE_AGENT_INVALID');+ }+ const wire: RemoteAgentWireStartOptions = { model: value.model };+ if (value.providerId === null || typeof value.providerId === 'string') wire.providerId = value.providerId as string | null;+ for (const key of START_STRING_FIELDS) {+ const item = optString(value[key]);+ if (item !== undefined) (wire as unknown as Record<string, unknown>)[key] = item;+ }+ for (const key of START_BOOL_FIELDS) {+ const item = optBool(value[key]);+ if (item !== undefined) (wire as unknown as Record<string, unknown>)[key] = item;+ }+ if (isRecord(value.vendorOptions)) {+ const vendor: Record<string, unknown> = {};+ for (const [key, item] of Object.entries(value.vendorOptions)) {+ if (VENDOR_OPTION_KEYS.has(key)) vendor[key] = item;+ }+ if (Object.keys(vendor).length) wire.vendorOptions = vendor;+ }+ if (value.invalidResumeCallback === true) wire.invalidResumeCallback = true;+ return wire;+}++const PLATFORMS = new Set(['aix', 'android', 'darwin', 'freebsd', 'haiku', 'linux', 'openbsd', 'sunos', 'win32', 'cygwin', 'netbsd']);++function decodeWorkspace(value: unknown): RemoteAgentWireWorkspace {+ if (!isRecord(value)) throw new Error('REMOTE_AGENT_INVALID');+ const workingDir = optString(value.workingDir, 4096);+ const platform = optString(value.platform, 32);+ if (!workingDir || !platform || !PLATFORMS.has(platform)) throw new Error('REMOTE_AGENT_INVALID');+ return {+ workingDir,+ extraDirs: stringArray(value.extraDirs) ?? [],+ writableDirs: stringArray(value.writableDirs) ?? [],+ platform: platform as NodeJS.Platform,+ shell: optString(value.shell, 256) ?? 'bash',+ ...(optString(value.osVersion, 256) ? { osVersion: optString(value.osVersion, 256) } : {}),+ ...(optString(value.homeDir, 4096) ? { homeDir: optString(value.homeDir, 4096) } : {}),+ isGitRepo: value.isGitRepo === true,+ };+}++/** 影子目录里允许出现的相对路径:不能越出、不能是隐藏的 Cindy/git 内部文件。 */+export function isSafeProjectFilePath(relative: string): boolean {+ if (!relative || relative.length > 1024 || relative.includes('\0') || relative.includes('\\')) return false;+ if (relative.startsWith('/') || /^[A-Za-z]:/.test(relative)) return false;+ const parts = relative.split('/');+ return parts.every((part) => part !== '' && part !== '.' && part !== '..') && parts[0] !== '.git';+}++export function decodeOpenPayload(value: unknown): RemoteAgentOpenPayload {+ if (!isRecord(value)) throw new Error('REMOTE_AGENT_INVALID');+ const sessionId = optString(value.sessionId, 128);+ if (!sessionId || !/^[A-Za-z0-9_-]+$/.test(sessionId)) throw new Error('REMOTE_AGENT_INVALID');+ const files = Array.isArray(value.projectFiles) ? value.projectFiles : [];+ if (files.length > MAX_PROJECT_FILES) throw new Error('REMOTE_AGENT_INVALID');+ const projectFiles = files.flatMap((item): RemoteAgentWireFile[] => {+ if (!isRecord(item) || typeof item.path !== 'string' || typeof item.data !== 'string') return [];+ return isSafeProjectFilePath(item.path) ? [{ path: item.path, data: item.data }] : [];+ });+ const ancestors = Array.isArray(value.ancestorFiles) ? value.ancestorFiles : [];+ if (ancestors.length > MAX_ANCESTOR_LEVELS * ANCESTOR_INSTRUCTION_FILES.length) throw new Error('REMOTE_AGENT_INVALID');+ const ancestorFiles = ancestors.flatMap((item): RemoteAgentWireAncestorFile[] => {+ if (!isRecord(item) || typeof item.name !== 'string' || typeof item.data !== 'string') return [];+ if (typeof item.up !== 'number' || !Number.isInteger(item.up) || item.up < 1 || item.up > MAX_ANCESTOR_LEVELS) return [];+ return (ANCESTOR_INSTRUCTION_FILES as readonly string[]).includes(item.name)+ ? [{ up: item.up, name: item.name, data: item.data }]+ : [];+ });+ return {+ sessionId,+ options: decodeStartOptions(value.options),+ workspace: decodeWorkspace(value.workspace),+ projectFiles,+ ancestorFiles,+ personal: decodePersonal(value.personal),+ mcpServers: (stringArray(value.mcpServers, 128) ?? []).filter((name) => /^[a-z0-9_-]{1,64}$/i.test(name)),+ };+}++function decodePersonal(value: unknown): RemoteAgentWirePersonal {+ if (!isRecord(value)) return { files: [] };+ const files = Array.isArray(value.files) ? value.files : [];+ if (files.length > MAX_PROJECT_FILES) throw new Error('REMOTE_AGENT_INVALID');+ const personal: RemoteAgentWirePersonal = {+ files: files.flatMap((item): RemoteAgentWireFile[] => {+ if (!isRecord(item) || typeof item.path !== 'string' || typeof item.data !== 'string') return [];+ const filePath = item.path;+ return isSafeProjectFilePath(filePath) && PERSONAL_PREFIXES.some((prefix) => filePath.startsWith(prefix))+ ? [{ path: filePath, data: item.data }]+ : [];+ }),+ };+ const memory = optString(value.memory);+ if (memory) personal.memory = memory;+ const instructions = optString(value.instructions);+ if (instructions) personal.instructions = instructions;+ if (isRecord(value.permissions)) {+ const rules = (key: string) => (stringArray(value.permissions && (value.permissions as Record<string, unknown>)[key], 1024) ?? []).slice(0, 512);+ const permissions = { allow: rules('allow'), deny: rules('deny'), ask: rules('ask') };+ if (permissions.allow.length || permissions.deny.length || permissions.ask.length) personal.permissions = permissions;+ }+ return personal;+}++// ─── 用户消息 ────────────────────────────────────────────────────++export interface RemoteAgentWireAttachment {+ /** base64 字节。 */+ data: string;+ ext: string;+}++type WireBlock =+ | { type: 'text'; text: string }+ | { type: 'image'; attachment: number; mimeType?: string; managedUrl?: string }+ | { type: 'file'; path: string; mimeType?: string }+ | { type: 'mention'; name: string; path: string; kind?: 'file' | 'dir' | 'agent' };++export interface RemoteAgentWireMessage {+ content: string | WireBlock[];+ attachments: RemoteAgentWireAttachment[];+}++function extensionOf(file: string, mimeType?: string): string {+ const match = /\.([A-Za-z0-9]{1,8})$/.exec(file);+ if (match) return match[1].toLowerCase();+ if (mimeType === 'image/png') return 'png';+ if (mimeType === 'image/jpeg') return 'jpg';+ if (mimeType === 'image/gif') return 'gif';+ if (mimeType === 'image/webp') return 'webp';+ return 'bin';+}++/** 控制端:图片按本机路径读出字节随消息带走;文件与提及只是路径引用,Agent 用工具到本机读。 */+export async function encodeUserMessage(+ message: UserMessage,+ readImage: (path: string) => Promise<Buffer>,+): Promise<RemoteAgentWireMessage> {+ if (typeof message.content === 'string') return { content: message.content, attachments: [] };+ const attachments: RemoteAgentWireAttachment[] = [];+ const content: WireBlock[] = [];+ for (const block of message.content) {+ if (block.type === 'image' && !/^https?:\/\//.test(block.path)) {+ const data = await readImage(block.path);+ if (data.length > REMOTE_AGENT_MAX_ATTACHMENT_BYTES) {+ throw new Error(`Image ${block.path} is too large to send to the other computer.`);+ }+ attachments.push({ data: data.toString('base64'), ext: extensionOf(block.path, block.mimeType) });+ content.push(prune({+ type: 'image' as const,+ attachment: attachments.length - 1,+ mimeType: block.mimeType,+ managedUrl: block.managedUrl,+ }));+ } else if (block.type === 'image') {+ content.push({ type: 'file', path: block.path, mimeType: block.mimeType });+ } else {+ content.push(jsonSafe(block) as WireBlock);+ }+ }+ return { content, attachments };+}++/** 被控端:把附件写到本次任务的附件目录,换成本机路径。 */+export async function decodeUserMessage(+ value: unknown,+ writeAttachment: (data: Buffer, ext: string) => Promise<string>,+): Promise<UserMessage> {+ if (!isRecord(value)) throw new Error('REMOTE_AGENT_INVALID');+ if (typeof value.content === 'string') return { type: 'user', content: value.content };+ if (!Array.isArray(value.content) || value.content.length > 512) throw new Error('REMOTE_AGENT_INVALID');+ const attachments = Array.isArray(value.attachments) ? value.attachments : [];+ const written = new Map<number, string>();+ const blocks: UserContentBlock[] = [];+ for (const raw of value.content) {+ if (!isRecord(raw)) continue;+ switch (raw.type) {+ case 'text':+ if (typeof raw.text === 'string') blocks.push({ type: 'text', text: raw.text });+ break;+ case 'image': {+ const index = optNumber(raw.attachment);+ const attachment = index !== undefined ? attachments[index] : undefined;+ if (!isRecord(attachment) || typeof attachment.data !== 'string') break;+ let file = written.get(index!);+ if (!file) {+ const ext = typeof attachment.ext === 'string' && /^[a-z0-9]{1,8}$/.test(attachment.ext) ? attachment.ext : 'bin';+ const data = Buffer.from(attachment.data, 'base64');+ if (data.length > REMOTE_AGENT_MAX_ATTACHMENT_BYTES) throw new Error('REMOTE_AGENT_INVALID');+ file = await writeAttachment(data, ext);+ written.set(index!, file);+ }+ blocks.push(prune({+ type: 'image' as const,+ path: file,+ mimeType: optString(raw.mimeType, 128),+ managedUrl: optString(raw.managedUrl, 2048),+ }));+ break;+ }+ case 'file':+ if (typeof raw.path === 'string') blocks.push(prune({ type: 'file' as const, path: raw.path, mimeType: optString(raw.mimeType, 128) }));+ break;+ case 'mention':+ if (typeof raw.path === 'string' && typeof raw.name === 'string') {+ const kind = raw.kind === 'file' || raw.kind === 'dir' || raw.kind === 'agent' ? raw.kind : undefined;+ blocks.push(prune({ type: 'mention' as const, name: raw.name, path: raw.path, kind }));+ }+ break;+ default:+ break;+ }+ }+ return { type: 'user', content: blocks };+}++// ─── 发送选项 ────────────────────────────────────────────────────++type WireForceConfirm = 'all' | 'channel' | 'channel-mutating';++interface WireTurnPolicy {+ forceConfirm: WireForceConfirm;+ origin: TurnPermissionOrigin;+ confirmationSurface: 'desktop' | 'channel';+ confirmationTimeoutMs?: number;+ autoReviewContext?: unknown;+ stateCallback?: boolean;+}++export interface RemoteAgentWireSendOptions {+ logTitle?: string;+ messageUuid?: string;+ retryTranscriptUserEntryId?: string;+ userName?: string;+ planMode?: boolean;+ throwOnStartFailure?: boolean;+ origin?: unknown;+ turnAttemptToken?: number;+ toolsDisabled?: boolean;+ transcriptCallback?: boolean;+ turnPolicy?: WireTurnPolicy;+ cindy?: {+ mainOwned?: { origin: TurnPermissionOrigin; rawChannelText?: string };+ autoReviewSourceContent?: RemoteAgentWireMessage;+ autoReviewUserIntent?: unknown;+ delegatedContinuation?: true;+ inheritedCapabilitySelection?: string;+ };+}++export interface EncodedSendOptions {+ wire: RemoteAgentWireSendOptions;+ /** 回调留在控制端,被控端经反向请求触发。 */+ onTranscriptUserEntry?: (entryId: string) => void | Promise<void>;+ onInteractionStateChange?: (state: 'waiting' | 'resolved' | 'cancelled') => void;+}++function forceConfirmKind(policy: TurnPermissionPolicy): WireForceConfirm {+ if (policy.forceConfirmToolCall === channelForceConfirmToolCall) return 'channel';+ if (policy.forceConfirmToolCall === channelForceConfirmMutatingToolCall) return 'channel-mutating';+ return 'all';+}++export async function encodeSendOptions(+ opts: SendOptions | undefined,+ readImage: (path: string) => Promise<Buffer>,+): Promise<EncodedSendOptions> {+ if (!opts) return { wire: {} };+ const wire: RemoteAgentWireSendOptions = prune({+ logTitle: opts.logTitle,+ messageUuid: opts.messageUuid,+ retryTranscriptUserEntryId: opts.retryTranscriptUserEntryId,+ userName: opts.userName,+ planMode: opts.planMode,+ throwOnStartFailure: opts.throwOnStartFailure,+ origin: jsonSafe(opts.origin),+ turnAttemptToken: opts.turnAttemptToken,+ toolsDisabled: opts.toolsDisabled,+ transcriptCallback: opts.onTranscriptUserEntry ? true : undefined,+ });+ const policy = opts.turnPermissionPolicy;+ if (policy) {+ wire.turnPolicy = prune({+ forceConfirm: forceConfirmKind(policy),+ origin: jsonSafe(policy.origin) as TurnPermissionOrigin,+ confirmationSurface: policy.confirmationSurface,+ confirmationTimeoutMs: policy.confirmationTimeoutMs,+ autoReviewContext: jsonSafe(policy.autoReviewContext),+ stateCallback: policy.onInteractionStateChange ? true : undefined,+ });+ }+ const cindy: NonNullable<RemoteAgentWireSendOptions['cindy']> = {};+ const mainOwned = opts[MAIN_OWNED_SEND_CONTEXT];+ if (mainOwned) cindy.mainOwned = jsonSafe(mainOwned) as NonNullable<typeof cindy.mainOwned>;+ const sourceContent = opts[AUTO_REVIEW_SOURCE_CONTENT];+ if (sourceContent !== undefined) {+ cindy.autoReviewSourceContent = await encodeUserMessage({ type: 'user', content: sourceContent }, readImage);+ }+ if (opts[AUTO_REVIEW_USER_INTENT] !== undefined) cindy.autoReviewUserIntent = jsonSafe(opts[AUTO_REVIEW_USER_INTENT]);+ if (opts[AUTO_REVIEW_DELEGATED_CONTINUATION]) cindy.delegatedContinuation = true;+ if (typeof opts[INHERITED_CAPABILITY_SELECTION] === 'string') cindy.inheritedCapabilitySelection = opts[INHERITED_CAPABILITY_SELECTION];+ if (Object.keys(cindy).length) wire.cindy = cindy;+ return {+ wire,+ ...(opts.onTranscriptUserEntry ? { onTranscriptUserEntry: opts.onTranscriptUserEntry } : {}),+ ...(policy?.onInteractionStateChange ? { onInteractionStateChange: policy.onInteractionStateChange } : {}),+ };+}++function decodeOrigin(value: unknown): TurnPermissionOrigin | undefined {+ if (!isRecord(value) || typeof value.kind !== 'string') return undefined;+ switch (value.kind) {+ case 'desktop':+ case 'scheduler':+ return { kind: value.kind };+ case 'hook':+ return typeof value.source === 'string' ? { kind: 'hook', source: value.source } : undefined;+ case 'im': {+ const channels = ['feishu', 'discord', 'slack', 'wechat', 'telegram', 'dingtalk', 'wecom'] as const;+ const channel = channels.find((item) => item === value.channel);+ return channel ? prune({ kind: 'im' as const, channel, taskId: optString(value.taskId, 256) }) : undefined;+ }+ default:+ return undefined;+ }+}++export interface DecodeSendCallbacks {+ onTranscriptUserEntry(entryId: string): Promise<void>;+ onInteractionStateChange(state: 'waiting' | 'resolved' | 'cancelled'): void;+ writeAttachment(data: Buffer, ext: string): Promise<string>;+}++export async function decodeSendOptions(value: unknown, callbacks: DecodeSendCallbacks): Promise<SendOptions> {+ if (!isRecord(value)) return {};+ const opts: Record<PropertyKey, unknown> = prune({+ logTitle: optString(value.logTitle, 1024),+ messageUuid: optString(value.messageUuid, 128),+ retryTranscriptUserEntryId: optString(value.retryTranscriptUserEntryId, 256),+ userName: optString(value.userName, 256),+ planMode: optBool(value.planMode),+ throwOnStartFailure: optBool(value.throwOnStartFailure),+ origin: isRecord(value.origin) && ['user', 'scheduler', 'goal'].includes(value.origin.kind as string) ? value.origin : undefined,+ turnAttemptToken: optNumber(value.turnAttemptToken),+ toolsDisabled: optBool(value.toolsDisabled),+ });+ if (value.transcriptCallback === true) opts.onTranscriptUserEntry = callbacks.onTranscriptUserEntry;+ if (isRecord(value.turnPolicy)) {+ const policy = value.turnPolicy;+ const origin = decodeOrigin(policy.origin);+ const surface = policy.confirmationSurface === 'channel' ? 'channel' : 'desktop';+ const force = policy.forceConfirm === 'channel'+ ? channelForceConfirmToolCall+ : policy.forceConfirm === 'channel-mutating'+ ? channelForceConfirmMutatingToolCall+ : () => true;+ if (origin) {+ opts.turnPermissionPolicy = prune({+ origin,+ confirmationSurface: surface,+ confirmationTimeoutMs: optNumber(policy.confirmationTimeoutMs),+ autoReviewContext: isRecord(policy.autoReviewContext) ? policy.autoReviewContext : undefined,+ onInteractionStateChange: policy.stateCallback === true ? callbacks.onInteractionStateChange : undefined,+ forceConfirmToolCall: force,+ }) as unknown as TurnPermissionPolicy;+ }+ }+ if (isRecord(value.cindy)) {+ const cindy = value.cindy;+ if (isRecord(cindy.mainOwned)) {+ const origin = decodeOrigin(cindy.mainOwned.origin);+ if (origin) {+ opts[MAIN_OWNED_SEND_CONTEXT] = prune({ origin, rawChannelText: optString(cindy.mainOwned.rawChannelText) });+ }+ }+ if (isRecord(cindy.autoReviewSourceContent)) {+ const message = await decodeUserMessage(cindy.autoReviewSourceContent, callbacks.writeAttachment);+ opts[AUTO_REVIEW_SOURCE_CONTENT] = message.content;+ }+ const intent = cindy.autoReviewUserIntent;+ if (typeof intent === 'string' || (isRecord(intent) && typeof intent.currentUserMessage === 'string'+ && Array.isArray(intent.earlierUserMessages) && intent.earlierUserMessages.every((item) => typeof item === 'string'))) {+ opts[AUTO_REVIEW_USER_INTENT] = intent;+ }+ if (cindy.delegatedContinuation === true) opts[AUTO_REVIEW_DELEGATED_CONTINUATION] = true;+ const inherited = optString(cindy.inheritedCapabilitySelection);+ if (inherited !== undefined) opts[INHERITED_CAPABILITY_SELECTION] = inherited;+ }+ return opts as SendOptions;+}diff --git a/apps/desktop/src/main/scheduler-host/__tests__/runnerModelSelection.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/runnerModelSelection.test.tsindex 52f3ce6d72..2784ef674b 100644--- a/apps/desktop/src/main/scheduler-host/__tests__/runnerModelSelection.test.ts+++ b/apps/desktop/src/main/scheduler-host/__tests__/runnerModelSelection.test.ts@@ -255,6 +255,7 @@ function createRunnerHarness(defaultEffort?: string | null;}>;checkModelRoute?: ConstructorParameters<typeof MakerScheduleRunner>[0]['checkModelRoute'];+ isAgentOnOtherDevice?: ConstructorParameters<typeof MakerScheduleRunner>[0]['isAgentOnOtherDevice'];resolveRouteCopyCapabilities?: ConstructorParameters<typeof MakerScheduleRunner>[0]['resolveRouteCopyCapabilities'];@@ -285,6 +286,7 @@ function createRunnerHarness(notifier,logger: createLogger(),checkModelRoute: opts.checkModelRoute,+ ...(opts.isAgentOnOtherDevice ? { isAgentOnOtherDevice: opts.isAgentOnOtherDevice } : {}),acquirePendingAgentSwitch: opts.acquirePendingAgentSwitch,applyPiModelSelectionUnderLock: opts.applyPiModelSelectionUnderLock ?? (async (_id, targetModel, providerId) => {await h.session.setModel(targetModel, { providerId });@@ -522,6 +524,41 @@ describe('MakerScheduleRunner model selection', () => {});});+ it('leaves route decisions for a task whose agent runs on another computer to that computer', async () => {+ const h = createSessionHarness();+ (h.session as { agentKind: string }).agentKind = 'pi';+ (h.session as { model: string }).model = 'spark/qwen';+ const transaction = vi.fn(async () => ({ status: 'applied' as const }));+ const checkModelRoute = vi.fn()+ .mockResolvedValueOnce({ kind: 'pass' as const })+ .mockResolvedValue({ kind: 'reject' as const, reason: 'model-unavailable' });+ const isAgentOnOtherDevice = vi.fn(async (sessionId: string) => sessionId === 'scheduler-session');+ const harness = createRunnerHarness(h, null, {+ checkModelRoute, isAgentOnOtherDevice, applyPiModelSelectionUnderLock: transaction,+ });+ await fireToCompletion(harness, h, baseSchedule({ agentKind: 'pi', model: h.session.model }));+ // 新建任务时的那一次照常裁决(定时任务新建的任务在本机运行);绑定到这个任务之后不再用本机目录裁决。+ expect(checkModelRoute).toHaveBeenCalledTimes(1);+ expect(isAgentOnOtherDevice).toHaveBeenCalledWith('scheduler-session');+ expect(transaction).not.toHaveBeenCalled();+ expect(h.send).toHaveBeenCalledTimes(1);+ });++ it('keeps deciding routes here when the lookup fails', async () => {+ const h = createSessionHarness();+ (h.session as { agentKind: string }).agentKind = 'pi';+ (h.session as { model: string }).model = 'chatgpt/gpt-5.6-sol';+ const checkModelRoute = vi.fn(async () => ({ kind: 'pass' as const }));+ const harness = createRunnerHarness(h, null, {+ checkModelRoute,+ isAgentOnOtherDevice: vi.fn(async () => {+ throw new Error('db closed');+ }),+ });+ await fireToCompletion(harness, h, baseSchedule({ agentKind: 'pi', model: h.session.model }));+ expect(checkModelRoute.mock.calls.length).toBeGreaterThan(1);+ });+it('prepares a late Pi reroute before binding the result listener or sending', async () => {const h = createSessionHarness();(h.session as { agentKind: string }).agentKind = 'pi';diff --git a/apps/desktop/src/main/scheduler-host/index.ts b/apps/desktop/src/main/scheduler-host/index.tsindex 555ec0b5ef..d02a818fc8 100644--- a/apps/desktop/src/main/scheduler-host/index.ts+++ b/apps/desktop/src/main/scheduler-host/index.ts@@ -24,6 +24,7 @@ import type { FeishuIM } from '@cindy/im';import { dialogueWorkspaceRoots } from '../localDb/dialogueWorkspace';import { sessions } from '../localDb/schema.js';+import { getDbClient } from '../localDb/client/current';import { isReviewSessionSource } from '../../shared/sessionSource.js';import { dbToMakerAgentKind } from '../../shared/agentKindConversion.js';import { assertScheduledHarnessSupported } from '../maker-ipc/scheduledModelSelection';@@ -129,6 +130,15 @@ async function startSchedulerInternal(deps: StartSchedulerDeps): Promise<SchedulonSessionCreated: broadcastSessionCreated,// 停用轴裁决:每次 fire 前判保存路由是否已被用户停用(见 runner deps 注释)。checkModelRoute: verdictForModelRoute,+ // Agent 在另一台电脑运行的任务按那台的目录裁决,本机停用轴不适用(读失败按本机任务处理)。+ isAgentOnOtherDevice: async (sessionId) => {+ const [row] = await getDbClient()+ .drizzle.select({ agentDeviceId: sessions.agentDeviceId, remoteHostId: sessions.remoteHostId })+ .from(sessions)+ .where(eq(sessions.id, sessionId))+ .limit(1);+ return !!row?.agentDeviceId && !row.remoteHostId;+ },// 隐式改道后按落地拷贝 reconcile effort/Fast(见 runner deps 注释,R27)。resolveRouteCopyCapabilities,resolveDefaultModelRoute: resolveDefaultScheduleRoute,diff --git a/apps/desktop/src/main/scheduler-host/runner.ts b/apps/desktop/src/main/scheduler-host/runner.tsindex e71264c5d2..6b12732f5e 100644--- a/apps/desktop/src/main/scheduler-host/runner.ts+++ b/apps/desktop/src/main/scheduler-host/runner.ts@@ -285,6 +285,11 @@ export interface MakerScheduleRunnerDeps {onSessionCreated?: (sessionId: string) => void;/** 可选:撞忙排队桥。未注入时心跳撞忙回退为顺延(deferFire)旧行为。 */schedulerQueue?: SchedulerQueueDeps;+ /**+ * 任务的 Agent 在同账号另一台电脑上运行:模型与来源属于那台的目录,本机停用轴不裁决+ * (由那台在启动 / 切换时裁决)。缺省 = 都按本机任务处理。+ */+ isAgentOnOtherDevice?: (sessionId: string) => Promise<boolean>;/*** 停用轴裁决(生产 = maker-host/model-route-guard-live 的 verdictForModelRoute)。* scheduler 的每次 fire 都是新的付费调用,不属于「运行中的会话不打断」豁免:@@ -408,6 +413,22 @@ export class MakerScheduleRunner implements ScheduleRunner {this.scheduler = scheduler;}+ /**+ * 停用轴裁决。Agent 在另一台电脑运行的任务用那台的模型目录,本机不裁决(那台启动 / 切换时+ * 会自己拒绝不可用的路由);其余任务与原来完全一致。只在 checkModelRoute 已注入时调用。+ */+ private async checkRouteFor(+ sessionId: string | undefined,+ agent: AgentKind,+ model: string,+ providerId: string | null,+ ): ReturnType<NonNullable<MakerScheduleRunnerDeps['checkModelRoute']>> {+ if (sessionId && (await this.deps.isAgentOnOtherDevice?.(sessionId).catch(() => false))) {+ return { kind: 'pass' };+ }+ return this.deps.checkModelRoute!(agent, model, providerId);+ }+private async retireHeartbeat(schedule: Schedule,ctx: FireContext,@@ -1051,7 +1072,7 @@ export class MakerScheduleRunner implements ScheduleRunner {// 可见),不能继续经停用路由扣费;隐式默认落点被停用而有启用替代拷贝时改路由过去。let reroutedProviderId: string | null = null;if (this.deps.checkModelRoute) {- const verdict = await this.deps.checkModelRoute(effectiveAgentKind, model, createProviderId);+ const verdict = await this.checkRouteFor(isHeartbeat ? sessionId : undefined, effectiveAgentKind, model, createProviderId);if (verdict.kind === 'reject') {throw new Error(`schedule route unavailable: ${describeModelRouteRejection(verdict.reason, model, createProviderId)} (${verdict.reason})`,@@ -1594,7 +1615,7 @@ export class MakerScheduleRunner implements ScheduleRunner {// state bind to the Session instance. The transaction may retire it.if (effectiveAgentKind === 'pi' && this.deps.checkModelRoute) {const currentProviderId = getSessionProvider(session.id);- const verdict = await this.deps.checkModelRoute('pi', runtimeModel, currentProviderId);+ const verdict = await this.checkRouteFor(session.id, 'pi', runtimeModel, currentProviderId);if (verdict.kind === 'reject') {throw new Error(`schedule route unavailable: ${describeModelRouteRejection(verdict.reason, runtimeModel, currentProviderId)} (${verdict.reason})`);}@@ -1700,7 +1721,8 @@ export class MakerScheduleRunner implements ScheduleRunner {// reject 即失败收口,不发出这次新的付费调用。if (this.deps.checkModelRoute) {const dispatchProviderId = getSessionProvider(session.id);- const verdict = await this.deps.checkModelRoute(+ const verdict = await this.checkRouteFor(+ session.id,effectiveAgentKind,runtimeModel,dispatchProviderId,@@ -2678,7 +2700,7 @@ export class MakerScheduleRunner implements ScheduleRunner {const routeProviderId = explicitProviderId ?? currentProviderId;let providerId = routeProviderId;if (this.deps.checkModelRoute) {- const verdict = await this.deps.checkModelRoute('pi', model, routeProviderId);+ const verdict = await this.checkRouteFor(sessionId, 'pi', model, routeProviderId);if (verdict.kind === 'reject') {throw new QueuedRouteDisabledError(`schedule route unavailable: ${describeModelRouteRejection(verdict.reason, model, routeProviderId)} (${verdict.reason})`,@@ -2742,7 +2764,7 @@ export class MakerScheduleRunner implements ScheduleRunner {// 误按隐式默认裁决放行,随后照旧沿停用来源派发(PR #744 review 第八轮)。// 两者都缺才是真正的隐式默认(reroute 才有意义)。const routeProviderId = explicitProviderId ?? currentProviderId;- const verdict = await this.deps.checkModelRoute(live.agentKind, targetModel, routeProviderId);+ const verdict = await this.checkRouteFor(live.id, live.agentKind, targetModel, routeProviderId);if (verdict.kind === 'reject') {throw new QueuedRouteDisabledError(`schedule route unavailable: ${describeModelRouteRejection(verdict.reason, targetModel, routeProviderId)} (${verdict.reason})`,@@ -2816,7 +2838,8 @@ export class MakerScheduleRunner implements ScheduleRunner {// 目标来源启用但需要凭证切换、而**当前**来源在排队等待期间被停用时,不裁决// 就成了绕过口,照发等于继续经停用路由扣费(PR #744 review 第十轮)。if (this.deps.checkModelRoute) {- const retained = await this.deps.checkModelRoute(+ const retained = await this.checkRouteFor(+ live.id,live.agentKind,live.model,currentProviderId,@@ -2909,7 +2932,8 @@ export class MakerScheduleRunner implements ScheduleRunner {// (runtimeModel, 落地来源) 重新裁决,reject 即中止派发(与上方同语义,由排队// onAccepted 在 vendor dispatch 之前收口)。if (this.deps.checkModelRoute && runtimeModel !== targetModel) {- const actual = await this.deps.checkModelRoute(+ const actual = await this.checkRouteFor(+ live.id,live.agentKind,runtimeModel,applyProviderId ?? currentProviderId,diff --git a/apps/desktop/src/main/session-share/sessionShareExport.ts b/apps/desktop/src/main/session-share/sessionShareExport.tsindex 2cb3cc8fc2..a800960e5f 100644--- a/apps/desktop/src/main/session-share/sessionShareExport.ts+++ b/apps/desktop/src/main/session-share/sessionShareExport.ts@@ -587,6 +587,10 @@ export async function exportSessionShare(if (session.remoteHostId) {throw codedError('PRECONDITION_FAILED', 'remote sessions cannot be exported');}+ // Agent 在另一台电脑运行的任务:转录在那台,本机打包不全。+ if (await sessionAgentRunsOnOtherDevice(opts.sessionId)) {+ throw codedError('PRECONDITION_FAILED', 'tasks whose agent runs on another computer cannot be exported');+ }if (session.orcaRole === 'worker') {throw codedError('PRECONDITION_FAILED',@@ -1042,6 +1046,14 @@ function resolveMediaFile(}}+async function sessionAgentRunsOnOtherDevice(sessionId: string): Promise<boolean> {+ const row = await getDbClient().queryOne<{ agentDeviceId: string | null }>(+ 'SELECT agent_device_id AS agentDeviceId FROM sessions WHERE id = ? LIMIT 1',+ [sessionId],+ );+ return Boolean(row?.agentDeviceId);+}+async function readSessionRow(sessionId: string): Promise<SessionRow | null> {return ((await getDbClient().queryOne<SessionRow>(diff --git a/apps/desktop/src/main/task-migration/service.ts b/apps/desktop/src/main/task-migration/service.tsindex ebf8c2bfa9..79c0fc7ad1 100644--- a/apps/desktop/src/main/task-migration/service.ts+++ b/apps/desktop/src/main/task-migration/service.ts@@ -236,6 +236,7 @@ interface SourceSession {workingDir: string;workspaceKind: string;remoteHostId: string | null;+ agentDeviceId: string | null;status: string;source: string;orcaRole: string | null;@@ -248,7 +249,7 @@ async function assertSource(worker = false,): Promise<SourceSession> {const row = await scope.db.queryOne<SourceSession>(- 'SELECT id, working_dir AS workingDir, workspace_kind AS workspaceKind, remote_host_id AS remoteHostId, status, source, orca_role AS orcaRole, agent_kind AS agentKind, updated_at AS updatedAt FROM sessions WHERE id = ?',+ 'SELECT id, working_dir AS workingDir, workspace_kind AS workspaceKind, remote_host_id AS remoteHostId, agent_device_id AS agentDeviceId, status, source, orca_role AS orcaRole, agent_kind AS agentKind, updated_at AS updatedAt FROM sessions WHERE id = ?',[sessionId],);scope.assertCurrent();@@ -257,6 +258,8 @@ async function assertSource(!(row.status === 'active' || (worker && row.status === 'archived')) ||!row.workingDir ||row.remoteHostId ||+ // Agent 在另一台电脑运行的任务:Agent 会话记录在那台,本机无法完整复制。+ row.agentDeviceId ||(worker ? row.orcaRole !== 'worker' : row.orcaRole === 'worker') ||!['desktop', 'shared', 'feishu'].includes(row.source))diff --git a/apps/desktop/src/renderer/__tests__/chatInputModelSelectorRouting.test.ts b/apps/desktop/src/renderer/__tests__/chatInputModelSelectorRouting.test.tsindex 12f70b6bb9..a5805454e2 100644--- a/apps/desktop/src/renderer/__tests__/chatInputModelSelectorRouting.test.ts+++ b/apps/desktop/src/renderer/__tests__/chatInputModelSelectorRouting.test.ts@@ -377,9 +377,11 @@ describe('ChatInput model source switching wiring', () => {// device-link 老被控端 capabilities-only:联合列表的数据源是供应商目录,没有目录// 就是一张空列表。判据必须是结构化的 unsupported,不是 providers.length===0// (后者在加载中恒成立,会让面板每次打开先闪一下旧布局)。+ // 目录所在电脑 = 远程任务的被控端,或 Agent 在另一台电脑运行时的那台。expect(chatInputSource).toContain(- 'const unifiedModelPanelEnabled = !deviceLinkDeviceId || !remoteProviders.unsupported;',+ 'const unifiedModelPanelEnabled = !catalogDeviceId || !remoteProviders.unsupported;',);+ expect(chatInputSource).toContain('const catalogDeviceId = deviceLinkDeviceId ?? agentDeviceId ?? undefined;');});/**diff --git a/apps/desktop/src/renderer/__tests__/deviceSwitcherAgentDevice.test.tsx b/apps/desktop/src/renderer/__tests__/deviceSwitcherAgentDevice.test.tsxnew file mode 100644index 0000000000..ff6034bc2b--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/deviceSwitcherAgentDevice.test.tsx@@ -0,0 +1,71 @@+// @vitest-environment jsdom++/**+ * 设备 pill 的「只让 Agent 在其他电脑运行」:与「在那台上创建任务」分段列出、互不冒充;+ * 选中后 pill 写明 Agent 所在的电脑,点「本机」回到全部在本机。+ */+import { cleanup, fireEvent, render, screen } from '@testing-library/react';+import { afterEach, describe, expect, it, vi } from 'vitest';++vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string, values?: Record<string, unknown>) =>+ values?.device ? `${key}(${String(values.device)})` : key,+ }),+}));++import { DeviceSwitcherPill } from '@/components/new-chat/DeviceSwitcherPill';++const devices = [+ { deviceId: 'dev-b', name: 'Office Mac', platform: 'darwin', online: true },+ { deviceId: 'dev-c', name: 'Old PC', platform: 'win32', online: false },+];++afterEach(() => cleanup());++function renderPill(props: Partial<Parameters<typeof DeviceSwitcherPill>[0]> = {}) {+ const onChange = vi.fn();+ const onAgentDeviceChange = vi.fn();+ const onOpenChange = vi.fn();+ render(+ <DeviceSwitcherPill+ devices={devices}+ value={null}+ onChange={onChange}+ open+ onOpenChange={onOpenChange}+ onAgentDeviceChange={onAgentDeviceChange}+ {...props}+ />,+ );+ return { onChange, onAgentDeviceChange, onOpenChange };+}++describe('device pill: agent on another computer', () => {+ it('lists computers for running only the agent separately from creating the task there', () => {+ const { onChange, onAgentDeviceChange, onOpenChange } = renderPill();+ expect(screen.getByText('newChat.deviceSwitcher.agentSection')).toBeTruthy();+ const agentRows = screen.getAllByTestId('create-agent-agent-device-option');+ expect(agentRows).toHaveLength(2);+ // 离线的电脑列出但不能选。+ expect((agentRows[1] as HTMLButtonElement).disabled).toBe(true);+ fireEvent.click(agentRows[0]);+ expect(onAgentDeviceChange).toHaveBeenCalledWith('dev-b', 'Office Mac');+ expect(onChange).not.toHaveBeenCalled();+ expect(onOpenChange).toHaveBeenCalledWith(false);+ });++ it('names the agent computer on the pill and returns everything here from 本机', () => {+ const { onChange } = renderPill({ agentDeviceId: 'dev-b' });+ const pill = screen.getByTestId('create-agent-device-pill');+ expect(pill.getAttribute('aria-label')).toContain('newChat.deviceSwitcher.agentPill(Office Mac)');+ const localRow = screen.getAllByTestId('create-agent-device-option')[0];+ fireEvent.click(localRow);+ expect(onChange).toHaveBeenCalledWith(null, null);+ });++ it('keeps the old menu when the caller does not offer it', () => {+ renderPill({ onAgentDeviceChange: undefined });+ expect(screen.queryByText('newChat.deviceSwitcher.agentSection')).toBeNull();+ });+});diff --git a/apps/desktop/src/renderer/__tests__/newMakerCreateAgentVisualContract.test.ts b/apps/desktop/src/renderer/__tests__/newMakerCreateAgentVisualContract.test.tsindex 0149255472..8b06f3dc38 100644--- a/apps/desktop/src/renderer/__tests__/newMakerCreateAgentVisualContract.test.ts+++ b/apps/desktop/src/renderer/__tests__/newMakerCreateAgentVisualContract.test.ts@@ -170,9 +170,9 @@ describe('NewMakerDraftRoute CREATE AGENT visual contract', () => {// 并非真实授予的上下文。本机草稿行为不变;把 picker 路由到对端后恢复,见 issue #1012。'onExtraDirsChange={isDeviceLinkDraft ? undefined : handleExtraDirsChange}','onNewGoal={(text) =>',- 'rememberedEffortByModel={isDeviceLinkDraft ? undefined : draft.effortByModel}',+ 'rememberedEffortByModel={usesDeviceCatalog ? undefined : draft.effortByModel}','onRememberedEffortChange={',- 'isDeviceLinkDraft ? undefined : handleRememberedEffortChange',+ 'usesDeviceCatalog ? undefined : handleRememberedEffortChange',"placeholder={t('newChat.chatInput.createAgentPlaceholder')}",// 统一模型选择器(M5):新会话的选中直通 + 收藏锚点选中态。撤掉 AgentSelect 后,// 「换引擎」这件事只剩这一条路径 —— 掉了它草稿就再也换不了引擎。diff --git a/apps/desktop/src/renderer/__tests__/newMakerDraft.test.ts b/apps/desktop/src/renderer/__tests__/newMakerDraft.test.tsindex 1b47202161..f9f8f0a98d 100644--- a/apps/desktop/src/renderer/__tests__/newMakerDraft.test.ts+++ b/apps/desktop/src/renderer/__tests__/newMakerDraft.test.ts@@ -1861,3 +1861,31 @@ describe('Bot default model write-through', () => {expect(store.getDraft()).toEqual(before);});});++// Agent 在同账号另一台电脑运行:任务、项目与命令仍在本机,只记下运行 Agent 的电脑。+describe('newMakerDraft agent computer', () => {+ it('keeps the agent computer across local folder changes and clears it for remote tasks', async () => {+ const { getDraft, patchDraft } = await loadModule();+ patchDraft({ agentDeviceId: ' dev-b ', agentDeviceName: 'Office Mac' });+ expect(getDraft().agentDeviceId).toBe('dev-b');+ // 换本机项目:Agent 仍在那台。+ patchDraft({ workingDir: '/local/proj' });+ expect(getDraft()).toMatchObject({ agentDeviceId: 'dev-b', agentDeviceName: 'Office Mac', workingDir: '/local/proj' });+ // 任务改建到远程设备或 SSH 主机时不成立。+ patchDraft({ deviceLinkDeviceId: 'dev-a', deviceLinkDeviceName: 'Studio', workingDir: null });+ expect(getDraft()).toMatchObject({ agentDeviceId: null, agentDeviceName: null });+ patchDraft({ deviceLinkDeviceId: null, deviceLinkDeviceName: null, workingDir: null });+ patchDraft({ agentDeviceId: 'dev-b', agentDeviceName: 'Office Mac' });+ patchDraft({ workingDir: '/remote/proj', remoteHostId: 'ssh-1' });+ expect(getDraft()).toMatchObject({ agentDeviceId: null, remoteHostId: 'ssh-1' });+ });++ it('does not restore the agent computer after a restart', async () => {+ let mod = await loadModule();+ mod.patchDraft({ workingDir: '/local/proj', agentDeviceId: 'dev-b', agentDeviceName: 'Office Mac' });+ await new Promise((resolve) => setTimeout(resolve, 600));+ vi.resetModules();+ mod = await loadModule();+ expect(mod.getDraft()).toMatchObject({ workingDir: '/local/proj', agentDeviceId: null, agentDeviceName: null });+ });+});diff --git a/apps/desktop/src/renderer/__tests__/newMakerProjectPicker.test.ts b/apps/desktop/src/renderer/__tests__/newMakerProjectPicker.test.tsindex f125f39fd1..a0e5812681 100644--- a/apps/desktop/src/renderer/__tests__/newMakerProjectPicker.test.ts+++ b/apps/desktop/src/renderer/__tests__/newMakerProjectPicker.test.ts@@ -559,8 +559,9 @@ describe('Shared create project picker', () => {// 路由以被控端(deviceId)为准计算 hidden。不可用性变化只收窄可选入口;不得由// 监听旧 draft 的 effect 再写回选中值,否则会覆盖同轮刚应用的新默认组合。+ // 目录所在电脑:远程任务的被控端,或 Agent 在另一台电脑运行时的那台。expect(newMakerDraftRouteSource).toMatch(- /useAvailableAgents\(\s*effectiveDeviceLinkDeviceId,?\s*\)/,+ /useAvailableAgents\(\s*catalogDeviceId,?\s*\)/,);expect(newMakerDraftRouteSource).not.toMatch(/hiddenSwitcherVendors\.includes\(draft\.vendor\)/,@@ -571,7 +572,7 @@ describe('Shared create project picker', () => {// 常态路径的门禁。**门禁没放松,只是换了承载物**:ChatInput 按同一个 runtime 注册// 结果算出 unifiedAgents 交给联合列表,未注册的引擎连行都不出现。expect(newMakerDraftRouteSource).toContain('hiddenVendors={hiddenSwitcherVendors}');- expect(chatInputSource).toMatch(/useAvailableAgents\(deviceLinkDeviceId\)/);+ expect(chatInputSource).toMatch(/useAvailableAgents\(catalogDeviceId\)/);expect(chatInputSource).toContain('unifiedAgents={effectiveUnifiedAgents}');// fail-open:注册结果没回来之前不隐藏任何引擎;当前引擎恒在列。expect(chatInputSource).toContain('if (!runtimeAgentsLoaded) return undefined;');@@ -936,7 +937,8 @@ describe('Shared create project picker', () => {expect(newMakerDraftRouteSource).toContain('capabilitiesError || (deviceProvidersError && !deviceProvidersUnsupported)',);- expect(newMakerDraftRouteSource.match(/remoteModelListStatus !== 'ready'/g)).toHaveLength(2);+ // 发送 + 远程任务的新建目标 + Agent 在另一台电脑时的新建目标。+ expect(newMakerDraftRouteSource.match(/remoteModelListStatus !== 'ready'/g)).toHaveLength(3);expect(newMakerDraftRouteSource).toContain("toast.error(t('newChat.modelSelector.remoteLoadFailed'))",);@@ -1280,8 +1282,9 @@ describe('Shared create project picker', () => {it('routes every draft-target transition through the single action', () => {// 五条路径:设备 pill、设备域浏览器选项目、工作区 picker、所选设备失效后的自动回落、// “对话”分组导航请求。声明本身是 `= useCallback(` 不匹配这个模式,所以数出来的就是调用点。+ // 第六条:选「只让 Agent 在其他电脑运行」时,原来要建到远程设备 / SSH 的草稿先回本机。const calls = newMakerDraftRouteSource.match(/applyDraftTarget\(\{/g) ?? [];- expect(calls.length).toBe(5);+ expect(calls.length).toBe(6);// 组件里不得再有任何一处手写这些副作用 —— 手写一处就等于又开了一条绕过推导的路。// patchDraft 仍可出现(入场清 extraDirs、发送后复位),但不得再带设备字段。expect(newMakerDraftRouteSource).not.toContain('deviceLinkDeviceId: deviceId,');@@ -1669,7 +1672,7 @@ describe('Shared create project picker', () => {expect(seed).toContain('capabilitiesChanged,');expect(seed).toContain('if (!capabilities || capabilitiesLoading');expect(seed).toContain('controllerTouched: dlRuntimeTouchedRef.current,');- expect(seed).toContain('remoteModelChosenByUser: remoteDraftState.value?.modelChosenByUser,');+ expect(seed).toContain('remoteModelChosenByUser: deviceDraftDefaults?.modelChosenByUser,');expect(seed).toContain('modelChosenByUser: true,');expect(seed).toContain('current.model,');@@ -1698,7 +1701,7 @@ describe('Shared create project picker', () => {newMakerDraftRouteSource.indexOf('// 远程草稿展示用:'),);// 播种 effect 侧的 key 构造(正本)。- expect(seed).toContain('const key = `${effectiveDeviceLinkDeviceId}:${capabilityAgentKind}`;');+ expect(seed).toContain('const key = `${catalogDeviceId}:${capabilityAgentKind}`;');const unified = newMakerDraftRouteSource.slice(newMakerDraftRouteSource.indexOf('const handleUnifiedDraftSelect = useCallback('),@@ -1706,7 +1709,7 @@ describe('Shared create project picker', () => {);// 选择侧:同一构造,agent 一维换成**目标引擎**(selection.vendor),且必须在 setDlSel 之前。expect(unified).toContain(- 'dlSeedKeyRef.current = `${effectiveDeviceLinkDeviceId}:${dbToMakerAgentKind(',+ 'dlSeedKeyRef.current = `${catalogDeviceId}:${dbToMakerAgentKind(',);expect(unified).toContain('normalizeDbAgentKind(selection.vendor),');expect(unified.indexOf('dlSeedKeyRef.current =')).toBeLessThan(@@ -1739,7 +1742,7 @@ describe('Shared create project picker', () => {);const body = derive.slice(0, derive.indexOf('}, ['));// 本机分支行为不变。- expect(body).toContain('if (!isDeviceLinkDraft) return localProviderIdForDraft;');+ expect(body).toContain('if (!usesDeviceCatalog) return localProviderIdForDraft;');// 远程分支按**被控端**目录 + 草稿当前模型复算,用与 main 同源的解析函数。expect(body).toContain('effectiveSourceIdForModel(');expect(body).toContain('deviceProviders,');diff --git a/apps/desktop/src/renderer/__tests__/remoteSessionSyncInvariants.test.ts b/apps/desktop/src/renderer/__tests__/remoteSessionSyncInvariants.test.tsindex ae6e021e8b..2bd12c484a 100644--- a/apps/desktop/src/renderer/__tests__/remoteSessionSyncInvariants.test.ts+++ b/apps/desktop/src/renderer/__tests__/remoteSessionSyncInvariants.test.ts@@ -114,7 +114,7 @@ describe('CCAgentSessionView 接线不变式', () => {});it('已有设备互联任务与保留原路由的 SSH 任务跳过来源门禁,草稿与本地任务仍保留门禁', () => {expect(chatInputSrc).toContain(- 'const enforceConnectedSourceGate = (!sessionId || !deviceLinkDeviceId) && !preserveSshCodexRoute;',+ 'const enforceConnectedSourceGate = (!sessionId || !catalogDeviceId) && !preserveSshCodexRoute;',);expect(chatInputSrc).toContain('const preserveSshCodexRoute = !!sessionId && !!sshCodexHostId &&');expect(chatInputSrc).toMatch(diff --git a/apps/desktop/src/renderer/__tests__/sidebarRemoteProjectIcon.test.ts b/apps/desktop/src/renderer/__tests__/sidebarRemoteProjectIcon.test.tsindex 933058fe98..4b064bf177 100644--- a/apps/desktop/src/renderer/__tests__/sidebarRemoteProjectIcon.test.ts+++ b/apps/desktop/src/renderer/__tests__/sidebarRemoteProjectIcon.test.ts@@ -28,7 +28,11 @@ describe('sidebar remote project icon', () => {});it('maps device-link sessions to the device-link project icon and SSH sessions to the SSH project icon', () => {- expect(remoteProjectIconSource).toContain("kind === 'device-link' ? MonitorSmartphone : Globe");+ expect(remoteProjectIconSource).toMatch(+ /kind === 'device-link'\s+\?\s+MonitorSmartphone\s+:\s+Globe/,+ );+ // Agent 在另一台电脑运行的本机任务有自己的标识,不冒充远程设备任务。+ expect(remoteProjectIconSource).toMatch(/kind === 'agent-device'\s+\?\s+Cpu/);expect(sessionItemSource).toMatch(/const remoteIconKind = session\.deviceLinkDeviceId\s+\?\s+'device-link'\s+:\s+session\.remoteHostId\s+\?\s+'ssh'\s+:\s+null/,);diff --git a/apps/desktop/src/renderer/components/chat/AgentOnOtherDeviceContext.tsx b/apps/desktop/src/renderer/components/chat/AgentOnOtherDeviceContext.tsxnew file mode 100644index 0000000000..a655bc2d5f--- /dev/null+++ b/apps/desktop/src/renderer/components/chat/AgentOnOtherDeviceContext.tsx@@ -0,0 +1,13 @@+/**+ * 当前聊天流所属任务的 Agent 是否在另一台电脑运行(MessageStream 顶层 provide)。+ *+ * 消息级「分叉」依赖本机的 Agent 会话记录;这类任务的会话记录在那台电脑上,入口先隐藏+ * (与 SSH 远程任务一致)。默认值 false:聊天流之外以及本机任务的行为不变。+ */+import { createContext, useContext } from 'react';++export const AgentOnOtherDeviceContext = createContext(false);++export function useAgentOnOtherDevice(): boolean {+ return useContext(AgentOnOtherDeviceContext);+}diff --git a/apps/desktop/src/renderer/components/chat/AssistantMessage.tsx b/apps/desktop/src/renderer/components/chat/AssistantMessage.tsxindex c407fee0ee..b1cf40e29b 100644--- a/apps/desktop/src/renderer/components/chat/AssistantMessage.tsx+++ b/apps/desktop/src/renderer/components/chat/AssistantMessage.tsx@@ -53,6 +53,7 @@ import type { AgentKind as RendererAgentKind } from '@/lib/ccAgent.types';import type { TurnUsageDetails } from '../../../shared/turnUsageDetails';import type { RegionalMoney } from '../../../shared/regionalMoney';import { useAgentCapabilities, type AgentKind as MakerAgentKind } from '@/hooks/useAgentCapabilities';+import { useAgentOnOtherDevice } from './AgentOnOtherDeviceContext';import { useSessionFileOrigin } from './ChatSessionFileContext';import { originDeviceId } from '@/lib/sessionFileOrigin';import { buildSessionMessageDeepLink } from '@/lib/deepLink';@@ -271,7 +272,9 @@ export const AssistantMessage = memo(function AssistantMessage({);const isRemote = Boolean(remoteHostId);const sharedGuest = isSharedTaskPeer(originDeviceId(sessionFileOrigin) ?? '');- const forkSupported = !isRemote && (!agentKind || (capabilities?.fork?.supported ?? true));+ const agentOnOtherDevice = useAgentOnOtherDevice();+ const forkSupported =+ !isRemote && !agentOnOtherDevice && (!agentKind || (capabilities?.fork?.supported ?? true));const handleFork = useForkAtMessage({sessionId: currentSessionId,messageClientId,diff --git a/apps/desktop/src/renderer/components/chat/MessageStream.tsx b/apps/desktop/src/renderer/components/chat/MessageStream.tsxindex 772d623b2b..99c81facdb 100644--- a/apps/desktop/src/renderer/components/chat/MessageStream.tsx+++ b/apps/desktop/src/renderer/components/chat/MessageStream.tsx@@ -344,6 +344,7 @@ import {import { ChatImageView } from './ChatImageView';import { ImageGalleryContext, type GalleryImage } from './ImageGalleryContext';import { GhostFulfillmentContext } from './GhostSummonCard';+import { AgentOnOtherDeviceContext } from './AgentOnOtherDeviceContext';import { ChatSessionFileProvider, useChatSessionFileValue } from './ChatSessionFileContext';import { toRemoteMediaOrigin } from '@/lib/sessionFileOrigin';import { rewriteToRemoteMediaOrigin, type RemoteMediaOrigin } from '@/../shared/remoteMediaUrl';@@ -424,6 +425,8 @@ interface MessageStreamProps {* so message-level controls can gate features unsupported on remote* (e.g. rewind on cc-remote daemon sessions). */remoteHostId?: string | null;+ /** 任务的 Agent 在另一台电脑运行(消息级分叉暂不可用)。 */+ agentOnOtherDevice?: boolean;/** Task origin. Personal WeChat must not be told to switch to Full access. */sessionSource?: string | null;/** Session working directory; passed down so MarkdownRenderer / UserMessage@@ -2678,6 +2681,7 @@ export function MessageStream({sessionTitle,agentKind,remoteHostId,+ agentOnOtherDevice = false,sessionSource,workingDir,assistantAvatar,@@ -6150,6 +6154,7 @@ export function MessageStream({return (<ChatSessionFileProvider value={sessionFileValue}>+ <AgentOnOtherDeviceContext.Provider value={agentOnOtherDevice}><GhostFulfillmentContext.Provider value={ghostCallsByUserTurn}><ImageGalleryContext.Provider value={sessionImageSrcs}><div className="relative h-full w-full">@@ -6571,6 +6576,7 @@ export function MessageStream({</div></ImageGalleryContext.Provider></GhostFulfillmentContext.Provider>+ </AgentOnOtherDeviceContext.Provider></ChatSessionFileProvider>);}diff --git a/apps/desktop/src/renderer/components/chat/UserMessage.tsx b/apps/desktop/src/renderer/components/chat/UserMessage.tsxindex 53986c9846..acefaecd1b 100644--- a/apps/desktop/src/renderer/components/chat/UserMessage.tsx+++ b/apps/desktop/src/renderer/components/chat/UserMessage.tsx@@ -66,6 +66,7 @@ import {useAgentCapabilities,type AgentKind as MakerAgentKind,} from '@/hooks/useAgentCapabilities';+import { useAgentOnOtherDevice } from './AgentOnOtherDeviceContext';import { useChatSessionFile } from './ChatSessionFileContext';import { isRemoteFileOrigin, originDeviceId, toRemoteMediaOrigin } from '@/lib/sessionFileOrigin';import { rewriteToRemoteMediaOrigin } from '../../../shared/remoteMediaUrl';@@ -886,7 +887,10 @@ export function UserMessage({// 远端 cc daemon 会话暂不支持 Fork/Rewind 依赖的 query rebuild (MVP),// remoteHostId 非空时直接关掉这两个能力, 避免点了落到后端错误。const isRemote = Boolean(remoteHostId);- const forkSupported = !isRemote && (!agentKind || (capabilities?.fork?.supported ?? true));+ // Agent 在另一台电脑运行:会话记录在那台,分叉入口先隐藏(回退照常可用)。+ const agentOnOtherDevice = useAgentOnOtherDevice();+ const forkSupported =+ !isRemote && !agentOnOtherDevice && (!agentKind || (capabilities?.fork?.supported ?? true));const rewindSupported =!isRemote &&(!agentKind || (capabilities?.rewind?.supported ?? true));diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsxindex 7548215a13..72dcd441df 100644--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx@@ -526,6 +526,12 @@ interface ChatInputProps {* 由 CCAgentSessionView(reactive remoteDeviceId)/ NewMakerDraftRoute(目标设备)传入;本地会话 undefined。*/deviceLinkDeviceId?: string | null;+ /**+ * 本机任务、但 Agent 在同账号另一台电脑上运行:那台电脑的 deviceId。只决定**模型目录**+ * (能力、供应商、可用引擎)从哪台读 —— 任务、文件、命令、斜杠命令、附件仍按本机任务处理,+ * 切换模型也走本机 IPC(由本机转给那台的 Agent)。与 deviceLinkDeviceId 互斥。+ */+ agentDeviceId?: string | null;/*** device-link「纯显示镜像」记忆 override:非空时优先于本机全局模型预设注入 ModelSelector,* 用于远程草稿 / 远程会话——非选中行读被控端镜像、改动经隧道写穿被控端,绝不碰控制端本地记忆@@ -1111,6 +1117,7 @@ export function ChatInput({initialWorkingDir,remoteHostId,deviceLinkDeviceId: _deviceLinkDeviceId,+ agentDeviceId: _agentDeviceId,modelMemoryOverride,initialModel,initialEffort,@@ -1188,6 +1195,10 @@ export function ChatInput({// device-link 远程会话:null = 已确认本地会话,undefined = 所有权尚未解析,string = 远程会话。// 预测守卫用原始值区分 null vs undefined,下游通路继续用 ?? undefined 归一化。const deviceLinkDeviceId = _deviceLinkDeviceId;+ /** Agent 在另一台电脑运行的本机任务(只影响模型目录来源)。 */+ const agentDeviceId = deviceLinkDeviceId ? null : (_agentDeviceId ?? null);+ /** 模型目录所在的电脑:远程任务在那台;Agent 在另一台电脑运行时也是那台。 */+ const catalogDeviceId = deviceLinkDeviceId ?? agentDeviceId ?? undefined;const sharedGuest = isSharedTaskPeer(deviceLinkDeviceId ?? '');const { t } = useTranslation();const navigate = useNavigate();@@ -1726,9 +1737,9 @@ export function ChatInput({const agentKind = vendorKeyToAgentKind(vendorKey);// device-link 远程会话:能力(模型 / fast / effort)从被控端读;本地会话 deviceLinkDeviceId undefined → 本地。- const ccCaps = useAgentCapabilities('claude-code', deviceLinkDeviceId ?? undefined);- const codexCaps = useAgentCapabilities('codex', deviceLinkDeviceId ?? undefined);- const piCaps = useAgentCapabilities('pi', deviceLinkDeviceId ?? undefined);+ const ccCaps = useAgentCapabilities('claude-code', catalogDeviceId);+ const codexCaps = useAgentCapabilities('codex', catalogDeviceId);+ const piCaps = useAgentCapabilities('pi', catalogDeviceId);const activeAgentCapabilities =agentKind === 'codex'? codexCaps.capabilities@@ -1856,8 +1867,8 @@ export function ChatInput({const sshCodexHostId = currentModelAgentKind === 'codex' && !deviceLinkDeviceId ? remoteHostId : null;const sshCodexProviders = useSshCodexProviders(sshCodexHostId);const localProviders = useProviders();- const remoteProviders = useDeviceProviders(deviceLinkDeviceId ?? undefined);- const providers = deviceLinkDeviceId ? remoteProviders.providers+ const remoteProviders = useDeviceProviders(catalogDeviceId);+ const providers = catalogDeviceId ? remoteProviders.providers: sshCodexHostId ? sshCodexProviders.providers : localProviders.providers;const sendProviders = filterChatBridgedCodexProviders(providers,@@ -1873,14 +1884,14 @@ export function ChatInput({// provider 目录,且真实读取失败时 fail closed。只有结构化 unsupported 才允许旧端回退。const { loading: localProvidersLoading } = useConnectedSource(currentModelAgentKind, activeModel);const remoteModelListStatus = resolveRemoteModelListStatus({- deviceId: deviceLinkDeviceId ?? undefined,+ deviceId: catalogDeviceId,agentKind: currentModelAgentKind,cc: ccCaps,codex: codexCaps,pi: piCaps,providers: remoteProviders,});- const providersLoading = deviceLinkDeviceId+ const providersLoading = catalogDeviceId? remoteModelListStatus === 'loading': sshCodexHostId ? sshCodexProviders.status === 'loading' : localProvidersLoading;// 统一模型选择器(model-selector-unified M5 / M6)在 composer 上的开关 —— **能力级**那一半@@ -1892,13 +1903,13 @@ export function ChatInput({// 的「已知边界」)。unsupported 是**结构化**判定(isDeviceProvidersUnsupportedError),// 不是 providers.length===0:后者在首帧加载中恒成立,拿它当条件会让面板每次打开先闪// 一下旧版布局。- const unifiedModelPanelEnabled = !deviceLinkDeviceId || !remoteProviders.unsupported;+ const unifiedModelPanelEnabled = !catalogDeviceId || !remoteProviders.unsupported;// 联合列表参与哪些引擎 —— 以**运行时注册结果**为准(device-link 取被控端的)。// 撤掉新会话工具条的 AgentSelect 后,它的 hiddenVendors 门禁就落到这里:Pi 二进制缺失// 时模型目录照样投影 Pi 模型,只看目录会让用户一路选到 requireAgent 的 not-registered。// 未加载完成 → 传 undefined(fail-open,不隐藏任何引擎);当前引擎恒在列。const { availableVendors: runtimeAvailableVendors, loaded: runtimeAgentsLoaded } =- useAvailableAgents(deviceLinkDeviceId);+ useAvailableAgents(catalogDeviceId);const unifiedAgents = useMemo<readonly AgentKind[] | undefined>(() => {if (!runtimeAgentsLoaded) return undefined;const kinds = UNIFIED_AGENT_KINDS.filter(@@ -1915,9 +1926,9 @@ export function ChatInput({!!activeModel && activeModel === (runtimeEffective?.model ?? initialModel) &&(activeProviderId ?? null) === (runtimeEffective ? runtimeEffective.providerId ?? null : initialProviderId ?? null) &&(!activeProviderId || activeProviderId === 'openai');- const enforceConnectedSourceGate = (!sessionId || !deviceLinkDeviceId) && !preserveSshCodexRoute;+ const enforceConnectedSourceGate = (!sessionId || !catalogDeviceId) && !preserveSshCodexRoute;const remoteModelListBlocked =- (!!deviceLinkDeviceId && enforceConnectedSourceGate && remoteModelListStatus !== 'ready') ||+ (!!catalogDeviceId && enforceConnectedSourceGate && remoteModelListStatus !== 'ready') ||(!!sshCodexHostId && sshCodexProviders.status !== 'ready');// chatEligibleSourcesForModel(不是裸 sourcesForModel):非聊天模型即便"存在于某个// 已连接来源"也不算有可发送来源(issue #882 第 3 点,2026-07 review)——否则 Send@@ -1938,7 +1949,7 @@ export function ChatInput({!remoteModelListBlocked &&// 老被控端明确不支持 provider:list 时只能依据 capabilities 放行;不能把缺少// provider 镜像误判成权威的「没有已连接来源」。- (!deviceLinkDeviceId || !remoteProviders.unsupported) &&+ (!catalogDeviceId || !remoteProviders.unsupported) &&!hasConnectedSendSource;// 会话显式选中的来源已断开(如外部删除订阅 OAuth 凭证):trigger 显示「已断开」错误态 +@@ -1949,7 +1960,7 @@ export function ChatInput({// providersLoading 期间不判(规则同 noConnectedSource,避免首帧闪断开态)。const selectedSourceDisconnected =!!sessionId &&- !deviceLinkDeviceId &&+ !catalogDeviceId &&!preserveSshCodexRoute &&isSelectedSourceDisconnected({providers,@@ -1986,7 +1997,8 @@ export function ChatInput({if (sshCodexHostId) return undefined;// device-link 远程草稿 / 会话:用纯显示镜像 override(读被控端全局预设、写穿被控端)。if (modelMemoryOverride) return modelMemoryOverride;- if (deviceLinkDeviceId) return undefined;+ // 模型目录在另一台电脑时不掺本机记忆(那台的来源 id 与本机的不是一回事)。+ if (catalogDeviceId) return undefined;return {getEffort: getProviderModelEffort,setEffort: setProviderModelEffort,@@ -2000,7 +2012,7 @@ export function ChatInput({clearEffort: clearProviderModelEffort,clearFast: clearProviderModelFast,};- }, [deviceLinkDeviceId, modelMemoryOverride, sshCodexHostId]);+ }, [catalogDeviceId, modelMemoryOverride, sshCodexHostId]);// 把「用户在当前来源下选定的 (model, effort)」记进模型全局预设,供其它非活跃行和之后的// 模型切换恢复。agent / 来源缺失(未知模型 / 0 已连接来源)/ device-link 无镜像时静默跳过。@@ -2011,12 +2023,12 @@ export function ChatInput({if (kind && effectiveSourceId && modelId) {if (modelMemory?.setChoice) {modelMemory.setChoice(kind, effectiveSourceId, modelId, eff);- } else if (!deviceLinkDeviceId) {+ } else if (!catalogDeviceId) {setProviderModelChoice(kind, effectiveSourceId, modelId, eff);}}},- [currentModelAgentKind, effectiveSourceId, modelMemory, deviceLinkDeviceId, sshCodexHostId],+ [currentModelAgentKind, effectiveSourceId, modelMemory, catalogDeviceId, sshCodexHostId],);const folderOpen = folderPickerOpen ?? internalFolderOpen;@@ -6072,8 +6084,8 @@ export function ChatInput({providerId?: string | null,targetAgentKind?: AgentKind,): { efforts: readonly Effort[]; defaultEffort: Effort | null } => {- if (deviceLinkDeviceId) {- const m = getModelById(modelId, deviceLinkDeviceId);+ if (catalogDeviceId) {+ const m = getModelById(modelId, catalogDeviceId);return { efforts: m?.efforts ?? [], defaultEffort: m?.defaultEffort ?? null };}const kinds: readonly AgentKind[] = targetAgentKind@@ -6101,7 +6113,7 @@ export function ChatInput({const legacy = getModelById(modelId);return { efforts: legacy?.efforts ?? [], defaultEffort: legacy?.defaultEffort ?? null };},- [deviceLinkDeviceId, currentModelAgentKind, providers],+ [catalogDeviceId, currentModelAgentKind, providers],);// 解析切到某 (供应商, 模型) 时应恢复的 fast —— 先读 (agent, model) 全局预设,再按目标来源@@ -6114,7 +6126,7 @@ export function ChatInput({const modelFastSupported = useCallback((targetModelId: string, providerId: string | null): boolean =>resolveFastSupported({- deviceId: deviceLinkDeviceId ?? undefined,+ deviceId: catalogDeviceId,deviceProviders: remoteProviders.providers,localProviders: providers,capabilities:@@ -6128,7 +6140,7 @@ export function ChatInput({agentKind: currentModelAgentKind,}),[- deviceLinkDeviceId,+ catalogDeviceId,remoteProviders.providers,providers,currentModelAgentKind,@@ -6164,7 +6176,8 @@ export function ChatInput({} = {},) => {const agentKind = opts.agentKind ?? currentModelAgentKind;- if (!sessionId || !agentKind || !modelId || sshCodexHostId) return;+ // Agent 在另一台电脑运行的任务:模型属于那台的目录,不写回本机的新建任务记忆。+ if (!sessionId || !agentKind || !modelId || sshCodexHostId || agentDeviceId) return;const activeProviderId =opts.activeProviderId !== undefined ? opts.activeProviderId : selectedProviderId;const memoryProviderId =@@ -6211,7 +6224,7 @@ export function ChatInput({log.warn('session draft model preference sync failed:', err);});},- [sessionId, deviceLinkDeviceId, currentModelAgentKind, selectedProviderId, effectiveSourceId, sshCodexHostId],+ [sessionId, deviceLinkDeviceId, agentDeviceId, currentModelAgentKind, selectedProviderId, effectiveSourceId, sshCodexHostId],);const persistFastModeChange = useCallback(@@ -9061,7 +9074,7 @@ export function ChatInput({}: undefined}- deviceId={deviceLinkDeviceId ?? undefined}+ deviceId={catalogDeviceId}// SSH 远程会话隐藏订阅直连模型(chatgpt/ / xai/):bridge 只挂在本地 compat-proxy,// 远程模式走 remoteEndpoint 不经翻译,选了必失败。excludeSubscriptionDirect={!!remoteHostId}diff --git a/apps/desktop/src/renderer/components/new-chat/DeviceSwitcherPill.tsx b/apps/desktop/src/renderer/components/new-chat/DeviceSwitcherPill.tsxindex 87ba893cf9..6136d2e210 100644--- a/apps/desktop/src/renderer/components/new-chat/DeviceSwitcherPill.tsx+++ b/apps/desktop/src/renderer/components/new-chat/DeviceSwitcherPill.tsx@@ -15,9 +15,12 @@* 主场景,默认停在某台远程机器有误发风险。* - 窄屏且有多台时收成图标 + 状态点:pill 排在窄屏会进正常流并 flex-wrap,省掉设备名可以* 少一次换行。只有一台对端时不收(名字短,信息更重要)。+ * - 「只让 Agent 在那台运行」单独成段(传了 onAgentDeviceChange 才显示):任务、项目文件与命令+ * 留在本机,Agent 用那台的登录、供应商与网络。它和「在那台上创建」是两件事 —— 后者整个任务+ * 都建在那台 —— 所以分段列出、各自写明,选中后 pill 显示「Agent 在 X」。*/-import { Check, ChevronDown, Laptop } from 'lucide-react';+import { Check, ChevronDown, Cpu, Laptop } from 'lucide-react';import { useTranslation } from 'react-i18next';import { cn } from '@/lib/utils';@@ -38,6 +41,10 @@ interface Props {/** 窄屏(pill 排进正常流)时收成图标 + 状态点。 */compact?: boolean;disabled?: boolean;+ /** 任务在本机、Agent 在这台电脑上运行;null = Agent 也在本机。 */+ agentDeviceId?: string | null;+ /** 不传 = 不提供「只让 Agent 在其他电脑运行」。 */+ onAgentDeviceChange?: (deviceId: string, deviceName: string | null) => void;}/**@@ -65,6 +72,8 @@ export function DeviceSwitcherPill({onOpenChange,compact = false,disabled = false,+ agentDeviceId = null,+ onAgentDeviceChange,}: Props) {const { t } = useTranslation();@@ -72,10 +81,18 @@ export function DeviceSwitcherPill({if (devices.length === 0) return null;const localLabel = t('ccAgent.sidebar.machineSwitcher.localMachine');- const label = resolveDeviceLabel(devices, value, localLabel);- const current = value == null ? null : devices.find((d) => d.deviceId === value);+ // 任务在本机、Agent 在另一台:pill 显示 Agent 所在的电脑(状态点也跟它走)。+ const agentDevice = value == null && agentDeviceId != null ? agentDeviceId : null;+ const label = agentDevice+ ? t('newChat.deviceSwitcher.agentPill', { device: resolveDeviceLabel(devices, agentDevice, localLabel) })+ : resolveDeviceLabel(devices, value, localLabel);+ const current = agentDevice+ ? devices.find((d) => d.deviceId === agentDevice)+ : value == null+ ? null+ : devices.find((d) => d.deviceId === value);// 本机不画状态点(它永远在线,画了只是噪音)。- const showDot = current != null;+ const showDot = current != null || agentDevice != null;// 当前值必须进 aria-label:compact 模式下按钮只剩图标 + 状态点、不渲染设备名文本,只报// 「设备」会让读屏用户完全不知道当前选的是哪台机器(Copilot review)。非 compact 时名字虽然// 可见,一并读出也不冗余 —— aria-label 会覆盖内文,不会重复播报。@@ -106,11 +123,15 @@ export function DeviceSwitcherPill({compact ? 'px-2.5' : 'min-w-20 max-w-[200px] px-3',)}>- <Laptop- size={12}- strokeWidth={2}- className="shrink-0 text-[var(--create-agent-control-icon)]"- />+ {agentDevice ? (+ <Cpu size={12} strokeWidth={2} className="shrink-0 text-[var(--create-agent-control-icon)]" />+ ) : (+ <Laptop+ size={12}+ strokeWidth={2}+ className="shrink-0 text-[var(--create-agent-control-icon)]"+ />+ )}{showDot && (<spanaria-hidden@@ -155,7 +176,7 @@ export function DeviceSwitcherPill({icon={<Laptop size={20} strokeWidth={2} className="shrink-0 text-[var(--folder-item-icon)]" />}name={localLabel}hint={t('newChat.deviceSwitcher.localHint')}- selected={value == null}+ selected={value == null && agentDevice == null}onSelect={() => select(null, null)}/>@@ -182,6 +203,39 @@ export function DeviceSwitcherPill({/>))}</div>++ {onAgentDeviceChange && (+ <>+ <div className="mx-2 my-1 h-px bg-[var(--folder-picker-border)]" />+ <div className="px-3 py-2">+ <span className="text-xs font-normal text-[var(--folder-label)]">+ {t('newChat.deviceSwitcher.agentSection')}+ </span>+ </div>+ <div className="pending-queue-scroll -mr-2 max-h-[216px] overflow-x-hidden overflow-y-auto overscroll-contain pr-2">+ {devices.map((device) => (+ <DeviceRow+ key={device.deviceId}+ testId="create-agent-agent-device-option"+ icon={<Cpu size={20} strokeWidth={2} className="shrink-0 text-[var(--folder-item-icon)]" />}+ name={device.name}+ hint={+ device.online+ ? t('newChat.deviceSwitcher.agentHint')+ : t('newChat.deviceSwitcher.offlineHint')+ }+ online={device.online}+ disabled={!device.online}+ selected={agentDevice === device.deviceId}+ onSelect={() => {+ onAgentDeviceChange(device.deviceId, device.name);+ onOpenChange(false);+ }}+ />+ ))}+ </div>+ </>+ )}</PopoverContent></Popover>);@@ -195,14 +249,15 @@ interface RowProps {disabled?: boolean;selected: boolean;onSelect: () => void;+ testId?: string;}-function DeviceRow({ icon, name, hint, online, disabled, selected, onSelect }: RowProps) {+function DeviceRow({ icon, name, hint, online, disabled, selected, onSelect, testId }: RowProps) {return (<buttontype="button"disabled={disabled}- data-testid="create-agent-device-option"+ data-testid={testId ?? 'create-agent-device-option'}onClick={onSelect}className={cn('flex w-full items-center gap-3 rounded-[8px] px-3 py-[10px] text-left',diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsxindex 1990c25bbe..9d2c20529e 100644--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx@@ -2088,17 +2088,26 @@ export function CCAgentSessionView({// device-link 远程会话用被控端经隧道带来的 providers(per-provider,fast 判定与本地同口径)。const { providers: localProviders } = useProviders();const { mode: authMode, user: authUser, dataOwnerId } = useAuth();- const { providers: deviceProviders } = useDeviceProviders(remoteDeviceId);- const providers = remoteDeviceId ? deviceProviders : localProviders;+ // Agent 在另一台电脑运行的任务:模型目录同样以那台为准(任务本身在本机)。+ const agentDeviceId = remoteDeviceId ? undefined : (session?.agentDeviceId ?? undefined);+ const catalogDeviceId = remoteDeviceId ?? agentDeviceId;+ const { providers: deviceProviders } = useDeviceProviders(catalogDeviceId);+ const providers = catalogDeviceId ? deviceProviders : localProviders;const canSwitchToClaudeSubscription = useMemo(() => {- if (remoteDeviceId || session?.remoteHostId || session?.agentKind !== 'cc' || !session.model) {+ if (+ remoteDeviceId ||+ agentDeviceId ||+ session?.remoteHostId ||+ session?.agentKind !== 'cc' ||+ !session.model+ ) {return false;}return connectedProvidersForAgent(localProviders, 'claude-code').some((provider) =>provider.id === 'anthropic' && providerOffersModel(provider, session.model, 'claude-code'),);- }, [localProviders, remoteDeviceId, session?.agentKind, session?.model, session?.remoteHostId]);+ }, [localProviders, remoteDeviceId, agentDeviceId, session?.agentKind, session?.model, session?.remoteHostId]);/*** 余额不足横幅的「查看余额」出口 —— 只在计费面对当前账号可见时提供(cloud +* personal,与设置页「用量和计费」同一判据)。org / local / 未登录账号在 Cindy 里@@ -3311,6 +3320,11 @@ export function CCAgentSessionView({toast.warning(t('review.toast.remoteUnsupported'));return { handled: true, accepted: false, message };}+ if (agentDeviceId) {+ // Agent 在另一台电脑运行:审查任务暂不能在那台以只读方式运行。+ toast.warning(t('review.toast.agentDeviceUnsupported'));+ return { handled: true, accepted: false, message };+ }const attachments = files?.length ? serializeAttachedFiles(files) : undefined;try {const request = {@@ -3353,6 +3367,7 @@ export function CCAgentSessionView({[getHelpCommandsSnapshot,isRemoteSession,+ agentDeviceId,session?.agentKind,session?.remoteHostId,session?.id,@@ -4311,7 +4326,10 @@ export function CCAgentSessionView({if (!shouldFallbackVendorModel(providers, sessionModel, agent, {providerId: sessionProviderId,hasSwitchIntent: agentSwitchIntent != null,- isRemote: Boolean(isRemoteSession || remoteDeviceId || getSessionDeviceId(sessionId)),+ // Agent 在另一台电脑运行时模型同样以那台为准,本机不替它纠正。+ isRemote: Boolean(+ isRemoteSession || remoteDeviceId || agentDeviceId || getSessionDeviceId(sessionId),+ ),})) return;// 用三值化后的 agent 映射选默认模型:Pi 会话必须回退到 Pi 目录默认,而不是被// `isCodex ? 'codex' : 'cc'` 误写成 CC 首选(可能是更贵的 Opus)(codex review)。@@ -4328,6 +4346,7 @@ export function CCAgentSessionView({providers,refreshServerSession,remoteDeviceId,+ agentDeviceId,sessionAgentKind,sessionId,sessionModel,@@ -4754,6 +4773,7 @@ export function CCAgentSessionView({// 消息下方 Fork / Rewind icon 的显示 (Codex rewind=false → 隐藏)。agentKind={session?.agentKind}remoteHostId={session?.remoteHostId ?? null}+ agentOnOtherDevice={Boolean(agentDeviceId)}sessionSource={session?.source}// text-lightbox-trigger-extension F1/F2: cwd flows from session// owner down through MessageStream → AssistantMessage / UserMessage.@@ -5526,6 +5546,7 @@ export function CCAgentSessionView({initialWorkingDir={session?.workingDir}remoteHostId={session?.remoteHostId ?? null}deviceLinkDeviceId={rightSidebarDeviceLinkDeviceId}+ agentDeviceId={session?.agentDeviceId ?? null}modelMemoryOverride={remoteModelMemoryOverride}initialModel={session?.model}initialProviderId={session?.providerId ?? null}diff --git a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsxindex 304acc9638..8c58034c11 100644--- a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx@@ -173,7 +173,7 @@ import {} from './deferredUiAssignment';import { CrossAgentConvertDialog } from '@/components/ui/cross-agent-convert-dialog';import type { MakerVendor } from '@/lib/ccAgent.types';-import { ChevronDown, MessageSquare, MonitorSmartphone } from 'lucide-react';+import { ChevronDown, Cpu, MessageSquare, MonitorSmartphone } from 'lucide-react';import { HomeSuggestionList } from './HomeSuggestionList';import { type HomeSuggestionId, homeSuggestionPromptKey } from './homeSuggestions';import {@@ -280,6 +280,7 @@ import {type DeviceLinkDraftSelection,type RemoteDraftDefaults,} from './deviceLinkDraftDefaults';+import { recallAgentDeviceSelection, rememberAgentDeviceSelection } from './agentDeviceDraftMemory';import { makeMirrorAccessors, replaceScope, clearScope } from '@/state/deviceLinkModelMirror';import type { ModelMemoryAccessors } from '@/components/new-chat/ModelSelector';import { resolveNewMakerDraftRightSidebar } from './newMakerDraftRightSidebar';@@ -901,12 +902,26 @@ export function NewMakerDraftRoute() {// 下面 isDeviceLinkDraft 与 create 分支的真值收窄对 undefined 同样成立)。const effectiveDeviceLinkDeviceId = draft.deviceLinkDeviceId ?? undefined;const effectiveDeviceLinkDeviceName = draft.deviceLinkDeviceName;+ /**+ * 「Agent 在另一台电脑运行」:任务、项目文件与命令留在本机,Agent 用那台的登录、供应商与网络。+ * 只对本机任务成立(与 device-link / SSH 目标互斥,store 已保证)。+ */+ const effectiveAgentDeviceId =+ !effectiveDeviceLinkDeviceId && !effectiveRemoteHostId ? (draft.agentDeviceId ?? undefined) : undefined;+ const isAgentDeviceDraft = effectiveAgentDeviceId != null;+ /**+ * 模型目录所在的电脑:任务建到远程设备时是那台;Agent 在另一台电脑运行时也是那台(模型、+ * Agent 登录与可用引擎都以运行 Agent 的电脑为准)。本机任务为 undefined。+ */+ const catalogDeviceId = effectiveDeviceLinkDeviceId ?? effectiveAgentDeviceId;+ /** 草稿的模型选择以 catalogDeviceId 那台的目录为准(dlSel),不读写本机草稿记忆。 */+ const usesDeviceCatalog = catalogDeviceId != null;// 入口门控:只在 runtime 已注册的 agent 上开放创建入口(Pi 二进制缺失时 buildPiAgent 返回// null,agent map 无 pi,但模型目录仍投影 Pi → 需按 maker:list-available-agents 过滤,// 否则一路创建到 requireAgent 的 not-registered 报错,codex review P2)。远程草稿以被控端// 的注册结果为准(hook 传 deviceId 走隧道)。未加载完成时不隐藏任何入口(fail-open)。const { availableVendors, loaded: availableAgentsLoaded } = useAvailableAgents(- effectiveDeviceLinkDeviceId,+ catalogDeviceId,);const hiddenSwitcherVendors = useMemo<MakerVendor[]>(() => {if (!availableAgentsLoaded) return [];@@ -1232,7 +1247,7 @@ export function NewMakerDraftRoute() {capabilities,loading: capabilitiesLoading,error: capabilitiesError,- } = useAgentCapabilities(capabilityAgentKind, effectiveDeviceLinkDeviceId);+ } = useAgentCapabilities(capabilityAgentKind, catalogDeviceId);// device-link「以被控端为准」:远程草稿用被控端经隧道带来的 providers(per-provider,含 fast 能力);// 本地草稿用本机 providers。fast 判定统一交给 resolveFastSupported(不在控制端另写远程逻辑)。const {@@ -1262,7 +1277,7 @@ export function NewMakerDraftRoute() {// 远程主机 / device-link 的可用 Harness 与来源属于执行端,不能拿控制端本机登录态替它选。if (!suggestedDefaultTuple ||- effectiveDeviceLinkDeviceId ||+ catalogDeviceId ||draft.remoteHostId ||hasLegacyDefaultChoice)@@ -1270,7 +1285,7 @@ export function NewMakerDraftRoute() {applySuggestedDefaultTuple(suggestedDefaultTuple);}, [suggestedDefaultTuple,- effectiveDeviceLinkDeviceId,+ catalogDeviceId,draft.remoteHostId,hasLegacyDefaultChoice,]);@@ -1279,13 +1294,13 @@ export function NewMakerDraftRoute() {loading: deviceProvidersLoading,error: deviceProvidersError,unsupported: deviceProvidersUnsupported,- } = useDeviceProviders(effectiveDeviceLinkDeviceId);- const providers = effectiveDeviceLinkDeviceId ? deviceProviders : localProviders;+ } = useDeviceProviders(catalogDeviceId);+ const providers = catalogDeviceId ? deviceProviders : localProviders;// 新旧用户统一使用 A。老被控端只有 capabilities、没有供应商目录时,// 保留兼容列表与引擎下拉;否则联合列表会为空,也无法切换引擎。- const unifiedModelPanelEnabled = !effectiveDeviceLinkDeviceId || !deviceProvidersUnsupported;+ const unifiedModelPanelEnabled = !catalogDeviceId || !deviceProvidersUnsupported;const unifiedModelPanelActive = unifiedModelPanelEnabled;- const remoteModelListStatus = !isDeviceLinkDraft+ const remoteModelListStatus = !usesDeviceCatalog? 'idle': capabilitiesError || (deviceProvidersError && !deviceProvidersUnsupported)? 'error'@@ -1356,7 +1371,7 @@ export function NewMakerDraftRoute() {return healthy.length > 0 ? healthy : calibrationProviders;}, [calibrationProviders, draftModelChosenByUser, chatPrefs.providerId]);const draftCalibration = useMemo<DraftModelCalibrationResult>(() => {- if (isDeviceLinkDraft) return { model: chatPrefs.model, providerId: null };+ if (usesDeviceCatalog) return { model: chatPrefs.model, providerId: null };return calibrateDraftModel({providers: autoCalibrationProviders,agent: capabilityAgentKind,@@ -1366,7 +1381,7 @@ export function NewMakerDraftRoute() {providersLoading: localProvidersLoading,});}, [- isDeviceLinkDraft,+ usesDeviceCatalog,autoCalibrationProviders,capabilityAgentKind,chatPrefs.model,@@ -1386,7 +1401,7 @@ export function NewMakerDraftRoute() {// 用与挑模型同一份候选:自动路径已剔除失败态供应商,来源解析若还看得见它们,就会把刚// 挑好的健康模型重新指回那个已知失败的原生默认来源(PR #548 review)。用户显式表达过时// autoCalibrationProviders 本身就等于完整候选,不受影响。- const source = isDeviceLinkDraft ? providers : autoCalibrationProviders;+ const source = usesDeviceCatalog ? providers : autoCalibrationProviders;// 来源优先级:用户显式选的 > 校准挑中的 > 原生默认(nativeDefaultSourceId)。// 中间那一档不能省:nativeDefaultSourceId 对 claude-code 无条件优先 XD 网关,校准好的// 「anthropic 订阅提供的 claude-opus-5」交出去只剩模型 id 时会被重新指回网关 ——@@ -1398,7 +1413,7 @@ export function NewMakerDraftRoute() {capabilityAgentKind,);}, [- isDeviceLinkDraft,+ usesDeviceCatalog,providers,autoCalibrationProviders,capabilityAgentKind,@@ -1411,7 +1426,7 @@ export function NewMakerDraftRoute() {// 的全局预设后,即使该模型正显示在首页 trigger 上,也应立即采用新 effort / fast。真实会话仍// 由 CCAgentSessionView 的 live DB/runtime props 保护,不会走这里。const localDraftEffort = useMemo<Effort>(() => {- if (isDeviceLinkDraft || !effectiveSourceId) return chatPrefs.effort;+ if (usesDeviceCatalog || !effectiveSourceId) return chatPrefs.effort;const provider = providers.find((item) => item.id === effectiveSourceId);// 按**校准后**的模型推导:effort 必须和最终提交的模型属于同一个能力集合。const model = provider@@ -1428,7 +1443,7 @@ export function NewMakerDraftRoute() {defaultEffort: model?.defaultEffort ?? null,});}, [- isDeviceLinkDraft,+ usesDeviceCatalog,effectiveSourceId,providers,capabilityAgentKind,@@ -1528,10 +1543,21 @@ export function NewMakerDraftRoute() {remoteDraftRetryEpoch,]);+ // 运行 Agent 的电脑只提供模型目录:任务在本机,没有远程草稿默认值,改用本次运行内对这台+ // 电脑的上一次选择(见 agentDeviceDraftMemory)。+ const deviceDraftDefaultsReady = isAgentDeviceDraft || remoteDraftState.status === 'ready';+ const deviceDraftDefaults = useMemo<RemoteDraftDefaults | null>(+ () =>+ isAgentDeviceDraft && effectiveAgentDeviceId+ ? recallAgentDeviceSelection(effectiveAgentDeviceId, capabilityAgentKind)+ : remoteDraftState.value,+ [isAgentDeviceDraft, effectiveAgentDeviceId, capabilityAgentKind, remoteDraftState.value],+ );+// seed dlSel:等被控端 capabilities + 草稿值都就绪后播种。切设备 / vendor 必须重种;同一目标// 在被控端明确未选过模型且控制端未编辑时,允许 capabilities 刷新重新校准区域默认。useEffect(() => {- if (!isDeviceLinkDraft || !effectiveDeviceLinkDeviceId) {+ if (!usesDeviceCatalog || !catalogDeviceId) {dlSeedKeyRef.current = null;dlSeedCapabilitiesRef.current = null;dlRuntimeTouchedRef.current = false;@@ -1540,8 +1566,8 @@ export function NewMakerDraftRoute() {}// provider revision 驱逐时 hook 会保留旧快照但标 loading;必须等新代际 ready,不能用 stale// capabilities 把 inline handoff 或用户当前选择校准回旧目录。- if (!capabilities || capabilitiesLoading || remoteDraftState.status !== 'ready') return;- const key = `${effectiveDeviceLinkDeviceId}:${capabilityAgentKind}`;+ if (!capabilities || capabilitiesLoading || !deviceDraftDefaultsReady) return;+ const key = `${catalogDeviceId}:${capabilityAgentKind}`;const newTarget = dlSeedKeyRef.current !== key;const capabilitiesChanged = dlSeedCapabilitiesRef.current !== capabilities;if (@@ -1550,7 +1576,7 @@ export function NewMakerDraftRoute() {nextSeedKey: key,capabilitiesChanged,controllerTouched: dlRuntimeTouchedRef.current,- remoteModelChosenByUser: remoteDraftState.value?.modelChosenByUser,+ remoteModelChosenByUser: deviceDraftDefaults?.modelChosenByUser,})) {if (capabilitiesChanged) {@@ -1582,30 +1608,38 @@ export function NewMakerDraftRoute() {setDlSel(resolveDeviceLinkDraftDefaults(capabilities,- remoteDraftState.value,+ deviceDraftDefaults,undefined,capabilityAgentKind,),);}, [- isDeviceLinkDraft,- effectiveDeviceLinkDeviceId,+ usesDeviceCatalog,+ catalogDeviceId,capabilityAgentKind,capabilities,capabilitiesLoading,- remoteDraftState,+ deviceDraftDefaultsReady,+ deviceDraftDefaults,]);+ // 记住这次对运行 Agent 的电脑的选择(仅本次运行),切走再切回时恢复。+ useEffect(() => {+ if (isAgentDeviceDraft && effectiveAgentDeviceId && dlSel) {+ rememberAgentDeviceSelection(effectiveAgentDeviceId, capabilityAgentKind, dlSel);+ }+ }, [isAgentDeviceDraft, effectiveAgentDeviceId, capabilityAgentKind, dlSel]);+// 远程草稿展示用:已 seed 用 dlSel;seed 完成前(等隧道 / 能力)先用 capabilities 默认占位,// 绝不回落控制端本地(仅 capabilities 未就绪的极早期暂为 null,此时与改造前行为一致)。const deviceLinkInitial = useMemo<DeviceLinkDraftSelection | null>(() => {- if (!isDeviceLinkDraft) return null;+ if (!usesDeviceCatalog) return null;if (dlSel) return dlSel;if (capabilities) {return resolveDeviceLinkDraftDefaults(capabilities, null, undefined, capabilityAgentKind);}return null;- }, [isDeviceLinkDraft, dlSel, capabilities, capabilityAgentKind]);+ }, [usesDeviceCatalog, dlSel, capabilities, capabilityAgentKind]);// ── device-link 草稿列表「纯显示镜像」(非选中行的 effort/fast) ──────────────────// scopeKey 按设备隔离。镜像 = 被控端 providerModelMemory 全量快照(草稿列表行的真实读源),@@ -1972,15 +2006,15 @@ export function NewMakerDraftRoute() {// 被隐藏 / SSH 排除、模型由另一个来源提供时,这里会去查那个被排除的来源 —— 要么藏掉本// 该有的 Fast 开关,要么把 Fast 开在不支持它的来源上。effort / fast 记忆 / 写回都已按// effectiveSourceId 推导,只剩这处没跟上(PR #548 review)。- const providerId = isDeviceLinkDraft+ const providerId = usesDeviceCatalog? (dlSel?.providerId ?? deviceLinkInitial?.providerId ?? null): effectiveSourceId;// 本地取**校准后**的模型:fast 能力必须按最终提交的那个模型判定。- const modelId = isDeviceLinkDraft+ const modelId = usesDeviceCatalog? (dlSel?.model ?? deviceLinkInitial?.model ?? chatPrefs.model): calibratedDraftModel;return resolveFastSupported({- deviceId: effectiveDeviceLinkDeviceId,+ deviceId: catalogDeviceId,deviceProviders,localProviders,capabilities,@@ -1989,13 +2023,13 @@ export function NewMakerDraftRoute() {agentKind: capabilityAgentKind,});}, [- isDeviceLinkDraft,+ usesDeviceCatalog,dlSel,deviceLinkInitial,effectiveSourceId,chatPrefs.model,calibratedDraftModel,- effectiveDeviceLinkDeviceId,+ catalogDeviceId,deviceProviders,localProviders,capabilities,@@ -2004,7 +2038,7 @@ export function NewMakerDraftRoute() {// device-link:fast 取镜像值(deviceLinkInitial.fastMode,seed 时已按被控端拍平能力校准),但再叠// 一道 per-provider 的 supportsFastMode gate —— 让 per-provider 判定对"显示+发送"都权威,堵住 seed// 拍平值在未来分叉下泄漏(seed 函数 deviceLinkDraftDefaults 保持纯/不依赖 ProviderView)。本地走原逻辑。- const effectiveFastMode = isDeviceLinkDraft+ const effectiveFastMode = usesDeviceCatalog? supportsFastMode? (deviceLinkInitial?.fastMode ?? false): false@@ -2019,13 +2053,13 @@ export function NewMakerDraftRoute() {// 校准);本地草稿用 chatPrefs(逐字节不变)。device-link 在 holder seed 完成前(等隧道 / 能力)// 极早期暂用 chatPrefs,随后被 deviceLinkInitial 取代。const { model: draftInitialModel, effort: draftInitialEffort } = useMemo(() => {- if (isDeviceLinkDraft && deviceLinkInitial) {+ if (usesDeviceCatalog && deviceLinkInitial) {return { model: deviceLinkInitial.model, effort: deviceLinkInitial.effort };}// 校准在 calibratedDraftModel 一处完成,effort / fast / 来源都已按它推导 —— 这里// 直接用,不再单独算一次(否则又会出现模型与能力参数不同源的分叉)。return { model: calibratedDraftModel, effort: localDraftEffort };- }, [isDeviceLinkDraft, deviceLinkInitial, calibratedDraftModel, localDraftEffort]);+ }, [usesDeviceCatalog, deviceLinkInitial, calibratedDraftModel, localDraftEffort]);// 远程草稿的权限档 / 来源同样取镜像 holder;本地走 chatPrefs。const chatInitialPermissionMode = isDeviceLinkDraft@@ -2050,7 +2084,7 @@ export function NewMakerDraftRoute() {// 本机与远程草稿均保留明确选中的连接。显示可用性与提交身份分开,// 防止控制端暂时缺少目录时把账号 A 变成默认账号 B。const chatInitialProviderId = useMemo<string | null>(() => {- if (!isDeviceLinkDraft) return localProviderIdForDraft;+ if (!usesDeviceCatalog) return localProviderIdForDraft;return deviceLinkInitial?.providerId || effectiveSourceIdForModel(deviceProviders,null,@@ -2058,7 +2092,7 @@ export function NewMakerDraftRoute() {capabilityAgentKind,);}, [- isDeviceLinkDraft,+ usesDeviceCatalog,localProviderIdForDraft,deviceProviders,deviceLinkInitial?.providerId,@@ -2553,7 +2587,7 @@ export function NewMakerDraftRoute() {const handleModelDidChange = useCallback((newModelId: string) => {- if (isDeviceLinkDraft) {+ if (usesDeviceCatalog) {dlRuntimeTouchedRef.current = true;// 远程草稿:只改 dlSel,绝不写本地 newMakerDraft。capabilities 未就绪时退化为仅换 model。if (!capabilities) {@@ -2565,7 +2599,7 @@ export function NewMakerDraftRoute() {// permission/source 非按模型记 → 保留草稿里的当前选择(prev),不被切模型重置。const resolved = resolveDeviceLinkDraftDefaults(capabilities,- remoteDraftState.value,+ deviceDraftDefaults,newModelId,capabilityAgentKind,);@@ -2582,16 +2616,16 @@ export function NewMakerDraftRoute() {// 不再维护一份可能与其它对话更新脱节的本地 state。},[- isDeviceLinkDraft,+ usesDeviceCatalog,capabilities,- remoteDraftState,+ deviceDraftDefaults,patchActiveTuplePrefs,capabilityAgentKind,],);const handleFastModeChange = useCallback((enabled: boolean) => {- if (isDeviceLinkDraft) {+ if (usesDeviceCatalog) {dlRuntimeTouchedRef.current = true;setDlSel((prev) => (prev ? { ...prev, fastMode: enabled } : prev));pushActiveDraftPref({ fast: enabled }); // 选中模型 fast 写穿被控端@@ -2616,7 +2650,7 @@ export function NewMakerDraftRoute() {setFastModeForModel(calibratedDraftModel, enabled);},[- isDeviceLinkDraft,+ usesDeviceCatalog,draft.vendor,calibratedDraftModel,supportsFastMode,@@ -2627,7 +2661,7 @@ export function NewMakerDraftRoute() {);const handleEffortDidChange = useCallback((newEffort: Effort) => {- if (isDeviceLinkDraft) {+ if (usesDeviceCatalog) {dlRuntimeTouchedRef.current = true;setDlSel((prev) => (prev ? { ...prev, effort: newEffort } : prev));pushActiveDraftPref({ effort: newEffort }); // 选中模型 effort 写穿被控端@@ -2636,17 +2670,17 @@ export function NewMakerDraftRoute() {markDefaultTupleCustomized(false);patchActiveTuplePrefs({ effort: newEffort });},- [isDeviceLinkDraft, patchActiveTuplePrefs, pushActiveDraftPref],+ [usesDeviceCatalog, patchActiveTuplePrefs, pushActiveDraftPref],);// ChatInput 内部决策完 newEffort 时回写这里, 让"每个 modelId 上次的 effort"// 跨 ChatInput 实例 / 跨重启保留 (修复: New Maker 先选 Haiku 发完, 再 New Maker// 切回 Opus 4.7 默认 Effort 退化成 Low 的问题)。device-link 不写本地 per-model 记忆。const handleRememberedEffortChange = useCallback((modelId: string, effort: Effort) => {- if (isDeviceLinkDraft) return;+ if (usesDeviceCatalog) return;setEffortForModel(modelId, effort);},- [isDeviceLinkDraft],+ [usesDeviceCatalog],);const handlePermissionModeDidChange = useCallback((newMode: PermissionMode) => {@@ -2673,7 +2707,7 @@ export function NewMakerDraftRoute() {// device-link 远程草稿:只改 dlSel(临时),不写本地 prefs。const handleProviderDidChange = useCallback((newProviderId: string | null) => {- if (isDeviceLinkDraft) {+ if (usesDeviceCatalog) {dlRuntimeTouchedRef.current = true;setDlSel((prev) => (prev ? { ...prev, providerId: newProviderId } : prev));return;@@ -2681,7 +2715,7 @@ export function NewMakerDraftRoute() {markDefaultTupleCustomized();patchActiveTuplePrefs({ providerId: newProviderId });},- [isDeviceLinkDraft, patchActiveTuplePrefs],+ [usesDeviceCatalog, patchActiveTuplePrefs],);// ─── 统一模型选择器:一次选中 = 一次完整写入 ─────────────────────────────@@ -2728,7 +2762,7 @@ export function NewMakerDraftRoute() {// 必须无条件进入 store 的 rebase:当前 renderer 的 draft.vendor 可能还停在 storage// event 到达前的旧 Harness。switchVendor 自身同值早返,不会制造额外写入。switchVendor(selection.vendor);- if (isDeviceLinkDraft) {+ if (usesDeviceCatalog) {dlRuntimeTouchedRef.current = true;// ★ 跨引擎选择必须**前置**把 seed key 推到目标引擎(2026-08-17 review 第三轮 G1)。//@@ -2743,8 +2777,8 @@ export function NewMakerDraftRoute() {// 目标引擎 capabilities 到达时只做合法性夹紧(保留 current.model),不再换成区域默认。// 重复渲染 / 重复播种窗口一并覆盖:key 一旦被显式选择占住,后续每一帧都判成同一目标。// 同引擎分支 key 不变,本就不会进入重播种(同样由 controllerTouched 挡住能力刷新重校)。- if (effectiveDeviceLinkDeviceId) {- dlSeedKeyRef.current = `${effectiveDeviceLinkDeviceId}:${dbToMakerAgentKind(+ if (catalogDeviceId) {+ dlSeedKeyRef.current = `${catalogDeviceId}:${dbToMakerAgentKind(normalizeDbAgentKind(selection.vendor),)}`;}@@ -2758,7 +2792,7 @@ export function NewMakerDraftRoute() {const baseline = capabilities? resolveDeviceLinkDraftDefaults(capabilities,- remoteDraftState.value ?? previous,+ deviceDraftDefaults ?? previous,selection.modelId,capabilityAgentKind,)@@ -2827,11 +2861,11 @@ export function NewMakerDraftRoute() {},[draft.vendor,- isDeviceLinkDraft,- effectiveDeviceLinkDeviceId,+ usesDeviceCatalog,+ catalogDeviceId,deviceLinkInitial,capabilities,- remoteDraftState,+ deviceDraftDefaults,capabilityAgentKind,pushActiveDraftPref,],@@ -2939,6 +2973,15 @@ export function NewMakerDraftRoute() {applyDraftTarget({ deviceId: null, deviceName: null, workingDir: null });}, [effectiveDeviceLinkDeviceId, selectableDevices, selectableDevicesLoaded, applyDraftTarget]);+ // 运行 Agent 的电脑同理:被解除配对 / 撤销远程控制后不再可选,回到「Agent 在本机」。+ // 任务本来就在本机,项目、附件与草稿都不用动。+ useEffect(() => {+ if (!effectiveAgentDeviceId || !selectableDevicesLoaded) return;+ if (selectableDevices.some((d) => d.deviceId === effectiveAgentDeviceId)) return;+ log.warn('[new-maker] selected agent computer is no longer selectable, running the agent here');+ patchDraft({ agentDeviceId: null, agentDeviceName: null });+ }, [effectiveAgentDeviceId, selectableDevices, selectableDevicesLoaded]);+// 创建目标正在异步提交时,发送、建目标以及设备/工作区切换必须共用同一把锁。// ref 负责同步 guard,state 只负责驱动 UI 禁用;所有写入都经 markSendInFlight,// 避免其中一半提前释放后让旧草稿目标被消费。@@ -2963,6 +3006,12 @@ export function NewMakerDraftRoute() {// 点已选中的那一行(包括本机时点「本机」)只是确认当前选择,不该有任何副作用。// 下面会剥 mention chip、丢路径型附件并清 workingDir / extraDirs —— 重选同一设备时执行这些,// 等于用户点一下就静默丢掉已选的项目、附件和部分已写好的消息。必须先早返回。+ // 「Agent 在另一台电脑」时点「本机」= 回到全部在本机:只清掉运行 Agent 的电脑,任务本来+ // 就在本机,项目、附件与草稿都保持不变。+ if (deviceId === null && effectiveAgentDeviceId && !effectiveDeviceLinkDeviceId) {+ patchDraft({ agentDeviceId: null, agentDeviceName: null });+ return;+ }if (deviceId === (effectiveDeviceLinkDeviceId ?? null)) return;// 换完停在这台设备的「对话」(workingDir=null):上一台的项目路径在新机器上基本不存在,// 留着会让用户以为项目跟过来了、发送时才在被控端 path guard 上失败。与 mobile 切设备后@@ -2975,7 +3024,28 @@ export function NewMakerDraftRoute() {// 早返回掉,deviceId 必然变化 → hook effect 必然重跑 → evict 后必然 cache miss 并自行 fetch。applyDraftTarget({ deviceId, deviceName, workingDir: null });},- [effectiveDeviceLinkDeviceId, applyDraftTarget],+ [effectiveDeviceLinkDeviceId, effectiveAgentDeviceId, applyDraftTarget],+ );+ /**+ * 「只让 Agent 在那台电脑运行」:任务、项目文件与命令留在本机。原来要把任务建到远程设备 /+ * SSH 主机时先回到本机(那边的项目路径在本机无效);模型目录换成那台的,按那台重新播种选择。+ */+ const handleAgentDeviceChange = useCallback(+ (deviceId: string, deviceName: string | null) => {+ if (sendInFlightRef.current) return;+ if (deviceId === (effectiveAgentDeviceId ?? null)) return;+ if (effectiveDeviceLinkDeviceId || effectiveRemoteHostId) {+ applyDraftTarget({ deviceId: null, deviceName: null, workingDir: null });+ }+ // 目录快照不在这里作废:catalogDeviceId 变了 hook 会按新电脑取,模型选择器打开时+ // 也会对这台电脑作废并重新预取(与远程任务同一条路径)。+ setDlSel(null);+ dlSeedKeyRef.current = null;+ dlSeedCapabilitiesRef.current = null;+ dlRuntimeTouchedRef.current = false;+ patchDraft({ agentDeviceId: deviceId, agentDeviceName: deviceName });+ },+ [effectiveAgentDeviceId, effectiveDeviceLinkDeviceId, effectiveRemoteHostId, applyDraftTarget],);const handleOpenRemoteProject = useCallback((deviceId?: string) => {setAddRemoteProjectDeviceId(deviceId ?? null);@@ -3351,7 +3421,7 @@ export function NewMakerDraftRoute() {// maker:get-new-maker-defaults 还没回来时放行,于是提交的是 deviceLinkInitial 的 capability// 兜底值(model / effort / permission / provider),而不是那台设备自己保存的草稿值;// 会话一旦建出来,晚到的响应也修不回去了。- if (isDeviceLinkDraft && remoteModelListStatus !== 'ready') {+ if (usesDeviceCatalog && remoteModelListStatus !== 'ready') {if (remoteModelListStatus === 'error') {toast.error(t('newChat.modelSelector.remoteLoadFailed'));} else {@@ -3453,8 +3523,9 @@ export function NewMakerDraftRoute() {if (isDeviceLinkDraft && !isCurrentDataOwner()) return;// device-link:远程草稿就绪态以被控端为准(传 deviceId 走隧道查被控端 maker:agent:status);// 本地草稿 effectiveDeviceLinkDeviceId 为 undefined → 仍走控制端本机就绪检查(行为不变)。+ // Agent 在另一台电脑运行时同样查那台的 Agent 登录(订阅 / 供应商都用那台的)。const { proceed } = await vendorAuthGate.checkAndConfirm(authVendor, {- deviceId: effectiveDeviceLinkDeviceId,+ deviceId: catalogDeviceId,});if (isDeviceLinkDraft && !isCurrentDataOwner()) return;if (!proceed) return;@@ -3940,6 +4011,7 @@ export function NewMakerDraftRoute() {extraDirs: effectiveExtraDirs,writableDirs: effectiveWritableDirs,remoteHostId: effectiveRemoteHostId ?? undefined,+ ...(effectiveAgentDeviceId ? { agentDeviceId: effectiveAgentDeviceId } : {}),providerId,});if (!newSession) {@@ -4196,6 +4268,8 @@ export function NewMakerDraftRoute() {// 自动分配 <userData>/dialogues/<date>/<sid>/ 作为运行目录,不进入项目段。workspaceKind: workingDir ? 'project' : 'dialogue',remoteHostId: workingDir ? (effectiveRemoteHostId ?? undefined) : undefined,+ // Agent 在另一台电脑运行:任务与文件仍在本机,只记下运行 Agent 的电脑。+ ...(effectiveAgentDeviceId ? { agentDeviceId: effectiveAgentDeviceId } : {}),// extraDirs 是 vendor 无关字段;Claude 与 Codex 都按只读引用目录透传。extraDirs: effectiveExtraDirs,writableDirs: effectiveWritableDirs,@@ -4443,6 +4517,9 @@ export function NewMakerDraftRoute() {effectiveRemoteHostId,isRemoteProjectDraft,isDeviceLinkDraft,+ usesDeviceCatalog,+ catalogDeviceId,+ effectiveAgentDeviceId,remoteModelListStatus,remoteDraftState.status,deviceProviders,@@ -4578,9 +4655,12 @@ export function NewMakerDraftRoute() {const shouldEnableCollab = effectiveCollab.enabled && collabPolicyEligible && policyEnabled;// 同 handleSend:remoteDraftState 未就绪时不得放行,否则提交 capability 兜底值而非该设备的// 草稿值(缓存已热时另两个 loading 会立刻为 false,拦不住)。- if (isDeviceLinkDraft && remoteModelListStatus === 'error') {+ if (usesDeviceCatalog && remoteModelListStatus === 'error') {throw new Error(t('newChat.modelSelector.remoteLoadFailed'));}+ if (isAgentDeviceDraft && remoteModelListStatus !== 'ready') {+ throw new Error(t('ccAgent.draft.deviceStillLoading'));+ }if (isDeviceLinkDraft && remoteDraftState.status === 'error') {setRemoteDraftRetryEpoch((value) => value + 1);throw new Error(t('ccAgent.draft.remoteDefaultsLoadFailed'));@@ -4592,7 +4672,7 @@ export function NewMakerDraftRoute() {throw new Error(t('ccAgent.draft.deviceStillLoading'));}const { proceed } = await vendorAuthGate.checkAndConfirm(authVendor, {- deviceId: effectiveDeviceLinkDeviceId,+ deviceId: catalogDeviceId,});if (!proceed) return; // 用户取消授权:弹窗关闭即可,不算错误。if (isDeviceLinkDraft) {@@ -4931,6 +5011,7 @@ export function NewMakerDraftRoute() {workingDir: goalWorkingDir,workspaceKind: goalWorkingDir ? 'project' : 'dialogue',remoteHostId: goalWorkingDir ? (effectiveRemoteHostId ?? undefined) : undefined,+ ...(effectiveAgentDeviceId ? { agentDeviceId: effectiveAgentDeviceId } : {}),extraDirs: effectiveExtraDirs,writableDirs: effectiveWritableDirs,providerId: chatInitialProviderId ?? null,@@ -5063,6 +5144,10 @@ export function NewMakerDraftRoute() {[markSendInFlight,isDeviceLinkDraft,+ usesDeviceCatalog,+ isAgentDeviceDraft,+ catalogDeviceId,+ effectiveAgentDeviceId,isRemoteProjectDraft,remoteModelListStatus,remoteDraftState.status,@@ -5432,6 +5517,8 @@ export function NewMakerDraftRoute() {devices={selectableDevices}value={effectiveDeviceLinkDeviceId ?? null}onChange={handleDeviceChange}+ agentDeviceId={effectiveAgentDeviceId ?? null}+ onAgentDeviceChange={handleAgentDeviceChange}open={devicePickerOpen}onOpenChange={handleDevicePickerOpenChange}// 窄屏 pill 排会进正常流并 flex-wrap;多台时收成图标 + 状态点少占一行。@@ -5529,6 +5616,7 @@ export function NewMakerDraftRoute() {initialWorkingDir={effectiveWorkingDir}remoteHostId={draft.remoteHostId ?? null}deviceLinkDeviceId={effectiveDeviceLinkDeviceId ?? null}+ agentDeviceId={effectiveAgentDeviceId ?? null}modelMemoryOverride={deviceLinkDraftMemory}initialModel={draftInitialModel}initialEffort={draftInitialEffort}@@ -5648,12 +5736,24 @@ export function NewMakerDraftRoute() {setNewGoalInitialObjective(text);setNewGoalOpen(true);}}- rememberedEffortByModel={isDeviceLinkDraft ? undefined : draft.effortByModel}+ rememberedEffortByModel={usesDeviceCatalog ? undefined : draft.effortByModel}onRememberedEffortChange={- isDeviceLinkDraft ? undefined : handleRememberedEffortChange+ usesDeviceCatalog ? undefined : handleRememberedEffortChange}/></div>+ {/* Agent 在另一台电脑运行:任务和文件在本机,只有 Agent 在那台。与下面的远程设备+ 标识同位置、同样式,两者互斥。 */}+ {isAgentDeviceDraft && (+ <div className="mt-3 flex max-w-full items-center gap-2 self-center rounded-full border border-[var(--border-default)] bg-[var(--surface-chip)] px-3 py-1 text-12 text-[var(--text-secondary)]">+ <Cpu size={14} strokeWidth={2} className="shrink-0 text-[var(--folder-item-icon)]" />+ <span className="min-w-0 truncate">+ {t('ccAgent.draft.agentDeviceBanner', {+ device: draft.agentDeviceName ?? effectiveAgentDeviceId ?? '',+ })}+ </span>+ </div>+ )}{/* device-link:为远程设备项目新建对话时的明显标识。让用户清楚这条对话会建在被控设备上、属于那台机器的项目,而不是本机。放输入框正下方并与其水平居中(父列 items-start,靠 self-center 相对 w-full 的输入框居中)。 */}diff --git a/apps/desktop/src/renderer/features/cc-agent/SessionContentHeader.tsx b/apps/desktop/src/renderer/features/cc-agent/SessionContentHeader.tsxindex a119e44a7a..c79961286e 100644--- a/apps/desktop/src/renderer/features/cc-agent/SessionContentHeader.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/SessionContentHeader.tsx@@ -77,9 +77,42 @@ import { isRemoteSessionWriteBlocked } from './lib/remoteSessionWriteGuard';import { Tip } from '@/components/ui/tooltip';import { TaskTagDots, TaskTagMenuSection, TaskTagEditor } from '@/features/task-tags/TaskTags';import { isSharedTaskPeer } from '@cindy/device-link';+import { useDeviceLinkDeviceList } from '@/features/device-link/useDeviceLinkDeviceList';const log = createLogger('SessionContentHeader');+/**+ * 任务在本机、Agent 在同账号另一台电脑上运行:标明那台电脑,离线时如实提示(不自动改在本机跑)。+ */+function AgentDeviceIndicator({ deviceId }: { deviceId: string }) {+ const { t } = useTranslation();+ const devices = useDeviceLinkDeviceList();+ const device = devices?.find((item) => item.deviceId === deviceId);+ const name = device?.name || deviceId;+ const offline = device ? !device.online : false;+ return (+ <Tip+ text={t(+ offline ? 'ccAgent.sessionHeader.agentDeviceOffline' : 'ccAgent.sessionHeader.agentDevice',+ { device: name },+ )}+ >+ <span+ role="img"+ aria-label={t('ccAgent.sessionHeader.agentDevice', { device: name })}+ className="inline-flex"+ style={WINDOW_NO_DRAG_STYLE}+ >+ <RemoteProjectIcon+ kind="agent-device"+ connectionStatus={offline ? 'disconnected' : 'connected'}+ className="mr-1 text-[var(--cmd-palette-item-meta)]"+ />+ </span>+ </Tip>+ );+}+/*** 注册器组件:由路由直挂的 CCAgentSessionView 条件渲染(仅当该实例"拥有"* 当前路由时),把 SessionContentHeader 注进 ContentHeader 槽位。@@ -539,6 +572,9 @@ export function SessionContentHeader({/></Tip>)}+ {!isEditing && !remoteIconKind && session.agentDeviceId && (+ <AgentDeviceIndicator deviceId={session.agentDeviceId} />+ )}{isEditing ? (<div style={WINDOW_NO_DRAG_STYLE}>diff --git a/apps/desktop/src/renderer/features/cc-agent/agentDeviceDraftMemory.ts b/apps/desktop/src/renderer/features/cc-agent/agentDeviceDraftMemory.tsnew file mode 100644index 0000000000..25604a7cff--- /dev/null+++ b/apps/desktop/src/renderer/features/cc-agent/agentDeviceDraftMemory.ts@@ -0,0 +1,37 @@+/**+ * 「Agent 在另一台电脑运行」草稿的模型选择记忆。+ *+ * 模型目录属于运行 Agent 的那台电脑,不能写进本机草稿记忆(lastByVendor / 模型预设)——+ * 否则回到本机任务时会带着本机没有的模型。这里按「电脑 + Agent」记住上一次的选择,+ * 只在本次运行内有效,与草稿里的 agentDeviceId 一样不跨重启。+ */+import type { DeviceLinkDraftSelection, RemoteDraftDefaults } from './deviceLinkDraftDefaults';++const memory = new Map<string, RemoteDraftDefaults>();++function key(deviceId: string, agentKind: string): string {+ return `${deviceId}:${agentKind}`;+}++export function rememberAgentDeviceSelection(+ deviceId: string,+ agentKind: string,+ selection: DeviceLinkDraftSelection,+): void {+ memory.set(key(deviceId, agentKind), {+ model: selection.model,+ modelChosenByUser: true,+ effort: selection.effort,+ fastMode: selection.fastMode,+ providerId: selection.providerId,+ });+}++export function recallAgentDeviceSelection(deviceId: string, agentKind: string): RemoteDraftDefaults | null {+ return memory.get(key(deviceId, agentKind)) ?? null;+}++/** 测试用。 */+export function clearAgentDeviceSelectionMemory(): void {+ memory.clear();+}diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/RemoteProjectIcon.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/RemoteProjectIcon.tsxindex e1aa7754f4..2462bc954d 100644--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/RemoteProjectIcon.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/RemoteProjectIcon.tsx@@ -1,9 +1,10 @@-import { Globe, MonitorOff, MonitorSmartphone } from 'lucide-react';+import { Cpu, Globe, MonitorOff, MonitorSmartphone } from 'lucide-react';import { cn } from '@/lib/utils';import type { DeviceLinkConnectionStatus } from '@/lib/ccAgent.types';-type RemoteProjectIconKind = 'device-link' | 'ssh';+/** agent-device:任务在本机、Agent 在同账号另一台电脑上运行。 */+type RemoteProjectIconKind = 'device-link' | 'ssh' | 'agent-device';interface RemoteProjectIconProps {kind: RemoteProjectIconKind;@@ -21,8 +22,15 @@ export function RemoteProjectIcon({connectionStatus,className,}: RemoteProjectIconProps) {- const disconnected = kind === 'device-link' && connectionStatus === 'disconnected';- const Icon = disconnected ? MonitorOff : kind === 'device-link' ? MonitorSmartphone : Globe;+ const disconnected = kind !== 'ssh' && connectionStatus === 'disconnected';+ const Icon =+ kind === 'agent-device'+ ? Cpu+ : disconnected+ ? MonitorOff+ : kind === 'device-link'+ ? MonitorSmartphone+ : Globe;return (<Iconsize={size}diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsxindex 105ff19587..63129ccb96 100644--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx@@ -544,7 +544,9 @@ export const SessionCard = withSidebarNavigation<SessionCardProps>(function Sess!isEmpty &&!session.remoteHostId &&session.orcaRole !== 'worker' &&- !session.deviceLinkDeviceId;+ !session.deviceLinkDeviceId &&+ // Agent 在另一台电脑运行:转录在那台,本机打包不全。+ !session.agentDeviceId;const exportShareMenuItem = canExportShare ? (<DropdownMenuItem onSelect={handleExportShareSelect} className={MENU_ITEM_CLASS}>@@ -558,6 +560,8 @@ export const SessionCard = withSidebarNavigation<SessionCardProps>(function Sess!isEmpty &&!session.remoteHostId &&!session.deviceLinkDeviceId &&+ // Agent 在另一台电脑运行:它的会话记录按项目路径存在那台,移动后无法继续。+ !session.agentDeviceId &&session.status !== 'archived';const moveToProjectSubmenu = canMoveToProject ? (@@ -811,6 +815,19 @@ export const SessionCard = withSidebarNavigation<SessionCardProps>(function Sess}/>)}+ {/* 任务在本机、Agent 在另一台电脑运行。 */}+ {!remoteIconKind && session.agentDeviceId && (+ <RemoteProjectIcon+ kind="agent-device"+ size={12}+ strokeWidth={1.8}+ className={+ isActive+ ? 'text-sidebar-item-active-foreground'+ : 'text-sidebar-action-icon'+ }+ />+ )}{sourceLabel ? (<spantitle={sourceLabel}@@ -1084,6 +1101,16 @@ export const SessionCard = withSidebarNavigation<SessionCardProps>(function Sess}/>)}+ {!remoteIconKind && session.agentDeviceId && (+ <RemoteProjectIcon+ kind="agent-device"+ size={11}+ strokeWidth={1.8}+ className={+ isActive ? 'text-sidebar-item-active-foreground' : 'text-[var(--text-tertiary)]'+ }+ />+ )}{/* 任务信息复选:卡片版右下角与 list/text 同源;默认仅 time 与旧渲染等价。 */}<SessionInfoMetapieces={cardInfoPieces}diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsxindex 1730480f9a..fcdf102f8e 100644--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsx@@ -808,6 +808,8 @@ export const SessionItem = withSidebarNavigation<SessionItemProps>(function Sess!isEmpty &&!session.remoteHostId &&!session.deviceLinkDeviceId &&+ // Agent 在另一台电脑运行:它的会话记录按项目路径存在那台,移动后无法继续。+ !session.agentDeviceId &&session.status !== 'archived';// 导出 .cshare 的可见性:draft 无内容、remote 转录在远端、device-link 数据在@@ -817,7 +819,9 @@ export const SessionItem = withSidebarNavigation<SessionItemProps>(function Sess!isEmpty &&!session.remoteHostId &&session.orcaRole !== 'worker' &&- !session.deviceLinkDeviceId;+ !session.deviceLinkDeviceId &&+ // Agent 在另一台电脑运行:转录在那台,本机打包不全。+ !session.agentDeviceId;const exportShareMenuItem = canExportShare ? (<DropdownMenuItem onSelect={handleExportShareSelect} className={MENU_ITEM_CLASS}>@@ -1079,6 +1083,17 @@ export const SessionItem = withSidebarNavigation<SessionItemProps>(function Sess)}/>)}+ {/* 任务在本机、Agent 在另一台电脑运行。 */}+ {!remoteIconKind && session.agentDeviceId && (+ <RemoteProjectIcon+ kind="agent-device"+ size={12}+ strokeWidth={1.8}+ className={cn(+ isActive ? 'text-sidebar-item-active-foreground' : 'text-sidebar-action-icon',+ )}+ />+ )}{sourceLabel ? (<spantitle={sourceLabel}diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionTaskMenu.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionTaskMenu.tsxindex b57bd70622..486028afc6 100644--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionTaskMenu.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionTaskMenu.tsx@@ -283,7 +283,8 @@ function ActiveSessionTaskMenu({))}{!guest && (<>- {!archived && !empty && !session.remoteHostId && (+ {/* Agent 在另一台电脑运行的任务:Agent 会话记录在那台,移动与复制到其他电脑都会丢失它。 */}+ {!archived && !empty && !session.remoteHostId && !session.agentDeviceId && (<TaskMoveSubmenusession={session}disabled={ownerActionsBlocked}diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/SessionTaskMenu.test.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/SessionTaskMenu.test.tsxindex 62c4df1e6a..42a97584a7 100644--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/SessionTaskMenu.test.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/SessionTaskMenu.test.tsx@@ -116,6 +116,13 @@ it('loads only on open and groups task organization, sharing, viewing and removaexpect(state.rowClick).not.toHaveBeenCalled();});+it('hides moving a task whose agent runs on another computer, since its agent record stays there', () => {+ render(<Harness target={{ ...session, agentDeviceId: 'device-b' } as Session} />);+ openMenu();+ expect(labels()).not.toContain('moveToProject');+ expect(labels()).toContain('openInNewWindow');+});+it('shows unpin without a branch entry even for a forked Pi task', () => {render(<Harnessdiff --git a/apps/desktop/src/renderer/hooks/useCCSessions.ts b/apps/desktop/src/renderer/hooks/useCCSessions.tsindex 48a0b67f95..4815904c1d 100644--- a/apps/desktop/src/renderer/hooks/useCCSessions.ts+++ b/apps/desktop/src/renderer/hooks/useCCSessions.ts@@ -60,6 +60,8 @@ interface UseCCSessionsReturn {extraDirs?: string[];writableDirs?: string[];remoteHostId?: string;+ /** Agent 在同账号另一台电脑上运行(任务与文件在本机)。 */+ agentDeviceId?: string;/** per-session 来源(供应商)显式选择; null/undefined = 跟随默认路由。透传到 sessionService.create。 */providerId?: string | null;/** Only the Cindy Make purpose may be requested from the renderer; Main validates it. */@@ -163,6 +165,8 @@ export function useCCSessions(options?: UseCCSessionsOptions): UseCCSessionsRetu/** 远端 host alias (Codex P2)。设置后 session.workingDir 必须是远端绝对路径,* agent 跑在远端 SSH 机器上, 本地不 spawn codex 子进程。 */remoteHostId?: string;+ /** Agent 在同账号另一台电脑上运行(任务与文件在本机)。 */+ agentDeviceId?: string;/** per-session 来源(供应商)显式选择; null/undefined = 跟随默认路由。透传到 sessionService.create → mapper 落盘。 */providerId?: string | null;source?: 'cindy-make';diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex f463e22a2f..1c35d60dcb 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -9364,7 +9364,10 @@"onlineHint": "Connected — available","offlineHint": "Offline — available once connected","attachmentsDropped": "Removed {{count}} attachment(s) — they live on the previous device",- "attachmentsRemoteUnsupported": "File attachments aren't supported on a remote device — skipped {{count}} (images are fine)"+ "attachmentsRemoteUnsupported": "File attachments aren't supported on a remote device — skipped {{count}} (images are fine)",+ "agentSection": "Run Only the Agent on Another Computer",+ "agentHint": "Session and files stay here; uses its sign-in and models",+ "agentPill": "Agent on {{device}}"},"pluginSuggestions": {"changed": "This suggestion has changed. Shuffle the suggestions and choose again.",@@ -10349,7 +10352,14 @@"REMOTE_PROVIDER_UNSUPPORTED": "Remote tasks cannot use this model provider yet. Pick another provider, or use it in a local task.","REMOTE_PROVIDER_UPDATING": "This model provider’s credentials are updating. Try again in a moment.","REMOTE_WORKDIR_UNAVAILABLE": "The remote working directory is unavailable. Check that the folder still exists on that computer, then try again.",- "REMOTE_OPTIMISTIC_SESSION_STATE_UNAVAILABLE": "The computer cannot yet confirm whether this message was sent. Wait a moment and try again. Do not send the same message twice."+ "REMOTE_OPTIMISTIC_SESSION_STATE_UNAVAILABLE": "The computer cannot yet confirm whether this message was sent. Wait a moment and try again. Do not send the same message twice.",+ "REMOTE_AGENT_UNAVAILABLE": "Can't reach the computer running the Agent. Make sure it's online and allows remote control, then try again.",+ "REMOTE_AGENT_PEER_TOO_OLD": "Cindy on the other computer is too old to run the Agent for this one. Update Cindy there first.",+ "REMOTE_AGENT_EXPIRED": "This session already ended on the computer running the Agent. Send your message again.",+ "REMOTE_AGENT_NOT_FOUND": "This session already ended on the computer running the Agent. Send your message again.",+ "REMOTE_AGENT_BUSY": "Too many sessions are running on the other computer. End some of them and try again.",+ "REMOTE_AGENT_UNSUPPORTED": "This Agent isn't available on the other computer. Install or sign in to it there, or pick another Agent.",+ "REMOTE_AGENT_INVALID": "Something went wrong talking to the computer running the Agent. Try again; if it keeps happening, update Cindy on both computers."},"generatedFiles": {"title": "Files created this message",@@ -10652,7 +10662,8 @@"worktreeRepoHint": "Try picking the working directory again, and retry once the folder badge at the bottom right refreshes","sessionInactive": "Session is no longer active","remoteProjectBanner": "New session in {{project}} on {{device}}",- "remoteDialogueBanner": "New chat on {{device}} (no project)"+ "remoteDialogueBanner": "New chat on {{device}} (no project)",+ "agentDeviceBanner": "Session and files stay on this computer — the Agent runs on {{device}}"},"jumpSession": {"emptyId": "Enter a sessionId to jump to",@@ -11048,7 +11059,9 @@},"sessionHeader": {"untitled": "Untitled session",- "moreActions": "More actions"+ "moreActions": "More actions",+ "agentDevice": "Agent runs on {{device}}",+ "agentDeviceOffline": "Agent runs on {{device}}, which is offline — it continues once that computer is back"},"gitContext": {"detached": "Detached HEAD",@@ -13257,7 +13270,8 @@"sessionTitle": "Review · {{title}}","toast": {"failed": "Couldn't start review",- "remoteUnsupported": "This version can only review local tasks"+ "remoteUnsupported": "This version can only review local tasks",+ "agentDeviceUnsupported": "Review isn't available yet for tasks whose Agent runs on another computer"},"externalArtifactConfirm": {"title": "Allow review of external files?",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 31d1577a89..d2174647ee 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -9351,7 +9351,10 @@"onlineHint": "接続済み — 作成できます","offlineHint": "オフライン — 接続後に利用可能","attachmentsDropped": "添付ファイル {{count}} 件を削除しました(前のデバイス上のファイルです)",- "attachmentsRemoteUnsupported": "リモートデバイスではファイル添付に未対応のため {{count}} 件をスキップしました(画像は可)"+ "attachmentsRemoteUnsupported": "リモートデバイスではファイル添付に未対応のため {{count}} 件をスキップしました(画像は可)",+ "agentSection": "Agent だけ別のパソコンで実行",+ "agentHint": "セッションとファイルはこちらに残し、そのパソコンのサインインとモデルを使います",+ "agentPill": "Agent: {{device}}"},"pluginSuggestions": {"changed": "このおすすめは更新されました。おすすめを入れ替えて、もう一度選んでください。",@@ -10332,7 +10335,14 @@"REMOTE_PROVIDER_UNSUPPORTED": "リモートのタスクでは、まだこのモデルプロバイダーを使えません。別のプロバイダーに変えるか、このパソコン上のタスクで使ってください。","REMOTE_PROVIDER_UPDATING": "このモデルプロバイダーの認証情報を更新しています。しばらくしてからもう一度お試しください。","REMOTE_WORKDIR_UNAVAILABLE": "リモートの作業ディレクトリを今は使えません。そのパソコンにフォルダがまだあるか確認してから、再試行してください。",- "REMOTE_OPTIMISTIC_SESSION_STATE_UNAVAILABLE": "パソコン側で、このメッセージが送信済みかまだ確認できません。少し待ってから再試行し、同じメッセージを重ねて送らないでください。"+ "REMOTE_OPTIMISTIC_SESSION_STATE_UNAVAILABLE": "パソコン側で、このメッセージが送信済みかまだ確認できません。少し待ってから再試行し、同じメッセージを重ねて送らないでください。",+ "REMOTE_AGENT_UNAVAILABLE": "Agent を実行しているパソコンに接続できません。そのパソコンがオンラインでリモート操作を許可していることを確認して、もう一度お試しください。",+ "REMOTE_AGENT_PEER_TOO_OLD": "相手のパソコンの Cindy が古いため、このパソコンの Agent を実行できません。先にそのパソコンで Cindy を更新してください。",+ "REMOTE_AGENT_EXPIRED": "このセッションは Agent を実行しているパソコンですでに終了しています。もう一度送信してください。",+ "REMOTE_AGENT_NOT_FOUND": "このセッションは Agent を実行しているパソコンですでに終了しています。もう一度送信してください。",+ "REMOTE_AGENT_BUSY": "相手のパソコンで実行中のセッションが多すぎます。いくつか終了してからもう一度お試しください。",+ "REMOTE_AGENT_UNSUPPORTED": "相手のパソコンではこの Agent を使えません。そのパソコンでインストールまたはサインインするか、別の Agent を選んでください。",+ "REMOTE_AGENT_INVALID": "Agent を実行しているパソコンとの通信でエラーが発生しました。もう一度お試しください。続く場合は両方のパソコンの Cindy を最新版に更新してください。"},"generatedFiles": {"title": "このメッセージで作成されたファイル",@@ -10626,7 +10636,8 @@"worktreeRepoHint": "作業ディレクトリを選び直し、右下のフォルダー表示が更新されてから再試行してください","sessionInactive": "セッションはすでにアクティブではありません","remoteProjectBanner": "{{device}} の {{project}} で新しいセッションを作成",- "remoteDialogueBanner": "{{device}} で新しい対話(プロジェクトなし)"+ "remoteDialogueBanner": "{{device}} で新しい対話(プロジェクトなし)",+ "agentDeviceBanner": "セッションとファイルはこのパソコンに残り、Agent は {{device}} で実行されます"},"jumpSession": {"emptyId": "移動先の sessionId を入力してください",@@ -11022,7 +11033,9 @@},"sessionHeader": {"untitled": "無題のセッション",- "moreActions": "その他の操作"+ "moreActions": "その他の操作",+ "agentDevice": "Agent は {{device}} で実行中",+ "agentDeviceOffline": "Agent は {{device}} で実行中ですが、そのパソコンはオフラインです。接続されると続行します"},"gitContext": {"detached": "Detached HEAD",@@ -13229,7 +13242,8 @@"sessionTitle": "レビュー · {{title}}","toast": {"failed": "レビューを開始できませんでした",- "remoteUnsupported": "このバージョンではローカルタスクのみレビューできます"+ "remoteUnsupported": "このバージョンではローカルタスクのみレビューできます",+ "agentDeviceUnsupported": "Agent を別のパソコンで実行しているタスクは、まだレビューできません"},"externalArtifactConfirm": {"title": "ワークスペース外の作品をレビューしますか?",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 6134a8ec92..05552c5651 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -9351,7 +9351,10 @@"onlineHint": "연결됨 — 생성 가능","offlineHint": "오프라인 — 연결 후 사용 가능","attachmentsDropped": "첨부파일 {{count}}개를 제거했습니다 — 이전 기기에 있는 파일입니다",- "attachmentsRemoteUnsupported": "원격 기기에서는 파일 첨부를 지원하지 않아 {{count}}개를 건너뛰었습니다(이미지는 가능)"+ "attachmentsRemoteUnsupported": "원격 기기에서는 파일 첨부를 지원하지 않아 {{count}}개를 건너뛰었습니다(이미지는 가능)",+ "agentSection": "Agent만 다른 컴퓨터에서 실행",+ "agentHint": "세션과 파일은 이곳에 두고, 그 컴퓨터의 로그인과 모델을 사용합니다",+ "agentPill": "Agent: {{device}}"},"pluginSuggestions": {"changed": "이 추천이 업데이트되었습니다. 추천을 바꾼 뒤 다시 선택해 주세요.",@@ -10332,7 +10335,14 @@"REMOTE_PROVIDER_UNSUPPORTED": "원격 작업에서는 아직 이 모델 제공자를 사용할 수 없습니다. 다른 제공자로 바꾸거나 이 컴퓨터의 작업에서 사용하세요.","REMOTE_PROVIDER_UPDATING": "이 모델 제공자의 자격 증명을 업데이트하는 중입니다. 잠시 후 다시 시도하세요.","REMOTE_WORKDIR_UNAVAILABLE": "원격 작업 디렉터리를 지금 사용할 수 없습니다. 그 컴퓨터에 폴더가 아직 있는지 확인한 뒤 다시 시도하세요.",- "REMOTE_OPTIMISTIC_SESSION_STATE_UNAVAILABLE": "컴퓨터에서 이 메시지가 이미 전송됐는지 아직 확인할 수 없습니다. 잠시 후 다시 시도하고, 같은 메시지를 중복으로 보내지 마세요."+ "REMOTE_OPTIMISTIC_SESSION_STATE_UNAVAILABLE": "컴퓨터에서 이 메시지가 이미 전송됐는지 아직 확인할 수 없습니다. 잠시 후 다시 시도하고, 같은 메시지를 중복으로 보내지 마세요.",+ "REMOTE_AGENT_UNAVAILABLE": "Agent를 실행하는 컴퓨터에 연결할 수 없습니다. 그 컴퓨터가 온라인이고 원격 제어를 허용하는지 확인한 뒤 다시 시도하세요.",+ "REMOTE_AGENT_PEER_TOO_OLD": "상대 컴퓨터의 Cindy가 오래되어 이 컴퓨터의 Agent를 실행할 수 없습니다. 먼저 그 컴퓨터에서 Cindy를 업데이트하세요.",+ "REMOTE_AGENT_EXPIRED": "이 세션은 Agent를 실행하는 컴퓨터에서 이미 종료되었습니다. 다시 보내 주세요.",+ "REMOTE_AGENT_NOT_FOUND": "이 세션은 Agent를 실행하는 컴퓨터에서 이미 종료되었습니다. 다시 보내 주세요.",+ "REMOTE_AGENT_BUSY": "상대 컴퓨터에서 실행 중인 세션이 너무 많습니다. 일부를 종료한 뒤 다시 시도하세요.",+ "REMOTE_AGENT_UNSUPPORTED": "상대 컴퓨터에서는 이 Agent를 사용할 수 없습니다. 그 컴퓨터에서 설치하거나 로그인한 뒤 다시 시도하거나, 다른 Agent를 선택하세요.",+ "REMOTE_AGENT_INVALID": "Agent를 실행하는 컴퓨터와 통신하는 중 오류가 발생했습니다. 다시 시도하고, 계속되면 두 컴퓨터의 Cindy를 모두 최신 버전으로 업데이트하세요."},"generatedFiles": {"title": "이 메시지에서 생성된 파일",@@ -10626,7 +10636,8 @@"worktreeRepoHint": "작업 디렉터리를 다시 선택한 뒤 오른쪽 아래 폴더 표시가 갱신되면 다시 시도하세요","sessionInactive": "세션이 더 이상 활성 상태가 아닙니다","remoteProjectBanner": "{{device}}의 {{project}}에서 새 세션 만들기",- "remoteDialogueBanner": "{{device}}에서 새 대화(프로젝트 없음)"+ "remoteDialogueBanner": "{{device}}에서 새 대화(프로젝트 없음)",+ "agentDeviceBanner": "세션과 파일은 이 컴퓨터에 남고, Agent는 {{device}}에서 실행됩니다"},"jumpSession": {"emptyId": "이동할 sessionId를 입력하세요",@@ -11022,7 +11033,9 @@},"sessionHeader": {"untitled": "제목 없는 세션",- "moreActions": "더 보기"+ "moreActions": "더 보기",+ "agentDevice": "Agent가 {{device}}에서 실행 중",+ "agentDeviceOffline": "Agent가 {{device}}에서 실행 중이지만 그 컴퓨터가 오프라인입니다. 다시 연결되면 계속됩니다"},"gitContext": {"detached": "Detached HEAD",@@ -13229,7 +13242,8 @@"sessionTitle": "검토 · {{title}}","toast": {"failed": "검토를 시작할 수 없습니다",- "remoteUnsupported": "이 버전에서는 로컬 작업만 검토할 수 있습니다"+ "remoteUnsupported": "이 버전에서는 로컬 작업만 검토할 수 있습니다",+ "agentDeviceUnsupported": "Agent를 다른 컴퓨터에서 실행하는 작업은 아직 검토할 수 없습니다"},"externalArtifactConfirm": {"title": "작업 공간 밖의 결과물을 검토할까요?",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 55a1c2dca9..5d65e67f30 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -7690,7 +7690,12 @@"reset": "恢复默认","reorder": "调整{{name}}顺序,按上下方向键"},- "items": { "automations": "自动化", "plugins": "插件", "bots": "伙伴", "search": "搜索" }+ "items": {+ "automations": "自动化",+ "plugins": "插件",+ "bots": "伙伴",+ "search": "搜索"+ }},"user": {"settingsLink": "设置,当前用户:{{name}}",@@ -9346,7 +9351,10 @@"onlineHint": "已连接,可在其上创建","offlineHint": "离线 · 连上后可用","attachmentsDropped": "已移除 {{count}} 个附件:它们是上一台设备上的文件",- "attachmentsRemoteUnsupported": "远程设备暂不支持文件附件,已跳过 {{count}} 个(图片可以)"+ "attachmentsRemoteUnsupported": "远程设备暂不支持文件附件,已跳过 {{count}} 个(图片可以)",+ "agentSection": "只让 Agent 在其他电脑运行",+ "agentHint": "任务和文件留在本机,用这台的登录与模型",+ "agentPill": "Agent 在 {{device}}"},"pluginSuggestions": {"changed": "这条推荐已更新,请换一批后重新选择。",@@ -10327,7 +10335,14 @@"REMOTE_PROVIDER_UNSUPPORTED": "远端任务还不能使用这个模型供应商。请换一个供应商,或在本机任务里使用它。","REMOTE_PROVIDER_UPDATING": "这个模型供应商的凭据正在更新。请稍后再试。","REMOTE_WORKDIR_UNAVAILABLE": "远端工作目录现在不可用。请确认那台电脑上的目录还在,然后重试。",- "REMOTE_OPTIMISTIC_SESSION_STATE_UNAVAILABLE": "电脑端暂时无法确认这条消息是否已经发出。请稍后再试,不要重复发送同一条。"+ "REMOTE_OPTIMISTIC_SESSION_STATE_UNAVAILABLE": "电脑端暂时无法确认这条消息是否已经发出。请稍后再试,不要重复发送同一条。",+ "REMOTE_AGENT_UNAVAILABLE": "运行 Agent 的电脑暂时连不上。确认那台电脑在线并允许远程控制后重试。",+ "REMOTE_AGENT_PEER_TOO_OLD": "那台电脑上的 Cindy 版本过旧,还不能替这台电脑运行 Agent。请先在那台电脑上更新 Cindy。",+ "REMOTE_AGENT_EXPIRED": "这个任务在运行 Agent 的电脑上已经结束。请重新发送。",+ "REMOTE_AGENT_NOT_FOUND": "这个任务在运行 Agent 的电脑上已经结束。请重新发送。",+ "REMOTE_AGENT_BUSY": "那台电脑上同时运行的任务太多。先结束一些任务后再试。",+ "REMOTE_AGENT_UNSUPPORTED": "那台电脑上这个 Agent 不可用。在那台电脑上安装或登录后再试,或换一个 Agent。",+ "REMOTE_AGENT_INVALID": "和运行 Agent 的电脑通信出错。请重试;如果一直出现,请把两台电脑上的 Cindy 都更新到最新版。"},"generatedFiles": {"title": "本条消息生成的文件",@@ -10621,7 +10636,8 @@"worktreeRepoHint": "可尝试重新选一次工作目录,等右下角文件夹标识刷新后再试","sessionInactive": "任务已不再处于活跃状态","remoteProjectBanner": "在 {{device}} 的 {{project}} 中新建任务",- "remoteDialogueBanner": "在 {{device}} 上新建对话(不绑定项目)"+ "remoteDialogueBanner": "在 {{device}} 上新建对话(不绑定项目)",+ "agentDeviceBanner": "任务和文件留在本机,Agent 在 {{device}} 上运行"},"jumpSession": {"emptyId": "请输入要跳转的任务 ID",@@ -11017,7 +11033,9 @@},"sessionHeader": {"untitled": "未命名任务",- "moreActions": "更多操作"+ "moreActions": "更多操作",+ "agentDevice": "Agent 在 {{device}} 上运行",+ "agentDeviceOffline": "Agent 在 {{device}} 上运行,那台电脑现在离线,连上后才能继续"},"gitContext": {"detached": "分离 HEAD",@@ -13224,7 +13242,8 @@"sessionTitle": "审查 · {{title}}","toast": {"failed": "无法开始审查",- "remoteUnsupported": "当前版本只支持审查本机任务"+ "remoteUnsupported": "当前版本只支持审查本机任务",+ "agentDeviceUnsupported": "Agent 在另一台电脑运行的任务暂不支持审查"},"externalArtifactConfirm": {"title": "允许审查工作区外的成果?",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex dcbd120163..6dd2102332 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -7690,7 +7690,12 @@"reset": "恢復預設","reorder": "調整{{name}}順序,按上下方向鍵"},- "items": { "automations": "自動化", "plugins": "插件", "bots": "夥伴", "search": "搜尋" }+ "items": {+ "automations": "自動化",+ "plugins": "插件",+ "bots": "夥伴",+ "search": "搜尋"+ }},"user": {"settingsLink": "設定,當前使用者:{{name}}",@@ -9346,7 +9351,10 @@"onlineHint": "已連線,可在其上建立","offlineHint": "離線 · 連上後可用","attachmentsDropped": "已移除 {{count}} 個附件:它們是上一臺裝置上的檔案",- "attachmentsRemoteUnsupported": "遠端裝置暫不支援檔案附件,已跳過 {{count}} 個(圖片可以)"+ "attachmentsRemoteUnsupported": "遠端裝置暫不支援檔案附件,已跳過 {{count}} 個(圖片可以)",+ "agentSection": "只讓 Agent 在其他電腦執行",+ "agentHint": "任務和檔案留在本機,使用這臺的登入與模型",+ "agentPill": "Agent 在 {{device}}"},"pluginSuggestions": {"changed": "這條推薦已更新,請換一批後重新選擇。",@@ -10326,7 +10334,14 @@"REMOTE_PROVIDER_UNSUPPORTED": "遠端任務還不能使用這個模型供應商。請換一個供應商,或在本機任務裡使用它。","REMOTE_PROVIDER_UPDATING": "這個模型供應商的憑證正在更新。請稍後再試。","REMOTE_WORKDIR_UNAVAILABLE": "遠端工作目錄現在無法使用。請確認那台電腦上的目錄還在,然後重試。",- "REMOTE_OPTIMISTIC_SESSION_STATE_UNAVAILABLE": "電腦端暫時無法確認這則訊息是否已經送出。請稍後再試,不要重複傳送同一則。"+ "REMOTE_OPTIMISTIC_SESSION_STATE_UNAVAILABLE": "電腦端暫時無法確認這則訊息是否已經送出。請稍後再試,不要重複傳送同一則。",+ "REMOTE_AGENT_UNAVAILABLE": "暫時連不上執行 Agent 的電腦。確認那臺電腦在線並允許遠端控制後重試。",+ "REMOTE_AGENT_PEER_TOO_OLD": "那臺電腦上的 Cindy 版本過舊,還不能替這臺電腦執行 Agent。請先在那臺電腦上更新 Cindy。",+ "REMOTE_AGENT_EXPIRED": "這個任務在執行 Agent 的電腦上已經結束。請重新傳送。",+ "REMOTE_AGENT_NOT_FOUND": "這個任務在執行 Agent 的電腦上已經結束。請重新傳送。",+ "REMOTE_AGENT_BUSY": "那臺電腦上同時執行的任務太多。先結束一些任務後再試。",+ "REMOTE_AGENT_UNSUPPORTED": "那臺電腦上這個 Agent 無法使用。在那臺電腦上安裝或登入後再試,或換一個 Agent。",+ "REMOTE_AGENT_INVALID": "與執行 Agent 的電腦通訊時出錯。請重試;如果持續出現,請把兩臺電腦上的 Cindy 都更新到最新版。"},"generatedFiles": {"title": "本條訊息生成的檔案",@@ -10621,7 +10636,8 @@"worktreeRepoHint": "可嘗試重新選一次工作目錄,等右下角資料夾標識重新整理後再試","sessionInactive": "任務已不再處於活躍狀態","remoteProjectBanner": "在 {{device}} 的 {{project}} 中新建任務",- "remoteDialogueBanner": "在 {{device}} 上新建對話(不繫結專案)"+ "remoteDialogueBanner": "在 {{device}} 上新建對話(不繫結專案)",+ "agentDeviceBanner": "任務和檔案留在本機,Agent 在 {{device}} 上執行"},"jumpSession": {"emptyId": "請輸入要跳轉的任務 ID",@@ -11017,7 +11033,9 @@},"sessionHeader": {"untitled": "未命名任務",- "moreActions": "更多操作"+ "moreActions": "更多操作",+ "agentDevice": "Agent 在 {{device}} 上執行",+ "agentDeviceOffline": "Agent 在 {{device}} 上執行,那臺電腦目前離線,連上後才能繼續"},"gitContext": {"detached": "分離 HEAD",@@ -13224,7 +13242,8 @@"sessionTitle": "審查 · {{title}}","toast": {"failed": "無法開始審查",- "remoteUnsupported": "當前版本只支援審查本機任務"+ "remoteUnsupported": "當前版本只支援審查本機任務",+ "agentDeviceUnsupported": "Agent 在另一臺電腦執行的任務暫不支援審查"},"externalArtifactConfirm": {"title": "允許審查工作區外的成果?",diff --git a/apps/desktop/src/renderer/lib/ccAgent.types.ts b/apps/desktop/src/renderer/lib/ccAgent.types.tsindex a2bb62bb39..1a6eccb615 100644--- a/apps/desktop/src/renderer/lib/ccAgent.types.ts+++ b/apps/desktop/src/renderer/lib/ccAgent.types.ts@@ -403,6 +403,12 @@ export interface Session {* 是远端路径。null/undefined = 本地。仅 Codex 支持。*/remoteHostId?: string | null;+ /**+ * Agent 在同账号另一台电脑上运行时,那台电脑的 deviceId。任务、项目文件与命令仍在本机+ * (workingDir 是本机路径,文件浏览、改动对比照本机方式工作);只有 Agent 进程、登录与供应商+ * 在那台电脑上。null/undefined = Agent 在本机。与 remoteHostId 互斥。+ */+ agentDeviceId?: string | null;/*** device-link 跨设备远程控制:本 session 实际归属的**被控设备 deviceId**。* 仅存在于控制端**内存**里(由 remoteProjectsStore 注入),**永不落本地 DB**——diff --git a/apps/desktop/src/renderer/lib/sessionService.ts b/apps/desktop/src/renderer/lib/sessionService.tsindex 98d150f79c..78683c59f5 100644--- a/apps/desktop/src/renderer/lib/sessionService.ts+++ b/apps/desktop/src/renderer/lib/sessionService.ts@@ -111,6 +111,11 @@ export async function create(body?: {/** Remote codex session (P2): 远端 SSH host alias。设置后 workingDir 须为* 远端绝对路径; codex agent 跑在远端机器, 本地不 spawn。 */remoteHostId?: string;+ /**+ * Agent 在同账号另一台电脑上运行:那台电脑的 deviceId。任务、项目文件与命令仍在本机,+ * 模型来源由那台电脑解析。与 remoteHostId 互斥。+ */+ agentDeviceId?: string;/*** per-session 来源(供应商)显式选择,落盘 sessions.provider_id(与 update 同列、同语义)。* null/undefined = 跟随默认路由。草稿态发送建会话时透传用户在草稿里选定的来源,diff --git a/apps/desktop/src/renderer/state/newMakerDraft.ts b/apps/desktop/src/renderer/state/newMakerDraft.tsindex f28e4fe95e..dccfe345da 100644--- a/apps/desktop/src/renderer/state/newMakerDraft.ts+++ b/apps/desktop/src/renderer/state/newMakerDraft.ts@@ -106,6 +106,14 @@ export interface NewMakerDraft {deviceLinkDeviceId: string | null;/** device-link 目标设备友好名(草稿页横幅展示),与 deviceLinkDeviceId 同源。 */deviceLinkDeviceName: string | null;+ /**+ * Agent 在同账号另一台电脑上运行(任务、项目文件与命令仍在本机):那台电脑的 deviceId。+ * 模型目录、Agent 登录与供应商都来自那台。与 remoteHostId / deviceLinkDeviceId 互斥;+ * 与 deviceLinkDeviceId 同理**不跨重启持久化**(绑的是一台可能离线的活动设备)。+ */+ agentDeviceId: string | null;+ /** agentDeviceId 那台电脑的友好名(展示用)。 */+ agentDeviceName: string | null;/** 协同模式开关 + Worker 类型(草稿期持久化,Send 时由 enableOrca 消费)。 */collab: CollabDraft;/**@@ -223,6 +231,8 @@ function makeDefault(): NewMakerDraft {remoteHostId: null,deviceLinkDeviceId: null,deviceLinkDeviceName: null,+ agentDeviceId: null,+ agentDeviceName: null,collab: defaultCollab(),worktreeEnabled: DEFAULT_WORKTREE_ENABLED,worktreePreferenceCustomized: false,@@ -446,6 +456,8 @@ function sanitize(raw: unknown): NewMakerDraft {// device-link 目标**不跨重启恢复**:绑定的是活动设备,重启后可能已离线 → 一律置 null。deviceLinkDeviceId: null,deviceLinkDeviceName: null,+ agentDeviceId: null,+ agentDeviceName: null,collab,// worktree 勾选记忆:系统默认 + 显式 override 合成。注意历史残留的// wtEnabled/wtName/wtSourceBranch/wtBaseRepo 根字段(2026-07 前的短暂持久化实验)@@ -843,6 +855,16 @@ export function patchDraft(patch: Partial<NewMakerDraft>): void {next.deviceLinkDeviceId = null;next.deviceLinkDeviceName = null;}+ // 「Agent 在另一台电脑运行」只用于本机任务:任务本身建到远程设备或 SSH 主机时不成立。+ if (next.deviceLinkDeviceId != null || next.remoteHostId != null) {+ next.agentDeviceId = null;+ next.agentDeviceName = null;+ } else if ('agentDeviceId' in normalizedPatch) {+ const agentDeviceId = normalizedPatch.agentDeviceId;+ next.agentDeviceId =+ typeof agentDeviceId === 'string' && agentDeviceId.trim().length > 0 ? agentDeviceId.trim() : null;+ if (next.agentDeviceId == null) next.agentDeviceName = null;+ }// 换目标设备(含本机 ↔ 被控设备、被控设备 A ↔ B)→ 丢掉 Worker 富配置,只留// enabled + worker。model / providerId / effort / fast 都是**设备作用域**的:被控端// 装的模型目录、连的供应商都是它自己那一套,原样透传过去会撞被控端 main 的精确diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex e71e761a63..63c6383273 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -4688,6 +4688,8 @@ interface ElectronAPI {extraDirs?: string[];writableDirs?: string[];remoteHostId?: string;+ /** Agent 在同账号另一台电脑上运行(任务与文件在本机);与 remoteHostId 互斥。 */+ agentDeviceId?: string;providerId?: string | null;/** Only the Cindy Make purpose may be requested; Main validates the checkout. */source?: 'cindy-make';diff --git a/apps/mobile/src/i18n/locales/en/session.json b/apps/mobile/src/i18n/locales/en/session.jsonindex 1aa9e8e461..f829dff12a 100644--- a/apps/mobile/src/i18n/locales/en/session.json+++ b/apps/mobile/src/i18n/locales/en/session.json@@ -549,7 +549,14 @@"REMOTE_PROVIDER_UNSUPPORTED": "Remote tasks cannot use this model provider yet. Pick another provider, or use it in a local task.","REMOTE_PROVIDER_UPDATING": "This model provider’s credentials are updating. Try again in a moment.","REMOTE_WORKDIR_UNAVAILABLE": "The remote working directory is unavailable. Check that the folder still exists on that computer, then try again.",- "REMOTE_OPTIMISTIC_SESSION_STATE_UNAVAILABLE": "The computer cannot yet confirm whether this message was sent. Wait a moment and try again. Do not send the same message twice."+ "REMOTE_OPTIMISTIC_SESSION_STATE_UNAVAILABLE": "The computer cannot yet confirm whether this message was sent. Wait a moment and try again. Do not send the same message twice.",+ "REMOTE_AGENT_UNAVAILABLE": "Can't reach the computer running the Agent. Make sure it's online and allows remote control, then try again.",+ "REMOTE_AGENT_PEER_TOO_OLD": "Cindy on the other computer is too old to run the Agent for this one. Update Cindy there first.",+ "REMOTE_AGENT_EXPIRED": "This session already ended on the computer running the Agent. Send your message again.",+ "REMOTE_AGENT_NOT_FOUND": "This session already ended on the computer running the Agent. Send your message again.",+ "REMOTE_AGENT_BUSY": "Too many sessions are running on the other computer. End some of them and try again.",+ "REMOTE_AGENT_UNSUPPORTED": "This Agent isn't available on the other computer. Install or sign in to it there, or pick another Agent.",+ "REMOTE_AGENT_INVALID": "Something went wrong talking to the computer running the Agent. Try again; if it keeps happening, update Cindy on both computers."},"collab": {"modeLabel": "Collaboration mode",diff --git a/apps/mobile/src/i18n/locales/ja/session.json b/apps/mobile/src/i18n/locales/ja/session.jsonindex ec69891c83..9c986a099d 100644--- a/apps/mobile/src/i18n/locales/ja/session.json+++ b/apps/mobile/src/i18n/locales/ja/session.json@@ -549,7 +549,14 @@"REMOTE_PROVIDER_UNSUPPORTED": "リモートのタスクでは、まだこのモデルプロバイダーを使えません。別のプロバイダーに変えるか、このパソコン上のタスクで使ってください。","REMOTE_PROVIDER_UPDATING": "このモデルプロバイダーの認証情報を更新しています。しばらくしてからもう一度お試しください。","REMOTE_WORKDIR_UNAVAILABLE": "リモートの作業ディレクトリを今は使えません。そのパソコンにフォルダがまだあるか確認してから、再試行してください。",- "REMOTE_OPTIMISTIC_SESSION_STATE_UNAVAILABLE": "パソコン側で、このメッセージが送信済みかまだ確認できません。少し待ってから再試行し、同じメッセージを重ねて送らないでください。"+ "REMOTE_OPTIMISTIC_SESSION_STATE_UNAVAILABLE": "パソコン側で、このメッセージが送信済みかまだ確認できません。少し待ってから再試行し、同じメッセージを重ねて送らないでください。",+ "REMOTE_AGENT_UNAVAILABLE": "Agent を実行しているパソコンに接続できません。そのパソコンがオンラインでリモート操作を許可していることを確認して、もう一度お試しください。",+ "REMOTE_AGENT_PEER_TOO_OLD": "相手のパソコンの Cindy が古いため、このパソコンの Agent を実行できません。先にそのパソコンで Cindy を更新してください。",+ "REMOTE_AGENT_EXPIRED": "このセッションは Agent を実行しているパソコンですでに終了しています。もう一度送信してください。",+ "REMOTE_AGENT_NOT_FOUND": "このセッションは Agent を実行しているパソコンですでに終了しています。もう一度送信してください。",+ "REMOTE_AGENT_BUSY": "相手のパソコンで実行中のセッションが多すぎます。いくつか終了してからもう一度お試しください。",+ "REMOTE_AGENT_UNSUPPORTED": "相手のパソコンではこの Agent を使えません。そのパソコンでインストールまたはサインインするか、別の Agent を選んでください。",+ "REMOTE_AGENT_INVALID": "Agent を実行しているパソコンとの通信でエラーが発生しました。もう一度お試しください。続く場合は両方のパソコンの Cindy を最新版に更新してください。"},"collab": {"modeLabel": "コラボレーションモード",diff --git a/apps/mobile/src/i18n/locales/ko/session.json b/apps/mobile/src/i18n/locales/ko/session.jsonindex 0079c6ad52..3f8dec5586 100644--- a/apps/mobile/src/i18n/locales/ko/session.json+++ b/apps/mobile/src/i18n/locales/ko/session.json@@ -545,7 +545,14 @@"REMOTE_PROVIDER_UNSUPPORTED": "원격 작업에서는 아직 이 모델 제공자를 사용할 수 없습니다. 다른 제공자로 바꾸거나 이 컴퓨터의 작업에서 사용하세요.","REMOTE_PROVIDER_UPDATING": "이 모델 제공자의 자격 증명을 업데이트하는 중입니다. 잠시 후 다시 시도하세요.","REMOTE_WORKDIR_UNAVAILABLE": "원격 작업 디렉터리를 지금 사용할 수 없습니다. 그 컴퓨터에 폴더가 아직 있는지 확인한 뒤 다시 시도하세요.",- "REMOTE_OPTIMISTIC_SESSION_STATE_UNAVAILABLE": "컴퓨터에서 이 메시지가 이미 전송됐는지 아직 확인할 수 없습니다. 잠시 후 다시 시도하고, 같은 메시지를 중복으로 보내지 마세요."+ "REMOTE_OPTIMISTIC_SESSION_STATE_UNAVAILABLE": "컴퓨터에서 이 메시지가 이미 전송됐는지 아직 확인할 수 없습니다. 잠시 후 다시 시도하고, 같은 메시지를 중복으로 보내지 마세요.",+ "REMOTE_AGENT_UNAVAILABLE": "Agent를 실행하는 컴퓨터에 연결할 수 없습니다. 그 컴퓨터가 온라인이고 원격 제어를 허용하는지 확인한 뒤 다시 시도하세요.",+ "REMOTE_AGENT_PEER_TOO_OLD": "상대 컴퓨터의 Cindy가 오래되어 이 컴퓨터의 Agent를 실행할 수 없습니다. 먼저 그 컴퓨터에서 Cindy를 업데이트하세요.",+ "REMOTE_AGENT_EXPIRED": "이 세션은 Agent를 실행하는 컴퓨터에서 이미 종료되었습니다. 다시 보내 주세요.",+ "REMOTE_AGENT_NOT_FOUND": "이 세션은 Agent를 실행하는 컴퓨터에서 이미 종료되었습니다. 다시 보내 주세요.",+ "REMOTE_AGENT_BUSY": "상대 컴퓨터에서 실행 중인 세션이 너무 많습니다. 일부를 종료한 뒤 다시 시도하세요.",+ "REMOTE_AGENT_UNSUPPORTED": "상대 컴퓨터에서는 이 Agent를 사용할 수 없습니다. 그 컴퓨터에서 설치하거나 로그인한 뒤 다시 시도하거나, 다른 Agent를 선택하세요.",+ "REMOTE_AGENT_INVALID": "Agent를 실행하는 컴퓨터와 통신하는 중 오류가 발생했습니다. 다시 시도하고, 계속되면 두 컴퓨터의 Cindy를 모두 최신 버전으로 업데이트하세요."},"collab": {"modeLabel": "협업 모드",diff --git a/apps/mobile/src/i18n/locales/zh-CN/session.json b/apps/mobile/src/i18n/locales/zh-CN/session.jsonindex 70e64683a9..95e85ca94f 100644--- a/apps/mobile/src/i18n/locales/zh-CN/session.json+++ b/apps/mobile/src/i18n/locales/zh-CN/session.json@@ -545,7 +545,14 @@"REMOTE_PROVIDER_UNSUPPORTED": "远程任务还不能使用这个模型供应商。请换一个供应商,或在本机任务里使用它。","REMOTE_PROVIDER_UPDATING": "这个模型供应商的凭据正在更新。请稍后再试。","REMOTE_WORKDIR_UNAVAILABLE": "远程工作目录现在不可用。请确认那台电脑上的目录还在,然后重试。",- "REMOTE_OPTIMISTIC_SESSION_STATE_UNAVAILABLE": "电脑端暂时无法确认这条消息是否已经发出。请稍后再试,不要重复发送同一条。"+ "REMOTE_OPTIMISTIC_SESSION_STATE_UNAVAILABLE": "电脑端暂时无法确认这条消息是否已经发出。请稍后再试,不要重复发送同一条。",+ "REMOTE_AGENT_UNAVAILABLE": "运行 Agent 的电脑暂时连不上。确认那台电脑在线并允许远程控制后重试。",+ "REMOTE_AGENT_PEER_TOO_OLD": "那台电脑上的 Cindy 版本过旧,还不能替这台电脑运行 Agent。请先在那台电脑上更新 Cindy。",+ "REMOTE_AGENT_EXPIRED": "这个任务在运行 Agent 的电脑上已经结束。请重新发送。",+ "REMOTE_AGENT_NOT_FOUND": "这个任务在运行 Agent 的电脑上已经结束。请重新发送。",+ "REMOTE_AGENT_BUSY": "那台电脑上同时运行的任务太多。先结束一些任务后再试。",+ "REMOTE_AGENT_UNSUPPORTED": "那台电脑上这个 Agent 不可用。在那台电脑上安装或登录后再试,或换一个 Agent。",+ "REMOTE_AGENT_INVALID": "和运行 Agent 的电脑通信出错。请重试;如果一直出现,请把两台电脑上的 Cindy 都更新到最新版。"},"collab": {"modeLabel": "协同模式",diff --git a/apps/mobile/src/i18n/locales/zh-TW/session.json b/apps/mobile/src/i18n/locales/zh-TW/session.jsonindex 45ed437594..383ffe4d77 100644--- a/apps/mobile/src/i18n/locales/zh-TW/session.json+++ b/apps/mobile/src/i18n/locales/zh-TW/session.json@@ -549,7 +549,14 @@"REMOTE_PROVIDER_UNSUPPORTED": "遠端任務還不能使用這個模型供應商。請換一個供應商,或在本機任務裡使用它。","REMOTE_PROVIDER_UPDATING": "這個模型供應商的憑證正在更新。請稍後再試。","REMOTE_WORKDIR_UNAVAILABLE": "遠端工作目錄現在無法使用。請確認那台電腦上的目錄還在,然後重試。",- "REMOTE_OPTIMISTIC_SESSION_STATE_UNAVAILABLE": "電腦端暫時無法確認這則訊息是否已經送出。請稍後再試,不要重複傳送同一則。"+ "REMOTE_OPTIMISTIC_SESSION_STATE_UNAVAILABLE": "電腦端暫時無法確認這則訊息是否已經送出。請稍後再試,不要重複傳送同一則。",+ "REMOTE_AGENT_UNAVAILABLE": "暫時連不上執行 Agent 的電腦。確認那臺電腦在線並允許遠端控制後重試。",+ "REMOTE_AGENT_PEER_TOO_OLD": "那臺電腦上的 Cindy 版本過舊,還不能替這臺電腦執行 Agent。請先在那臺電腦上更新 Cindy。",+ "REMOTE_AGENT_EXPIRED": "這個任務在執行 Agent 的電腦上已經結束。請重新傳送。",+ "REMOTE_AGENT_NOT_FOUND": "這個任務在執行 Agent 的電腦上已經結束。請重新傳送。",+ "REMOTE_AGENT_BUSY": "那臺電腦上同時執行的任務太多。先結束一些任務後再試。",+ "REMOTE_AGENT_UNSUPPORTED": "那臺電腦上這個 Agent 無法使用。在那臺電腦上安裝或登入後再試,或換一個 Agent。",+ "REMOTE_AGENT_INVALID": "與執行 Agent 的電腦通訊時出錯。請重試;如果持續出現,請把兩臺電腦上的 Cindy 都更新到最新版。"},"collab": {"modeLabel": "協同模式",diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex 93edc3765e..c282467f66 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -435,6 +435,45 @@ handler 无 sender 依赖;不加入共享任务访客白名单,不进入自旧控制端行为不变。Mobile 未接入,服务端无需改动。实现见 `makerTransport.ts` 与`useRemoteSessionBackgroundTasks.ts`。+## 远程 Agent:Agent 在另一台电脑运行++同账号的 A(任务、项目文件与命令所在)可以让 B(打开了「允许远程控制」)用 B 自己的 Agent 程序、+登录(含 Claude 订阅)、供应商与网络运行 Agent。新增 invoke channel `maker:remote-agent:v1`+(`packages/device-link/src/remoteAgent.ts`),只进同账号 allowlist,不进共享任务清单;被控端+`dispatch.ts` 对共享任务访客再拒一次。++- **方向**:A 始终是发起方。`open / call / reply / push / close / upload / caps` 是 A → B 的指令,+ `poll` 按游标拉取 B 的 NDJSON 事件流:同一台 B 上的全部任务共用一个 poll(一次带上各任务游标,+ 最多 64 个;无新数据时 B 挂起最多 10s)。A 登记新任务时可再发一个覆盖全部任务的 poll,两个 poll+ 返回的数据可能重叠,回包里的 `from` 标明数据起点,A 按 `from` 去重、游标只进不退;B 不认识的任务+ 或超出已写范围的游标回 `missing`。B 需要 A 处理的事(权限确认、执行器与 MCP 的 HTTP 请求、+ Codex exec-server 的 WebSocket 帧、`cancel`)都作为事件流里的反向请求,A 用 `reply / push` 回传。+- **幂等**:`poll` 按游标幂等,只有它在 peer reset 后自动重读(`isPeerResetRetryableInvoke`);+ `open` 按 runId、`call` 按 callId、`reply` 按 requestId、`push` 按 seq 去重,不自动重放;+ 该 channel 的结果不进全局去重缓存。+- **大小**:内联载荷 1MB,更大的 gzip 后按 512KB 分段 `upload`(单个载荷 64MB);单次 `poll`+ 每个任务最多 512KB、合计 1.5MB(B 轮流决定从哪个任务开始取,积压多的任务不会一直挤占额度);`push` 单帧 1MB、单次合计 3MB,超长 WebSocket 消息拆段(`more: true`)。+- **前向兼容**:A 解析事件流时忽略不认识的行类型;B 对不认识的 op / 方法回 `REMOTE_AGENT_INVALID`+ / `REMOTE_AGENT_UNSUPPORTED`。旧版 B 回 `CHANNEL_NOT_ALLOWED`,A 提示对方版本过旧,不回退到本机运行。+- **凭证**:模型请求只由 B 上的 Agent 用 B 自己的登录与供应商发出,任何凭证不进事件流;B 本机+ 隧道每个任务一个随机令牌,只监听 127.0.0.1。+- **Codex 依赖**:B 的 Codex 通过 app-server 的实验接口 `environment/add` + `environments` 把 A 注册为+ exec-server 执行环境,A 为每条连接起本机 `codex exec-server --listen stdio://`。该接口随 Codex 版本+ 可能变化,升级 Codex 时需回归 `remote-agent/__tests__/codexHosted.e2e.test.ts`。+- **影子目录与配置同步**:`open` 载荷除项目说明文件外还带 `ancestorFiles`(项目上级目录里的+ `CLAUDE.md` / `CLAUDE.local.md` / `AGENTS.md` / `AGENTS.override.md`,按层级 `up`,最多 24 级)与+ `personal`(A 的个人配置:Claude Code 的 `~/.claude/CLAUDE.md`、`skills/agents/commands`、`settings.json`+ 里的权限规则;Codex 的 `AGENTS(.override).md`;不含 hooks / env)。两者缺省按空处理。B 把影子目录按+ A 的真实路径逐级镜像在 `<runs>/workspaces/<控制端>/<任务>/fs/` 下,`open` 回包的 `mirrorRoot` 告诉 A+ 镜像根,A 据此把影子路径逐级映射回真实路径;项目里已有的同名文件以项目为准。+- **回退**:`REMOTE_AGENT_METHODS` 含 `previewRewindFiles` / `commitRewindFiles`,B 在 `describeHandle`+ 里声明支持后 A 才提供回退;文件按 A 本机的保存点链回退,对话由 B 截断。B 不支持时 A 关闭回退并提示+ 升级那台的 Cindy。+- **持久化**:A 的 `sessions.agent_device_id`(migration 0123)记住 Agent 所在电脑;旧版本读不到该列,+ 按本机任务处理。服务端代码无改动。+- **暂不支持**:分叉、审查、移动项目、复制到其他电脑、导出 `.cshare`(Agent 会话记录在 B),入口隐藏、+ 主进程拒绝。+## 事实来源| 内容 | 权威来源 |diff --git a/docs/dev-rules/remote-and-mobile-adaptation.md b/docs/dev-rules/remote-and-mobile-adaptation.mdindex 27e66f929d..58611f1847 100644--- a/docs/dev-rules/remote-and-mobile-adaptation.md+++ b/docs/dev-rules/remote-and-mobile-adaptation.md@@ -68,6 +68,21 @@ relay 以 close 1013 `inbound backpressure` 主动断连,此时任何「立即一起打掉线,由 #1405 收窄止损半径修复。协议兼容、allowlist、单测三层防线对这类问题全部免疫,只有 review 时点名问「半径」才拦得住。+## 远程 Agent 的拉取与恢复(`maker:remote-agent:v1`)++协议见 [`protocol-compatibility.md`](protocol-compatibility.md)「远程 Agent」。恢复策略按故障半径三问:++1. **故障层级**:只处理同一台被控端的事件拉取。`poll` 遇到 peer reset、超时、背压或链路暂断时,+ 用同样的游标重拉(0.5s 起指数退避,上限 5s;另一个在途 poll 成功即提前恢复);连续 2 分钟拉不到+ 才结束这台被控端上的任务并提示对方不可达。单个任务的流数据与游标对不上时只结束那一个任务。+ 其余 op 不自动重放。+2. **动作层级**:与故障同半径——只影响这台被控端的拉取器,不重建 link、不断开 relay、不影响其它+ 被控端和普通远控请求。被控端侧对无人拉取的任务按任务超时(3 分钟)收尾,不波及其它任务。+3. **多 peer**:被控端按 `(控制端, runId)` 隔离任务;每个控制端最多 16 个任务。控制端每台被控端一个+ 拉取器,全部任务共用一个挂起最多 10s 的 `poll`,同时在途最多两个,任务再多也不占满共享的+ 12 个在途配额;被控端连续立即返回空结果时控制端放慢到 1s 一次,防止空转。2 台控制端共享被控端、+ 其中一台静默的回归仍需在双实例实机验证中补测。+## 共享恢复与请求策略普通出站 invoke 在共享 `InvokeScheduler` 中按目标设备排队:每台最多 12 个在途,diff --git a/packages/device-link/src/__tests__/remoteAgent.test.ts b/packages/device-link/src/__tests__/remoteAgent.test.tsnew file mode 100644index 0000000000..086291760e--- /dev/null+++ b/packages/device-link/src/__tests__/remoteAgent.test.ts@@ -0,0 +1,102 @@+import { describe, expect, it } from 'vitest';+import {+ REMOTE_AGENT_CHANNEL,+ REMOTE_AGENT_MAX_INLINE_PAYLOAD_CHARS,+ REMOTE_AGENT_UPLOAD_CHUNK_BYTES,+ REMOTE_INVOKE_ALLOWLIST,+ isPeerResetRetryableInvoke,+ isRemoteAgentReadInvoke,+ parseRemoteAgentCaps,+ parseRemoteAgentPollResult,+ parseRemoteAgentReadResult,+ parseRemoteAgentReply,+ parseRemoteAgentRequest,+ parseRemoteAgentStreamItem,+ remoteAgentErrorCode,+} from '../index';++const runId = '0f9c4a2e-6d1b-4c3a-9e8f-1a2b3c4d5e6f';+const otherId = '1a2b3c4d-5e6f-4a1b-8c2d-3e4f5a6b7c8d';++describe('remote agent channel', () => {+ // Shared-task guests are refused by the desktop shared-task gate (not in its channel list).+ it('is registered on the same-account allowlist', () => {+ expect(REMOTE_INVOKE_ALLOWLIST.has(REMOTE_AGENT_CHANNEL)).toBe(true);+ });++ it('parses every op and drops unknown fields', () => {+ expect(parseRemoteAgentRequest({ op: 'caps', x: 1 })).toEqual({ op: 'caps' });+ expect(parseRemoteAgentRequest({ op: 'open', runId, agentKind: 'pi', payload: { json: { a: 1 } }, extra: 1 }))+ .toEqual({ op: 'open', runId, agentKind: 'pi', payload: { json: { a: 1 } } });+ expect(parseRemoteAgentRequest({ op: 'call', runId, callId: otherId, method: 'send', payload: { json: [1] } }))+ .toEqual({ op: 'call', runId, callId: otherId, method: 'send', payload: { json: [1] } });+ expect(parseRemoteAgentRequest({ op: 'poll', runs: [{ runId, cursor: 7 }, { runId: otherId, cursor: 0 }] }))+ .toEqual({ op: 'poll', runs: [{ runId, cursor: 7 }, { runId: otherId, cursor: 0 }] });+ expect(parseRemoteAgentRequest({ op: 'reply', runId, requestId: otherId, payload: { uploadId: otherId, chunks: 2, bytes: 10 } }))+ .toEqual({ op: 'reply', runId, requestId: otherId, payload: { uploadId: otherId, chunks: 2, bytes: 10 } });+ expect(parseRemoteAgentRequest({ op: 'push', runId, seq: 3, frames: [{ connId: 'c1', kind: 'message', data: '{}' }] }))+ .toEqual({ op: 'push', runId, seq: 3, frames: [{ connId: 'c1', kind: 'message', data: '{}' }] });+ expect(parseRemoteAgentRequest({ op: 'close', runId, mode: 'detach', reason: 'navigation' })).toEqual({ op: 'close', runId, mode: 'detach', reason: 'navigation' });+ expect(parseRemoteAgentRequest({ op: 'upload', uploadId: otherId, index: 0, data: 'AAAA' }))+ .toEqual({ op: 'upload', uploadId: otherId, index: 0, data: 'AAAA' });+ });++ it('rejects malformed identities, unknown methods and oversize payloads', () => {+ const bad: unknown[] = [+ null,+ { op: 'nope' },+ { op: 'open', runId: 'x', agentKind: 'pi', payload: { json: 1 } },+ { op: 'open', runId, agentKind: 'gemini', payload: { json: 1 } },+ { op: 'call', runId, callId: otherId, method: 'dispose', payload: { json: [] } },+ { op: 'call', runId, callId: otherId, method: 'send', payload: { json: 'x'.repeat(REMOTE_AGENT_MAX_INLINE_PAYLOAD_CHARS + 1) } },+ { op: 'reply', runId, requestId: otherId, payload: { uploadId: otherId, chunks: 0, bytes: 0 } },+ { op: 'reply', runId, requestId: otherId, payload: { uploadId: otherId, chunks: 1, bytes: REMOTE_AGENT_UPLOAD_CHUNK_BYTES + 1 } },+ { op: 'poll', runs: [{ runId, cursor: -1 }] },+ { op: 'poll', runs: [] },+ { op: 'poll', runs: [{ runId, cursor: 1 }, { runId, cursor: 2 }] },+ { op: 'push', runId, seq: 1, frames: [] },+ { op: 'push', runId, seq: 1, frames: [{ connId: 'bad id!', kind: 'message', data: '' }] },+ { op: 'push', runId, seq: 1, frames: [{ connId: 'c1', kind: 'message' }] },+ { op: 'close', runId, mode: 'kill', reason: 'navigation' },+ { op: 'close', runId, mode: 'close', reason: 'whatever' },+ { op: 'upload', uploadId: otherId, index: 0, data: 'not base64!' },+ ];+ for (const value of bad) expect(() => parseRemoteAgentRequest(value)).toThrow('REMOTE_AGENT_INVALID');+ });++ it('retries only cursor polls after a peer reset', () => {+ expect(isRemoteAgentReadInvoke(REMOTE_AGENT_CHANNEL, [{ op: 'poll', runs: [{ runId, cursor: 0 }] }])).toBe(true);+ expect(isPeerResetRetryableInvoke(REMOTE_AGENT_CHANNEL, [{ op: 'poll', runs: [{ runId, cursor: 0 }] }])).toBe(true);+ for (const op of ['open', 'call', 'reply', 'push', 'close', 'upload', 'caps', 'read']) {+ expect(isPeerResetRetryableInvoke(REMOTE_AGENT_CHANNEL, [{ op }])).toBe(false);+ }+ expect(isPeerResetRetryableInvoke('local-db:sessions:list')).toBe(true);+ });++ it('parses stream items defensively and skips unknown kinds from newer hosts', () => {+ expect(parseRemoteAgentStreamItem(JSON.stringify({ t: 'event', event: { type: 'text', text: 'hi' } })))+ .toEqual({ t: 'event', event: { type: 'text', text: 'hi' } });+ expect(parseRemoteAgentStreamItem(JSON.stringify({ t: 'future-kind' }))).toBeNull();+ expect(parseRemoteAgentStreamItem(JSON.stringify({+ t: 'request', requestId: otherId,+ request: { type: 'http', method: 'POST', path: '/exec/read', headers: [['content-type', 'application/json']], body: 'e30=' },+ }))).toMatchObject({ t: 'request', request: { type: 'http', path: '/exec/read' } });+ expect(parseRemoteAgentStreamItem(JSON.stringify({ t: 'result', callId: otherId, ok: false, error: { code: 'X', message: 'm'.repeat(5000), name: 'AgentNotAuthenticatedError' } })))+ .toMatchObject({ ok: false, error: { code: 'X', name: 'AgentNotAuthenticatedError' } });+ expect(() => parseRemoteAgentStreamItem('{not json')).toThrow('REMOTE_AGENT_INVALID');+ expect(() => parseRemoteAgentStreamItem(JSON.stringify({ t: 'request', requestId: otherId, request: { type: 'http', method: 'POST', path: 'no-slash', headers: [] } })))+ .toThrow('REMOTE_AGENT_INVALID');+ });++ it('validates host replies and read results', () => {+ expect(parseRemoteAgentReply({ type: 'http', status: 200, headers: [], body: 'YQ==' })).toEqual({ type: 'http', status: 200, headers: [], body: 'YQ==' });+ expect(() => parseRemoteAgentReply({ type: 'http', status: 42, headers: [] })).toThrow();+ expect(parseRemoteAgentReadResult({ cursor: 3, data: 'YWJj', done: true })).toEqual({ cursor: 3, data: 'YWJj', done: true });+ expect(parseRemoteAgentPollResult({ runs: [{ runId, cursor: 3, data: 'YWJj' }, { runId: otherId, cursor: 0, missing: true }] }))+ .toEqual({ runs: [{ runId, cursor: 3, data: 'YWJj' }, { runId: otherId, cursor: 0, missing: true }] });+ expect(parseRemoteAgentCaps({ version: 1, agents: [{ kind: 'pi', available: true }, { kind: 'x' }], maxRuns: 16, uploadChunkBytes: 1024, maxPayloadBytes: 10 }))+ .toEqual({ version: 1, agents: [{ kind: 'pi', available: true }], maxRuns: 16, uploadChunkBytes: 1024, maxPayloadBytes: 10 });+ expect(remoteAgentErrorCode('[REMOTE_AGENT_BUSY] x')).toBe('REMOTE_AGENT_BUSY');+ expect(remoteAgentErrorCode('[REMOTE_AGENT_SOMETHING] x')).toBeNull();+ });+});diff --git a/packages/device-link/src/allowlist.ts b/packages/device-link/src/allowlist.tsindex 33373077b4..b8a3242e90 100644--- a/packages/device-link/src/allowlist.ts+++ b/packages/device-link/src/allowlist.ts@@ -25,6 +25,7 @@* Renderer 可调用。它由业务 dispatch 拦截,绝不放行通用 UI / shell IPC。*/import { FILE_PEER_CHANNEL } from './filePeer.js';+import { REMOTE_AGENT_CHANNEL } from './remoteAgent.js';import { TASK_MIGRATION_CHANNEL } from './taskMigration.js';import { SESSION_ACTIVITY_CHANNEL, SESSION_SYNC_CHANNEL } from './topics.js';import { REMOTE_DESKTOP_INVOKE_MS } from './remoteDesktopIce.js';@@ -330,6 +331,10 @@ const CORE_INVOKE_CHANNELS: readonly string[] = [DL_MEDIA_FETCH_CHANNEL,FILE_PEER_CHANNEL,TASK_MIGRATION_CHANNEL,+ // 远程 Agent(被控端 dispatch 拦截执行,不落 ipcMain handler):在被控端用它自己的登录与+ // 供应商运行 Agent,文件、命令与 Cindy 工具回到控制端执行。准入同 fs:list-dir 的论证:+ // 同账号 + 被控端显式打开远程控制时,控制端本就能驱动被控端的 Agent;不进共享任务白名单。+ REMOTE_AGENT_CHANNEL,// 出方向语音转写(被控端 dispatch 拦截执行,不落 ipcMain handler;复用被控端 ASR 配置)。DL_VOICE_TRANSCRIBE_CHANNEL,// 临时 voice credential 同步(被控端 dispatch 拦截执行,不落 ipcMain handler;禁止泛化)。diff --git a/packages/device-link/src/client.ts b/packages/device-link/src/client.tsindex b4f3ed82ef..27a0281105 100644--- a/packages/device-link/src/client.ts+++ b/packages/device-link/src/client.ts@@ -1,4 +1,4 @@-import { isPeerResetRetryableReadChannel, isBackgroundInvoke, bypassInvokeScheduling } from './invokePolicy.js';+import { isPeerResetRetryableInvoke, isBackgroundInvoke, bypassInvokeScheduling } from './invokePolicy.js';import { InvokeScheduler } from './invokeScheduler.js';import { encodeSharedTaskEnvelope, decodeSharedTaskEnvelope } from './sharedTaskEnvelope.js';import { isSharedTaskPeer } from './sharedTaskPeer.js';@@ -508,8 +508,8 @@ interface PendingRequest {function isPeerResetRetryableRead(env: Omit<Envelope, 'id'>): boolean {if (env.kind !== 'invoke') return false;- const channel = (env.payload as InvokePayload | undefined)?.channel;- return typeof channel === 'string' && isPeerResetRetryableReadChannel(channel);+ const payload = env.payload as InvokePayload | undefined;+ return typeof payload?.channel === 'string' && isPeerResetRetryableInvoke(payload.channel, payload.args);}interface PendingReliableMessage {diff --git a/packages/device-link/src/index.ts b/packages/device-link/src/index.tsindex 4c5fe55299..85ae720825 100644--- a/packages/device-link/src/index.ts+++ b/packages/device-link/src/index.ts@@ -54,4 +54,5 @@ export * from "./pluginDeviceAuthorization.js";export * from "./pluginOauthAuthentication.js";export * from "./inputDelivery.js";export * from "./taskMigration.js";+export * from "./remoteAgent.js";export * from './pluginPages.js';diff --git a/packages/device-link/src/invokePolicy.ts b/packages/device-link/src/invokePolicy.tsindex cad6d8450b..70a1fbc0f9 100644--- a/packages/device-link/src/invokePolicy.ts+++ b/packages/device-link/src/invokePolicy.ts@@ -5,6 +5,7 @@ import {TASK_MIGRATION_RECEIVE_TIMEOUT_MS,} from './taskMigration.js';import type { InvokePayload } from './protocol.js';+import { isRemoteAgentReadInvoke } from './remoteAgent.js';/** These reads may wait behind current-task work. Not a retry or authorization policy.* sessions:list also serves initial loading and recovery probes, so it stays foreground.@@ -168,6 +169,14 @@ const PEER_RESET_RETRYABLE_READ_CHANNELS = new Set([]);/** Safe to retry after a peer reset; this does not grant permission or allow coalescing. */+/**+ * peer reset 后可重试的边界(按 op 判断)。远程 Agent 的 poll 按游标幂等,重拉不会重复执行;+ * 它的其它 op(open / call / reply / push / close)仍不可重试。+ */+export function isPeerResetRetryableInvoke(channel: string, args?: unknown[]): boolean {+ return isPeerResetRetryableReadChannel(channel) || isRemoteAgentReadInvoke(channel, args);+}+export function isPeerResetRetryableReadChannel(channel: string): boolean {return PEER_RESET_RETRYABLE_READ_CHANNELS.has(channel);}diff --git a/packages/device-link/src/remoteAgent.ts b/packages/device-link/src/remoteAgent.tsnew file mode 100644index 0000000000..034cb1360e--- /dev/null+++ b/packages/device-link/src/remoteAgent.ts@@ -0,0 +1,529 @@+/**+ * 远程 Agent(同账号):任务、项目文件与命令留在控制端(用户操作的电脑),Agent 进程跑在+ * 被控端(提供 Agent 登录、订阅与供应商的电脑)。被控端用它自己的程序、登录与供应商配置+ * 启动 Agent;读写文件、执行命令与 Cindy 工具经本通道回到控制端执行。+ *+ * 通信方向始终由控制端发起,被控端从不反过来控制控制端:+ * - `open / call / reply / push / close`:控制端 → 被控端的指令与回复;+ * - `poll`:控制端按游标拉取被控端的事件字节流(每行一个 JSON,见 RemoteAgentStreamItem)。+ * 同一台被控端上的全部任务共用一个 poll(一次带上各任务的游标),任务再多也只占一个在途请求。+ * Agent 事件、方法调用结果、被控端需要控制端处理的反向请求(权限确认、MCP 与执行器 HTTP、+ * Codex exec-server WebSocket 帧)都在这条流里,读多快才发多快,不主动推送到共享 relay;+ * - 大内容(带图片的消息、文件内容回复)先分段 `upload` 暂存,再由 open / call / reply 引用。+ *+ * 幂等:poll 按游标幂等,peer reset 后可重读;open 按 runId、call 按 callId、reply 按 requestId、+ * push 按 seq 去重。除 read 外都不自动重试(结果不明时由上层按自身语义处理)。+ */+export const REMOTE_AGENT_CHANNEL = 'maker:remote-agent:v1';+export const REMOTE_AGENT_VERSION = 1;++export const REMOTE_AGENT_KINDS = ['claude-code', 'codex', 'pi'] as const;+export type RemoteAgentKind = (typeof REMOTE_AGENT_KINDS)[number];++/** 每段上传的原始字节(gzip 之后)。base64 后约 683KB,远低于单条逻辑消息 4MB 上限。 */+export const REMOTE_AGENT_UPLOAD_CHUNK_BYTES = 512 * 1024;+/** gzip 后单个暂存载荷上限。 */+export const REMOTE_AGENT_MAX_PAYLOAD_BYTES = 64 * 1024 * 1024;+export const REMOTE_AGENT_MAX_UPLOAD_CHUNKS =+ REMOTE_AGENT_MAX_PAYLOAD_BYTES / REMOTE_AGENT_UPLOAD_CHUNK_BYTES;+/** 内联载荷(JSON 序列化后)上限;更大的走 upload。 */+export const REMOTE_AGENT_MAX_INLINE_PAYLOAD_CHARS = 1024 * 1024;+/** 单个任务一次 poll 最多返回的事件流字节。 */+export const REMOTE_AGENT_READ_MAX_BYTES = 512 * 1024;+/** 一次 poll 所有任务合计最多返回的字节(base64 后仍远低于单条逻辑消息 4MB)。 */+export const REMOTE_AGENT_POLL_MAX_BYTES = 1536 * 1024;+/** 没有新数据时被控端最多挂起 poll 的时长;远低于通道超时,留出回程余量。 */+export const REMOTE_AGENT_READ_WAIT_MS = 10_000;+/** 一次 poll 最多带的任务数。 */+export const REMOTE_AGENT_MAX_POLL_RUNS = 64;+export const REMOTE_AGENT_INVOKE_TIMEOUT_MS = 30_000;+/** 同一控制端在一台被控端上同时运行的远程 Agent 任务上限。 */+export const REMOTE_AGENT_MAX_RUNS_PER_CONTROLLER = 16;+/** 一次 push 最多携带的 WebSocket 帧数。 */+export const REMOTE_AGENT_MAX_PUSH_FRAMES = 64;++/**+ * 控制端可以调用的 Agent 会话方法(白名单)。与 maker-core AgentSessionHandle 同名;+ * 不在表里的方法被控端一律拒绝。+ */+export const REMOTE_AGENT_METHODS = [+ 'send',+ 'steer',+ 'abort',+ 'requestGracefulStop',+ 'setModel',+ 'requiresModelSwitchRebuild',+ 'previewModelSwitch',+ 'setPermissionMode',+ 'setEffort',+ 'setFastMode',+ 'setPlanMode',+ 'setThinkingEnabled',+ 'setExtraDirs',+ 'setWritableDirs',+ 'setVendorOptions',+ 'stopBackgroundTask',+ 'resumeBackgroundTask',+ 'compactSession',+ 'getContextUsage',+ 'getCodexContextWindowInfo',+ 'useCindyAutoReviewFallback',+ // 回到某条消息:对话在 Agent 那边截断(文件在控制端按保存点回退)。+ 'previewRewindFiles',+ 'commitRewindFiles',+] as const;+export type RemoteAgentMethod = (typeof REMOTE_AGENT_METHODS)[number];++export const REMOTE_AGENT_ERROR_CODES = [+ 'REMOTE_AGENT_INVALID',+ 'REMOTE_AGENT_NOT_FOUND',+ 'REMOTE_AGENT_UNSUPPORTED',+ 'REMOTE_AGENT_BUSY',+ 'REMOTE_AGENT_EXPIRED',+ 'REMOTE_AGENT_ACCOUNT_CHANGED',+ 'REMOTE_AGENT_UNAVAILABLE',+] as const;+export type RemoteAgentErrorCode = (typeof REMOTE_AGENT_ERROR_CODES)[number];++/** 内联 JSON 或引用已上传的 gzip(JSON) 分段。 */+export type RemoteAgentPayload =+ | { json: unknown }+ | { uploadId: string; chunks: number; bytes: number };++export interface RemoteAgentErrorInfo {+ code: string;+ message: string;+ /** 原错误类名(仅用于控制端还原 maker-core 的特定错误类型)。 */+ name?: string;+}++/** 被控端请控制端处理的反向请求。 */+export type RemoteAgentReverseRequest =+ | { type: 'interaction'; request: unknown }+ | {+ type: 'http';+ /** 被控端隧道上的路由(如 `/exec/read`、`/mcp/cindy_memory`)。 */+ method: string;+ path: string;+ headers: Array<[string, string]>;+ /** base64 请求体。 */+ body?: string;+ }+ | { type: 'callback'; name: RemoteAgentCallbackName; args: unknown[] };++export const REMOTE_AGENT_CALLBACKS = [+ 'onTranscriptUserEntry',+ 'onInvalidResumeSession',+ 'onInteractionStateChange',+] as const;+export type RemoteAgentCallbackName = (typeof REMOTE_AGENT_CALLBACKS)[number];++/** 控制端对反向请求的回复。 */+export type RemoteAgentReply =+ | { type: 'interaction'; result: unknown }+ | { type: 'http'; status: number; headers: Array<[string, string]>; body?: string }+ | { type: 'callback'; value?: unknown }+ | { type: 'error'; error: RemoteAgentErrorInfo };++/**+ * 控制端发给被控端 WebSocket 连接的帧(Codex exec-server 隧道)。单帧过大的消息拆成多段,+ * 除最后一段外都带 `more: true`,被控端拼好后再作为一条 WebSocket 消息发出。+ */+export interface RemoteAgentPushFrame {+ connId: string;+ kind: 'message' | 'close';+ data?: string;+ more?: true;+}++/** 一次 push 里所有帧数据的总长度上限(远低于单条逻辑消息 4MB)。 */+export const REMOTE_AGENT_MAX_PUSH_CHARS = 3 * 1024 * 1024;++export type RemoteAgentRequest =+ | { op: 'caps' }+ | { op: 'upload'; uploadId: string; index: number; data: string }+ | { op: 'open'; runId: string; agentKind: RemoteAgentKind; payload: RemoteAgentPayload }+ | { op: 'call'; runId: string; callId: string; method: RemoteAgentMethod; payload: RemoteAgentPayload }+ /**+ * waitMs:没有新数据时最多挂起多久(缺省 READ_WAIT_MS)。控制端在已有一个长等待在途时,+ * 可以再发一个 waitMs=0 的短 poll 立刻取新任务或刚触发的数据;两个 poll 返回的数据可能重叠,+ * 控制端按 from 去重。+ */+ | { op: 'poll'; runs: Array<{ runId: string; cursor: number }>; waitMs?: number }+ | { op: 'reply'; runId: string; requestId: string; payload: RemoteAgentPayload }+ | { op: 'push'; runId: string; seq: number; frames: RemoteAgentPushFrame[] }+ | { op: 'close'; runId: string; mode: 'close' | 'detach'; reason: RemoteAgentTeardownReason };++/** 与 maker-core AgentSessionTeardownReason 同值。 */+export const REMOTE_AGENT_TEARDOWN_REASONS = ['navigation', 'account-boundary', 'app-quit'] as const;+export type RemoteAgentTeardownReason = (typeof REMOTE_AGENT_TEARDOWN_REASONS)[number];++export interface RemoteAgentCaps {+ version: number;+ agents: Array<{ kind: RemoteAgentKind; available: boolean }>;+ maxRuns: number;+ uploadChunkBytes: number;+ maxPayloadBytes: number;+}++export interface RemoteAgentReadResult {+ /** 本次数据的起始偏移(缺省等于请求的游标)。并发 poll 时可能晚于请求的游标。 */+ from?: number;+ /** 本次返回数据之后的游标(事件流字节偏移)。 */+ cursor: number;+ /** base64 的事件流字节(NDJSON,可能在行中间截断,控制端按行拼接)。 */+ data?: string;+ /** 流已结束且全部读完。 */+ done?: true;+}++/** poll 的结果:只列出有新数据、已结束或已不存在的任务。 */+export interface RemoteAgentPollResult {+ runs: Array<RemoteAgentReadResult & { runId: string; missing?: true }>;+}++/** 事件流里的一行。 */+export type RemoteAgentStreamItem =+ | { t: 'started'; handle: Record<string, unknown> }+ | { t: 'start-failed'; error: RemoteAgentErrorInfo }+ | { t: 'event'; event: unknown }+ | { t: 'state'; state: Record<string, unknown> }+ | { t: 'result'; callId: string; ok: true; value?: unknown }+ | { t: 'result'; callId: string; ok: false; error: RemoteAgentErrorInfo }+ | { t: 'request'; requestId: string; request: RemoteAgentReverseRequest }+ /** 被控端放弃了一个尚未回包的反向请求(如 Agent 取消了工具调用),控制端应中止对应执行。 */+ | { t: 'cancel'; requestId: string }+ | { t: 'ws'; connId: string; kind: 'open' | 'message' | 'close'; path?: string; data?: string }+ | { t: 'closed'; reason: string; error?: RemoteAgentErrorInfo };++const ID = /^[0-9a-f-]{36}$/;+const CONN_ID = /^[A-Za-z0-9_-]{1,64}$/;+const HEADER_NAME = /^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,128}$/;+const MAX_HEADERS = 64;+const MAX_HEADER_VALUE = 8192;+const MAX_PATH = 2048;+const MAX_MESSAGE = 2048;+const BASE64 = /^[A-Za-z0-9+/]*={0,2}$/;++function invalid(): never {+ throw new Error('REMOTE_AGENT_INVALID');+}++function record(value: unknown): Record<string, unknown> {+ if (!value || typeof value !== 'object' || Array.isArray(value)) invalid();+ return value as Record<string, unknown>;+}++function id(value: unknown): string {+ if (typeof value !== 'string' || !ID.test(value)) invalid();+ return value;+}++function count(value: unknown, max: number): number {+ if (!Number.isSafeInteger(value) || (value as number) < 0 || (value as number) > max) invalid();+ return value as number;+}++function base64Chars(bytes: number): number {+ return Math.ceil(bytes / 3) * 4;+}++function base64(value: unknown, maxBytes: number): string {+ if (typeof value !== 'string' || value.length > base64Chars(maxBytes) || !BASE64.test(value)) invalid();+ return value;+}++function oneOf<T extends string>(value: unknown, allowed: readonly T[]): T {+ if (typeof value !== 'string' || !(allowed as readonly string[]).includes(value)) invalid();+ return value as T;+}++function payload(value: unknown): RemoteAgentPayload {+ const v = record(value);+ if ('json' in v) {+ // 内联载荷的大小由序列化后的长度约束;控制端发送前同样检查。+ let size: number;+ try {+ size = JSON.stringify(v.json)?.length ?? 0;+ } catch {+ invalid();+ }+ if (size > REMOTE_AGENT_MAX_INLINE_PAYLOAD_CHARS) invalid();+ return { json: v.json };+ }+ const chunks = count(v.chunks, REMOTE_AGENT_MAX_UPLOAD_CHUNKS);+ const bytes = count(v.bytes, REMOTE_AGENT_MAX_PAYLOAD_BYTES);+ if (chunks < 1 || bytes > chunks * REMOTE_AGENT_UPLOAD_CHUNK_BYTES) invalid();+ return { uploadId: id(v.uploadId), chunks, bytes };+}++function pushFrames(value: unknown): RemoteAgentPushFrame[] {+ if (!Array.isArray(value) || value.length === 0 || value.length > REMOTE_AGENT_MAX_PUSH_FRAMES) invalid();+ let total = 0;+ return value.map((item) => {+ const frame = record(item);+ if (typeof frame.connId !== 'string' || !CONN_ID.test(frame.connId)) invalid();+ const kind = oneOf(frame.kind, ['message', 'close'] as const);+ if (kind === 'message' && typeof frame.data !== 'string') invalid();+ if (typeof frame.data === 'string' && frame.data.length > REMOTE_AGENT_MAX_INLINE_PAYLOAD_CHARS) invalid();+ total += typeof frame.data === 'string' ? frame.data.length : 0;+ if (total > REMOTE_AGENT_MAX_PUSH_CHARS) invalid();+ if (frame.more !== undefined && (frame.more !== true || kind !== 'message')) invalid();+ return {+ connId: frame.connId,+ kind,+ ...(typeof frame.data === 'string' ? { data: frame.data } : {}),+ ...(frame.more === true ? { more: true as const } : {}),+ };+ });+}++/** 被控端解析控制端请求;不合法一律抛 `REMOTE_AGENT_INVALID`。 */+export function parseRemoteAgentRequest(value: unknown): RemoteAgentRequest {+ const v = record(value);+ switch (v.op) {+ case 'caps':+ return { op: 'caps' };+ case 'upload':+ return {+ op: 'upload',+ uploadId: id(v.uploadId),+ index: count(v.index, REMOTE_AGENT_MAX_UPLOAD_CHUNKS - 1),+ data: base64(v.data, REMOTE_AGENT_UPLOAD_CHUNK_BYTES),+ };+ case 'open':+ return {+ op: 'open',+ runId: id(v.runId),+ agentKind: oneOf(v.agentKind, REMOTE_AGENT_KINDS),+ payload: payload(v.payload),+ };+ case 'call':+ return {+ op: 'call',+ runId: id(v.runId),+ callId: id(v.callId),+ method: oneOf(v.method, REMOTE_AGENT_METHODS),+ payload: payload(v.payload),+ };+ case 'poll': {+ if (!Array.isArray(v.runs) || v.runs.length === 0 || v.runs.length > REMOTE_AGENT_MAX_POLL_RUNS) invalid();+ const runs = v.runs.map((item) => {+ const entry = record(item);+ return { runId: id(entry.runId), cursor: count(entry.cursor, Number.MAX_SAFE_INTEGER) };+ });+ if (new Set(runs.map((run) => run.runId)).size !== runs.length) invalid();+ return {+ op: 'poll',+ runs,+ ...(v.waitMs !== undefined ? { waitMs: count(v.waitMs, REMOTE_AGENT_READ_WAIT_MS) } : {}),+ };+ }+ case 'reply':+ return { op: 'reply', runId: id(v.runId), requestId: id(v.requestId), payload: payload(v.payload) };+ case 'push':+ return { op: 'push', runId: id(v.runId), seq: count(v.seq, Number.MAX_SAFE_INTEGER), frames: pushFrames(v.frames) };+ case 'close':+ return {+ op: 'close',+ runId: id(v.runId),+ mode: oneOf(v.mode, ['close', 'detach'] as const),+ reason: oneOf(v.reason, REMOTE_AGENT_TEARDOWN_REASONS),+ };+ default:+ invalid();+ }+}++/** poll 按游标幂等:peer reset 后可以重读,其余 op 不可重试。 */+export function isRemoteAgentReadInvoke(channel: string, args: unknown[] | undefined): boolean {+ if (channel !== REMOTE_AGENT_CHANNEL) return false;+ const request = args?.[0];+ return !!request && typeof request === 'object' && (request as { op?: unknown }).op === 'poll';+}++// ─── 控制端解析被控端回包(对端可能是不同版本,按最小合同防御)───────────────++/** 控制端接受的单次 read 数据上限:高于本版本的 READ_MAX_BYTES,给新版被控端留余量。 */+const READ_RESULT_ACCEPT_BYTES = 2 * 1024 * 1024;++export function parseRemoteAgentCaps(value: unknown): RemoteAgentCaps {+ const v = record(value);+ const agents = Array.isArray(v.agents)+ ? v.agents.flatMap((item) => {+ const entry = item && typeof item === 'object' ? item as Record<string, unknown> : null;+ if (!entry || !(REMOTE_AGENT_KINDS as readonly unknown[]).includes(entry.kind)) return [];+ return [{ kind: entry.kind as RemoteAgentKind, available: entry.available === true }];+ })+ : [];+ const caps = {+ version: count(v.version, 1_000),+ agents,+ maxRuns: count(v.maxRuns, 1_000),+ uploadChunkBytes: count(v.uploadChunkBytes, REMOTE_AGENT_UPLOAD_CHUNK_BYTES),+ maxPayloadBytes: count(v.maxPayloadBytes, Number.MAX_SAFE_INTEGER),+ };+ if (caps.version < 1 || caps.maxRuns < 1 || caps.uploadChunkBytes < 1) invalid();+ return caps;+}++export function parseRemoteAgentReadResult(value: unknown): RemoteAgentReadResult {+ const v = record(value);+ const result: RemoteAgentReadResult = { cursor: count(v.cursor, Number.MAX_SAFE_INTEGER) };+ if (v.from !== undefined) {+ result.from = count(v.from, Number.MAX_SAFE_INTEGER);+ if (result.from > result.cursor) invalid();+ }+ if (v.data !== undefined) result.data = base64(v.data, READ_RESULT_ACCEPT_BYTES);+ if (v.done !== undefined) {+ if (v.done !== true) invalid();+ result.done = true;+ }+ return result;+}++export function parseRemoteAgentPollResult(value: unknown): RemoteAgentPollResult {+ const v = record(value);+ if (!Array.isArray(v.runs) || v.runs.length > REMOTE_AGENT_MAX_POLL_RUNS) invalid();+ return {+ runs: v.runs.map((item) => {+ const entry = record(item);+ return {+ runId: id(entry.runId),+ ...parseRemoteAgentReadResult(entry),+ ...(entry.missing === true ? { missing: true as const } : {}),+ };+ }),+ };+}++function errorInfo(value: unknown): RemoteAgentErrorInfo {+ const v = record(value);+ return {+ code: typeof v.code === 'string' ? v.code.slice(0, 128) : 'INTERNAL',+ message: typeof v.message === 'string' ? v.message.slice(0, MAX_MESSAGE) : '',+ ...(typeof v.name === 'string' && /^[A-Za-z][A-Za-z0-9_]{0,63}$/.test(v.name) ? { name: v.name } : {}),+ };+}++function headerList(value: unknown): Array<[string, string]> {+ if (!Array.isArray(value) || value.length > MAX_HEADERS) invalid();+ return value.map((entry) => {+ if (!Array.isArray(entry) || entry.length !== 2) invalid();+ const [name, headerValue] = entry as unknown[];+ if (typeof name !== 'string' || !HEADER_NAME.test(name)) invalid();+ if (typeof headerValue !== 'string' || headerValue.length > MAX_HEADER_VALUE || /[\r\n\0]/.test(headerValue)) invalid();+ return [name, headerValue] as [string, string];+ });+}++function reverseRequest(value: unknown): RemoteAgentReverseRequest {+ const v = record(value);+ switch (v.type) {+ case 'interaction':+ return { type: 'interaction', request: v.request };+ case 'http': {+ if (typeof v.method !== 'string' || !/^[A-Z]{3,7}$/.test(v.method)) invalid();+ if (typeof v.path !== 'string' || !v.path.startsWith('/') || v.path.length > MAX_PATH || /[\s\0]/.test(v.path)) invalid();+ return {+ type: 'http',+ method: v.method,+ path: v.path,+ headers: headerList(v.headers),+ ...(v.body !== undefined ? { body: base64(v.body, REMOTE_AGENT_MAX_PAYLOAD_BYTES) } : {}),+ };+ }+ case 'callback':+ return {+ type: 'callback',+ name: oneOf(v.name, REMOTE_AGENT_CALLBACKS),+ args: Array.isArray(v.args) ? v.args : [],+ };+ default:+ invalid();+ }+}++/**+ * 控制端解析事件流的一行。不认识的行类型返回 null(新版被控端可能新增类型,旧控制端跳过),+ * 已知类型但字段不合法时抛 `REMOTE_AGENT_INVALID`。+ */+export function parseRemoteAgentStreamItem(line: string): RemoteAgentStreamItem | null {+ let parsed: unknown;+ try {+ parsed = JSON.parse(line);+ } catch {+ invalid();+ }+ const v = record(parsed);+ switch (v.t) {+ case 'started':+ return { t: 'started', handle: record(v.handle) };+ case 'start-failed':+ return { t: 'start-failed', error: errorInfo(v.error) };+ case 'event':+ return { t: 'event', event: v.event };+ case 'state':+ return { t: 'state', state: record(v.state) };+ case 'result':+ return v.ok === true+ ? { t: 'result', callId: id(v.callId), ok: true, ...(v.value !== undefined ? { value: v.value } : {}) }+ : { t: 'result', callId: id(v.callId), ok: false, error: errorInfo(v.error) };+ case 'request':+ return { t: 'request', requestId: id(v.requestId), request: reverseRequest(v.request) };+ case 'cancel':+ return { t: 'cancel', requestId: id(v.requestId) };+ case 'ws': {+ if (typeof v.connId !== 'string' || !CONN_ID.test(v.connId)) invalid();+ const kind = oneOf(v.kind, ['open', 'message', 'close'] as const);+ return {+ t: 'ws',+ connId: v.connId,+ kind,+ ...(typeof v.path === 'string' && v.path.length <= MAX_PATH ? { path: v.path } : {}),+ ...(typeof v.data === 'string' ? { data: v.data } : {}),+ };+ }+ case 'closed':+ return {+ t: 'closed',+ reason: typeof v.reason === 'string' ? v.reason.slice(0, 128) : 'unknown',+ ...(v.error !== undefined ? { error: errorInfo(v.error) } : {}),+ };+ default:+ return null;+ }+}++/** 被控端校验控制端对反向请求的回复。 */+export function parseRemoteAgentReply(value: unknown): RemoteAgentReply {+ const v = record(value);+ switch (v.type) {+ case 'interaction':+ return { type: 'interaction', result: v.result };+ case 'http': {+ const status = count(v.status, 599);+ if (status < 100) invalid();+ return {+ type: 'http',+ status,+ headers: headerList(v.headers),+ ...(v.body !== undefined ? { body: base64(v.body, REMOTE_AGENT_MAX_PAYLOAD_BYTES) } : {}),+ };+ }+ case 'callback':+ return { type: 'callback', ...(v.value !== undefined ? { value: v.value } : {}) };+ case 'error':+ return { type: 'error', error: errorInfo(v.error) };+ default:+ invalid();+ }+}++/** 从 `[CODE] message` 形式的 IPC 错误里取出远程 Agent 错误码。 */+export function remoteAgentErrorCode(message: string | undefined): RemoteAgentErrorCode | null {+ const code = /\[(REMOTE_AGENT_[A-Z_]+)\]/.exec(message ?? '')?.[1];+ return code && (REMOTE_AGENT_ERROR_CODES as readonly string[]).includes(code)+ ? (code as RemoteAgentErrorCode)+ : null;+}diff --git a/packages/lizi-mcps/src/__tests__/listAvailableModelsTool.test.ts b/packages/lizi-mcps/src/__tests__/listAvailableModelsTool.test.tsindex 23368e28ad..2fa6bc6305 100644--- a/packages/lizi-mcps/src/__tests__/listAvailableModelsTool.test.ts+++ b/packages/lizi-mcps/src/__tests__/listAvailableModelsTool.test.ts@@ -33,5 +33,30 @@ describe('list_available_models tool', () => {providers: [{ provider_id: 'xd', provider_name: 'XD Gateway' }],default_provider_id: 'xd',}]);+ // 没有调用方任务时参数与原来完全一致。+ expect(listAvailableModels).toHaveBeenCalledWith({ agent: 'codex' });+ });++ it('passes the calling task so a task whose agent runs on another computer lists that computer', async () => {+ const listAvailableModels = vi.fn(async () => ({ ok: true as const, codex: [] }));+ const registry = new XdtHelperToolRegistry();+ registerListAvailableModelsTool(registry, {+ getSessionContext: () => ({ sessionId: 'lead-1' }),+ listAvailableModels,+ });++ await registry.call('list_available_models', { agent: 'codex' });++ expect(listAvailableModels).toHaveBeenCalledWith({ agent: 'codex', callerSessionId: 'lead-1' });+ });++ it('omits the caller when the MCP context has no task', async () => {+ const listAvailableModels = vi.fn(async () => ({ ok: true as const }));+ const registry = new XdtHelperToolRegistry();+ registerListAvailableModelsTool(registry, { getSessionContext: () => ({}), listAvailableModels });++ await registry.call('list_available_models', {});++ expect(listAvailableModels).toHaveBeenCalledWith({ agent: undefined });});});diff --git a/packages/lizi-mcps/src/orca/server.ts b/packages/lizi-mcps/src/orca/server.tsindex 5e68f94b5d..de8261d9b7 100644--- a/packages/lizi-mcps/src/orca/server.ts+++ b/packages/lizi-mcps/src/orca/server.ts@@ -214,7 +214,7 @@ export interface OrcaMcpDeps {ControlResult<{ workerId: string }, 'WORKER_NOT_FOUND'>>;/** 列出 agent 可用 model 清单。 */- listAvailableModels: (params: { agent?: ControlWorkerAgent }) => Promise<+ listAvailableModels: (params: { agent?: ControlWorkerAgent; callerSessionId?: string }) => Promise<ControlResult<{codex?: ModelDescriptor[];claude_code?: ModelDescriptor[];@@ -495,6 +495,7 @@ export function createOrcaMcpServer(archiveWorker: deps.archiveWorker,});registerListAvailableModelsTool(sink, {+ getSessionContext,listAvailableModels: deps.listAvailableModels,});registerOrcaDiagnosticTools(sink, deps, getSessionContext);diff --git a/packages/lizi-mcps/src/xdt-helper/list_available_models.ts b/packages/lizi-mcps/src/xdt-helper/list_available_models.tsindex 9261a263c4..06157dddcf 100644--- a/packages/lizi-mcps/src/xdt-helper/list_available_models.ts+++ b/packages/lizi-mcps/src/xdt-helper/list_available_models.ts@@ -60,8 +60,11 @@ function tagTier(models: ModelDescriptor[] | undefined): TaggedModel[] | undefin}export interface ListAvailableModelsDeps {+ /** 调用方任务(可选):它的 Agent 在另一台电脑运行时,按那台的模型目录列出。 */+ getSessionContext?: () => { sessionId?: string };listAvailableModels: (params: {agent?: 'claude-code' | 'codex' | 'pi';+ callerSessionId?: string;}) => Promise<ControlResult<{codex?: ModelDescriptor[];claude_code?: ModelDescriptor[];@@ -107,7 +110,8 @@ export function registerListAvailableModelsTool(.describe('可选, 只查某一 agent 的 model 列表; 不传返三者'),},handler: async ({ agent }) => {- const result = await deps.listAvailableModels({ agent });+ const callerSessionId = deps.getSessionContext?.().sessionId;+ const result = await deps.listAvailableModels({ agent, ...(callerSessionId ? { callerSessionId } : {}) });if (!result.ok) {if (result.errorCode === 'HOST_NOT_READY') {return errorPayload('HOST_NOT_READY', `${BRAND_NAME} 主进程协同服务尚未就绪。`);diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.tsindex 29e9aff1ce..33731c6e96 100644--- a/packages/maker-core/src/agents/base-agent.ts+++ b/packages/maker-core/src/agents/base-agent.ts@@ -330,6 +330,8 @@ export class PiNativeProviderProxyNotReadyError extends Error {* sessionId 缺省 → host 不注册、URL 不带 query(匿名会话走无 ctx 兜底,行为同改动前)。*/export interface PiExtraSpawnConfigContext {+ /** 使用这些工具的 Agent(缺省 pi)。Agent 在另一台电脑上运行的任务也借这套桥身份。 */+ agentKind?: AgentKind;sessionId?: string;/** 当前 Maker Session 实例代号;用于阻断旧 bridge 请求借用新实例权限。 */sessionInstanceId?: string;@@ -1730,6 +1732,32 @@ export class TurnDispatchRejectedError extends Error {}}+/** 设备托管会话的描述(见 StartSessionOptions.deviceHosted)。 */+export interface DeviceHostedSession {+ /** 任务所在电脑上的真实工作目录:模型看到的、工具使用的都是这个路径。 */+ workingDir: string;+ extraDirs: string[];+ writableDirs: string[];+ /** 任务所在电脑的平台与 shell(写进给模型的环境说明)。 */+ platform: NodeJS.Platform;+ shell: string;+ osVersion?: string;+ homeDir?: string;+ isGitRepo: boolean;+ /** 本机 loopback 隧道:Agent 经它访问任务所在电脑的执行器与 Cindy 工具。 */+ tunnelUrl: string;+ tunnelToken: string;+ /** 经隧道可用的 Cindy MCP 服务名(`<tunnelUrl>/mcp/<name>`)。 */+ mcpServers: string[];+ /**+ * 本机影子目录按任务所在电脑的真实路径逐级镜像时的镜像根:其下每一级目录都对应那台电脑上的+ * 同一级目录(上级目录里的项目说明放在对应位置,Agent 照常向上加载)。+ */+ mirrorRoot?: string;+ /** 任务所在电脑上用户的个人说明(该 Agent 的用户级说明文件),写进给模型的环境说明。 */+ personalInstructions?: string;+}+export interface StartSessionOptions {/*** Business 层 session id (host 调用 maker.createSession 时传的 opts.id, 由@@ -1765,6 +1793,13 @@ export interface StartSessionOptions {* 目前仅 Codex 支持; Claude 不消费此字段 (会被忽略)。*/remoteHostId?: string;+ /**+ * 设备托管:Agent 进程在本机运行(用本机的程序、登录、供应商与网络),任务、项目文件与+ * 命令执行在同账号的另一台电脑上。workingDir 是本机的影子目录(只放同步过来的项目说明,+ * 供 Agent 照常加载);文件与命令工具、Cindy 工具全部经 tunnel 回到任务所在电脑执行。+ * 与 remoteHostId 互斥。+ */+ deviceHosted?: DeviceHostedSession;model: string;/*** 本次会话显式选择的供应商来源。maker-core 只用它推导子进程凭证形态;diff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.tsindex ff03dbc78f..77fbb0d902 100644--- a/packages/maker-core/src/agents/claude-code/index.ts+++ b/packages/maker-core/src/agents/claude-code/index.ts@@ -215,6 +215,19 @@ import {type ReviewReadGrant,} from '../shared/review-read-scope.js';+import {+ DEVICE_HOSTED_DISALLOWED_CLAUDE_TOOLS,+ DEVICE_HOSTED_EXEC_MCP_SERVER,+ deviceHostedBuiltinToolName,+ deviceHostedClaudeNote,+ deviceHostedMcpUrl,+ deviceHostedSubagentAllows,+ parseClaudeAgentToolRule,+ type DeviceHostedAgentToolRule,+} from '../shared/device-hosted.js';+import { isSensitiveCredentialPath } from '../shared/sensitive-credential-paths.js';+import { classifyShellCommand } from '../shared/auto-review.js';+type ClaudeSdkEffort = 'low' | 'medium' | 'high' | 'xhigh' | 'max';export function buildClaudeSystemPromptAppend(parts: {@@ -227,10 +240,13 @@ export function buildClaudeSystemPromptAppend(parts: {botProfileContextPrompt?: string;botUserProfilePrompt?: string;userPrompt?: string;+ /** 设备托管:项目在哪台电脑、文件与命令工具是哪些。 */+ deviceHostedNote?: string;}): string {return [parts.botProfilePrompt,MAKER_SYSTEM_PROMPT_APPEND,+ parts.deviceHostedNote,parts.makerMemoryRules,parts.contactsRules,parts.ghostRosterPrompt,@@ -1361,6 +1377,10 @@ export class ClaudeCodeAgent extends BaseAgent {if (reviewMode && opts.remoteHostId) {throw new Error('Cindy Review currently supports local Claude Code sessions only');}+ // 设备托管:Claude Code 在本机运行(本机的登录、订阅与供应商),项目、文件与命令在任务所在+ // 电脑上。自带的文件与命令工具关掉,改用经隧道回到那台电脑的 Cindy 工具(cindy_exec);+ // Cindy 自己的工具也都经隧道。opts.workingDir 是本机影子目录(只放项目说明)。+ const hosted = opts.deviceHosted && !opts.remoteHostId && !reviewMode ? opts.deviceHosted : undefined;let reviewReadGrants: Awaited<ReturnType<typeof buildReviewReadGrants>> = [];if (reviewMode) {try {@@ -1722,11 +1742,12 @@ export class ClaudeCodeAgent extends BaseAgent {// This per-session injection flag must not mutate the shared manager.if (makerMemoryEnabled && makerMemory) {try {- const store = await makerMemory.getStore(memoryScopeKey);+ // 设备托管:记忆在任务所在电脑上,只用随启动选项带来的快照,不打开本机记忆库。+ const store = hosted ? null : await makerMemory.getStore(memoryScopeKey);makerMemoryRules = opts.makerMemoryScopeKey?.startsWith('bot:')? '': MAKER_MEMORY_RULES;- makerMemoryIndex = opts.makerMemoryIndexSnapshot ?? await store.getIndex();+ makerMemoryIndex = opts.makerMemoryIndexSnapshot ?? (store ? await store.getIndex() : '');memoryFlushController = new MemoryFlushController({logger: log.child('memory-flush'),workdir: memoryScopeKey,@@ -1825,6 +1846,19 @@ export class ClaudeCodeAgent extends BaseAgent {if (currentQ === q) nonHarnessMcpServerNames = fallbackNames;};const buildMcpServers = (): Record<string, McpServerConfig> | undefined => {+ if (hosted) {+ // 设备托管:只用经隧道的服务——cindy_exec(文件与命令)+ 任务所在电脑提供的 Cindy 工具。+ const headers = { Authorization: `Bearer ${hosted.tunnelToken}` };+ const out: Record<string, McpServerConfig> = Object.create(null);+ for (const name of [DEVICE_HOSTED_EXEC_MCP_SERVER, ...hosted.mcpServers]) {+ if (Object.prototype.hasOwnProperty.call(out, name)) continue;+ out[name] = { type: 'http', url: deviceHostedMcpUrl(hosted, name), headers } as McpServerConfig;+ }+ hostMcpServerNames = new Set(Object.keys(out));+ registeredMcpServerNames = hostMcpServerNames;+ nonHarnessMcpServerNames = hostMcpServerNames;+ return { ...out };+ }const providers = mcpProviders;if (providers.length === 0) {hostMcpServerNames = new Set();@@ -1926,8 +1960,44 @@ export class ClaudeCodeAgent extends BaseAgent {.filter(Boolean).join('\n');};+ // 设备托管:子代理定义(影子目录里同步过来的项目 / 个人子代理)里的工具限制,按需读一次。+ let hostedAgentRules: Promise<Map<string, DeviceHostedAgentToolRule>> | null = null;+ const loadHostedAgentRules = (): Promise<Map<string, DeviceHostedAgentToolRule>> => {+ hostedAgentRules ??= (async () => {+ const rules = new Map<string, DeviceHostedAgentToolRule>();+ const dir = path.join(opts.workingDir, '.claude', 'agents');+ const entries = await fs.readdir(dir, { recursive: true }).catch(() => [] as string[]);+ for (const entry of entries) {+ if (typeof entry !== 'string' || !entry.endsWith('.md')) continue;+ const parsed = parseClaudeAgentToolRule(await fs.readFile(path.join(dir, entry), 'utf8').catch(() => ''));+ if (parsed) rules.set(parsed.name, parsed.rule);+ }+ return rules;+ })();+ return hostedAgentRules;+ };const turnChangeCaptureHook: HookCallback = async (input) => {if (input.hook_event_name === 'PreToolUse' && activeToolsDisabled) return denyTextOnlyTool();+ // 设备托管:改动发生在任务所在电脑上,由那边的执行器在写之前抓取。子代理的工具限制在这里+ // 按子代理定义判(顶替工具是 MCP 工具,SDK 不按名字收窄)。+ if (hosted) {+ if (input.hook_event_name === 'PreToolUse') {+ const pre = input as PreToolUseHookInput & { agent_id?: string; agent_type?: string };+ const builtin = deviceHostedBuiltinToolName(pre.tool_name);+ if (builtin && pre.agent_id && pre.agent_type+ && !deviceHostedSubagentAllows(pre.agent_type, builtin, await loadHostedAgentRules())) {+ return {+ continue: true,+ hookSpecificOutput: {+ hookEventName: 'PreToolUse' as const,+ permissionDecision: 'deny' as const,+ permissionDecisionReason: `The ${pre.agent_type} agent cannot use ${builtin}.`,+ },+ };+ }+ }+ return { continue: true };+ }const captureCwd = opts.workingDir;const captureSessionId = opts.sessionId;if (!this.deps.turnChangeCapture || !captureCwd || !captureSessionId) {@@ -2451,21 +2521,24 @@ export class ClaudeCodeAgent extends BaseAgent {|| builtinReviewAction?.kind === 'file-write';const reviewPermissionMode = mutablePermissionMode;if (reviewPermissionMode === 'auto' || (mcpApprovalPolicy === 'auto-approve' && !turnPolicyForcePrompt)) {- const workspaceRoots = [opts.workingDir, ...mutableExtraDirs, ...mutableWritableDirs].filter(+ // 设备托管:路径都在任务所在电脑上,以那台电脑的真实工作目录为准。+ const reviewWorkingDir = hosted?.workingDir ?? opts.workingDir;+ const workspaceRoots = [reviewWorkingDir, ...mutableExtraDirs, ...mutableWritableDirs].filter((d): d is string => typeof d === 'string' && d.length > 0,);- const writableRoots = [opts.workingDir, ...mutableWritableDirs].filter(+ const writableRoots = [reviewWorkingDir, ...mutableWritableDirs].filter((d): d is string => typeof d === 'string' && d.length > 0,);const action = builtinReviewAction!;- if (action.kind === 'exec' && opts.remoteHostId) {+ if (action.kind === 'exec' && (opts.remoteHostId || hosted)) {action.destructivePathResolution = 'unavailable';}if (action.kind === 'file-write') {const resolutionDirectoryGeneration = autoReviewDirectoryGeneration;// SSH paths belong to the remote filesystem. Until the remote manager can// attest a real path, never use a same-named controller path as evidence.- const [resolvedPath, resolvedWritableRoots] = opts.remoteHostId+ // 设备托管同理:路径在任务所在电脑上,本机文件系统不能作证。+ const [resolvedPath, resolvedWritableRoots] = (opts.remoteHostId || hosted)? [null, null] as const: await Promise.all([resolveClaudeFileWriteTarget(opts.workingDir, action.path),@@ -2484,7 +2557,7 @@ export class ClaudeCodeAgent extends BaseAgent {turnPolicyForcePrompt ? toolAutoReviewAction(toolName, input, undefined, action) : action,workspaceRoots,writableRoots,- opts.remoteHostId ? 'linux' : process.platform,+ hosted ? hosted.platform : opts.remoteHostId ? 'linux' : process.platform,mcpApprovalPolicy === 'auto-approve' && !turnPolicyForcePrompt,reviewPermissionMode !== 'auto',);@@ -2597,6 +2670,78 @@ export class ClaudeCodeAgent extends BaseAgent {return { behavior: 'deny', message: formatPermissionDenial(isSystemPermissionDenialReason(decision.reason) ? 'system' : 'user', decision.reason) };};+ // 设备托管:cindy_exec 工具按对应的自带工具名走同一套权限判断(确认卡、会话规则、自动审查、+ // IM 等每轮策略看到的都是 Bash / Read 等原名);本机任务里 Claude Code 自己就免确认的操作+ // (工作区内读取、静态可证只读的命令、自动接受编辑档下的工作区写入)这里同样免确认。+ const hostedPath = hosted?.platform === 'win32' ? path.win32 : path.posix;+ const hostedInside = (target: unknown, roots: readonly string[]): boolean => {+ if (!hosted || typeof target !== 'string' || !target) return false;+ const resolved = hostedPath.resolve(hosted.workingDir, target);+ if (isSensitiveCredentialPath(resolved)) return false;+ return roots.some((root) => {+ const relative = hostedPath.relative(root, resolved);+ return relative === '' || (!relative.startsWith('..') && !hostedPath.isAbsolute(relative));+ });+ };+ const hostedAutoAllowed = (builtin: string, input: Record<string, unknown>): boolean => {+ if (!hosted) return false;+ const readRoots = [hosted.workingDir, ...mutableExtraDirs, ...mutableWritableDirs];+ switch (builtin) {+ case 'Read':+ return hostedInside(input.file_path, readRoots);+ case 'BashOutput':+ case 'KillShell':+ return true;+ case 'Bash':+ return typeof input.command === 'string'+ && classifyShellCommand(input.command, readRoots, { cwd: hosted.workingDir, platform: hosted.platform }) === 'auto-approve';+ case 'Write':+ case 'Edit':+ return mutablePermissionMode === 'acceptEdits'+ && hostedInside(input.file_path, [hosted.workingDir, ...mutableWritableDirs]);+ case 'NotebookEdit':+ return mutablePermissionMode === 'acceptEdits'+ && hostedInside(input.notebook_path, [hosted.workingDir, ...mutableWritableDirs]);+ default:+ return false;+ }+ };+ const remapHostedRules = (value: unknown, from: string, to: string): unknown => {+ if (!Array.isArray(value)) return value;+ return value.map((update) => {+ if (!update || typeof update !== 'object') return update;+ const rules = (update as { rules?: unknown }).rules;+ if (!Array.isArray(rules)) return update;+ return {+ ...(update as Record<string, unknown>),+ rules: rules.map((rule) => (rule && typeof rule === 'object' && (rule as { toolName?: unknown }).toolName === from+ ? { ...(rule as Record<string, unknown>), toolName: to }+ : rule)),+ };+ });+ };+ const sdkCanUseTool: CanUseTool = !hosted ? canUseTool : async (toolName, input, options) => {+ const builtin = deviceHostedBuiltinToolName(toolName);+ if (!builtin) return canUseTool(toolName, input, options);+ const record = (input ?? {}) as Record<string, unknown>;+ if (+ mutablePermissionMode !== 'bypassPermissions'+ && !isPlanToolBlocked(builtin)+ && !forceTurnConfirmation(builtin, record)+ && hostedAutoAllowed(builtin, record)+ ) {+ return { behavior: 'allow', updatedInput: record };+ }+ const result = await canUseTool(builtin, input, {+ ...options,+ suggestions: remapHostedRules(options.suggestions, toolName, builtin) as typeof options.suggestions,+ });+ if (result.behavior === 'allow' && result.updatedPermissions) {+ result.updatedPermissions = remapHostedRules(result.updatedPermissions, builtin, toolName) as typeof result.updatedPermissions;+ }+ return result;+ };+// ── thinking display 配置(与 vendor/claude/runtime.ts:121-126 等价) ─────const thinkingOpts = opts.displayReasoning === 'summarized'? { thinking: { type: 'adaptive', display: 'summarized' } as unknown as { type: 'adaptive' } }@@ -3567,6 +3712,7 @@ export class ClaudeCodeAgent extends BaseAgent {reviewMode ? undefined : opts.botProfileContextPrompt,botUserProfilePrompt: reviewMode ? undefined : opts.botUserProfilePrompt,userPrompt: reviewMode || opts.botRuntimeProfile ? undefined : opts.userPrompt,+ ...(hosted ? { deviceHostedNote: deviceHostedClaudeNote(hosted, opts.workingDir) } : {}),});return {type: 'preset' as const,@@ -4081,7 +4227,8 @@ export class ClaudeCodeAgent extends BaseAgent {cwd: opts.workingDir,// 附加目录在 Query 创建时冻结;运行时 setter 立即收紧 Cindy 审核,后续 Query// 重建再取最新 closure。空数组省略字段,让 SDK 走默认。- ...(additionalDirectories.length > 0 ? { additionalDirectories } : {}),+ // 设备托管:附加目录在任务所在电脑上,由 cindy_exec 工具访问。+ ...(additionalDirectories.length > 0 && !hosted ? { additionalDirectories } : {}),// Bot 自有技能和已按启用状态/白名单过滤的 Cindy 托管技能,// 只通过本次 Query 的本地插件加载,不写用户共用技能目录。// 与 additionalDirectories 同理:路径是本机的,远端 cc-mgr 分支不透传。@@ -4121,6 +4268,7 @@ export class ClaudeCodeAgent extends BaseAgent {reviewMode ? undefined : opts.botProfileContextPrompt,botUserProfilePrompt: reviewMode ? undefined : opts.botUserProfilePrompt,userPrompt: reviewMode || opts.botRuntimeProfile ? undefined : opts.userPrompt,+ ...(hosted ? { deviceHostedNote: deviceHostedClaudeNote(hosted, opts.workingDir) } : {}),});return {type: 'preset' as const,@@ -4130,7 +4278,8 @@ export class ClaudeCodeAgent extends BaseAgent {})(),...(resumeSdkSid ? { resume: resumeSdkSid } : {}),...(newSdkSessionId ? { sessionId: newSdkSessionId } : {}),- enableFileCheckpointing,+ // 设备托管:文件改在任务所在电脑上,Claude Code 的文件检查点看不到。+ enableFileCheckpointing: enableFileCheckpointing && !hosted,...(finalResumeAt ? { resumeSessionAt: finalResumeAt } : {}),...(finalFork ? { forkSession: true } : {}),env,@@ -4174,12 +4323,17 @@ export class ClaudeCodeAgent extends BaseAgent {// 第一方只读工具由 host 精确列名, 直接走 SDK public allowlist, 避免// permissionMode=auto 时再调用远程安全分类器。动态聚合入口不在列表中。...(claudeAllowedTools ? { allowedTools: [...claudeAllowedTools] } : {}),- canUseTool,+ canUseTool: sdkCanUseTool,// Bot MCP selection is explicit; native delegation remains available.- ...(opts.botRuntimeProfile ? { strictMcpConfig: true } : {}),+ // 设备托管:只用经隧道的 MCP(本机用户 / 项目里的 MCP 启动命令会在本机执行)。+ ...(opts.botRuntimeProfile || hosted ? { strictMcpConfig: true } : {}),+ // 设备托管:自带文件与命令工具只能操作本机,关掉,由 cindy_exec 顶替。+ ...(hosted ? { disallowedTools: [...DEVICE_HOSTED_DISALLOWED_CLAUDE_TOOLS] } : {}),+ // 设备托管:个人配置(用户级设置、hooks)属于任务所在电脑,不加载本机用户级设置;+ // 项目级设置来自同步过来的影子目录(只保留权限规则)。settingSources: reviewMode || !!opts.botRuntimeProfile? []- : ['user', 'project', 'local'],+ : hosted ? ['project', 'local'] : ['user', 'project', 'local'],// Settings (SDK "flag settings" 层, 优先级最高 — 覆盖 user/project/local 文件层):// - showThinkingSummaries : reasoning summary 展示开关// - autoMemoryEnabled / autoDream: memory 联动 (host 通过 runtimeConfig.memoryEnabled 或diff --git a/packages/maker-core/src/agents/codex/app-server/protocol.ts b/packages/maker-core/src/agents/codex/app-server/protocol.tsindex f2f091a220..885bfe09b9 100644--- a/packages/maker-core/src/agents/codex/app-server/protocol.ts+++ b/packages/maker-core/src/agents/codex/app-server/protocol.ts@@ -1238,6 +1238,8 @@ export const Method = {// Memory (实验性, experimentalApi 必须 true 才能用):// app-server/README.md:202-203 + 155ConfigRead: 'config/read',+ /** EXPERIMENTAL. Register a remote exec-server as a named environment. */+ EnvironmentAdd: 'environment/add',ExperimentalFeatureEnablementSet: 'experimentalFeature/enablement/set',MemoryReset: 'memory/reset',// ServerRequest (Phase 2 + permissions):diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.tsindex f165ff6b2e..7fa91028e3 100644--- a/packages/maker-core/src/agents/codex/index.ts+++ b/packages/maker-core/src/agents/codex/index.ts@@ -20,6 +20,7 @@* - renderer 不感知 thread_id / app-server 任何概念*/+import { deviceHostedEnvironmentNote } from '../shared/device-hosted.js';import { LIBRARY_READ_ROOT, withLibraryNativeReadContext } from '../shared/library-native-read.js';import os from 'node:os';import path from 'node:path';@@ -3555,6 +3556,11 @@ assertRouteCurrent();const sid = opts.sessionId ?? '';const log = this.deps.logger.child(sid ? `s:${sid}/codex` : 'codex');const reviewMode = opts.reviewMode === true;+ // 设备托管:Codex 在本机运行(本机的登录与供应商),项目、文件与命令在任务所在电脑上。+ // 那台电脑经隧道提供 Codex 原生的 exec-server 环境,命令、读写与补丁都在那里执行;+ // Cindy 工具也经隧道。opts.workingDir 是本机影子目录。+ const hosted = opts.deviceHosted && !opts.remoteHostId && !reviewMode ? opts.deviceHosted : undefined;+ const hostedEnvironmentId = hosted ? `cindy-device-${randomUUID()}` : undefined;const botSkillGrants = !opts.remoteHostId && !reviewMode? snapshotManagedSkillGrants(opts.botRuntimeProfile?.skillPolicy) : undefined;let refreshedBotSkillConfig: Record<string, unknown> | undefined;@@ -3602,11 +3608,12 @@ assertRouteCurrent();// This per-session injection flag must not mutate the shared manager.if (makerMemoryEnabled && makerMemory) {try {- const store = await makerMemory.getStore(memoryScopeKey);+ // 设备托管:记忆在任务所在电脑上,只用随启动选项带来的快照,不打开本机记忆库。+ const store = hosted ? null : await makerMemory.getStore(memoryScopeKey);makerMemoryRules = opts.makerMemoryScopeKey?.startsWith('bot:')? '': MAKER_MEMORY_RULES;- makerMemoryIndex = opts.makerMemoryIndexSnapshot ?? await store.getIndex();+ makerMemoryIndex = opts.makerMemoryIndexSnapshot ?? (store ? await store.getIndex() : '');memoryFlushController = new MemoryFlushController({logger: log.child('memory-flush'),workdir: memoryScopeKey,@@ -5370,7 +5377,23 @@ assertRouteCurrent(););}}+ // 设备托管:本机 MCP 一律停用,只用任务所在电脑经隧道提供的 Cindy 工具(令牌放在隧道路径里,+ // 本机 MCP 的 bearer 令牌对隧道无效)。+ let hostedLocalMcpNames: string[] = [];+ const readHostedMcpConfig = (): Record<string, unknown> => {+ const out: Record<string, unknown> = {};+ for (const name of hostedLocalMcpNames) {+ if (!hosted!.mcpServers.includes(name)) out[`mcp_servers.${name}.enabled`] = false;+ }+ const base = `${hosted!.tunnelUrl.replace(/\/+$/, '')}/t/${encodeURIComponent(hosted!.tunnelToken)}/mcp/`;+ for (const name of hosted!.mcpServers) {+ out[`mcp_servers.${name}.url`] = `${base}${encodeURIComponent(name)}`;+ out[`mcp_servers.${name}.enabled`] = true;+ }+ return out;+ };const readSessionMcpConfig = (): Record<string, unknown> => {+ if (hosted) return readHostedMcpConfig();const config = host.getSessionMcpConfig(opts.sessionInstanceId, { vendorOptions: vo });if (opts.remoteHostId && opts.botRuntimeProfile?.mcpPolicy&& typeof config['mcp_servers.cindy_helper.url'] !== 'string') {@@ -5525,17 +5548,18 @@ assertRouteCurrent();const codexExtraWritableRoots = reviewMode || !sessionCodexHome? []: [joinCodexHome('memories')];+ // 设备托管:工作区在任务所在电脑上,根目录用那台电脑的真实路径(随 exec-server 环境下发)。const runtimeWorkspaceRoots = (): string[] =>reviewMode? [opts.workingDir]- : [...new Set([opts.workingDir, ...mutableExtraDirs, ...mutableWritableDirs])];+ : [...new Set([hosted?.workingDir ?? opts.workingDir, ...mutableExtraDirs, ...mutableWritableDirs])];const runtimeWritableRoots = (): string[] =>- reviewMode ? [] : [...new Set([opts.workingDir, ...mutableWritableDirs])];+ reviewMode ? [] : [...new Set([hosted?.workingDir ?? opts.workingDir, ...mutableWritableDirs])];// Auto-review 传给 core 的会话平台(决定是否抹平 macOS /private firmlink)。远端会话的 host// process.platform 不代表远端 OS(host 可能 macOS、远端 Linux)——远端 OS 未接入前保守传 'linux'// 关掉抹平 → fail-closed(不把远端 /private/tmp 误当 /tmp 区内)。本地用真实 process.platform。// 定义在此(startSession 作用域,opts=session)以避开 awaitApprovalDecision 内层 opts 的遮蔽。- const sessionReviewPlatform: NodeJS.Platform = opts.remoteHostId ? 'linux' : process.platform;+ const sessionReviewPlatform: NodeJS.Platform = opts.remoteHostId ? 'linux' : hosted ? hosted.platform : process.platform;const reviewAutoAction = (action: ReviewableAction, hostAutoApprove = false, hostShortcutOnly = false): Promise<AutoReviewDecision> => {const directoryGeneration = autoReviewDirectoryGeneration;const request = {@@ -6227,6 +6251,18 @@ assertRouteCurrent();let appliedContextLimit = currentContextLimit();activeTurnContextLimit = effectiveThreadContextWindow(appliedContextLimit);+ /** 设备托管:线程与每轮都选中任务所在电脑上的 exec-server 环境(工作目录与根都是那台电脑的路径)。 */+ function hostedEnvironmentParams(): { environments?: Array<Record<string, unknown>> } {+ if (!hosted || !hostedEnvironmentId) return {};+ return {+ environments: [{+ environmentId: hostedEnvironmentId,+ cwd: hosted.workingDir,+ runtimeWorkspaceRoots: runtimeWorkspaceRoots(),+ }],+ };+ }+function currentThreadWorkspaceConfig(contextLimit = currentContextLimit()): Pick<ThreadStartParams,| 'approvalPolicy'@@ -6300,7 +6336,9 @@ assertRouteCurrent();// Review disables only transport-bearing entries discovered above.// Its host omits Cindy's MCP bridge, so a bare memory override would// create an invalid transport even though the entry is disabled.+ // 设备托管:只停用本机确实配置了的 cindy_memory(没有传输配置的空条目会让 Codex 拒绝配置)。...(!reviewMode && !makerMemoryEnabled && !opts.botRuntimeProfile+ && (!hosted || hostedLocalMcpNames.includes('cindy_memory'))? { 'mcp_servers.cindy_memory.enabled': false }: {}),// Configure the native window and its 90% compaction budget together.@@ -6318,11 +6356,13 @@ assertRouteCurrent();const shared = {approvalPolicy,...(approvalsReviewer ? { approvalsReviewer } : {}),- ...(readonlyReferenceDirsSupported+ // 设备托管:工作区根随 exec-server 环境下发,本机线程不设本地根。+ ...(readonlyReferenceDirsSupported && !hosted? {runtimeWorkspaceRoots: runtimeWorkspaceRoots(),}: {}),+ ...(hostedEnvironmentParams()),...(Object.keys(config).length > 0 ? { config } : {}),};if (permissionProfile) {@@ -6356,9 +6396,10 @@ assertRouteCurrent();const shared = {approvalPolicy,...(approvalsReviewer ? { approvalsReviewer } : {}),- ...(readonlyReferenceDirsSupported+ ...(readonlyReferenceDirsSupported && !hosted? { runtimeWorkspaceRoots: runtimeWorkspaceRoots() }: {}),+ ...(hostedEnvironmentParams()),};if (currentWorkspacePermissionProfile() !== undefined &&@@ -6712,9 +6753,15 @@ assertRouteCurrent();makerMemoryRules,contactsRules,ghostRosterPrompt,- runtimeSystemPrompt: opts.botRuntimeProfile- ? undefined- : this.deps.runtimeConfig.systemPrompt,+ // 本机任务逐字保持原值;设备托管时在末尾加上「项目在哪台电脑」的说明。+ runtimeSystemPrompt: hosted+ ? [+ opts.botRuntimeProfile ? undefined : this.deps.runtimeConfig.systemPrompt,+ deviceHostedEnvironmentNote(hosted, opts.workingDir),+ ].filter((part): part is string => !!part && part.trim().length > 0).join('\n\n')+ : opts.botRuntimeProfile+ ? undefined+ : this.deps.runtimeConfig.systemPrompt,makerMemoryIndex,botProfilePrompt: reviewMode ? undefined : opts.botProfilePrompt,botProfileContextPrompt: reviewMode ? undefined : opts.botProfileContextPrompt,@@ -6740,7 +6787,7 @@ assertRouteCurrent();let codexProductPromptDelivery: AgentSessionHandle['codexProductPromptDelivery'];const withMcpDiscoveryContext = <T>(run: () => Promise<T>): Promise<T> => {- if (reviewMode || !sid || !opts.sessionInstanceId || !this.deps.withCodexMcpDiscoveryContext) return run();+ if (hosted || reviewMode || !sid || !opts.sessionInstanceId || !this.deps.withCodexMcpDiscoveryContext) return run();return this.deps.withCodexMcpDiscoveryContext({sessionId: sid, sessionInstanceId: opts.sessionInstanceId,workingDir: opts.workingDir, vendorOptions: vo,@@ -6848,6 +6895,25 @@ assertRouteCurrent();settingsUpdateChain = run;return run;};+ if (hosted && hostedEnvironmentId) {+ // 设备托管:本机 MCP 名单(全部停用,只留隧道提供的),再把任务所在电脑的 exec-server 接成环境。+ try {+ const response = await host.request<{ config?: Record<string, unknown> }>(+ Method.ConfigRead, { includeLayers: false },+ { timeoutMs: CRITICAL_THREAD_RPC_TIMEOUT_MS },+ );+ hostedLocalMcpNames = Object.keys(asRecord(asRecord(response.config).mcp_servers));+ } catch (error) {+ log.warn('codex: hosted session could not list local MCP servers', { error: String(error) });+ }+ assertCurrentHost('environment/add');+ await host.request(Method.EnvironmentAdd, {+ environmentId: hostedEnvironmentId,+ execServerUrl: `${hosted.tunnelUrl.replace(/^http/, 'ws').replace(/\/+$/, '')}/ws/exec-server`,+ authBearerToken: hosted.tunnelToken,+ }, { timeoutMs: CRITICAL_THREAD_RPC_TIMEOUT_MS });+ assertCurrentHost('environment/add');+ }if (opts.resumeSessionId && isLikelyValidThreadId(opts.resumeSessionId)) {// Phase 3: thread/resume is the historical-session path. Only the exact// provider "no rollout found" response below may fall back to thread/start.diff --git a/packages/maker-core/src/agents/index.ts b/packages/maker-core/src/agents/index.tsindex 4d37854339..16527b7d5f 100644--- a/packages/maker-core/src/agents/index.ts+++ b/packages/maker-core/src/agents/index.ts@@ -121,6 +121,7 @@ export {export { toolAutoReviewAction } from './shared/auto-review-decision.js';export { AUTO_REVIEW_CONTINUATION_POLICY } from './shared/continuation-policy.js';export type { ReviewableAction } from './shared/auto-review.js';+export { classifyShellCommand } from './shared/auto-review.js';export type {ToolLoopReviewDecision,ToolLoopReviewer,diff --git a/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts b/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.tsindex d17d57741b..150485913b 100644--- a/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts@@ -1838,9 +1838,9 @@ describe('cindy-bridge extension source', () => {expect(source).toContain('const controlPlaneWrite = Boolean(');expect(source).toContain('...(controlPlaneWrite ? { controlPlaneWrite: true } : {})');expect(source).toContain('resolvedWritePath: writeTargetResolved');- expect(source).toContain(- 'resolvedWritableRoots: resolveWritableRootsForHost(permission.writableRoots)',- );+ // 设备托管会话改用任务所在电脑的真实工作目录作可写根(见 CINDY_HOSTED),其余照旧。+ expect(source).toContain('resolvedWritableRoots: CINDY_HOSTED');+ expect(source).toContain(': resolveWritableRootsForHost(permission.writableRoots)');expect(source).toContain('event.input.path = writeTargetResolved');expect(source).toContain('Cindy could not verify the real file-write target.');});diff --git a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts b/packages/maker-core/src/agents/pi/cindy-bridge-source.tsindex 4a9f164c3d..9ad21020a7 100644--- a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts+++ b/packages/maker-core/src/agents/pi/cindy-bridge-source.ts@@ -77,6 +77,28 @@ import {} from '@earendil-works/pi-coding-agent';import * as piCodingAgent from '@earendil-works/pi-coding-agent';+// 设备托管(CINDY_PI_HOSTED):Pi 在本机运行,任务、项目文件与命令在同账号另一台电脑上。+// 文件与命令工具改走本机隧道上的执行器;工具与提示里的路径都是那台电脑的真实工作目录。+type CindyHostedConfig = { url: string; token: string; cwd: string; platform: string; shell: string; mirrorRoot: string };+const CINDY_HOSTED: CindyHostedConfig | null = (() => {+ try {+ const raw = process.env.CINDY_PI_HOSTED;+ if (!raw) return null;+ const value = JSON.parse(raw);+ if (!value || typeof value.url !== 'string' || typeof value.token !== 'string' || typeof value.cwd !== 'string') return null;+ return {+ url: value.url.replace(/\/+$/, ''),+ token: value.token,+ cwd: value.cwd,+ platform: typeof value.platform === 'string' ? value.platform : '',+ shell: typeof value.shell === 'string' ? value.shell : '',+ mirrorRoot: typeof value.mirrorRoot === 'string' ? value.mirrorRoot : '',+ };+ } catch {+ return null;+ }+})();+const PERMISSION_TITLE = 'cindy:permission';const TURN_CHANGE_CAPTURE_TITLE = 'cindy:turn-change-capture';const PERMISSION_ALLOW = 'allow';@@ -120,6 +142,7 @@ const SECRET_ENV_NAMES = new Set<string>([MANAGED_RG_PATH_ENV,SUBAGENT_RUN_DIR_ENV,'PI_CODING_AGENT_DIR',+ 'CINDY_PI_HOSTED',]);try {const names = JSON.parse(process.env.CINDY_PI_SECRET_ENV_NAMES ?? '[]');@@ -3674,6 +3697,187 @@ async function nativeFastPayload(payload, model, ctx) {${PI_NATIVE_PROVIDER_ADAPTER_SOURCE}+// ─── 设备托管:执行器操作 ───────────────────────────────────────────+async function cindyHostedCall(op: string, body: unknown, signal?: AbortSignal): Promise<any> {+ if (!CINDY_HOSTED) throw new Error('Cindy hosted executor is not configured.');+ const response = await fetch(CINDY_HOSTED.url + '/exec/' + op, {+ method: 'POST',+ headers: { authorization: 'Bearer ' + CINDY_HOSTED.token, 'content-type': 'application/json' },+ body: JSON.stringify(body),+ signal,+ });+ const text = await response.text();+ let parsed: any;+ try {+ parsed = JSON.parse(text);+ } catch {+ throw new Error('The computer running this task returned an invalid response (HTTP ' + String(response.status) + ').');+ }+ if (!response.ok || (parsed && parsed.error)) {+ const error: any = new Error(parsed && parsed.error && typeof parsed.error.message === 'string'+ ? parsed.error.message+ : 'Request failed on the computer running this task (HTTP ' + String(response.status) + ').');+ if (parsed && parsed.error && typeof parsed.error.code === 'string') error.code = parsed.error.code;+ throw error;+ }+ return parsed;+}++function cindyHostedReadOps() {+ return {+ readFile: async (filePath: string) => Buffer.from((await cindyHostedCall('fs.read', { path: filePath })).data, 'base64'),+ access: async (filePath: string) => {+ await cindyHostedCall('fs.access', { path: filePath });+ },+ detectImageMimeType: async (filePath: string) => {+ const result = await cindyHostedCall('fs.mime', { path: filePath });+ return typeof result.mime === 'string' ? result.mime : null;+ },+ };+}++function cindyHostedWriteOps() {+ return {+ writeFile: async (filePath: string, content: string) => {+ await cindyHostedCall('fs.write', { path: filePath, data: Buffer.from(content, 'utf8').toString('base64') });+ },+ mkdir: async (dirPath: string) => {+ await cindyHostedCall('fs.mkdir', { path: dirPath });+ },+ };+}++function cindyHostedEditOps() {+ const read = cindyHostedReadOps();+ const write = cindyHostedWriteOps();+ return {+ readFile: read.readFile,+ writeFile: write.writeFile,+ access: async (filePath: string) => {+ await cindyHostedCall('fs.access', { path: filePath, mode: 'write' });+ },+ };+}++function cindyHostedExists(filePath: string): Promise<boolean> {+ return cindyHostedCall('fs.stat', { path: filePath }).then(() => true, () => false);+}++function cindyHostedLsOps() {+ return {+ exists: cindyHostedExists,+ stat: async (filePath: string) => {+ const info = await cindyHostedCall('fs.stat', { path: filePath });+ return {+ isDirectory: () => info.type === 'directory',+ isFile: () => info.type === 'file',+ isSymbolicLink: () => info.type === 'symlink',+ size: info.size,+ mtimeMs: info.mtimeMs,+ mtime: new Date(info.mtimeMs),+ };+ },+ readdir: async (dirPath: string) => (await cindyHostedCall('fs.readdir', { path: dirPath })).entries,+ };+}++function cindyHostedFindOps() {+ return {+ exists: cindyHostedExists,+ glob: async (pattern: string, cwd: string, options: { limit: number }) =>+ (await cindyHostedCall('fs.glob', { pattern, cwd, limit: options && options.limit ? options.limit : 1000 })).paths,+ };+}++function cindyHostedBashOps() {+ return {+ exec: async (command: string, cwd: string, options: { onData: (data: Buffer) => void; signal?: AbortSignal; timeout?: number }) => {+ if (options.signal && options.signal.aborted) throw new Error('aborted');+ let result: any;+ try {+ result = await cindyHostedCall('exec.run', { command, cwd, timeout: options.timeout }, options.signal);+ } catch (error) {+ if (options.signal && options.signal.aborted) throw new Error('aborted');+ throw error;+ }+ if (typeof result.output === 'string' && result.output.length > 0) options.onData(Buffer.from(result.output, 'base64'));+ if (result.aborted) throw new Error('aborted');+ if (result.timedOut) throw new Error('timeout:' + String(options.timeout));+ return { exitCode: typeof result.exitCode === 'number' ? result.exitCode : null };+ },+ };+}++async function cindyHostedGrep(params: unknown, signal?: AbortSignal) {+ const result = await cindyHostedCall('pi.grep', { params }, signal);+ return {+ content: [{ type: 'text', text: typeof result.text === 'string' ? result.text : '' }],+ details: result.details,+ };+}++/**+ * 托管时用执行器操作重新注册文件、命令与搜索工具(同一扩展内后注册的同名工具生效),+ * 参数说明沿用本机同名工具;并把系统提示里的本机影子目录换成任务所在电脑的真实目录。+ */+function registerCindyHostedTools(+ pi: any,+ localBash: any,+ applyBashTimeout: (params: unknown) => Record<string, unknown>,+): void {+ if (!CINDY_HOSTED) return;+ const cwd = CINDY_HOSTED.cwd;+ // 用工具定义(带提示片段)注册,系统提示里的工具清单与本机任务一致;旧版 Pi 没有定义工厂时退回工具工厂。+ const agentApi: any = piCodingAgent;+ // 只在托管时从命名空间取,本机任务加载的导入与原来完全一致。+ const readFactory = typeof agentApi.createReadToolDefinition === 'function' ? agentApi.createReadToolDefinition : agentApi.createReadTool;+ const writeFactory = typeof agentApi.createWriteToolDefinition === 'function' ? agentApi.createWriteToolDefinition : agentApi.createWriteTool;+ const editFactory = typeof agentApi.createEditToolDefinition === 'function' ? agentApi.createEditToolDefinition : agentApi.createEditTool;+ pi.registerTool(readFactory(cwd, { operations: cindyHostedReadOps() }));+ pi.registerTool(writeFactory(cwd, { operations: cindyHostedWriteOps() }));+ pi.registerTool(editFactory(cwd, { operations: cindyHostedEditOps() }));+ const grepTool = createGrepTool(cwd);+ pi.registerTool({+ ...grepTool,+ execute: async (_id: string, params: unknown, signal: AbortSignal) => cindyHostedGrep(params, signal),+ });+ pi.registerTool(createFindTool(cwd, { operations: cindyHostedFindOps() } as any));+ pi.registerTool(createLsTool(cwd, { operations: cindyHostedLsOps() } as any));+ const bashTool = createBashTool(cwd, { operations: cindyHostedBashOps() } as any);+ pi.registerTool({+ ...bashTool,+ parameters: localBash && localBash.parameters ? localBash.parameters : bashTool.parameters,+ description: localBash && typeof localBash.description === 'string' ? localBash.description : bashTool.description,+ execute: async (id: string, params: unknown, signal: AbortSignal, onUpdate: unknown) =>+ bashTool.execute(id, applyBashTimeout(params) as any, signal, onUpdate as any),+ });+ pi.on('before_agent_start', async (event: any) => {+ const hosted = CINDY_HOSTED!;+ const prompt = typeof event.systemPrompt === 'string' ? event.systemPrompt : '';+ // 影子目录里的项目说明就是那台电脑上同一目录的副本,提示里一律换成真实目录。影子目录按真实+ // 路径逐级镜像,上级目录(放着上级目录的说明文件)也逐级换回真实路径;先换最深的一级。+ let replaced = prompt;+ let shadow = process.cwd();+ let real = hosted.cwd;+ const realPath = hosted.platform === 'win32' ? path.win32 : path.posix;+ for (let level = 0; level < 32; level += 1) {+ replaced = replaced.split(shadow).join(real);+ const nextShadow = path.dirname(shadow);+ const nextReal = realPath.dirname(real);+ if (!hosted.mirrorRoot || nextShadow === shadow || nextReal === real) break;+ if (!nextShadow.startsWith(hosted.mirrorRoot + path.sep)) break;+ shadow = nextShadow;+ real = nextReal;+ }+ const note = [+ '',+ '# Where this task runs',+ 'The project lives on the user\'s computer at ' + hosted.cwd + ' (' + hosted.platform + ', shell: ' + hosted.shell + '). Every file and shell tool operates on that computer.',+ ].join('\n');+ return { systemPrompt: replaced + '\n' + note };+ });+}+export default async function cindyBridge(pi: any) {installTextOnlyTurnPolicy(pi);const nativeProviderAdapters = await registerCindyNativeProviderAdapters(pi);@@ -4048,6 +4252,9 @@ export default async function cindyBridge(pi: any) {},});+ // 设备托管:文件、命令与搜索工具改用任务所在电脑上的执行器(替换上面的本机注册)。+ registerCindyHostedTools(pi, bashTool, applyCindyBashTimeoutParams);+// ── 权限门 ────────────────────────────────────────────────────────────────pi.on('tool_call', async (event: any, ctx: any) => {if (toolsDisabledForTurn()) {@@ -4102,7 +4309,11 @@ export default async function cindyBridge(pi: any) {// 漏掉 **symlink 父目录**(agentHome/link/perm.json, link -> /outside)。修:// 目标存在 → realpath 目标;目标不存在 → realpath 最近的**存在的父目录**,// 用真实父目录判定(父目录链上的 symlink 一并解析)。- const writeTargetResolved = resolveFileWriteTargetPath(targetPath);+ // 设备托管:目标在任务所在电脑上,本机文件系统无从解析,按真实工作目录词法解析+ // (那台电脑的执行器会按真实路径再守一道凭证与高危上限)。+ const writeTargetResolved = CINDY_HOSTED+ ? (targetPath ? path.resolve(CINDY_HOSTED.cwd, targetPath) : null)+ : resolveFileWriteTargetPath(targetPath);if (targetPath&& FILE_WRITE_BUILTINS.has(event.toolName)@@ -4209,7 +4420,9 @@ export default async function cindyBridge(pi: any) {...(FILE_WRITE_BUILTINS.has(event.toolName)? {resolvedWritePath: writeTargetResolved,- resolvedWritableRoots: resolveWritableRootsForHost(permission.writableRoots),+ resolvedWritableRoots: CINDY_HOSTED+ ? [...new Set([CINDY_HOSTED.cwd, ...permission.writableRoots])]+ : resolveWritableRootsForHost(permission.writableRoots),...(controlPlaneWrite ? { controlPlaneWrite: true } : {}),}: {}),diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.tsindex 39e76de27a..0d68168eee 100644--- a/packages/maker-core/src/agents/pi/index.ts+++ b/packages/maker-core/src/agents/pi/index.ts@@ -213,6 +213,7 @@ import {} from './project-resource-assembly.js';import { applyPiBotSkillPolicy } from './bot-skill-policy.js';import { resolveAllowedManagedSkills, snapshotManagedSkillGrants } from '../shared/managed-skill-policy.js';+import { DEVICE_HOSTED_PI_ENV, deviceHostedPiEnvValue, deviceHostedPiMcpBridge } from '../shared/device-hosted.js';import {assertPiSpawnArgvFitsPlatform,collectPiProjectResourceCliPaths,@@ -2528,10 +2529,12 @@ export class PiAgent extends BaseAgent {const sessionMemoryEnabled = !reviewMode&& (opts.makerMemoryEnabled ?? this.deps.runtimeConfig.makerMemoryEnabled ?? false) === true&& (botMemoryScope || (this.memoryOverride ?? true));- const compactionMemoryEnabled = sessionMemoryEnabled && !!this.deps.makerMemory;+ // 设备托管:记忆存在任务所在的电脑上(经 Cindy 工具读写),本机记忆库不参与;提示里的+ // 记忆索引只用对方随启动选项带来的快照。+ const compactionMemoryEnabled = sessionMemoryEnabled && !!this.deps.makerMemory && !opts.deviceHosted;const makerMemoryPromptEnabled =sessionMemoryEnabled &&- (opts.makerMemoryIndexSnapshot !== undefined || !!this.deps.makerMemory);+ (opts.makerMemoryIndexSnapshot !== undefined || (!!this.deps.makerMemory && !opts.deviceHosted));// Maker Memory 关闭时跳过 git 探测 (Codex #2399 P1): 解析结果不会被用。// 解析必须发生在 MCP ctx 注册之前, 并把结果冻进 ctx, 避免工具侧 60s TTL// 后再解析漂移到 raw worktree 路径 (Codex #2399 P2)。@@ -2539,6 +2542,10 @@ export class PiAgent extends BaseAgent {? (opts.makerMemoryScopeKey ?? (await resolveMemoryScopeKey(opts.workingDir, opts.remoteHostId))): (opts.makerMemoryScopeKey ?? opts.workingDir);const remote = Boolean(opts.remoteHostId);+ // 设备托管:Pi 在本机运行,文件与命令在任务所在电脑。权限判断、提示里的路径都按那台+ // 电脑的真实工作目录;opts.workingDir 只是本机影子目录(进程 cwd 与项目说明)。+ const hosted = opts.deviceHosted && !remote ? opts.deviceHosted : undefined;+ const logicalWorkingDir = hosted?.workingDir ?? opts.workingDir;const sessionPiAutoCompactPct = this.deps.runtimeConfig.piAutoCompactThresholdPct;// BYOM:host 解析当前会话可用的原生 provider(用户自定义/本地模型)+ 需注入的 env(keys)。@@ -3179,6 +3186,8 @@ export class PiAgent extends BaseAgent {const localSubagentSupported = Boolean(!reviewMode&& !remote+ // 设备托管:子代理进程继承 CINDY_PI_HOSTED 与同一份 cindy-bridge,文件与命令工具同样经+ // 隧道回到任务所在电脑(隧道随任务关闭,任务结束后仍在后台跑的子代理会失去工具)。&& this.deps.spawnPiSubagentRunner,);if (localSubagentSupported) {@@ -3521,7 +3530,12 @@ export class PiAgent extends BaseAgent {opts.remoteHostId && this.deps.remotePiSkipMcpBridge?.(opts.remoteHostId));const mcpReadyStartedAt = Date.now();let mcpReadyStatus: 'ok' | 'degraded' | 'skipped' = 'skipped';- if (!reviewMode && !remoteSkipMcpBridge && this.deps.preparePiExtraSpawnConfig) {+ if (hosted) {+ // 设备托管:Cindy 工具都在任务所在电脑上,经隧道访问;本机的 MCP 桥不参与。+ mcpBridge = deviceHostedPiMcpBridge(hosted);+ for (const server of mcpBridge.servers) registeredMcpServerNames.add(server.name);+ mcpReadyStatus = 'ok';+ } else if (!reviewMode && !remoteSkipMcpBridge && this.deps.preparePiExtraSpawnConfig) {try {const extra = await this.deps.preparePiExtraSpawnConfig(// The Desktop bridge is generation-cached, so it must be built from the@@ -4064,8 +4078,9 @@ export class PiAgent extends BaseAgent {precedingBlockedActions: autoReviewActionContext.precedingBlockedActions,...(currentAutoReviewAuthority ? { authorizationContext: currentAutoReviewAuthority } : {}),action,- workspaceRoots: [opts.workingDir, ...mutableExtraDirs, ...mutableWritableDirs],- writableRoots: [opts.workingDir, ...mutableWritableDirs],+ // 设备托管:路径在任务所在电脑上,以那台电脑的真实工作目录为准。+ workspaceRoots: [opts.deviceHosted?.workingDir ?? opts.workingDir, ...mutableExtraDirs, ...mutableWritableDirs],+ writableRoots: [opts.deviceHosted?.workingDir ?? opts.workingDir, ...mutableWritableDirs],platform: opts.remoteHostId ? ('linux' as const) : process.platform,};let cacheKey: string | undefined;@@ -4643,9 +4658,9 @@ export class PiAgent extends BaseAgent {normalizePiToolForAutoReview({toolName,input,- workspaceRoots: [opts.workingDir],- readRoots: [opts.workingDir, ...mutableExtraDirs, ...mutableWritableDirs],- writableRoots: [opts.workingDir, ...mutableWritableDirs],+ workspaceRoots: [logicalWorkingDir],+ readRoots: [logicalWorkingDir, ...mutableExtraDirs, ...mutableWritableDirs],+ writableRoots: [logicalWorkingDir, ...mutableWritableDirs],}),Boolean(opts.remoteHostId),);@@ -5246,6 +5261,7 @@ export class PiAgent extends BaseAgent {...Object.keys(nativeEnv),...Object.keys(mcpEnv),...(mcpBridge && mcpBridge.servers.length > 0 ? [PI_MCP_BRIDGE_ENV] : []),+ ...(hosted ? [DEVICE_HOSTED_PI_ENV] : []),// 子代理路由快照:虽然不是凭证,但它是**控制面** —— 一次获批的 bash 拿到路径就能改写// provider/model,让后续每次委派都打到攻击者选定的 endpoint(提示词与代码随之外泄)。// 与 CINDY_PI_PERMISSION_FILE 同一类:靠改写受信文件给后续调用永久换向(review)。@@ -5292,6 +5308,7 @@ export class PiAgent extends BaseAgent {PI_CODING_AGENT_DIR: configHome,[PI_BASH_PACKAGE_HOME_ENV]: bashPackageHome,CINDY_PI_PERMISSION_FILE: permissionFile,+ ...(hosted ? { [DEVICE_HOSTED_PI_ENV]: deviceHostedPiEnvValue(hosted) } : {}),...(fastModels.length > 0 ? { CINDY_PI_FAST_MODELS: JSON.stringify(fastModels) } : {}),CINDY_PI_TURN_TOOL_POLICY: remote ? '' : runtimeInstanceId,...(allowPiPackageManagement ? { [PI_PACKAGE_MANAGEMENT_ENV]: piPackageManagementToken } : {}),@@ -5419,9 +5436,9 @@ export class PiAgent extends BaseAgent {currentModelIds: [mutableModel, mutableWireModel],readNativeFast: (provider, model) => !requestPrefsClosed && nativeFastEnabled &&fastModels.some(candidate => candidate.provider === provider && candidate.id === model),- workspaceRoots: [opts.workingDir],- readRoots: [opts.workingDir, ...mutableExtraDirs, ...mutableWritableDirs],- writableRoots: [opts.workingDir, ...mutableWritableDirs],+ workspaceRoots: [logicalWorkingDir],+ readRoots: [logicalWorkingDir, ...mutableExtraDirs, ...mutableWritableDirs],+ writableRoots: [logicalWorkingDir, ...mutableWritableDirs],reviewAutoAction,recordUserClarification: (question, answer) => setAutoReviewIntent(composeAutoReviewIntentWithClarification(currentAutoReviewIntent, [{ question, answer }])),notifyAutoReviewUnavailable: () => autoReviewUnavailableNotice.notify(),@@ -5434,6 +5451,7 @@ export class PiAgent extends BaseAgent {sessionId: opts.sessionId ?? '',workingDir: opts.workingDir ?? '',remote: Boolean(opts.remoteHostId),+ deviceHosted: Boolean(hosted),allowPiPackageManagement,piPackageManagementToken,controlSubagentRunner: async (action, runId) => {@@ -8162,6 +8180,8 @@ export class PiAgent extends BaseAgent {sessionId: string;workingDir: string;remote: boolean;+ /** 设备托管会话:文件改动由任务所在电脑的执行器抓取。 */+ deviceHosted?: boolean;allowPiPackageManagement: boolean;piPackageManagementToken?: string;controlSubagentRunner: (@@ -8515,7 +8535,8 @@ export class PiAgent extends BaseAgent {}const context = getPermissionCtx();void (async () => {- if (!context.sessionId || !context.workingDir) return;+ // 设备托管:改动在任务所在电脑上由执行器抓取,本机不抓影子目录。+ if (!context.sessionId || !context.workingDir || context.deviceHosted) return;const targetPath = typeof input.path === 'string' ? input.path : null;if (targetPath && (toolName === 'edit' || toolName === 'write')) {await this.deps.turnChangeCapture?.beforeKnownFileWrite({diff --git a/packages/maker-core/src/agents/shared/device-hosted.test.ts b/packages/maker-core/src/agents/shared/device-hosted.test.tsnew file mode 100644index 0000000000..609a8ed502--- /dev/null+++ b/packages/maker-core/src/agents/shared/device-hosted.test.ts@@ -0,0 +1,130 @@+import { describe, expect, it } from 'vitest';++import type { DeviceHostedSession } from '../base-agent.js';+import {+ deviceHostedEnvironmentNote,+ deviceHostedPiEnvValue,+ deviceHostedSubagentAllows,+ parseClaudeAgentToolRule,+ type DeviceHostedAgentToolRule,+} from './device-hosted.js';++function hosted(overrides: Partial<DeviceHostedSession> = {}): DeviceHostedSession {+ return {+ tunnelUrl: 'http://127.0.0.1:4000/t/tok/',+ tunnelToken: 'tok',+ workingDir: '/Users/me/project',+ platform: 'darwin',+ shell: 'zsh',+ extraDirs: [],+ writableDirs: [],+ isGitRepo: true,+ mcpServers: [],+ ...overrides,+ };+}++describe('deviceHostedPiEnvValue', () => {+ it('omits the mirror root when the shadow is not mirrored', () => {+ expect(JSON.parse(deviceHostedPiEnvValue(hosted()))).not.toHaveProperty('mirrorRoot');+ });++ it('carries the mirror root so the bridge can map shadow ancestors back', () => {+ expect(JSON.parse(deviceHostedPiEnvValue(hosted({ mirrorRoot: '/runs/ws/abc/s1/fs' }))).mirrorRoot)+ .toBe('/runs/ws/abc/s1/fs');+ });+});++describe('deviceHostedEnvironmentNote', () => {+ it('has no personal section without personal instructions', () => {+ expect(deviceHostedEnvironmentNote(hosted(), '/shadow')).not.toContain('personal instructions');+ expect(deviceHostedEnvironmentNote(hosted({ personalInstructions: ' \n ' }), '/shadow'))+ .not.toContain('personal instructions');+ });++ it("appends the user's personal instructions from their computer", () => {+ const note = deviceHostedEnvironmentNote(hosted({ personalInstructions: ' Always answer in Chinese.\n' }), '/shadow');+ expect(note).toContain("# The user's personal instructions (from their computer)\nAlways answer in Chinese.");+ expect(note.indexOf('Is a git repository')).toBeLessThan(note.indexOf('personal instructions'));+ });+});++describe('parseClaudeAgentToolRule', () => {+ it('reads name, tools and disallowedTools from frontmatter', () => {+ expect(parseClaudeAgentToolRule([+ '---',+ 'name: reviewer',+ 'description: Reviews code',+ 'tools: Read, Grep, Bash(git diff:*)',+ 'disallowedTools: ["Write", \'Edit\']',+ '---',+ 'Body',+ ].join('\n'))).toEqual({+ name: 'reviewer',+ rule: { tools: ['Read', 'Grep', 'Bash(git diff:*)'], disallowedTools: ['Write', 'Edit'] },+ });+ });++ it('accepts the kebab-case key and CRLF line endings', () => {+ expect(parseClaudeAgentToolRule('---\r\nname: "docs"\r\ndisallowed-tools: Bash\r\n---\r\n'))+ .toEqual({ name: 'docs', rule: { disallowedTools: ['Bash'] } });+ });++ it('returns no rule when the agent inherits every tool', () => {+ expect(parseClaudeAgentToolRule('---\nname: helper\n---\n')).toEqual({ name: 'helper', rule: {} });+ });++ it('ignores files without frontmatter or a name', () => {+ expect(parseClaudeAgentToolRule('# Just markdown')).toBeNull();+ expect(parseClaudeAgentToolRule('---\ntools: Read\n---\n')).toBeNull();+ });+});++describe('deviceHostedSubagentAllows', () => {+ const none = new Map<string, DeviceHostedAgentToolRule>();++ it('keeps the built-in read-only agents read-only', () => {+ for (const agent of ['Explore', 'Plan']) {+ expect(deviceHostedSubagentAllows(agent, 'Write', none)).toBe(false);+ expect(deviceHostedSubagentAllows(agent, 'Edit', none)).toBe(false);+ expect(deviceHostedSubagentAllows(agent, 'NotebookEdit', none)).toBe(false);+ expect(deviceHostedSubagentAllows(agent, 'Read', none)).toBe(true);+ expect(deviceHostedSubagentAllows(agent, 'Bash', none)).toBe(true);+ }+ });++ it('does not restrict agents without a definition', () => {+ expect(deviceHostedSubagentAllows('general-purpose', 'Write', none)).toBe(true);+ expect(deviceHostedSubagentAllows('unknown', 'Bash', none)).toBe(true);+ });++ it('applies a custom allow list, including parameterised and prefixed entries', () => {+ const rules = new Map<string, DeviceHostedAgentToolRule>([+ ['reader', { tools: ['Read', 'Bash(git log:*)'] }],+ ['prefixed', { tools: ['mcp__cindy_exec__Edit'] }],+ ['star', { tools: ['*'] }],+ ]);+ expect(deviceHostedSubagentAllows('reader', 'Read', rules)).toBe(true);+ expect(deviceHostedSubagentAllows('reader', 'Bash', rules)).toBe(true);+ expect(deviceHostedSubagentAllows('reader', 'Write', rules)).toBe(false);+ expect(deviceHostedSubagentAllows('prefixed', 'Edit', rules)).toBe(true);+ expect(deviceHostedSubagentAllows('prefixed', 'Read', rules)).toBe(false);+ expect(deviceHostedSubagentAllows('star', 'Write', rules)).toBe(true);+ });++ it('lets background shell helpers follow Bash', () => {+ const rules = new Map<string, DeviceHostedAgentToolRule>([+ ['no-shell', { disallowedTools: ['Bash'] }],+ ['shell', { tools: ['Bash'] }],+ ]);+ expect(deviceHostedSubagentAllows('no-shell', 'BashOutput', rules)).toBe(false);+ expect(deviceHostedSubagentAllows('no-shell', 'KillShell', rules)).toBe(false);+ expect(deviceHostedSubagentAllows('shell', 'BashOutput', rules)).toBe(true);+ expect(deviceHostedSubagentAllows('shell', 'Read', rules)).toBe(false);+ });++ it('lets a custom definition override a built-in name', () => {+ const rules = new Map<string, DeviceHostedAgentToolRule>([['Plan', { tools: ['Write'] }]]);+ expect(deviceHostedSubagentAllows('Plan', 'Write', rules)).toBe(true);+ });+});diff --git a/packages/maker-core/src/agents/shared/device-hosted.ts b/packages/maker-core/src/agents/shared/device-hosted.tsnew file mode 100644index 0000000000..90dd260e15--- /dev/null+++ b/packages/maker-core/src/agents/shared/device-hosted.ts@@ -0,0 +1,145 @@+/**+ * 设备托管会话(StartSessionOptions.deviceHosted)的共用部分:Agent 在本机运行,任务、项目+ * 文件与命令在同账号另一台电脑上,工具经本机 loopback 隧道回到那台电脑执行。+ */+import type { DeviceHostedSession, PiExtraSpawnConfig } from '../base-agent.js';++/** 交给 Pi 内 cindy-bridge 的托管配置(隧道地址、令牌、真实工作目录)。 */+export const DEVICE_HOSTED_PI_ENV = 'CINDY_PI_HOSTED';++export function deviceHostedPiEnvValue(hosted: DeviceHostedSession): string {+ return JSON.stringify({+ url: hosted.tunnelUrl,+ token: hosted.tunnelToken,+ cwd: hosted.workingDir,+ platform: hosted.platform,+ shell: hosted.shell,+ ...(hosted.mirrorRoot ? { mirrorRoot: hosted.mirrorRoot } : {}),+ });+}++/** 隧道上某个 MCP 服务的地址。 */+export function deviceHostedMcpUrl(hosted: DeviceHostedSession, name: string): string {+ return `${hosted.tunnelUrl.replace(/\/+$/, '')}/mcp/${encodeURIComponent(name)}`;+}++/** Pi 的 MCP 桥配置:全部指向隧道,令牌是本任务的隧道令牌。 */+export function deviceHostedPiMcpBridge(hosted: DeviceHostedSession): NonNullable<PiExtraSpawnConfig['mcpBridge']> {+ return {+ token: hosted.tunnelToken,+ servers: hosted.mcpServers.map((name) => ({ name, url: deviceHostedMcpUrl(hosted, name) })),+ };+}++/** 设备托管时顶替 Claude Code 自带文件与命令工具的 Cindy MCP 服务名。 */+export const DEVICE_HOSTED_EXEC_MCP_SERVER = 'cindy_exec';+/** 顶替的工具名(与自带工具同名)。 */+export const DEVICE_HOSTED_EXEC_TOOL_NAMES = ['Bash', 'BashOutput', 'KillShell', 'Read', 'Write', 'Edit', 'NotebookEdit'] as const;+/** 设备托管时关掉的 Claude Code 自带工具:它们只能操作本机,项目不在这里。 */+export const DEVICE_HOSTED_DISALLOWED_CLAUDE_TOOLS = [+ 'Bash', 'BashOutput', 'KillShell', 'Read', 'Write', 'Edit', 'MultiEdit', 'NotebookEdit',+ 'Glob', 'Grep', 'LS', 'PowerShell', 'EnterWorktree', 'ExitWorktree',+] as const;++const EXEC_PREFIX = `mcp__${DEVICE_HOSTED_EXEC_MCP_SERVER}__`;++/** `mcp__cindy_exec__Bash` → `Bash`;不是顶替工具时返回 null。 */+export function deviceHostedBuiltinToolName(toolName: string): string | null {+ if (!toolName.startsWith(EXEC_PREFIX)) return null;+ const name = toolName.slice(EXEC_PREFIX.length);+ return (DEVICE_HOSTED_EXEC_TOOL_NAMES as readonly string[]).includes(name) ? name : null;+}++/** `Bash` → `mcp__cindy_exec__Bash`。 */+export function deviceHostedExecToolName(builtin: string): string {+ return `${EXEC_PREFIX}${builtin}`;+}++/**+ * 给模型的环境说明:项目在哪台电脑、哪个目录,工具在哪执行。只陈述事实,让模型使用真实路径。+ */+export function deviceHostedEnvironmentNote(hosted: DeviceHostedSession, localWorkingDir: string): string {+ const lines = [+ '# Where this task runs',+ `The project lives on the user's computer at \`${hosted.workingDir}\` (${hosted.platform}, shell: ${hosted.shell}${hosted.osVersion ? `, ${hosted.osVersion}` : ''}).`,+ `Every file and shell tool operates on that computer. Use paths under \`${hosted.workingDir}\`; relative paths resolve against it.`,+ `The local working directory \`${localWorkingDir}\` only holds a copy of the project instructions; do not use it.`,+ ];+ if (hosted.extraDirs.length || hosted.writableDirs.length) {+ lines.push(`Additional directories on that computer: ${[...new Set([...hosted.extraDirs, ...hosted.writableDirs])].map((dir) => `\`${dir}\``).join(', ')}.`);+ }+ lines.push(`Is a git repository: ${hosted.isGitRepo ? 'yes' : 'no'}.`);+ if (hosted.personalInstructions?.trim()) {+ lines.push('', "# The user's personal instructions (from their computer)", hosted.personalInstructions.trim());+ }+ return lines.join('\n');+}++/** Claude Code 版:说明文件与命令工具由 Cindy 工具顶替。 */+export function deviceHostedClaudeNote(hosted: DeviceHostedSession, localWorkingDir: string): string {+ const tools = DEVICE_HOSTED_EXEC_TOOL_NAMES.map((name) => deviceHostedExecToolName(name)).join(', ');+ return [+ deviceHostedEnvironmentNote(hosted, localWorkingDir),+ `File and shell tools are provided as ${tools}. Use them wherever these instructions mention Bash, Read, Write, Edit or NotebookEdit; search files with Bash (rg, find).`,+ ].join('\n');+}++/**+ * 子代理的工具限制(设备托管)。本机任务里 Claude Code 按子代理定义收窄自带工具;顶替成 Cindy+ * 工具后 SDK 不再按名字收窄(MCP 工具一律放行),这里按同样的定义判一次:+ * - 自带的只读子代理(Explore / Plan)不能写文件;+ * - 自定义子代理写了 tools 时只能用列出的工具,写了 disallowedTools 时不能用列出的工具。+ * 不认识的子代理不额外限制(与本机一致:没有定义就继承全部工具)。+ */+export interface DeviceHostedAgentToolRule {+ tools?: string[];+ disallowedTools?: string[];+}++const READ_ONLY_BUILTIN_AGENTS: Record<string, DeviceHostedAgentToolRule> = {+ Explore: { disallowedTools: ['Write', 'Edit', 'NotebookEdit'] },+ Plan: { disallowedTools: ['Write', 'Edit', 'NotebookEdit'] },+};++/** 子代理定义文件(Markdown + frontmatter)里的名字与工具规则;没有 frontmatter 时返回 null。 */+export function parseClaudeAgentToolRule(markdown: string): { name: string; rule: DeviceHostedAgentToolRule } | null {+ const match = /^---\r?\n([\s\S]*?)\r?\n---/.exec(markdown);+ if (!match) return null;+ const fields = new Map<string, string>();+ for (const line of match[1].split(/\r?\n/)) {+ const field = /^([A-Za-z][\w-]*)\s*:\s*(.*)$/.exec(line);+ if (field) fields.set(field[1], field[2].trim());+ }+ const name = fields.get('name')?.replace(/^["']|["']$/g, '');+ if (!name) return null;+ const list = (value: string | undefined) => value+ ?.replace(/^\[|\]$/g, '')+ .split(',')+ .map((item) => item.trim().replace(/^["']|["']$/g, ''))+ .filter(Boolean);+ const tools = list(fields.get('tools'));+ const disallowedTools = list(fields.get('disallowedTools') ?? fields.get('disallowed-tools'));+ return {+ name,+ rule: {+ ...(tools && tools.length ? { tools } : {}),+ ...(disallowedTools && disallowedTools.length ? { disallowedTools } : {}),+ },+ };+}++/** 子代理能否用某个顶替工具(自带工具名)。BashOutput / KillShell 跟随 Bash。 */+export function deviceHostedSubagentAllows(+ agentType: string,+ builtin: string,+ customRules: ReadonlyMap<string, DeviceHostedAgentToolRule>,+): boolean {+ const rule = customRules.get(agentType) ?? READ_ONLY_BUILTIN_AGENTS[agentType];+ if (!rule) return true;+ const name = builtin === 'BashOutput' || builtin === 'KillShell' ? 'Bash' : builtin;+ const matches = (entry: string) => entry === name || entry === builtin || entry === deviceHostedExecToolName(builtin)+ || entry.startsWith(`${name}(`);+ if (rule.disallowedTools?.some(matches)) return false;+ if (rule.tools && !rule.tools.some((entry) => entry === '*' || matches(entry))) return false;+ return true;+}diff --git a/packages/maker-core/src/index.ts b/packages/maker-core/src/index.tsindex eaf7ce01ef..4548161d77 100644--- a/packages/maker-core/src/index.ts+++ b/packages/maker-core/src/index.ts@@ -25,7 +25,7 @@ export {resolveReviewReadPath,type ReviewReadGrant,} from './agents/shared/review-read-scope.js';-export { isReviewSensitiveCredentialPath } from './agents/shared/sensitive-credential-paths.js';+export { isReviewSensitiveCredentialPath, isSensitiveCredentialPath } from './agents/shared/sensitive-credential-paths.js';// codex app-server transport interface — host 实现自定义 transport (e.g. SSH-bridged// for remote codex) 时需要这个接口形状。diff --git a/packages/maker-core/src/interfaces/session-storage.ts b/packages/maker-core/src/interfaces/session-storage.tsindex 292019fe77..2a594fe684 100644--- a/packages/maker-core/src/interfaces/session-storage.ts+++ b/packages/maker-core/src/interfaces/session-storage.ts@@ -31,6 +31,11 @@ export interface SessionMeta {* 仅 Codex 支持; Claude 暂忽略此字段。*/remoteHostId?: string;+ /**+ * Agent 在同账号另一台电脑上运行时,那台电脑的设备 id。任务、项目文件与命令仍在本机;+ * 恢复会话时据此重新让那台电脑启动 Agent。与 remoteHostId 互斥。+ */+ agentDeviceId?: string;}// 历史: 这里曾有 status: 'active'|'closed'|'error'。// 这是 SDK 子进程的运行时瞬态, 不该持久化 —— 它跟 desktop DB 的产品语义 statusdiff --git a/packages/maker-core/src/maker.agentDevice.test.ts b/packages/maker-core/src/maker.agentDevice.test.tsnew file mode 100644index 0000000000..664c315ee8--- /dev/null+++ b/packages/maker-core/src/maker.agentDevice.test.ts@@ -0,0 +1,155 @@+/**+ * 「Agent 在另一台电脑运行」的 Maker 路由:任务仍是本机任务(本机存储、本机 Session),+ * 只把 Agent 的启动交给 startDeviceAgentSession;那台电脑记进任务记录,恢复时回到同一台。+ */+import { describe, expect, it, vi } from 'vitest';++import { Maker } from './maker.js';+import type { AgentSessionHandle, BaseAgent } from './agents/base-agent.js';+import { NotSupportedError } from './types/capabilities.js';+import type { SessionMeta, SessionStorage } from './interfaces/session-storage.js';+import type { AgentEvent } from './types/events.js';++function storage(): SessionStorage & { rows: Map<string, SessionMeta> } {+ const rows = new Map<string, SessionMeta>();+ return {+ rows,+ async create(meta) {+ const row = { ...meta, createdAt: Date.now(), updatedAt: Date.now() };+ rows.set(row.id, row);+ return row;+ },+ async get(id) {+ return rows.get(id) ?? null;+ },+ async list() {+ return [...rows.values()];+ },+ async update(id, patch) {+ const next = { ...rows.get(id)!, ...patch, updatedAt: Date.now() };+ rows.set(id, next);+ return next;+ },+ async compareAndClearSdkSessionId() {+ return false;+ },+ async delete(id) {+ rows.delete(id);+ },+ };+}++const logger = { trace() {}, debug() {}, info() {}, warn() {}, error() {}, fatal() {}, child() { return logger; } };++async function* idle(): AsyncGenerator<AgentEvent> {+ await new Promise<never>(() => {});+ yield undefined as never;+}++function handle(id: string): AgentSessionHandle {+ return {+ id,+ agentKind: 'pi',+ model: 'spark/qwen',+ async send() {},+ async steer() {},+ async abort() {},+ async close() {},+ events: () => idle(),+ getUsageSnapshot: () => ({ tokenUsage: 0, contextTokens: 0, contextWindow: 0, costUsd: 0 }),+ setInteractionResolver() {},+ } as unknown as AgentSessionHandle;+}++function localAgent(): BaseAgent & { startSession: ReturnType<typeof vi.fn> } {+ return {+ kind: 'pi',+ capabilities: {+ availableModels: [], effortLevels: [], permissionModes: [], reasoning: { supported: false },+ images: { supported: false }, slashCommands: { supported: false }, customSlashCommands: { supported: false },+ memory: { supported: false }, fork: { supported: false }, rewind: { supported: true }, extraDirs: { supported: false },+ },+ startSession: vi.fn(async () => handle('local-sdk')),+ filterActiveSkillCommands: (result: unknown) => result,+ async dispose() {},+ } as unknown as BaseAgent & { startSession: ReturnType<typeof vi.fn> };+}++describe('Maker: agent on another computer', () => {+ it('starts the agent through the device starter and records the computer on the task', async () => {+ const store = storage();+ const agent = localAgent();+ const startDeviceAgentSession = vi.fn<(input: { agentKind: string; deviceId: string; options: unknown }) => Promise<AgentSessionHandle>>(+ async () => handle('remote-sdk'),+ );+ const maker = new Maker({ agents: { pi: agent }, storage: store, logger, startDeviceAgentSession });+ const session = await maker.createSession({+ id: 'task-1', agentKind: 'pi', workingDir: '/repo', model: 'spark/qwen', providerId: 'spark', agentDeviceId: 'dev-b',+ });+ expect(agent.startSession).not.toHaveBeenCalled();+ expect(startDeviceAgentSession).toHaveBeenCalledTimes(1);+ expect(startDeviceAgentSession.mock.calls[0][0]).toMatchObject({+ agentKind: 'pi',+ deviceId: 'dev-b',+ options: expect.objectContaining({ sessionId: 'task-1', workingDir: '/repo', model: 'spark/qwen', providerId: 'spark' }),+ });+ expect(store.rows.get('task-1')?.agentDeviceId).toBe('dev-b');+ // 那台的 Cindy 不能转发对话截断时不提供回退(文件按本机保存点回退,对话在那台截断)。+ expect(session.capabilities.rewind).toMatchObject({+ supported: false,+ message: expect.stringMatching(/Update Cindy on the computer running the agent/),+ });+ await maker.shutdown();+ });++ it('offers rewind when the agent computer forwards conversation truncation', async () => {+ const agent = localAgent();+ const remote = { ...handle('remote-sdk'), commitRewindFiles: vi.fn(async () => ({ ok: true })) } as unknown as AgentSessionHandle;+ const maker = new Maker({+ agents: { pi: agent }, storage: storage(), logger, startDeviceAgentSession: async () => remote,+ });+ const session = await maker.createSession({+ id: 'task-r', agentKind: 'pi', workingDir: '/repo', model: 'spark/qwen', agentDeviceId: 'dev-b',+ });+ expect(session.capabilities.rewind.supported).toBe(true);+ await maker.shutdown();+ });++ it('keeps the agent capabilities untouched for local tasks', async () => {+ const agent = localAgent();+ const maker = new Maker({ agents: { pi: agent }, storage: storage(), logger });+ const session = await maker.createSession({ id: 'task-l', agentKind: 'pi', workingDir: '/repo', model: 'm' });+ expect(session.capabilities).toBe(agent.capabilities);+ await maker.shutdown();+ });++ it('refuses to mix with SSH hosts and reports a missing starter instead of running here', async () => {+ const maker = new Maker({ agents: { pi: localAgent() }, storage: storage(), logger });+ await expect(maker.createSession({ id: 't2', agentKind: 'pi', workingDir: '/repo', model: 'm', agentDeviceId: 'dev-b' }))+ .rejects.toBeInstanceOf(NotSupportedError);+ const withStarter = new Maker({+ agents: { pi: localAgent() }, storage: storage(), logger, startDeviceAgentSession: async () => handle('x'),+ });+ await expect(withStarter.createSession({+ id: 't3', agentKind: 'pi', workingDir: '/repo', model: 'm', agentDeviceId: 'dev-b', remoteHostId: 'ssh-1',+ })).rejects.toThrow();+ await maker.shutdown();+ await withStarter.shutdown();+ });++ it('only starts hosted sessions that carry the controller workspace', async () => {+ const agent = localAgent();+ const maker = new Maker({ agents: { pi: agent }, storage: storage(), logger });+ await expect(maker.startHostedAgentSession('pi', { workingDir: '/shadow', model: 'm' })).rejects.toThrow(/deviceHosted/);+ await maker.startHostedAgentSession('pi', {+ workingDir: '/shadow',+ model: 'm',+ deviceHosted: {+ workingDir: '/repo', extraDirs: [], writableDirs: [], platform: 'darwin', shell: 'zsh', isGitRepo: false,+ tunnelUrl: 'http://127.0.0.1:1', tunnelToken: 't', mcpServers: [],+ },+ });+ expect(agent.startSession).toHaveBeenCalledTimes(1);+ await maker.shutdown();+ });+});diff --git a/packages/maker-core/src/maker.ts b/packages/maker-core/src/maker.tsindex 7287e9c208..458d8a9ee1 100644--- a/packages/maker-core/src/maker.ts+++ b/packages/maker-core/src/maker.ts@@ -39,6 +39,7 @@ import type { PiRuntimeCapabilityManifest } from './types/pi-runtime-capabilitieimport { piExplicitSkillRuntimePath } from './agents/pi/skill-runtime-provenance.js';import { fingerprintPiProjectSkillEntrypoint } from './agents/pi/project-resource-assembly.js';import { Session, generateSessionId, type SessionStartupPreferences } from './session.js';+import { NotSupportedError } from './types/capabilities.js';import {AgentNotAuthenticatedError,AgentStartupCleanupPendingError,@@ -120,6 +121,15 @@ export interface SessionLifecycleHooks {export interface MakerDeps {agents: Partial<Record<AgentKind, BaseAgent>>;+ /**+ * 可选:在同账号另一台电脑上启动 Agent(CreateSessionOptions.agentDeviceId)。返回的句柄由+ * host 实现(对方运行 Agent、本机执行文件与命令)。缺省时这类会话无法创建。+ */+ startDeviceAgentSession?: (input: {+ agentKind: AgentKind;+ deviceId: string;+ options: StartSessionOptions;+ }) => Promise<AgentSessionHandle>;storage: SessionStorage;logger: Logger;/** 可选: session 生命周期副作用钩子 (host 层注入)。详见 SessionLifecycleHooks。 */@@ -157,6 +167,12 @@ export interface CreateSessionOptions extends StartSessionOptions {visionBridge?: import('./types/vision-bridge.js').VisionBridgeHook;/** 可选:父会话 id,用于 fork / orchestration 等会话关系。 */parentSessionId?: string;+ /**+ * 可选:Agent 在同账号的另一台电脑上运行(那台电脑的设备 id)。任务、项目文件与命令留在本机,+ * Agent 用那台电脑的程序、登录、供应商与网络。由 MakerDeps.startDeviceAgentSession 启动;+ * 持久化到 SessionMeta.agentDeviceId,恢复时据此找回那台电脑。与 remoteHostId 互斥。+ */+ agentDeviceId?: string;/*** 可选:调用方提供的 sessionId(通常来自外部 DB row)。提供后:* - storage 已有同 id 的 row → 跳过 create, 直接复用@@ -184,11 +200,31 @@ export type MakerEvent =export type MakerEventListener = (event: MakerEvent) => void;+/** Codex thread 归属键:SSH 主机或运行 Agent 的另一台电脑(两者的 thread 都不在本机)。 */+function codexThreadOwnerKey(opts: { remoteHostId?: string; agentDeviceId?: string }): string | undefined {+ return opts.remoteHostId ?? (opts.agentDeviceId ? `device:${opts.agentDeviceId}` : undefined);+}+function capabilitiesForSession(agentKind: AgentKind,base: Capabilities,remoteHostId?: string | null,+ agentDeviceId?: string | null,+ handle?: AgentSessionHandle,): Capabilities {+ if (agentDeviceId) {+ // Agent 在另一台电脑上:对话在那台截断(handle 转发 commitRewindFiles),文件由本机按保存点+ // 回退。那台的 Cindy 不支持转发时不提供。+ if (base.rewind.supported && typeof handle?.commitRewindFiles === 'function') return base;+ return {+ ...base,+ rewind: {+ supported: false,+ reason: 'platform-limited',+ message: 'Update Cindy on the computer running the agent to rewind this task',+ },+ };+ }if (agentKind !== 'codex' || !remoteHostId) return base;return {...base,@@ -448,10 +484,12 @@ export class Maker {/** 视觉桥钩子(层 B)全局默认(可选)。见 MakerDeps.visionBridge。 */protected readonly visionBridge: import('./types/vision-bridge.js').VisionBridgeHook | undefined;private readonly toolLoopReviewer: import('./agents/shared/tool-loop-review.js').ToolLoopReviewer | undefined;+ private readonly startDeviceAgentSession: MakerDeps['startDeviceAgentSession'];constructor(deps: MakerDeps) {this.agents = deps.agents;this.storage = deps.storage;+ this.startDeviceAgentSession = deps.startDeviceAgentSession;this.visionBridge = deps.visionBridge;this.toolLoopReviewer = deps.toolLoopReviewer;// 不 child 自己名字 — host 传进来的 logger 通常已经命名(如 'maker'),@@ -713,12 +751,37 @@ export class Maker {codexThreadClaim = this.claimCodexThread({sessionId: id,sessionInstanceId,- remoteHostId: startOpts.remoteHostId,+ remoteHostId: codexThreadOwnerKey(startOpts),threadId: startOpts.resumeSessionId,});}agentStartAttempted = true;- handle = await agent.startSession({+ if (startOpts.agentDeviceId) {+ if (startOpts.remoteHostId) {+ throw new Error('A session cannot run its agent on another computer and on an SSH host at the same time');+ }+ if (!this.startDeviceAgentSession) {+ throw new NotSupportedError('remoteSession', {+ supported: false,+ reason: 'not-implemented',+ message: 'Running the agent on another computer is not available in this host',+ });+ }+ handle = await this.startDeviceAgentSession({+ agentKind: opts.agentKind,+ deviceId: startOpts.agentDeviceId,+ options: {+ ...startOpts,+ sessionId: id,+ sessionInstanceId,+ onInvalidResumeSession:+ opts.agentKind === 'claude-code' || opts.agentKind === 'pi'+ ? (expectedSdkSessionId) =>+ this.invalidateAndClearSdkSessionId(id, expectedSdkSessionId)+ : undefined,+ },+ });+ } else handle = await agent.startSession({...startOpts,sessionId: id,sessionInstanceId,@@ -765,7 +828,7 @@ export class Maker {codexThreadClaim = this.claimCodexThread({sessionId: id,sessionInstanceId,- remoteHostId: startOpts.remoteHostId,+ remoteHostId: codexThreadOwnerKey(startOpts),threadId: handle.id,});}@@ -850,6 +913,7 @@ export class Maker {// remoteHostId: 远端 session 把目标机器持久化, 之后 resume / list 都能识别。// 本地 session 留 undefined (sqlite 落空), 跟历史行为兼容。remoteHostId: opts.remoteHostId,+ ...(opts.agentDeviceId ? { agentDeviceId: opts.agentDeviceId } : {}),sdkSessionId: handle.id !== '<pending>' ? handle.id : undefined,});createdMetadata = true;@@ -987,7 +1051,13 @@ export class Maker {workDir: startOpts.workingDir,handle,hostStartupPreferences: opts.hostStartupPreferences,- capabilities: capabilitiesForSession(meta.agentKind, agent.capabilities, meta.remoteHostId),+ capabilities: capabilitiesForSession(+ meta.agentKind,+ agent.capabilities,+ meta.remoteHostId,+ meta.agentDeviceId ?? startOpts.agentDeviceId,+ handle,+ ),logger: this.logger,permissionMode: startOpts.permissionMode,// 透传 remoteHostId 让 host 层在 hot path 上能 O(1) 判 local/remote@@ -1009,7 +1079,7 @@ export class Maker {codexThreadClaim = this.claimCodexThread({sessionId: id,sessionInstanceId,- remoteHostId: startOpts.remoteHostId,+ remoteHostId: codexThreadOwnerKey(startOpts),threadId: evt.data,});}@@ -1361,6 +1431,17 @@ export class Maker {return true;}+ /**+ * 设备托管:同账号另一台电脑上的任务让 Agent 在本机运行。直接用本机的 agent 启动会话,+ * 不建本机 Session 与持久化记录(任务、消息与状态都在对方电脑上);opts.deviceHosted 必填。+ */+ async startHostedAgentSession(kind: AgentKind, opts: StartSessionOptions): Promise<AgentSessionHandle> {+ if (this.shutdownStarted) throw new Error('Maker is shutting down; refusing to start a hosted session');+ if (!opts.deviceHosted) throw new Error('hosted sessions require deviceHosted');+ if (opts.remoteHostId) throw new Error('hosted sessions cannot target an SSH host');+ return this.requireAgent(kind).startSession(opts);+ }+/*** Agent 内置 command (palette 'agent-builtin' 类目) —— 同步硬编码白名单。* 见 agents/<kind>/commands.ts。