Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(plugins): 接入调用回执上报并精简个人统计
nana7a6ad446e991
diff --git a/apps/desktop/drizzle/0127_thin_midnight.sql b/apps/desktop/drizzle/0127_thin_midnight.sqlnew file mode 100644index 0000000000..3c7e671b9c--- /dev/null+++ b/apps/desktop/drizzle/0127_thin_midnight.sql@@ -0,0 +1 @@+CREATE INDEX `plugin_usage_events_pending_idx` ON `plugin_usage_events` (`next_attempt_at`,`occurred_at`) WHERE "plugin_usage_events"."report_state" = 'pending';\ No newline at end of filediff --git a/apps/desktop/drizzle/meta/0127_snapshot.json b/apps/desktop/drizzle/meta/0127_snapshot.jsonnew file mode 100644index 0000000000..6a6199dd43--- /dev/null+++ b/apps/desktop/drizzle/meta/0127_snapshot.json@@ -0,0 +1,7186 @@+{+ "version": "6",+ "dialect": "sqlite",+ "id": "a508b14e-e857-4f0e-bfe4-4ad9fe48c70d",+ "prevId": "8e5032cb-8b2c-41b1-8d92-7b18a9ac1c7a",+ "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_remote_opens": {+ "name": "orca_remote_opens",+ "columns": {+ "remote_session_id": {+ "name": "remote_session_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "device_id": {+ "name": "device_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": {},+ "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+ },+ "execution_device_id": {+ "name": "execution_device_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "remote_session_id": {+ "name": "remote_session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_bridged_message_id": {+ "name": "last_bridged_message_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "remote_released_at": {+ "name": "remote_released_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "pending_remote_report": {+ "name": "pending_remote_report",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "remote_stop_confirmed_at": {+ "name": "remote_stop_confirmed_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_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": {}+ },+ "plugin_usage_events": {+ "name": "plugin_usage_events",+ "columns": {+ "call_id": {+ "name": "call_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "subject_id": {+ "name": "subject_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "history_generation": {+ "name": "history_generation",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "occurred_at": {+ "name": "occurred_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "tool_name": {+ "name": "tool_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "version": {+ "name": "version",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "release_id": {+ "name": "release_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "outcome": {+ "name": "outcome",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'unknown'"+ },+ "report_target": {+ "name": "report_target",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "report_state": {+ "name": "report_state",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'not-applicable'"+ },+ "next_attempt_at": {+ "name": "next_attempt_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "attempt_count": {+ "name": "attempt_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ }+ },+ "indexes": {+ "plugin_usage_events_time_idx": {+ "name": "plugin_usage_events_time_idx",+ "columns": [+ "subject_id",+ "occurred_at"+ ],+ "isUnique": false+ },+ "plugin_usage_events_task_idx": {+ "name": "plugin_usage_events_task_idx",+ "columns": [+ "subject_id",+ "session_id",+ "occurred_at"+ ],+ "isUnique": false+ },+ "plugin_usage_events_pending_idx": {+ "name": "plugin_usage_events_pending_idx",+ "columns": [+ "next_attempt_at",+ "occurred_at"+ ],+ "isUnique": false,+ "where": "\"plugin_usage_events\".\"report_state\" = 'pending'"+ }+ },+ "foreignKeys": {+ "plugin_usage_events_subject_id_plugin_usage_subjects_id_fk": {+ "name": "plugin_usage_events_subject_id_plugin_usage_subjects_id_fk",+ "tableFrom": "plugin_usage_events",+ "tableTo": "plugin_usage_subjects",+ "columnsFrom": [+ "subject_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "plugin_usage_subjects": {+ "name": "plugin_usage_subjects",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "stable_key": {+ "name": "stable_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "source_kind": {+ "name": "source_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "plugin_id": {+ "name": "plugin_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "source_key": {+ "name": "source_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "server_root": {+ "name": "server_root",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "ghost_id": {+ "name": "ghost_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "display_name": {+ "name": "display_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "binding_revision": {+ "name": "binding_revision",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "recording_started_at": {+ "name": "recording_started_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "history_generation": {+ "name": "history_generation",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ }+ },+ "indexes": {+ "plugin_usage_subjects_source_idx": {+ "name": "plugin_usage_subjects_source_idx",+ "columns": [+ "stable_key"+ ],+ "isUnique": true+ },+ "plugin_usage_subjects_binding_idx": {+ "name": "plugin_usage_subjects_binding_idx",+ "columns": [+ "ghost_id",+ "binding_revision"+ ],+ "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+ },+ "orca_remote_lead": {+ "name": "orca_remote_lead",+ "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 83d73eba70..29352d2819 100644--- a/apps/desktop/drizzle/meta/_journal.json+++ b/apps/desktop/drizzle/meta/_journal.json@@ -890,6 +890,13 @@"when": 1791787150111,"tag": "0126_dazzling_pyro","breakpoints": true+ },+ {+ "idx": 127,+ "version": "6",+ "when": 1791807544299,+ "tag": "0127_thin_midnight",+ "breakpoints": true}]}\ No newline at end of filediff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex 0b7de83547..2c444a3e54 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -3025,10 +3025,18 @@ function pluginUsageServerRoot(): string {}async function bindPluginUsage(ghost: InstalledGhost, previousRevision?: string): Promise<void> {+ const scope = activeOwnerScopeKey();const service = currentPluginUsageService();- const identity = service && readPluginUsageIdentity(ghost);- if (!service || !identity) return;- try { await service.bind(identity, previousRevision); }+ if (!service) return;+ try {+ await withGhostInstallLock(ghost.manifest.id, async () => {+ if (activeOwnerScopeKey() !== scope || isAppSessionBoundaryPending()) return;+ // A fallback bind can wait behind update/uninstall. Read the final committed identity.+ const installed = getGhostManager().list().find(g => g.manifest.id === ghost.manifest.id);+ const identity = installed && readPluginUsageIdentity(installed);+ if (identity) await service.bind(identity, previousRevision);+ });+ }catch { log.warn('plugin usage binding unavailable'); }}diff --git a/apps/desktop/src/main/localDb/__tests__/migrationReplay.test.ts b/apps/desktop/src/main/localDb/__tests__/migrationReplay.test.tsindex a585df8a19..47834dc3f8 100644--- a/apps/desktop/src/main/localDb/__tests__/migrationReplay.test.ts+++ b/apps/desktop/src/main/localDb/__tests__/migrationReplay.test.ts@@ -109,9 +109,10 @@ describeMigrationReplay('migration replay', () => {db.exec("CREATE TABLE migration_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL); CREATE TABLE migration_history (seq INTEGER PRIMARY KEY, file_name TEXT NOT NULL, content_hash TEXT NOT NULL, applied_at INTEGER NOT NULL)");if (shape !== 'missing') db.exec(`CREATE TABLE orca_workers (id TEXT PRIMARY KEY${shape === 'partial' ? ', pending_remote_report TEXT' : ''}); INSERT INTO orca_workers (id) VALUES ('worker-1');`);const result = runMigrationReplay(db, { drizzleDir: drizzleDir(), currentVersion: 124 });- expect(result.applied.map((migration) => migration.seq)).toEqual([125, 126]);+ expect(result.applied.map((migration) => migration.seq)).toEqual([125, 126, 127]);expect(tableExists(db, 'plugin_usage_subjects')).toBe(true);expect(tableExists(db, 'plugin_usage_events')).toBe(true);+ expect(db.prepare("SELECT name FROM sqlite_master WHERE type='index' AND name='plugin_usage_events_pending_idx'").get()).toEqual({ name: 'plugin_usage_events_pending_idx' });expect(tableExists(db, 'orca_remote_opens')).toBe(true);if (shape !== 'missing') {expect(columnNames(db, 'orca_workers')).toEqual(expect.arrayContaining(['pending_remote_report', 'remote_stop_confirmed_at']));diff --git a/apps/desktop/src/main/localDb/client/__tests__/DbClient.inproc.test.ts b/apps/desktop/src/main/localDb/client/__tests__/DbClient.inproc.test.tsindex 8034698687..cb98d5b006 100644--- a/apps/desktop/src/main/localDb/client/__tests__/DbClient.inproc.test.ts+++ b/apps/desktop/src/main/localDb/client/__tests__/DbClient.inproc.test.ts@@ -3,6 +3,7 @@ import os from 'node:os';import path from 'node:path';import { afterEach, describe, expect, it, vi } from 'vitest';+import type { PluginUsageTransaction, PluginUsageHandle } from '../../../../shared/pluginUsage';vi.mock('electron', () => ({app: {@@ -141,7 +142,8 @@ describe('DbClient in-proc fallback', () => {for (const statement of usageMigration.split('--> statement-breakpoint').filter(s => s.trim())) await client.exec(statement);const identity = { ghostId: 'inproc-plugin', displayName: 'Test', revision: 'revision', sourceKind: 'manual' as const,stableKey: null, pluginId: null, organizationId: null, sourceKey: null, serverRoot: null, version: '1.0', releaseId: null };- const handle = await client.tx('pluginUsage.execute', { action: 'bind', identity, newId: 'inproc-subject', now: 1 });+ const bindUsage = { action: 'bind', identity, newId: 'inproc-subject', now: 1 } satisfies PluginUsageTransaction;+ const handle = await client.tx<PluginUsageHandle | null>('pluginUsage.execute', bindUsage);await client.tx('pluginUsage.execute', { action: 'accept', handle: handle!, callId: 'inproc-call', toolName: 'tool', sessionId: null, occurredAt: 2 });await client.tx('pluginUsage.execute', { action: 'clear', subjectId: handle!.subjectId, now: 3 });await client.tx('pluginUsage.execute', { action: 'settle', handle: handle!, callId: 'inproc-call', outcome: 'failed' });diff --git a/apps/desktop/src/main/localDb/schema.ts b/apps/desktop/src/main/localDb/schema.tsindex 73c04032d9..0ad053748d 100644--- a/apps/desktop/src/main/localDb/schema.ts+++ b/apps/desktop/src/main/localDb/schema.ts@@ -57,6 +57,7 @@ export const pluginUsageEvents = sqliteTable('plugin_usage_events', {}, (t) => ({byTime: index('plugin_usage_events_time_idx').on(t.subjectId, t.occurredAt),byTask: index('plugin_usage_events_task_idx').on(t.subjectId, t.sessionId, t.occurredAt),+ pendingReports: index('plugin_usage_events_pending_idx').on(t.nextAttemptAt, t.occurredAt).where(sql`${t.reportState} = 'pending'`),}));/** Per-profile authority journal. Snapshots are recovery/audit data, not offline grants. */diff --git a/apps/desktop/src/main/localDb/worker/opHandlers/pluginUsageTx.ts b/apps/desktop/src/main/localDb/worker/opHandlers/pluginUsageTx.tsindex 9df3e99e18..61f8b0e2eb 100644--- a/apps/desktop/src/main/localDb/worker/opHandlers/pluginUsageTx.ts+++ b/apps/desktop/src/main/localDb/worker/opHandlers/pluginUsageTx.ts@@ -54,8 +54,8 @@ export function runPluginUsageTransaction(const { handle, callId, toolName, sessionId, occurredAt } = body;db.prepare(`INSERT OR IGNORE INTO plugin_usage_events- (call_id,subject_id,history_generation,occurred_at,tool_name,session_id,version,release_id)- SELECT ?,id,history_generation,?,?,?,?,? FROM plugin_usage_subjects WHERE id=? AND history_generation=?`,+ (call_id,subject_id,history_generation,occurred_at,tool_name,session_id,version,release_id,report_target,report_state)+ SELECT ?,id,history_generation,?,?,?,?,?,?,? FROM plugin_usage_subjects WHERE id=? AND history_generation=?`,).run(callId,occurredAt,@@ -63,6 +63,8 @@ export function runPluginUsageTransaction(sessionId,handle.identity.version,handle.identity.releaseId,+ handle.reportTarget ? JSON.stringify(handle.reportTarget) : null,+ handle.reportTarget ? 'pending' : 'not-applicable',handle.subjectId,handle.historyGeneration,);@@ -92,6 +94,22 @@ export function runPluginUsageTransaction(body.ghostId,);return null;+ case 'report': {+ const update =+ db.prepare(`UPDATE plugin_usage_events SET report_state=?,next_attempt_at=?,attempt_count=attempt_count+1+ WHERE call_id=? AND subject_id=? AND history_generation=? AND report_target=? AND report_state='pending'+ AND EXISTS (SELECT 1 FROM plugin_usage_subjects s WHERE s.id=subject_id AND s.history_generation=plugin_usage_events.history_generation)`);+ for (const { row, state, nextAttemptAt } of body.updates)+ update.run(+ state,+ nextAttemptAt,+ row.callId,+ row.subjectId,+ row.historyGeneration,+ row.reportTarget,+ );+ return null;+ }}})();}diff --git a/apps/desktop/src/main/plugin-market/__tests__/api.test.ts b/apps/desktop/src/main/plugin-market/__tests__/api.test.tsindex 19e9022921..630270df73 100644--- a/apps/desktop/src/main/plugin-market/__tests__/api.test.ts+++ b/apps/desktop/src/main/plugin-market/__tests__/api.test.ts@@ -18,6 +18,20 @@ vi.mock('../../clientEndpointsService.js', () => ({const PLUGIN_A = `c${'a'.repeat(24)}`;const PLUGIN_B = `c${'b'.repeat(24)}`;+it('reports only the bounded event contract with explicit auth and rechecks before HTTP serialization', async () => {+ const guard = vi.fn();+ const events = [{ eventId: 'event-1', releaseId: 'release-1', occurredAt: '2026-10-12T00:00:00.000Z' }];+ const fetcher = vi.fn().mockImplementation(async (_path, options) => {+ expect(options).toMatchObject({ method: 'POST', token: 'test-token', skipAutoRefresh: true, skipSessionInvalidation: true });+ expect(options.bodyFactory()).toEqual({ events });+ return { accepted: ['event-1'], duplicate: [], rejected: [] };+ });+ expect(await new PluginMarketApi(fetcher).reportUsage('plugin/id', events, { token: 'test-token', assertCurrent: guard }))+ .toMatchObject({ accepted: ['event-1'] });+ expect(fetcher.mock.calls[0][0]).toBe('/api/plugins/plugin%2Fid/usage-events');+ expect(guard).toHaveBeenCalledTimes(3);+});+function summary(id: string, ghostId: string) {return {id,diff --git a/apps/desktop/src/main/plugin-market/__tests__/install-manifest-read.test.ts b/apps/desktop/src/main/plugin-market/__tests__/install-manifest-read.test.tsindex f5a5e5a2f6..108362b5f8 100644--- a/apps/desktop/src/main/plugin-market/__tests__/install-manifest-read.test.ts+++ b/apps/desktop/src/main/plugin-market/__tests__/install-manifest-read.test.ts@@ -36,6 +36,7 @@ const brain = vi.hoisted(() => ({),}));vi.mock('../../cindy-brain/index.js', () => ({+ refreshPluginUsageBindings: vi.fn(async () => undefined),getGhostManager: () => ({ inspect: brain.inspect }),installOrUpdateMarketGhostPackage: async (filePath: string,diff --git a/apps/desktop/src/main/plugin-market/__tests__/ledger.test.ts b/apps/desktop/src/main/plugin-market/__tests__/ledger.test.tsindex 8621395428..f020259eb7 100644--- a/apps/desktop/src/main/plugin-market/__tests__/ledger.test.ts+++ b/apps/desktop/src/main/plugin-market/__tests__/ledger.test.ts@@ -217,6 +217,17 @@ describe('PluginMarketLedger', () => {ledger.markRemovedRecordIfUnchanged(replacement, 'user-1');expect(ledger.installationForGhost('cindy-test')).toMatchObject({ installed: false });});+ it('pins a verified server root once and refuses stale ledger backfills', () => {+ const { ledger, filePath } = harness();+ const legacy = record();+ ledger.upsertInstallation(legacy);+ expect(ledger.backfillServerRoot(legacy, 'https://one')).toBe(true);+ expect(new PluginMarketLedger(filePath).installationForGhost(legacy.ghostId)).toEqual({ ...legacy, serverRoot: 'https://one' });+ expect(ledger.backfillServerRoot(legacy, 'https://two')).toBe(false);+ const replaced = record({ releaseId: 'replacement' });+ ledger.upsertInstallation(replaced);+ expect(ledger.backfillServerRoot(legacy, 'https://one')).toBe(false);+ });it('writes provenance atomically and reads it back', () => {const { filePath, ledger } = harness();ledger.upsertInstallation(record({diff --git a/apps/desktop/src/main/plugin-market/__tests__/service-custom-sources.test.ts b/apps/desktop/src/main/plugin-market/__tests__/service-custom-sources.test.tsindex 45c7e42416..217d5c9f3e 100644--- a/apps/desktop/src/main/plugin-market/__tests__/service-custom-sources.test.ts+++ b/apps/desktop/src/main/plugin-market/__tests__/service-custom-sources.test.ts@@ -74,6 +74,7 @@ vi.mock('../../logger.js', () => ({createLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn() }),}));vi.mock('../../cindy-brain/index.js', () => ({+ refreshPluginUsageBindings: vi.fn(async () => undefined),getGhostManager: () => ({list: () =>(runtime.listSequence ? runtime.listSequence() : runtime.ghosts).map((ghost) => ({diff --git a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts b/apps/desktop/src/main/plugin-market/__tests__/service.test.tsindex 0cba1909eb..8d2b76883b 100644--- a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts+++ b/apps/desktop/src/main/plugin-market/__tests__/service.test.ts@@ -103,6 +103,7 @@ vi.mock('../../logger.js', () => ({createLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn() }),}));vi.mock('../../cindy-brain/index.js', () => ({+ refreshPluginUsageBindings: vi.fn(async () => undefined),getGhostManager: () => ({resumePendingResidentsOffline: runtime.resumeOfflineResidents,reconcilePendingRootNamespaces: runtime.reconcilePendingRootNamespaces,@@ -805,6 +806,7 @@ describe('PluginMarketService migration and defaultInstall', () => {expect(snapshot.items[0]?.installState).toBe('installed');expect(h.ledger.installationForGhost(item.ghostId)).toEqual({...legacyRecord,+ serverRoot: runtime.pluginApiBaseUrl,rawManifestSha256: crypto.createHash('sha256').update(bytes).digest('hex'),});});@@ -2424,6 +2426,7 @@ describe('PluginMarketService migration and defaultInstall', () => {expect(h.ledger.installationForGhost('cindy-github')).toEqual({...original,+ serverRoot: runtime.pluginApiBaseUrl,manifestDigest: ghostManifestDigest(rawManifest),rawManifestSha256: crypto.createHash('sha256').update(packageBytes).digest('hex'),});diff --git a/apps/desktop/src/main/plugin-market/api.ts b/apps/desktop/src/main/plugin-market/api.tsindex 6a40aa2b54..68c2c287d9 100644--- a/apps/desktop/src/main/plugin-market/api.ts+++ b/apps/desktop/src/main/plugin-market/api.ts@@ -9,6 +9,9 @@ import {type OrganizationPluginAccessError,type PluginRemovalNotice,type PluginDownloadResponse,+ parsePluginUsageAck,+ type PluginUsageEventInput,+ type PluginUsageAck,} from '@cindy/plugin-protocol';import { getClientEndpoint } from '../clientEndpointsService.js';@@ -193,4 +196,29 @@ export class PluginMarketApi {),);}++ async reportUsage(+ pluginId: string,+ events: PluginUsageEventInput[],+ context: { token: string | null; assertCurrent(): void },+ ): Promise<PluginUsageAck> {+ context.assertCurrent();+ const response = await this.fetcher<unknown>(+ `/api/plugins/${encodeURIComponent(pluginId)}/usage-events`,+ {+ ...this.requestOptions(),+ method: 'POST',+ token: context.token,+ timeoutMs: 5_000,+ skipAutoRefresh: true,+ skipSessionInvalidation: true,+ bodyFactory: () => {+ context.assertCurrent();+ return { events };+ },+ },+ );+ context.assertCurrent();+ return parsePluginUsageAck(response, events.map(event => event.eventId));+ }}diff --git a/apps/desktop/src/main/plugin-market/ledger.ts b/apps/desktop/src/main/plugin-market/ledger.tsindex c235a4dd8e..f64617ec19 100644--- a/apps/desktop/src/main/plugin-market/ledger.ts+++ b/apps/desktop/src/main/plugin-market/ledger.ts@@ -62,6 +62,8 @@ export interface PluginMarketInstallationRecord {* clients that still interpret it as a normalized digest.*/rawManifestSha256?: string;+ /** Verified delivery endpoint; absent legacy records require catalog verification before reporting. */+ serverRoot?: string;}export type PluginMarketAuthorizationTarget = { ghostId: string; namespace?: string | null };@@ -542,6 +544,15 @@ export class PluginMarketLedger {this.write(data);}+ backfillServerRoot(expected: PluginMarketInstallationRecord, serverRoot: string): boolean {+ const data = this.read();+ const current = data.installations[expected.ghostId];+ if (!current || current.serverRoot || canonicalJson(current) !== canonicalJson(expected)) return false;+ data.installations[current.ghostId] = { ...current, serverRoot };+ this.write(data);+ return true;+ }+/*** Stamp namespace onto a pre-namespace market row. Known namespace is never* replaced; a mismatch leaves the existing value in place.diff --git a/apps/desktop/src/main/plugin-market/service.ts b/apps/desktop/src/main/plugin-market/service.tsindex c4943464ce..01d1175026 100644--- a/apps/desktop/src/main/plugin-market/service.ts+++ b/apps/desktop/src/main/plugin-market/service.ts@@ -55,6 +55,7 @@ import {installOrUpdateMarketGhostPackage,isGhostAvailableForActiveSession,isBuiltinGhostRemovedByUser,+ refreshPluginUsageBindings,uninstallGhostAndCleanup,} from '../cindy-brain/index.js';import {@@ -1061,6 +1062,7 @@ export class PluginMarketService {let currentOrganization: PluginCurrentOrganization | null | undefined;let organizationAccessError: string | null = null;let customDiscovery: CustomMarketDiscovery;+ const catalogServerRoot = getClientEndpoint('pluginApiBaseUrl').replace(/\/+$/, '');try {// 官方目录与自定义发现并行;单个本地/网络盘来源卡顿不会串行拖住官方请求。const [catalog, discovered] = await Promise.all([this.api.listAll(), customDiscoveryPromise]);@@ -1097,6 +1099,29 @@ export class PluginMarketService {error: error instanceof Error ? error.message : String(error),});}+ // Only an exact delivered release proves a legacy installation's reporting endpoint.+ if (catalogServerRoot === getClientEndpoint('pluginApiBaseUrl').replace(/\/+$/, '')) {+ let rebound = false;+ try {+ await this.withCapturedLedgerMutation(ledger, () => {+ requireSameMarketOwner(owner);+ const installations = ledger.read().installations;+ for (const plugin of plugins) {+ const record = installations[plugin.ghostId];+ if (record?.installed && !record.serverRoot && record.source !== 'git-market'+ && record.source !== 'local-market' && record.pluginId === plugin.id+ && record.scope === plugin.scope && record.organizationId === plugin.organizationId+ && record.releaseId === plugin.currentRelease.id && record.sha256 === plugin.currentRelease.sha256) {+ rebound = ledger.backfillServerRoot(record, catalogServerRoot) || rebound;+ }+ }+ });+ } catch {+ requireSameMarketOwner(owner);+ log.warn('plugin usage reporting provenance unavailable');+ }+ if (rebound) await refreshPluginUsageBindings();+ }await this.backfillOfficialCindyGithubTrust(ledger, owner);// A snapshot is passive discovery: an empty runtime list can be caused by// startup, an owner transition, or a transient filesystem view. Only an@@ -2275,8 +2300,12 @@ export class PluginMarketService {}}+ const downloadServerRoot = getClientEndpoint('pluginApiBaseUrl').replace(/\/+$/, '');const download = await this.api.download(plugin.id, plugin.currentRelease.id);assertInstallIdentityCurrent();+ const verifiedServerRoot = downloadServerRoot === getClientEndpoint('pluginApiBaseUrl').replace(/\/+$/, '')+ ? downloadServerRoot : undefined;+ requireSameMarketOwner(owner);if (download.sha256 !== plugin.currentRelease.sha256 ||download.sizeBytes !== plugin.currentRelease.sizeBytes ||@@ -2324,6 +2353,7 @@ export class PluginMarketService {{consent,expectedInstalled: options.expectedInstalled,+ verifiedServerRoot,...(options.expectedInstalledApproval !== undefined? { expectedInstalledApproval: options.expectedInstalledApproval }: {}),@@ -2360,6 +2390,7 @@ export class PluginMarketService {sourceReplacementMode: ServerSourceReplacementMode;beforeCommitInLock?: () => void;expectedInstalled: boolean;+ verifiedServerRoot?: string;},owner: ActiveAppSession,ledger: PluginMarketLedger,@@ -2465,12 +2496,12 @@ export class PluginMarketService {// 包已落位且仍持原 owner mutation lease;即使切号终止等待超时推进了// 当前 generation,也必须把来源写进操作开始时捕获的旧 owner 账本。await this.withCapturedLedgerMutation(ledger, () => {- ledger.upsertInstallation(recordFrom(plugin, 'market', {+ ledger.upsertInstallation({ ...recordFrom(plugin, 'market', {manifest: evidence.canonicalManifest,rawManifestSha256: evidence.rawManifestSha256,legacyManifestDigest: evidence.legacyManifestDigest,legacyManifestDigests: [],- }));+ }), ...(options.verifiedServerRoot ? { serverRoot: options.verifiedServerRoot } : {}) });});},}).catch((error) => {diff --git a/apps/desktop/src/main/plugin-usage/__tests__/current.test.ts b/apps/desktop/src/main/plugin-usage/__tests__/current.test.tsindex 2a004b6c7a..48b482b6b5 100644--- a/apps/desktop/src/main/plugin-usage/__tests__/current.test.ts+++ b/apps/desktop/src/main/plugin-usage/__tests__/current.test.ts@@ -16,6 +16,7 @@ vi.mock('../../appSessionState', () => ({isAppSessionBoundaryPending: () => state.boundary,}));vi.mock('../../logger', () => ({ createLogger: () => ({ warn: vi.fn() }) }));+vi.mock('../reporting', () => ({ createPluginUsageReporting: () => undefined }));const identity: PluginUsageIdentity = {ghostId: 'plugin',displayName: 'Plugin',diff --git a/apps/desktop/src/main/plugin-usage/__tests__/identity.test.ts b/apps/desktop/src/main/plugin-usage/__tests__/identity.test.tsindex 93cf4ca946..f17b77ad59 100644--- a/apps/desktop/src/main/plugin-usage/__tests__/identity.test.ts+++ b/apps/desktop/src/main/plugin-usage/__tests__/identity.test.ts@@ -67,3 +67,17 @@ it('separates identical plugin ids from distinct server roots and preserves cust?.stableKey,).toBeNull();});+it('keeps a verified installed origin when the current endpoint changes or becomes unavailable', () => {+ const pinned = { ...record, serverRoot: 'https://original' };+ for (const endpoint of ['https://other', '']) {+ expect(pluginUsageIdentity(ghost, pinned, snapshot, endpoint)).toMatchObject({+ serverRoot: 'https://original',+ verifiedServerRoot: 'https://original',+ reportingScope: 'public',+ stableKey: JSON.stringify(['server', 'https://original', record.pluginId]),+ });+ }+ expect(+ pluginUsageIdentity(ghost, record, snapshot, 'https://original')?.verifiedServerRoot,+ ).toBeUndefined();+});diff --git a/apps/desktop/src/main/plugin-usage/__tests__/ipc.test.ts b/apps/desktop/src/main/plugin-usage/__tests__/ipc.test.tsindex c5d5c4e5c8..66d8f20822 100644--- a/apps/desktop/src/main/plugin-usage/__tests__/ipc.test.ts+++ b/apps/desktop/src/main/plugin-usage/__tests__/ipc.test.ts@@ -2,6 +2,8 @@ import { expect, it, vi } from 'vitest';import { registerPluginUsageIpc } from '../ipc';import type { PluginUsageService } from '../service';import type { IpcMain, IpcMainInvokeEvent } from 'electron';+import { withGhostInstallLock } from '../../cindy-brain/ghostInstallLock';+import type { PluginUsageIdentity } from '../../../shared/pluginUsage';function harness(trusted = true) {const handlers = new Map<string, Parameters<IpcMain['handle']>[1]>();const service = {@@ -12,16 +14,18 @@ function harness(trusted = true) {capture: vi.fn(),} as unknown as PluginUsageService;const warn = vi.fn();+ const identity = vi.fn<() => PluginUsageIdentity | null>(() => null);+ const current = { service };registerPluginUsageIpc({ipcMain: { handle: (name, fn) => handlers.set(name, fn) } as Pick<IpcMain, 'handle'>,assertTrusted: () => {if (!trusted) throw new Error('Untrusted frame');},- service: () => service,- identity: () => null,+ service: () => current.service,+ identity,warn,});- return { handlers, service, warn };+ return { handlers, service, warn, identity, current };}it('checks trusted top-level app sender on every usage endpoint before reading or clearing', async () => {const { handlers, service } = harness(false);@@ -31,6 +35,56 @@ it('checks trusted top-level app sender on every usage endpoint before reading oexpect(service.clear).not.toHaveBeenCalled();expect(service.history).not.toHaveBeenCalled();});+it('waits for the install transaction before reading a revision or creating a history binding', async () => {+ const { handlers, service, identity } = harness();+ let release!: () => void;+ let entered!: () => void;+ const ready = new Promise<void>((r) => {+ entered = r;+ });+ const updating = withGhostInstallLock('upgrading-plugin', async () => {+ entered();+ await new Promise<void>((r) => {+ release = r;+ });+ });+ await ready;+ const summary = handlers.get('ghosts:usage-summary')!(+ {} as IpcMainInvokeEvent,+ 'upgrading-plugin',+ );+ await Promise.resolve();+ expect(identity).not.toHaveBeenCalled();+ expect(service.bind).not.toHaveBeenCalled();+ release();+ await updating;+ await expect(summary).rejects.toMatchObject({ code: 'NOT_FOUND' });+ expect(identity).toHaveBeenCalledOnce();+});+it('does not read the next owner when an account changes while waiting for installation', async () => {+ const { handlers, identity, current } = harness();+ let release!: () => void;+ let entered!: () => void;+ const ready = new Promise<void>((r) => {+ entered = r;+ });+ const updating = withGhostInstallLock('switching-plugin', async () => {+ entered();+ await new Promise<void>((r) => {+ release = r;+ });+ });+ await ready;+ const summary = handlers.get('ghosts:usage-summary')!(+ {} as IpcMainInvokeEvent,+ 'switching-plugin',+ );+ current.service = {} as PluginUsageService;+ release();+ await updating;+ await expect(summary).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });+ expect(identity).not.toHaveBeenCalled();+});it('never treats a missing or malformed subject as clear-all; only explicit null clears all', async () => {const { handlers, service } = harness();const clear = handlers.get('ghosts:usage-clear')!;diff --git a/apps/desktop/src/main/plugin-usage/__tests__/reporting.test.ts b/apps/desktop/src/main/plugin-usage/__tests__/reporting.test.tsnew file mode 100644index 0000000000..6aace71691--- /dev/null+++ b/apps/desktop/src/main/plugin-usage/__tests__/reporting.test.ts@@ -0,0 +1,91 @@+import { beforeEach, expect, it, vi } from 'vitest';+import type { PluginUsageIdentity } from '../../../shared/pluginUsage';+import { createPluginUsageReporting } from '../reporting';+vi.mock('electron', () => ({ app: { getVersion: () => '1.0.0' } }));++const state = vi.hoisted(() => ({+ allowed: true,+ local: false,+ owner: 'owner',+ root: 'https://one/',+ token: 'test-token',+ report: vi.fn(),+}));+vi.mock('../../authManager', () => ({+ getAccessToken: () => state.token,+ getCurrentUserId: () => state.owner,+ isLocalMode: () => state.local,+}));+vi.mock('../../analytics-settings-store', () => ({ isAnalyticsAllowed: () => state.allowed }));+vi.mock('../../clientEndpointsService', () => ({ getClientEndpoint: () => state.root }));+vi.mock('../../plugin-market/api', () => ({+ PluginMarketApi: class {+ reportUsage = state.report;+ },+}));++const identity: PluginUsageIdentity = {+ ghostId: 'plugin',+ displayName: 'Official',+ revision: 'rev',+ sourceKind: 'server',+ stableKey: 'source',+ pluginId: 'id',+ organizationId: null,+ sourceKey: null,+ serverRoot: 'https://one',+ verifiedServerRoot: 'https://one',+ reportingScope: 'public',+ version: '1',+ releaseId: 'release',+};+beforeEach(() => {+ Object.assign(state, {+ allowed: true,+ local: false,+ owner: 'owner',+ root: 'https://one/',+ token: 'test-token',+ });+ state.report.mockReset();+});++it('requires verified distribution, never labels or custom public flags', () => {+ const r = createPluginUsageReporting('owner');+ expect(r.target(identity)).toMatchObject({ serverRoot: 'https://one', ownerId: 'owner' });+ for (const change of [+ { sourceKind: 'manual' as const },+ { sourceKind: 'git-market' as const },+ { reportingScope: 'personal' as const },+ { verifiedServerRoot: undefined },+ { releaseId: null },+ { reportingScope: 'organization' as const },+ ]) {+ expect(r.target({ ...identity, ...change })).toBeNull();+ }+ expect(+ r.target({ ...identity, reportingScope: 'organization', organizationId: 'org' }),+ ).not.toBeNull();+});++it.each([{ allowed: false }, { local: true }, { owner: 'other' }, { root: 'https://two' }])(+ 'blocks a frozen target when context changes: %o',+ (change) => {+ const r = createPluginUsageReporting('owner');+ const target = r.target(identity)!;+ Object.assign(state, change);+ expect(r.canSend(target)).toBe(false);+ expect(r.target(identity)).toBeNull();+ },+);++it('rechecks the root at request serialization and never falls back to another current account token', async () => {+ const r = createPluginUsageReporting('owner');+ const target = r.target(identity)!;+ state.report.mockImplementation(async (_plugin, _events, context) => {+ expect(context.token).toBe('test-token');+ state.root = 'https://other';+ context.assertCurrent();+ });+ await expect(r.send(target, [], vi.fn())).rejects.toThrow('source changed');+});diff --git a/apps/desktop/src/main/plugin-usage/__tests__/service.test.ts b/apps/desktop/src/main/plugin-usage/__tests__/service.test.tsindex e09cd8c154..678c674fe5 100644--- a/apps/desktop/src/main/plugin-usage/__tests__/service.test.ts+++ b/apps/desktop/src/main/plugin-usage/__tests__/service.test.ts@@ -9,6 +9,10 @@ import { PluginUsageService } from '../service';import { runPluginUsageTransaction } from '../../localDb/worker/opHandlers/pluginUsageTx';import { createDbClient, type DbClient } from '../../localDb/client/DbClient';import type { PluginUsageIdentity } from '../../../shared/pluginUsage';+import type { PluginUsageReporting } from '../reporter';+import { registerPluginUsageIpc } from '../ipc';+import { withGhostInstallLock } from '../../cindy-brain/ghostInstallLock';+import type { IpcMain, IpcMainInvokeEvent } from 'electron';const identity: PluginUsageIdentity = {ghostId: 'test-plugin',@@ -57,10 +61,262 @@ beforeEach(() => {});afterEach(async () => {await service.close();+ vi.useRealTimers();db.close();});const capture = () => service.capture(identity)!;+it('keeps one SQLite subject when a detail request overlaps the committed local upgrade', async () => {+ await service.bind(identity);+ const old = capture();+ service.accept(old, 'before-upgrade', 'tool', null, now - 2);+ const upgraded = { ...identity, revision: 'new-revision', version: '2.0' };+ const handlers = new Map<string, Parameters<IpcMain['handle']>[1]>();+ registerPluginUsageIpc({+ ipcMain: { handle: (name, fn) => handlers.set(name, fn) } as Pick<IpcMain, 'handle'>,+ assertTrusted: () => {},+ service: () => service,+ identity: () => upgraded,+ warn: vi.fn(),+ });+ let resume!: () => void;+ let entered!: () => void;+ const ready = new Promise<void>((r) => {+ entered = r;+ });+ const upgrade = withGhostInstallLock(identity.ghostId, async () => {+ entered();+ await new Promise<void>((r) => {+ resume = r;+ });+ await service.bind(upgraded, identity.revision);+ });+ await ready;+ const reading = handlers.get('ghosts:usage-summary')!({} as IpcMainInvokeEvent, identity.ghostId);+ resume();+ await upgrade;+ expect(await reading).toMatchObject({ subjectId: old.subjectId, totalCalls: 1 });+ service.accept(service.capture(upgraded)!, 'after-upgrade', 'tool', null, now - 1);+ expect((await service.summary(old.subjectId))?.totalCalls).toBe(2);+ expect(db.prepare('SELECT COUNT(*) AS n FROM plugin_usage_subjects').get()).toEqual({ n: 1 });+});++async function withReporting() {+ await service.close();+ vi.useFakeTimers();+ const target = {+ serverRoot: 'https://plugins.example',+ ownerId: 'owner',+ pluginId: 'plugin1',+ scope: 'public' as const,+ organizationId: null,+ };+ const reporting = {+ allowed: vi.fn(() => true),+ target: vi.fn(() => target),+ canSend: vi.fn(() => true),+ send: vi.fn<PluginUsageReporting['send']>(async (_target, events) => ({+ accepted: events.map((e) => e.eventId),+ duplicate: [],+ rejected: [],+ })),+ };+ service = new PluginUsageService({+ client,+ isCurrent: () => ownerCurrent,+ now: () => clock,+ deviceName: 'Test',+ warn: vi.fn(),+ reporting,+ });+ await service.bind(identity);+ return reporting;+}++it('resumes persisted pending rows on the next service and never recreates cleared data from an ACK', async () => {+ const reporting = await withReporting();+ const h = capture();+ service.accept(h, 'restart', 'tool', null, now);+ await service.close();+ service = new PluginUsageService({+ client,+ isCurrent: () => ownerCurrent,+ now: () => clock,+ deviceName: 'Test',+ warn: vi.fn(),+ reporting,+ });+ await vi.advanceTimersByTimeAsync(2500);+ expect(reporting.send).toHaveBeenCalledTimes(1);+ expect(db.prepare('SELECT report_state AS state FROM plugin_usage_events').get()).toEqual({+ state: 'sent',+ });+ const oldRow = {+ callId: 'restart',+ subjectId: h.subjectId,+ historyGeneration: h.historyGeneration,+ releaseId: 'release',+ occurredAt: now,+ reportTarget: JSON.stringify(h.reportTarget),+ attemptCount: 0,+ };+ await service.bind(identity);+ await service.clear(h.subjectId);+ service.accept(capture(), 'restart', 'tool', null, now);+ await service.summary(h.subjectId);+ runPluginUsageTransaction(db, {+ action: 'report',+ updates: [{ row: oldRow, state: 'sent', nextAttemptAt: null }],+ });+ expect(+ db+ .prepare(+ 'SELECT report_state AS state,history_generation AS generation FROM plugin_usage_events',+ )+ .get(),+ ).toEqual({ state: 'pending', generation: 1 });+});++it('persists the frozen target, batches at most 100, and confirms only ACKed events without deleting history', async () => {+ const reporting = await withReporting();+ reporting.send.mockImplementationOnce(async (_target, events) => ({+ accepted: [events[0].eventId],+ duplicate: [events[1].eventId],+ rejected: [{ eventId: events[2].eventId, code: 'FUTURE_REASON' }],+ }));+ const h = capture();+ h.identity.releaseId = 'release-1';+ for (let i = 0; i < 101; i++)+ service.accept(h, `call-${i}`, 'tool', 'private-task', now - 1000 + i);+ await service.summary(h.subjectId);+ await vi.advanceTimersByTimeAsync(2500);+ expect(reporting.send).toHaveBeenCalledTimes(1);+ expect(reporting.send.mock.calls[0][1]).toHaveLength(100);+ expect(reporting.send.mock.calls[0][1][0]).toEqual({+ eventId: 'call-0',+ releaseId: 'release-1',+ occurredAt: new Date(now - 1000).toISOString(),+ });+ expect(+ db+ .prepare(+ 'SELECT report_state AS state,COUNT(*) AS n FROM plugin_usage_events GROUP BY report_state ORDER BY state',+ )+ .all(),+ ).toEqual([+ { state: 'pending', n: 99 },+ { state: 'sent', n: 2 },+ ]);+ expect((await service.summary(h.subjectId))?.totalCalls).toBe(101);+});++it('does not upload disabled-period calls or replay historical not-applicable rows after enabling', async () => {+ const reporting = await withReporting();+ reporting.allowed.mockReturnValue(false);+ service.accept(capture(), 'disabled', 'tool', null, now);+ await service.summary(capture().subjectId);+ reporting.allowed.mockReturnValue(true);+ await vi.advanceTimersByTimeAsync(2500);+ expect(reporting.send).not.toHaveBeenCalled();+ expect(db.prepare('SELECT report_state AS state FROM plugin_usage_events').get()).toEqual({+ state: 'not-applicable',+ });+});++it('retains personal history and retries the identical event after a missing endpoint', async () => {+ const reporting = await withReporting();+ reporting.send.mockRejectedValueOnce({ statusCode: 404 });+ const h = capture();+ service.accept(h, 'retry', 'tool', null, now);+ await service.summary(h.subjectId);+ await vi.advanceTimersByTimeAsync(2500);+ expect(+ db+ .prepare(+ 'SELECT report_state AS state,attempt_count AS attempts,next_attempt_at AS next FROM plugin_usage_events',+ )+ .get(),+ ).toEqual({ state: 'pending', attempts: 1, next: now + 300_000 });+ clock += 300_000;+ await vi.advanceTimersByTimeAsync(300_000);+ expect(reporting.send).toHaveBeenCalledTimes(2);+ expect(reporting.send.mock.calls[1][1]).toEqual(reporting.send.mock.calls[0][1]);+ expect((await service.summary(h.subjectId))?.totalCalls).toBe(1);+});++it('splits a 413 batch while preserving event facts and personal history', async () => {+ const reporting = await withReporting();+ reporting.send.mockRejectedValueOnce({ statusCode: 413 });+ const h = capture();+ h.identity.releaseId = 'release-1';+ for (let i = 0; i < 4; i++) service.accept(h, `split-${i}`, 'tool', null, now - 4 + i);+ await service.summary(h.subjectId);+ await vi.advanceTimersByTimeAsync(2500);+ expect(reporting.send.mock.calls[0][1]).toHaveLength(4);+ expect(+ db.prepare("SELECT COUNT(*) AS n FROM plugin_usage_events WHERE report_state='pending'").get(),+ ).toEqual({ n: 4 });+ clock += 2500;+ await vi.advanceTimersByTimeAsync(2500);+ clock += 2500;+ await vi.advanceTimersByTimeAsync(2500);+ expect(reporting.send.mock.calls.map((call) => call[1].length)).toEqual([4, 2, 2]);+ expect(reporting.send.mock.calls.slice(1).flatMap((call) => call[1])).toEqual(+ reporting.send.mock.calls[0][1],+ );+ expect(+ db.prepare("SELECT COUNT(*) AS n FROM plugin_usage_events WHERE report_state='sent'").get(),+ ).toEqual({ n: 4 });+ expect((await service.summary(h.subjectId))?.totalCalls).toBe(4);+});++it('backs off a single-event 413 without deleting it or retrying in a tight loop', async () => {+ const reporting = await withReporting();+ reporting.send.mockRejectedValueOnce({ statusCode: 413 });+ const h = capture();+ service.accept(h, 'single-413', 'tool', null, now);+ await service.summary(h.subjectId);+ await vi.advanceTimersByTimeAsync(2500);+ clock += 10_000;+ await vi.advanceTimersByTimeAsync(10_000);+ expect(reporting.send).toHaveBeenCalledTimes(1);+ expect(+ db+ .prepare('SELECT report_state AS state,next_attempt_at AS next FROM plugin_usage_events')+ .get(),+ ).toEqual({ state: 'pending', next: now + 60_000 });+ expect((await service.summary(h.subjectId))?.totalCalls).toBe(1);+});++it.each(['clear', 'owner', 'close'] as const)(+ 'does not apply a late network ACK after %s',+ async (action) => {+ const reporting = await withReporting();+ let resolve!: (value: Awaited<ReturnType<PluginUsageReporting['send']>>) => void;+ reporting.send.mockImplementationOnce(+ () =>+ new Promise((r) => {+ resolve = r;+ }),+ );+ const h = capture();+ service.accept(h, 'late-ack', 'tool', null, now);+ await service.summary(h.subjectId);+ await vi.advanceTimersByTimeAsync(2500);+ if (action === 'clear') await service.clear(h.subjectId);+ else if (action === 'owner') ownerCurrent = false;+ else await service.close();+ resolve({ accepted: ['late-ack'], duplicate: [], rejected: [] });+ await vi.advanceTimersByTimeAsync(3000);+ expect(+ db.prepare("SELECT COUNT(*) AS n FROM plugin_usage_events WHERE report_state='sent'").get(),+ ).toEqual({ n: 0 });+ expect(reporting.send).toHaveBeenCalledTimes(1);+ if (action === 'clear')+ expect(db.prepare('SELECT COUNT(*) AS n FROM plugin_usage_events').get()).toEqual({ n: 0 });+ },+);+it('counts unique dispatched calls over a rolling 168h window without deleting older events', async () => {await service.bind(identity);const h = capture();diff --git a/apps/desktop/src/main/plugin-usage/current.ts b/apps/desktop/src/main/plugin-usage/current.tsindex 60917dca08..38881a9851 100644--- a/apps/desktop/src/main/plugin-usage/current.ts+++ b/apps/desktop/src/main/plugin-usage/current.ts@@ -7,6 +7,7 @@ import {} from '../appSessionState.js';import { createLogger } from '../logger.js';import { PluginUsageService } from './service.js';+import { createPluginUsageReporting } from './reporting.js';const log = createLogger('plugin-usage');let current: { epoch: number; ownerKey: string; service: PluginUsageService } | null = null;@@ -29,9 +30,11 @@ export function currentPluginUsageService(): PluginUsageService | null {const service = new PluginUsageService({client: snapshot.client,deviceName: os.hostname(),+ reporting: createPluginUsageReporting(snapshot.userId),isCurrent: () => {const latest = getCurrentDbClientSnapshot();return (+ !isAppSessionBoundaryPending() &&latest?.client === snapshot.client &&latest.clientEpoch === snapshot.clientEpoch &&latest.userId === snapshot.userId &&diff --git a/apps/desktop/src/main/plugin-usage/identity.ts b/apps/desktop/src/main/plugin-usage/identity.tsindex 93160d23ae..52c7e302ed 100644--- a/apps/desktop/src/main/plugin-usage/identity.ts+++ b/apps/desktop/src/main/plugin-usage/identity.ts@@ -44,14 +44,17 @@ export function pluginUsageIdentity(releaseId: record.releaseId,};}- if (!serverRoot) return base;+ const verifiedRoot = typeof record.serverRoot === 'string' ? record.serverRoot : undefined;+ if (!verifiedRoot && !serverRoot) return base;return {...base,sourceKind: 'server',+ reportingScope: record.scope,+ verifiedServerRoot: verifiedRoot,pluginId: record.pluginId,organizationId: record.organizationId,- serverRoot,- stableKey: JSON.stringify(['server', serverRoot, record.pluginId]),+ serverRoot: verifiedRoot || serverRoot,+ stableKey: JSON.stringify(['server', verifiedRoot || serverRoot, record.pluginId]),releaseId: record.releaseId,};}diff --git a/apps/desktop/src/main/plugin-usage/ipc.ts b/apps/desktop/src/main/plugin-usage/ipc.tsindex 13674887ab..7e48429b13 100644--- a/apps/desktop/src/main/plugin-usage/ipc.ts+++ b/apps/desktop/src/main/plugin-usage/ipc.ts@@ -4,6 +4,7 @@ import { isIpcError } from '../../shared/ipc-errors.js';import type { PluginUsageIdentity } from '../../shared/pluginUsage.js';import { throwIpcError } from '../utils/ipcValidate.js';import type { PluginUsageService } from './service.js';+import { withGhostInstallLock } from '../cindy-brain/ghostInstallLock.js';export function registerPluginUsageIpc(deps: {ipcMain: Pick<IpcMain, 'handle'>;@@ -41,12 +42,16 @@ export function registerPluginUsageIpc(deps: {if (typeof id !== 'string' || !isValidGhostId(id))throwIpcError('INVALID_PARAMS', 'Invalid plugin id');const current = service();- const identity = deps.identity(id);- if (!identity) throwIpcError('NOT_FOUND', 'Plugin usage identity unavailable');- await current.bind(identity);- const handle = current.capture(identity);- if (!handle) throwIpcError('PRECONDITION_FAILED', 'Plugin usage unavailable');- return current.summary(handle.subjectId);+ return withGhostInstallLock(id, async () => {+ if (service() !== current)+ throwIpcError('PRECONDITION_FAILED', 'Plugin usage owner changed');+ const identity = deps.identity(id);+ if (!identity) throwIpcError('NOT_FOUND', 'Plugin usage identity unavailable');+ await current.bind(identity);+ const handle = current.capture(identity);+ if (!handle) throwIpcError('PRECONDITION_FAILED', 'Plugin usage unavailable');+ return current.summary(handle.subjectId);+ });}),);deps.ipcMain.handle('ghosts:usage-history', (event) => invoke(event, () => service().history()));diff --git a/apps/desktop/src/main/plugin-usage/reporter.ts b/apps/desktop/src/main/plugin-usage/reporter.tsnew file mode 100644index 0000000000..c81b93ac36--- /dev/null+++ b/apps/desktop/src/main/plugin-usage/reporter.ts@@ -0,0 +1,185 @@+import {+ PLUGIN_USAGE_REJECTION_CODES,+ type PluginUsageAck,+ type PluginUsageEventInput,+} from '@cindy/plugin-protocol';+import type {+ PluginUsageIdentity,+ PluginUsageReportRow,+ PluginUsageReportTarget,+} from '../../shared/pluginUsage.js';++export interface PluginUsageReporting {+ allowed(): boolean;+ target(identity: PluginUsageIdentity): PluginUsageReportTarget | null;+ canSend(target: PluginUsageReportTarget): boolean;+ send(+ target: PluginUsageReportTarget,+ events: PluginUsageEventInput[],+ assertCurrent: () => void,+ ): Promise<PluginUsageAck>;+}++export interface UsageReportUpdate {+ row: PluginUsageReportRow;+ state: 'pending' | 'sent' | 'rejected';+ nextAttemptAt: number | null;+}++/** One bounded background chain per active owner; network work never holds the DB write queue. */+export class PluginUsageReporter {+ private timer: ReturnType<typeof setTimeout> | null = null;+ private running = false;+ private stopped = false;+ private revision = 0;+ private wakeRequested = false;+ private wakeAt = 0;+ private batchLimit = 100;++ constructor(+ private readonly deps: {+ reporting: PluginUsageReporting;+ isCurrent(): boolean;+ now(): number;+ select(): Promise<{ rows: PluginUsageReportRow[]; nextAttemptAt: number } | null>;+ revalidate(rows: PluginUsageReportRow[]): Promise<PluginUsageReportRow[]>;+ update(updates: UsageReportUpdate[], valid: () => boolean): Promise<void>;+ warn(): void;+ },+ ) {}++ wake(delayMs = 2_500): void {+ if (this.stopped || !this.deps.isCurrent()) return;+ if (this.running) {+ this.wakeRequested = true;+ return;+ }+ const wakeAt = this.deps.now() + delayMs;+ if (this.timer && this.wakeAt <= wakeAt) return;+ if (this.timer) clearTimeout(this.timer);+ this.wakeAt = wakeAt;+ this.timer = setTimeout(() => {+ this.timer = null;+ void this.run();+ }, delayMs);+ this.timer.unref?.();+ }++ invalidate(): void {+ this.revision += 1;+ this.wake();+ }++ stop(): void {+ this.stopped = true;+ this.revision += 1;+ if (this.timer) clearTimeout(this.timer);+ this.timer = null;+ }++ private async run(): Promise<void> {+ if (this.stopped || !this.deps.isCurrent()) return;+ if (!this.deps.reporting.allowed()) {+ this.wake(60_000);+ return;+ }+ this.running = true;+ this.wakeRequested = false;+ const revision = this.revision;+ const valid = () =>+ !this.stopped &&+ this.revision === revision &&+ this.deps.isCurrent() &&+ this.deps.reporting.allowed();+ let nextDelay: number | null = null;+ try {+ const batch = await this.deps.select();+ if (!batch || !valid()) return;+ if (batch.nextAttemptAt > this.deps.now()) {+ nextDelay = Math.min(batch.nextAttemptAt - this.deps.now(), 60_000);+ return;+ }+ const rows = await this.deps.revalidate(batch.rows.slice(0, this.batchLimit));+ if (!rows.length || !valid()) {+ nextDelay = 1_000;+ return;+ }+ let target: PluginUsageReportTarget | null;+ try {+ target = JSON.parse(rows[0].reportTarget) as PluginUsageReportTarget;+ } catch {+ target = null;+ }+ if (!target || !this.deps.reporting.canSend(target)) {+ await this.deps.update(+ rows.map((row) => ({ row, state: 'pending', nextAttemptAt: this.deps.now() + 300_000 })),+ valid,+ );+ nextDelay = 1_000;+ return;+ }+ const assertCurrent = () => {+ if (!valid() || !this.deps.reporting.canSend(target))+ throw new Error('Plugin usage reporting context changed');+ };+ const events = rows.map((row) => ({+ eventId: row.callId,+ releaseId: row.releaseId,+ occurredAt: new Date(row.occurredAt).toISOString(),+ }));+ let updates: UsageReportUpdate[];+ try {+ assertCurrent();+ const ack = await this.deps.reporting.send(target, events, assertCurrent);+ if (!valid()) return;+ const confirmed = new Set([...ack.accepted, ...ack.duplicate]);+ const rejected = new Set(+ ack.rejected+ .filter((row) => (PLUGIN_USAGE_REJECTION_CODES as readonly string[]).includes(row.code))+ .map((row) => row.eventId),+ );+ updates = rows.map((row) => ({+ row,+ state: confirmed.has(row.callId)+ ? 'sent'+ : rejected.has(row.callId)+ ? 'rejected'+ : 'pending',+ nextAttemptAt:+ confirmed.has(row.callId) || rejected.has(row.callId) ? null : this.deps.now() + 60_000,+ }));+ } catch (error) {+ if (!valid()) return;+ const status =+ error && typeof error === 'object' && 'statusCode' in error ? error.statusCode : null;+ const reduceBatch = status === 413 && rows.length > 1;+ if (reduceBatch) this.batchLimit = Math.max(1, Math.floor(rows.length / 2));+ const minimum =+ status === 401 || status === 403 || status === 404 || status === 405 ? 300_000 : 60_000;+ updates = rows.map((row) => ({+ row,+ state: 'pending',+ nextAttemptAt:+ this.deps.now() ++ (reduceBatch+ ? 2_500+ : Math.min(3_600_000, minimum * 2 ** Math.min(row.attemptCount, 6))),+ }));+ }+ await this.deps.update(updates, valid);+ nextDelay = 2_500;+ } catch {+ if (valid()) {+ this.deps.warn();+ nextDelay = 60_000;+ }+ } finally {+ this.running = false;+ if (!this.stopped && this.deps.isCurrent()) {+ if (this.wakeRequested || revision !== this.revision) this.wake();+ else if (nextDelay !== null) this.wake(nextDelay);+ else if (!this.deps.reporting.allowed()) this.wake(60_000);+ }+ }+ }+}diff --git a/apps/desktop/src/main/plugin-usage/reporting.ts b/apps/desktop/src/main/plugin-usage/reporting.tsnew file mode 100644index 0000000000..bb7cb81c25--- /dev/null+++ b/apps/desktop/src/main/plugin-usage/reporting.ts@@ -0,0 +1,67 @@+import { app } from 'electron';+import { getAccessToken, getCurrentUserId, isLocalMode } from '../authManager.js';+import { isAnalyticsAllowed } from '../analytics-settings-store.js';+import { getClientEndpoint } from '../clientEndpointsService.js';+import { PluginMarketApi } from '../plugin-market/api.js';+import type { PluginUsageReporting } from './reporter.js';++/** The installed release's verified origin is frozen into each event, never inferred on retry. */+export function createPluginUsageReporting(ownerId: string): PluginUsageReporting {+ const api = new PluginMarketApi(undefined, () => app.getVersion());+ const root = () => {+ try {+ return getClientEndpoint('pluginApiBaseUrl').replace(/\/+$/, '');+ } catch {+ return '';+ }+ };+ const allowed = () => !isLocalMode() && getCurrentUserId() === ownerId && isAnalyticsAllowed();+ const canSend: PluginUsageReporting['canSend'] = (target) =>+ Boolean(+ target &&+ allowed() &&+ target.ownerId === ownerId &&+ target.serverRoot &&+ target.serverRoot === root() &&+ typeof target.pluginId === 'string' &&+ target.pluginId.length > 0 &&+ ((target.scope === 'public' && target.organizationId === null) ||+ (target.scope === 'organization' &&+ typeof target.organizationId === 'string' &&+ target.organizationId.length > 0)),+ );+ return {+ allowed,+ canSend,+ target(identity) {+ if (+ !allowed() ||+ identity.sourceKind !== 'server' ||+ !identity.pluginId ||+ !identity.releaseId ||+ !identity.verifiedServerRoot ||+ identity.verifiedServerRoot !== identity.serverRoot ||+ (identity.reportingScope !== 'public' && identity.reportingScope !== 'organization')+ )+ return null;+ const target = {+ serverRoot: identity.verifiedServerRoot,+ pluginId: identity.pluginId,+ ownerId,+ scope: identity.reportingScope,+ organizationId: identity.organizationId,+ };+ return canSend(target) ? target : null;+ },+ async send(target, events, assertCurrent) {+ const guard = () => {+ assertCurrent();+ if (!canSend(target)) throw new Error('Plugin usage reporting source changed');+ };+ guard();+ const token = getAccessToken();+ if (!token) throw new Error('Plugin usage reporting authentication unavailable');+ return api.reportUsage(target.pluginId, events, { token, assertCurrent: guard });+ },+ };+}diff --git a/apps/desktop/src/main/plugin-usage/service.ts b/apps/desktop/src/main/plugin-usage/service.tsindex 075c6fcfb2..40d9eee34d 100644--- a/apps/desktop/src/main/plugin-usage/service.ts+++ b/apps/desktop/src/main/plugin-usage/service.ts@@ -7,7 +7,9 @@ import type {PluginUsageOutcome,PluginUsageSummary,PluginUsageTransaction,+ PluginUsageReportRow,} from '../../shared/pluginUsage.js';+import { PluginUsageReporter, type PluginUsageReporting } from './reporter.js';export interface PluginUsageServiceDeps {client: DbClient;@@ -15,6 +17,7 @@ export interface PluginUsageServiceDeps {isCurrent(): boolean;deviceName: string;now?: () => number;+ reporting?: PluginUsageReporting;warn(): void;}@@ -25,9 +28,70 @@ export class PluginUsageService {private readonly handles = new Map<string, PluginUsageHandle>();private readonly paused = new Set<string>();private readonly now: () => number;+ private readonly reporter?: PluginUsageReporter;constructor(private readonly deps: PluginUsageServiceDeps) {this.now = deps.now ?? Date.now;+ if (deps.reporting) {+ this.reporter = new PluginUsageReporter({+ reporting: deps.reporting,+ isCurrent: () => !this.stopped && deps.isCurrent(),+ now: this.now,+ select: () =>+ this.enqueue(() =>+ runAsBackgroundDbRpc(async () => {+ const first = await deps.client.queryOne<{ target: string; nextAttemptAt: number }>(+ `SELECT e.report_target AS target,COALESCE(e.next_attempt_at,0) AS nextAttemptAt+ FROM plugin_usage_events e JOIN plugin_usage_subjects s ON s.id=e.subject_id AND s.history_generation=e.history_generation+ WHERE e.report_state='pending' ORDER BY e.next_attempt_at,e.occurred_at LIMIT 1`,+ );+ this.assertCurrent();+ if (!first) return null;+ const rows = await deps.client.query<PluginUsageReportRow>(+ `SELECT e.call_id AS callId,e.subject_id AS subjectId,e.history_generation AS historyGeneration,+ e.release_id AS releaseId,e.occurred_at AS occurredAt,e.report_target AS reportTarget,e.attempt_count AS attemptCount+ FROM plugin_usage_events e JOIN plugin_usage_subjects s ON s.id=e.subject_id AND s.history_generation=e.history_generation+ WHERE e.report_state='pending' AND e.report_target=? AND COALESCE(e.next_attempt_at,0)<=?+ ORDER BY e.occurred_at,e.call_id LIMIT 100`,+ [first.target, this.now()],+ );+ return { rows, nextAttemptAt: first.nextAttemptAt };+ }),+ ),+ revalidate: (rows) =>+ this.enqueue(() =>+ runAsBackgroundDbRpc(async () => {+ if (!rows.length) return [];+ const live = await deps.client.query<{+ callId: string;+ subjectId: string;+ historyGeneration: number;+ reportTarget: string;+ }>(+ `SELECT e.call_id AS callId,e.subject_id AS subjectId,e.history_generation AS historyGeneration,e.report_target AS reportTarget+ FROM plugin_usage_events e JOIN plugin_usage_subjects s ON s.id=e.subject_id AND s.history_generation=e.history_generation+ WHERE e.report_state='pending' AND e.call_id IN (${rows.map(() => '?').join(',')})`,+ rows.map((row) => row.callId),+ );+ return rows.filter((row) =>+ live.some(+ (found) =>+ found.callId === row.callId &&+ found.subjectId === row.subjectId &&+ found.historyGeneration === row.historyGeneration &&+ found.reportTarget === row.reportTarget,+ ),+ );+ }),+ ),+ update: (updates, valid) =>+ this.enqueue(async () => {+ if (valid()) await this.tx({ action: 'report', updates });+ }),+ warn: deps.warn,+ });+ this.reporter.wake();+ }}private assertCurrent(): void {@@ -77,16 +141,23 @@ export class PluginUsageService {void this.bind(identity).catch(() => undefined);return null;}- return { ...handle, identity: { ...identity } };+ return this.freeze(handle, identity);}/** Install/startup binding owns source verification; dispatch never rereads package files. */captureBound(ghostId: string, revision: string): PluginUsageHandle | null {if (this.stopped || !this.deps.isCurrent() || this.paused.has(ghostId)) return null;const handle = this.handles.get(ghostId);- return handle?.identity.revision === revision- ? { ...handle, identity: { ...handle.identity } }- : null;+ return handle?.identity.revision === revision ? this.freeze(handle, handle.identity) : null;+ }++ private freeze(handle: PluginUsageHandle, identity: PluginUsageIdentity): PluginUsageHandle {+ const reporting = this.deps.reporting;+ return {+ ...handle,+ identity: { ...identity },+ reportTarget: reporting?.allowed() ? reporting.target(identity) : null,+ };}accept(@@ -99,7 +170,10 @@ export class PluginUsageService {void this.enqueue(async () => {const refreshed = await this.tx({action: 'accept',- handle,+ handle: {+ ...handle,+ reportTarget: this.deps.reporting?.allowed() ? handle.reportTarget : null,+ },callId,toolName,sessionId,@@ -107,6 +181,7 @@ export class PluginUsageService {});// Refresh only future captures after a cross-instance clear. Never replay this call.this.assertCurrent();+ this.reporter?.wake();const current = this.handles.get(handle.identity.ghostId);if (refreshed &&@@ -131,6 +206,7 @@ export class PluginUsageService {}async clear(subjectId: string | null): Promise<void> {+ this.reporter?.invalidate();const affected = [...this.handles.values()].filter((h) => subjectId === null || h.subjectId === subjectId,);@@ -216,6 +292,7 @@ export class PluginUsageService {/** Stop admission first; worker close is not a drain. No cross-owner retry on timeout. */async close(budgetMs = 2_000): Promise<void> {this.stopped = true;+ this.reporter?.stop();let timer: ReturnType<typeof setTimeout> | undefined;try {await Promise.race([diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsxindex 05832aaa6e..629961689e 100644--- a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx@@ -67,7 +67,6 @@ interface GhostPluginDetailViewProps {enabledOverride?: boolean;onBack: () => void;usageOwnerKey?: string;- onOpenUsageTask?: (sessionId: string) => void;confirmClearUsage?: () => Promise<boolean>;onToggle: (enabled: boolean) => void;/** 主动作:面板型「使用」/ 指令或 Host 能力型「对话」;纯工具型不渲染主按钮。 */@@ -113,7 +112,6 @@ export function GhostPluginDetailView({onToggle,onUse,usageOwnerKey,- onOpenUsageTask,confirmClearUsage,mainViewSidebarVisible = true,onMainViewSidebarVisibleChange,@@ -427,7 +425,7 @@ export function GhostPluginDetailView({) : null}</header>- {ghost ? <PluginUsageCard key={`${usageOwnerKey ?? "local"}:${ghost.manifest.id}`} ghostId={ghost.manifest.id} onOpenTask={onOpenUsageTask} confirmClear={confirmClearUsage} /> : null}+ {ghost ? <PluginUsageCard key={`${usageOwnerKey ?? "local"}:${ghost.manifest.id}`} ghostId={ghost.manifest.id} confirmClear={confirmClearUsage} /> : null}{hasConfiguration ? (<sectiondiff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsxindex 82f966a259..901dc67dac 100644--- a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx@@ -129,9 +129,6 @@ import {} from './PluginManagementLayout';import { usePluginListScrollRestoration } from './lib/usePluginListScrollRestoration';import { GhostPagePanelHost } from './GhostPagePanelHost';-import { resolveSessionRoute } from '@/lib/orcaSessionIdentity';-import { ensureBotProfilesLoaded, getBotProfiles } from '@/features/bots/botStore';-import { createSessionEntryNavigator, resolveBotRouteForSessionEntry } from '@/features/bots/botSessionOwners';import { GhostPluginDetailView } from './GhostPluginDetailView';import {currentMainViewVisibilityOwner,@@ -431,11 +428,6 @@ export function GhostPluginPage({const navigate = useNavigate();const [searchParams, setSearchParams] = useSearchParams();const { confirm } = useConfirmDialog();- const [openUsageTask] = useState(() => createSessionEntryNavigator({- resolveBotRoute: id => resolveBotRouteForSessionEntry(id, { readProfiles: getBotProfiles, loadProfiles: ensureBotProfilesLoaded }),- openBotRoute: route => navigate(route),- openOrdinary: (id, _messageId, isLatest) => { void resolveSessionRoute(id).then(route => { if (isLatest()) navigate(route); }); },- }));const showPluginMarketActionError = useCallback(async (error: unknown) => {@@ -1678,7 +1670,6 @@ export function GhostPluginPage({<div className="min-h-0 flex-1"><GhostPluginDetailViewusageOwnerKey={`${panelOwnerKey}:${dataOwnerGeneration}`}- onOpenUsageTask={openUsageTask}confirmClearUsage={() => confirm({ title: t('settings.ghosts.usage.clearTitle'), description: t('settings.ghosts.usage.clearDescription'), confirmText: t('settings.ghosts.usage.clear'), confirmVariant: 'destructive' })}ghost={selectedGhost}detail={selectedDetail}diff --git a/apps/desktop/src/renderer/features/plugin/PluginSharedUsage.tsx b/apps/desktop/src/renderer/features/plugin/PluginSharedUsage.tsxindex 14e03f79db..68d1612d2d 100644--- a/apps/desktop/src/renderer/features/plugin/PluginSharedUsage.tsx+++ b/apps/desktop/src/renderer/features/plugin/PluginSharedUsage.tsx@@ -1,63 +1,29 @@-import { ArrowDownToLine, PackageCheck, Tally5 } from 'lucide-react';+import { ArrowDownToLine } from 'lucide-react';import { useTranslation } from 'react-i18next';import { Tip } from '@/components/ui/tooltip';import type { PluginMarketItem } from '../../../shared/pluginMarket';-/** Only server-authorized aggregates; custom public flags never grant shared statistics. */+/** Only server-authorized download counts; custom public flags never grant shared statistics. */export function PluginSharedUsage({ detail }: { detail: PluginMarketItem }) {const { t, i18n } = useTranslation();if (detail.sourceType !== 'server' || detail.scope === 'personal') return null;- const stats = detail.usageStatistics;const downloads = detail.downloadStatistics;- if (!stats && !downloads) return null;- const explanation = stats- ? t('settings.ghosts.usage.sharedExplanation', {- scope: t(`settings.ghosts.usage.sharedScope.${detail.scope}`),- }) + ` ${t('settings.ghosts.usage.asOf', { time: stats.asOf })}`- : '';+ if (!downloads) return null;return (<><span aria-hidden="true">·</span>- {downloads ? (- <Tip text={t('settings.ghosts.usage.downloadExplanation')}>- <button- type="button"- className="inline-flex min-h-7 items-center gap-1 rounded-full focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"- >- <ArrowDownToLine size={12} aria-hidden="true" />- <span>- {t('settings.ghosts.usage.downloads')}{' '}- {BigInt(downloads.requestCount).toLocaleString(i18n.language)}- </span>- </button>- </Tip>- ) : null}- {stats ? (- <>- <Tip text={explanation}>- <button- type="button"- className="inline-flex min-h-7 items-center gap-1 rounded-full focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"- >- <PackageCheck size={12} aria-hidden="true" />- <span>- {t('settings.ghosts.usage.installs')} {stats.installationCount}- </span>- </button>- </Tip>- <Tip text={explanation}>- <button- type="button"- className="inline-flex min-h-7 items-center gap-1 rounded-full focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"- >- <Tally5 size={12} aria-hidden="true" />- <span>- {t('settings.ghosts.usage.uses')} {stats.usageCount}- </span>- </button>- </Tip>- </>- ) : null}+ <Tip text={t('settings.ghosts.usage.downloadExplanation')}>+ <button+ type="button"+ className="inline-flex min-h-7 items-center gap-1 rounded-full focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"+ >+ <ArrowDownToLine size={12} aria-hidden="true" />+ <span>+ {t('settings.ghosts.usage.downloads')}{' '}+ {BigInt(downloads.requestCount).toLocaleString(i18n.language)}+ </span>+ </button>+ </Tip></>);}diff --git a/apps/desktop/src/renderer/features/plugin/PluginUsageCard.tsx b/apps/desktop/src/renderer/features/plugin/PluginUsageCard.tsxindex 127299c763..ef9a44d36e 100644--- a/apps/desktop/src/renderer/features/plugin/PluginUsageCard.tsx+++ b/apps/desktop/src/renderer/features/plugin/PluginUsageCard.tsx@@ -1,17 +1,21 @@import { useCallback, useEffect, useId, useState } from 'react';import { useTranslation } from 'react-i18next';-import { ChevronRight, Info, RefreshCw } from 'lucide-react';+import { MoreHorizontal } from 'lucide-react';import { Button } from '@/components/ui/button';import { Tip } from '@/components/ui/tooltip';+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from '@/components/ui/dropdown-menu';import type { PluginUsageSummary } from '../../../shared/pluginUsage';export function PluginUsageCard({ghostId,- onOpenTask,confirmClear,}: {ghostId: string;- onOpenTask?: (sessionId: string) => void;confirmClear?: () => Promise<boolean>;}) {const { t, i18n } = useTranslation();@@ -75,51 +79,50 @@ export function PluginUsageCard({});return (<section- className="mt-6 max-w-[760px] rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] p-4"+ className="mt-6 w-full max-w-[480px] rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] p-5"aria-labelledby={titleId}><div className="flex items-center justify-between gap-3">- <div className="flex items-center gap-2">- <h2- id={titleId}- className="text-14 font-medium leading-[1.571] text-[var(--text-primary)]"- >- {t('settings.ghosts.usage.title')}- </h2>+ <h2 id={titleId} className="text-13 font-medium leading-5 text-[var(--text-secondary)]"><Tip text={t('settings.ghosts.usage.explanation')}><buttontype="button"- aria-label={t('settings.ghosts.usage.explanationLabel')}- className="flex h-7 w-7 items-center justify-center rounded-full text-[var(--text-tertiary)] focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"+ aria-label={`${t('settings.ghosts.usage.title')} · ${t('settings.ghosts.usage.explanationLabel')}`}+ className="-ml-2 min-h-7 rounded-full px-2 hover:bg-[var(--surface-hover)] focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]">- <Info size={14} />+ {t('settings.ghosts.usage.title')}</button></Tip>- </div>- <div className="flex items-center gap-1">- <Tip text={t('settings.ghosts.usage.refresh')}>- <button- type="button"- aria-label={t('settings.ghosts.usage.refresh')}- disabled={state === 'loading' || clearing}- onClick={() => void refresh()}- className="flex h-7 w-7 items-center justify-center rounded-full text-[var(--text-tertiary)] hover:bg-[var(--surface-hover)] focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] disabled:opacity-50"- >- <RefreshCw size={14} />- </button>+ </h2>+ <DropdownMenu>+ <Tip text={t('settings.ghosts.usage.more')}>+ <DropdownMenuTrigger asChild>+ <button+ type="button"+ aria-label={t('settings.ghosts.usage.more')}+ className="-mr-1 flex h-7 w-7 items-center justify-center rounded-full text-[var(--text-tertiary)] hover:bg-[var(--surface-hover)] focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"+ >+ <MoreHorizontal size={16} aria-hidden="true" />+ </button>+ </DropdownMenuTrigger></Tip>- {summary && confirmClear ? (- <Button- variant="secondary"- tone="quiet"- size="sm"- disabled={clearing}- onClick={() => void clear()}+ <DropdownMenuContent align="end">+ <DropdownMenuItem+ disabled={state === 'loading' || clearing}+ onSelect={() => void refresh()}>- {t('settings.ghosts.usage.clear')}- </Button>- ) : null}- </div>+ {t('settings.ghosts.usage.refresh')}+ </DropdownMenuItem>+ {summary && confirmClear ? (+ <DropdownMenuItem+ disabled={state === 'loading' || clearing}+ onSelect={() => void clear()}+ >+ {t('settings.ghosts.usage.clear')}+ </DropdownMenuItem>+ ) : null}+ </DropdownMenuContent>+ </DropdownMenu></div>{state === 'loading' ? (<p aria-live="polite" className="mt-3 text-13 leading-5 text-[var(--text-secondary)]">@@ -131,70 +134,30 @@ export function PluginUsageCard({{t('settings.ghosts.usage.unavailable')}</p><Button variant="secondary" tone="quiet" size="sm" onClick={() => void refresh()}>- <RefreshCw size={14} />{t('settings.ghosts.usage.retry')}</Button></div>) : summary ? (- <>- <dl className="mt-3 grid grid-cols-2 gap-4">- <div>- <dt className="text-12 leading-[1.5] text-[var(--text-secondary)]">- {t('settings.ghosts.usage.lastUsed')}- </dt>- <dd className="mt-1 text-14 leading-[1.571] text-[var(--text-primary)]">- {summary.lastUsedAt === null- ? t('settings.ghosts.usage.never')- : time(summary.lastUsedAt)}- </dd>- </div>- <div>- <dt className="text-12 leading-[1.5] text-[var(--text-secondary)]">- {t('settings.ghosts.usage.last7Days')}- </dt>- <dd className="mt-1 text-14 leading-[1.571] text-[var(--text-primary)]">- {summary.callsLast7Days.toLocaleString(i18n.language)}- </dd>- </div>- </dl>- <div className="mt-4 border-t border-[var(--border-default)] pt-3">- <h3 className="text-12 leading-[1.5] text-[var(--text-secondary)]">- {t('settings.ghosts.usage.tasks')}- </h3>- {summary.recentTasks.length === 0 ? (- <p className="mt-2 text-13 leading-5 text-[var(--text-secondary)]">- {t('settings.ghosts.usage.noTasks')}- </p>- ) : (- <ul className="mt-1 space-y-1">- {summary.recentTasks.map((task) => (- <li key={task.sessionId}>- <button- type="button"- disabled={!onOpenTask}- onClick={() => onOpenTask?.(task.sessionId)}- className="flex min-h-9 w-full items-center gap-3 rounded-full px-2 text-left hover:bg-[var(--surface-hover)] focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"- >- <span className="min-w-0 flex-1 truncate text-13 leading-5 text-[var(--text-primary)]">- {task.title || t('settings.ghosts.usage.untitled')}- </span>- <span className="shrink-0 text-12 leading-[1.5] text-[var(--text-tertiary)]">- {time(task.lastUsedAt)}- </span>- <ChevronRight size={14} className="shrink-0 text-[var(--text-tertiary)]" />- </button>- </li>- ))}- </ul>- )}+ <dl className="mt-4 grid grid-cols-[minmax(0,1.4fr)_minmax(0,1fr)] gap-5">+ <div className="min-w-0">+ <dt className="text-12 leading-[1.5] text-[var(--text-secondary)]">+ {t('settings.ghosts.usage.lastUsed')}+ </dt>+ <dd className="mt-2 text-20 font-medium leading-8 tabular-nums text-[var(--text-primary)]">+ {summary.lastUsedAt === null+ ? t('settings.ghosts.usage.never')+ : time(summary.lastUsedAt)}+ </dd></div>- <p className="mt-3 text-12 leading-[1.5] text-[var(--text-tertiary)]">- {t('settings.ghosts.usage.localSince', {- device: summary.deviceName,- time: time(summary.recordingStartedAt),- })}- </p>- </>+ <div className="min-w-0 border-l border-[var(--border-default)] pl-5">+ <dt className="text-12 leading-[1.5] text-[var(--text-secondary)]">+ {t('settings.ghosts.usage.last7Days')}+ </dt>+ <dd className="mt-2 break-words text-24 font-medium leading-8 tabular-nums text-[var(--text-primary)]">+ {summary.callsLast7Days.toLocaleString(i18n.language)}+ </dd>+ </div>+ </dl>) : null}</section>);diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/PluginUsageCard.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/PluginUsageCard.test.tsxindex e78e8ebf72..a86e422909 100644--- a/apps/desktop/src/renderer/features/plugin/__tests__/PluginUsageCard.test.tsx+++ b/apps/desktop/src/renderer/features/plugin/__tests__/PluginUsageCard.test.tsx@@ -27,13 +27,18 @@ function api(load = vi.fn(async () => summary)) {});return { load, clear };}-it('opens original task and clears only after confirmation, then re-reads host records', async () => {+it('shows only two personal metrics and clears from the menu after confirmation', async () => {const { load, clear } = api();- const open = vi.fn();const confirm = vi.fn(async () => true);- render(<PluginUsageCard ghostId="plugin" onOpenTask={open} confirmClear={confirm} />);- fireEvent.click(await screen.findByText('Current title'));- expect(open).toHaveBeenCalledWith('task1');+ render(<PluginUsageCard ghostId="plugin" confirmClear={confirm} />);+ await screen.findByText('7');+ expect(screen.queryByText('Current title')).toBeNull();+ expect(screen.queryByText('settings.ghosts.usage.tasks')).toBeNull();+ expect(screen.queryByText('settings.ghosts.usage.clear')).toBeNull();+ fireEvent.keyDown(screen.getByRole('button', { name: 'settings.ghosts.usage.more' }), {+ key: 'Enter',+ });+ await screen.findByRole('menuitem', { name: 'settings.ghosts.usage.clear' });fireEvent.click(screen.getByText('settings.ghosts.usage.clear'));await waitFor(() => expect(clear).toHaveBeenCalledWith('subject1'));await waitFor(() => expect(load).toHaveBeenCalledTimes(2));@@ -41,7 +46,11 @@ it('opens original task and clears only after confirmation, then re-reads host rit('cancelled confirmation never deletes records', async () => {const { clear } = api();render(<PluginUsageCard ghostId="plugin" confirmClear={async () => false} />);- await screen.findByText('Current title');+ await screen.findByText('7');+ fireEvent.keyDown(screen.getByRole('button', { name: 'settings.ghosts.usage.more' }), {+ key: 'Enter',+ });+ await screen.findByRole('menuitem', { name: 'settings.ghosts.usage.clear' });fireEvent.click(screen.getByText('settings.ghosts.usage.clear'));await Promise.resolve();expect(clear).not.toHaveBeenCalled();@@ -65,7 +74,7 @@ it('distinguishes unavailable from actual zero with no invented usage', async ()await screen.findByText('settings.ghosts.usage.never');expect(screen.getByText('0')).toBeTruthy();});-it('hides missing shared statistics and preserves an explicitly reported zero', () => {+it('hides shared usage and legacy installations when download data is absent', () => {const detail = { sourceType: 'server', scope: 'public' } as PluginMarketItem;const view = render(<PluginSharedUsage detail={detail} />);expect(view.container.childElementCount).toBe(0);@@ -82,8 +91,7 @@ it('hides missing shared statistics and preserves an explicitly reported zero',}}/>,);- expect(screen.getByText('settings.ghosts.usage.installs 0')).toBeTruthy();- expect(screen.getByText('settings.ghosts.usage.uses 10')).toBeTruthy();+ expect(view.container.childElementCount).toBe(0);view.rerender(<PluginSharedUsage detail={detail} />);expect(view.container.childElementCount).toBe(0);});@@ -106,6 +114,33 @@ it.each([expect(view.container.textContent).toBe('');});+it('does not expose aggregate calls in the marketplace header', () => {+ const detail = {+ sourceType: 'server',+ scope: 'public',+ usageStatistics: {+ usageCount: '0',+ usageCountLast7Days: '0',+ asOf: '2026-10-12T00:00:00.000Z',+ },+ } as PluginMarketItem;+ const view = render(<PluginSharedUsage detail={detail} />);+ expect(view.container.childElementCount).toBe(0);+ expect(view.container.textContent).not.toContain('installs');+ view.rerender(+ <PluginSharedUsage+ detail={{+ ...detail,+ usageStatistics: {+ usageCountLast7Days: '3',+ asOf: '2026-10-12T00:00:00.000Z',+ },+ }}+ />,+ );+ expect(view.container.childElementCount).toBe(0);+});+it.each(['public', 'organization'] as const)('shows only the cumulative download value in %s without invented installs or usage',(scope) => {diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex a2c3fbaae8..fae80aa43a 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -6708,34 +6708,22 @@}},"usage": {- "title": "Personal usage",+ "title": "Your calls","explanationLabel": "How usage is counted","explanation": "Tool calls dispatched on this computer by the current account, including failures, timeouts and cancellations. The last 7 days is a rolling 168 hours. Panels, Skills and debugging are excluded. Records remain until cleared.","clear": "Clear records","loading": "Loading records…","unavailable": "Personal records unavailable","retry": "Retry",- "lastUsed": "Last used",+ "lastUsed": "Last call","last7Days": "Calls in last 7 days",- "never": "Not used yet",- "tasks": "Participating Sessions",- "noTasks": "No participating Sessions to show",- "untitled": "Untitled Session",- "localSince": "{{device}} · Recording since {{time}}",+ "never": "No calls yet","clearTitle": "Clear this Plugin’s usage records?","clearDescription": "Remove call records and Session links for this account on this computer. New calls start a fresh history. Shared totals already received by the server are not withdrawn.","downloads": "Downloads","downloadExplanation": "Cumulative download URL requests. Each successfully issued package URL counts once, including updates, reinstalls and retries that request a new URL. This is not a count of completed installations.",- "installs": "Installs",- "uses": "Uses",- "sharedUnavailable": "Unavailable",- "sharedExplanation": "Shared totals for {{scope}}. Installs count successful installation receipts; ordinary updates do not add a receipt and uninstalling does not subtract one. Uses count dispatched tool calls, including failures, timeouts and cancellations. These are not current installed users, panel visits or Skill actions. Missing server statistics are not zero.",- "asOf": "As of {{time}}",- "sharedScope": {- "public": "this public Plugin",- "organization": "users currently authorized to view this organization Plugin"- },- "refresh": "Refresh records"+ "refresh": "Refresh records",+ "more": "Record options"}},"mcp": {diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 3c41979b57..1d24dc56a5 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -6683,34 +6683,22 @@}},"usage": {- "title": "個人の使用記録",+ "title": "自分の呼び出し","explanationLabel": "集計方法","explanation": "この端末の現在のアカウントで送信されたツール呼び出しを集計します。失敗・タイムアウト・キャンセルも含みます。過去 7 日は直近 168 時間です。パネル、Skill、デバッグは含みません。記録は消去するまで保持されます。","clear": "記録を消去","loading": "記録を読み込み中…","unavailable": "個人の記録を取得できません","retry": "再試行",- "lastUsed": "最終使用",- "last7Days": "過去 7 日の呼び出し",- "never": "未使用",- "tasks": "参加セッション",- "noTasks": "表示できる参加セッションはありません",- "untitled": "無題のセッション",- "localSince": "{{device}} · {{time}} から記録",+ "lastUsed": "最終呼び出し",+ "last7Days": "過去7日間の呼び出し",+ "never": "呼び出しはまだありません","clearTitle": "このプラグインの使用記録を消去しますか?","clearDescription": "この端末の現在のアカウントの呼び出し記録とセッションへの関連を消去します。以降の呼び出しから記録を再開します。サーバーが受信済みの共有累計は取り消されません。","downloads": "ダウンロード","downloadExplanation": "ダウンロード URL の累計リクエスト数です。パッケージ URL の発行成功ごとに 1 回と数え、更新、再インストール、新しい URL を取得する再試行も含みます。インストール成功数ではありません。",- "installs": "インストール",- "uses": "使用",- "sharedUnavailable": "取得不可",- "sharedExplanation": "{{scope}}の共有累計です。インストールは成功通知を集計し、通常の更新では増加せず、アンインストールでも減りません。使用は送信済みツール呼び出し(失敗・タイムアウト・キャンセルを含む)です。現在の利用者数、パネル、Skill 操作ではありません。サーバー未対応の統計は 0 と表示しません。",- "asOf": "集計時刻:{{time}}",- "sharedScope": {- "public": "公開プラグイン",- "organization": "この組織プラグインを閲覧する権限のあるユーザー"- },- "refresh": "記録を更新"+ "refresh": "記録を更新",+ "more": "記録のオプション"}},"mcp": {diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 204777fd2d..0aabb3bc10 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -6683,34 +6683,22 @@}},"usage": {- "title": "개인 사용 기록",+ "title": "내 호출","explanationLabel": "집계 방식","explanation": "이 컴퓨터의 현재 계정에서 전달된 도구 호출을 집계하며 실패, 시간 초과, 취소도 포함합니다. 최근 7일은 지난 168시간입니다. 패널, Skill, 디버깅은 제외합니다. 기록은 지울 때까지 보관됩니다.","clear": "기록 지우기","loading": "기록 불러오는 중…","unavailable": "개인 기록을 불러올 수 없습니다","retry": "다시 시도",- "lastUsed": "최근 사용",+ "lastUsed": "최근 호출","last7Days": "최근 7일 호출",- "never": "아직 사용하지 않음",- "tasks": "참여 세션",- "noTasks": "표시할 참여 세션이 없습니다",- "untitled": "제목 없는 세션",- "localSince": "{{device}} · {{time}}부터 기록",+ "never": "아직 호출 없음","clearTitle": "이 플러그인의 사용 기록을 지울까요?","clearDescription": "이 컴퓨터의 현재 계정에서 호출 기록과 세션 연결을 지웁니다. 이후 호출부터 새로 기록합니다. 서버가 이미 받은 공유 합계는 취소되지 않습니다.","downloads": "다운로드","downloadExplanation": "누적 다운로드 URL 요청 수입니다. 패키지 URL 발급 성공마다 1회로 집계하며 업데이트, 재설치, 새 URL을 요청하는 재시도도 포함합니다. 설치 완료 횟수가 아닙니다.",- "installs": "설치",- "uses": "사용",- "sharedUnavailable": "사용 불가",- "sharedExplanation": "{{scope}}의 공유 합계입니다. 설치는 성공한 설치 수신을 집계하며 일반 업데이트는 추가하지 않고 제거해도 차감하지 않습니다. 사용은 전달된 도구 호출이며 실패, 시간 초과, 취소를 포함합니다. 현재 설치 사용자 수나 패널, Skill 작업이 아닙니다. 서버에서 제공하지 않은 통계는 0으로 표시하지 않습니다.",- "asOf": "집계 시각: {{time}}",- "sharedScope": {- "public": "공개 플러그인",- "organization": "현재 이 조직 플러그인을 볼 권한이 있는 사용자"- },- "refresh": "기록 새로고침"+ "refresh": "기록 새로고침",+ "more": "기록 옵션"}},"mcp": {diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 18f9d5b5f6..3a6b7403b8 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -6683,34 +6683,22 @@}},"usage": {- "title": "个人使用记录",+ "title": "个人调用","explanationLabel": "统计口径","explanation": "仅统计本机当前账户成功派发的工具调用,失败、超时或取消也计入。近 7 天为滚动 168 小时;面板、Skill 与调试操作不计入。记录默认保留,清除后重新开始。","clear": "清除记录","loading": "正在读取记录…","unavailable": "个人记录暂不可用","retry": "重试",- "lastUsed": "最近使用",- "last7Days": "近 7 天调用",- "never": "尚未使用",- "tasks": "参与任务",- "noTasks": "暂无可查看的参与任务",- "untitled": "未命名任务",- "localSince": "{{device}} · 从 {{time}} 开始记录",+ "lastUsed": "最近调用",+ "last7Days": "近 7 日调用",+ "never": "尚未调用","clearTitle": "清除该插件的使用记录?","clearDescription": "清除本机当前账户的调用记录及任务关联,后续调用重新开始记录。已共享的累计统计不会撤回。","downloads": "下载","downloadExplanation": "累计下载请求次数:成功获取安装包下载地址后计一次,包括更新、重装及重新获取地址的重试;不代表成功安装次数。",- "installs": "安装",- "uses": "使用",- "sharedUnavailable": "暂不可用",- "sharedExplanation": "{{scope}}共享累计。安装按成功安装回执计数,普通升级不增加,卸载不倒扣;使用按成功派发的工具调用计数(含失败、超时和取消)。不代表当前安装人数,也不包含面板或 Skill 操作。服务端尚未提供统计时不显示为 0。",- "asOf": "统计时间:{{time}}",- "sharedScope": {- "public": "公开插件",- "organization": "当前有权查看该企业插件的用户"- },- "refresh": "刷新记录"+ "refresh": "刷新记录",+ "more": "记录选项"}},"mcp": {diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 19f04dab73..ea031abcc8 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -6683,34 +6683,22 @@}},"usage": {- "title": "個人使用記錄",+ "title": "個人呼叫","explanationLabel": "統計口徑","explanation": "僅統計本機目前帳戶成功派發的工具呼叫,失敗、逾時或取消也計入。近 7 天為滾動 168 小時;面板、Skill 與除錯操作不計入。記錄預設保留,清除後重新開始。","clear": "清除記錄","loading": "正在讀取記錄…","unavailable": "個人記錄暫時無法使用","retry": "重試",- "lastUsed": "最近使用",- "last7Days": "近 7 天呼叫",- "never": "尚未使用",- "tasks": "參與任務",- "noTasks": "暫無可查看的參與任務",- "untitled": "未命名任務",- "localSince": "{{device}} · 從 {{time}} 開始記錄",+ "lastUsed": "最近呼叫",+ "last7Days": "近 7 日呼叫",+ "never": "尚未呼叫","clearTitle": "清除此插件的使用記錄?","clearDescription": "清除本機目前帳戶的呼叫記錄及任務關聯,後續呼叫重新開始記錄。已共享的累計統計不會撤回。","downloads": "下載","downloadExplanation": "累計下載請求次數:成功取得安裝包下載位址後計一次,包括更新、重新安裝及重新取得位址的重試;不代表成功安裝次數。",- "installs": "安裝",- "uses": "使用",- "sharedUnavailable": "暫時無法使用",- "sharedExplanation": "{{scope}}共享累計。安裝按成功安裝回執計數,普通更新不增加,解除安裝不扣除;使用按成功派發的工具呼叫計數(含失敗、逾時和取消)。不代表目前安裝人數,也不包含面板或 Skill 操作。伺服器尚未提供統計時不顯示為 0。",- "asOf": "統計時間:{{time}}",- "sharedScope": {- "public": "公開插件",- "organization": "目前有權查看此企業插件的使用者"- },- "refresh": "重新整理記錄"+ "refresh": "重新整理記錄",+ "more": "記錄選項"}},"mcp": {diff --git a/apps/desktop/src/shared/pluginUsage.ts b/apps/desktop/src/shared/pluginUsage.tsindex f0210c1e11..edeed4568c 100644--- a/apps/desktop/src/shared/pluginUsage.ts+++ b/apps/desktop/src/shared/pluginUsage.ts@@ -25,12 +25,33 @@ export interface PluginUsageIdentity {serverRoot: string | null;version: string | null;releaseId: string | null;+ reportingScope?: 'public' | 'organization' | 'personal';+ verifiedServerRoot?: string;}export interface PluginUsageHandle {subjectId: string;historyGeneration: number;identity: PluginUsageIdentity;+ reportTarget?: PluginUsageReportTarget | null;+}++export interface PluginUsageReportTarget {+ serverRoot: string;+ pluginId: string;+ ownerId: string;+ scope: 'public' | 'organization';+ organizationId: string | null;+}++export interface PluginUsageReportRow {+ callId: string;+ subjectId: string;+ historyGeneration: number;+ releaseId: string;+ occurredAt: number;+ reportTarget: string;+ attemptCount: number;}export type PluginUsageTransaction =@@ -51,4 +72,12 @@ export type PluginUsageTransaction =}| { action: 'settle'; handle: PluginUsageHandle; callId: string; outcome: PluginUsageOutcome }| { action: 'clear'; subjectId: string | null; now: number }- | { action: 'detach'; ghostId: string };+ | { action: 'detach'; ghostId: string }+ | {+ action: 'report';+ updates: {+ row: PluginUsageReportRow;+ state: 'pending' | 'sent' | 'rejected';+ nextAttemptAt: number | null;+ }[];+ };diff --git a/docs/fixtures/plugin-usage.json b/docs/fixtures/plugin-usage.jsonnew file mode 100644index 0000000000..1795843dea--- /dev/null+++ b/docs/fixtures/plugin-usage.json@@ -0,0 +1,11 @@+{+ "schemaVersion": 2,+ "request": { "events": [{ "eventId": "00000000-0000-4000-8000-000000000001", "releaseId": "example-release", "occurredAt": "2026-10-12T08:00:00.000Z" }] },+ "accepted": { "accepted": ["00000000-0000-4000-8000-000000000001"], "duplicate": [], "rejected": [] },+ "retry": { "accepted": [], "duplicate": ["00000000-0000-4000-8000-000000000001"], "rejected": [] },+ "conflict": { "accepted": [], "duplicate": [], "rejected": [{ "eventId": "00000000-0000-4000-8000-000000000001", "code": "EVENT_ID_CONFLICT" }] },+ "zero": { "usageStatistics": { "usageCount": "0", "usageCountLast7Days": "0", "asOf": "2026-10-12T08:00:00.000Z" } },+ "independent": { "usageStatistics": { "usageCount": "1234", "usageCountLast7Days": "123", "asOf": "2026-10-12T08:00:00.000Z" }, "downloadStatistics": { "requestCount": "4321", "last7DaysRequestCount": "12" } },+ "unavailable": {},+ "retryableError": { "error": { "code": "USAGE_STORAGE_UNAVAILABLE", "message": "调用回执存储暂不可用" } }+}diff --git a/packages/plugin-protocol/src/__tests__/usageAck.test.ts b/packages/plugin-protocol/src/__tests__/usageAck.test.tsnew file mode 100644index 0000000000..550a6e03c7--- /dev/null+++ b/packages/plugin-protocol/src/__tests__/usageAck.test.ts@@ -0,0 +1,31 @@+import { expect, it } from "vitest";+import { parsePluginUsageAck } from "../usage.js";++it("accepts partial ACKs and preserves future rejection codes for retry", () => {+ expect(+ parsePluginUsageAck(+ {+ accepted: ["a"],+ duplicate: ["b"],+ rejected: [{ eventId: "c", code: "FUTURE_REASON" }],+ },+ ["a", "b", "c", "d"],+ ),+ ).toEqual({+ accepted: ["a"],+ duplicate: ["b"],+ rejected: [{ eventId: "c", code: "FUTURE_REASON" }],+ });+});+it.each([+ { accepted: ["outside"], duplicate: [], rejected: [] },+ { accepted: ["a"], duplicate: ["a"], rejected: [] },+ {+ accepted: [],+ duplicate: [],+ rejected: [{ eventId: "a", code: "private message" }],+ },+ { accepted: [], rejected: [] },+])("rejects malformed or cross-batch ACKs", (ack) => {+ expect(() => parsePluginUsageAck(ack, ["a"])).toThrow();+});diff --git a/packages/plugin-protocol/src/__tests__/usageServerFixtures.test.ts b/packages/plugin-protocol/src/__tests__/usageServerFixtures.test.tsnew file mode 100644index 0000000000..91eea17503--- /dev/null+++ b/packages/plugin-protocol/src/__tests__/usageServerFixtures.test.ts@@ -0,0 +1,46 @@+import { readFileSync } from "node:fs";+import { expect, it } from "vitest";+import { parsePluginUsageAck } from "../usage.js";+import {+ parsePluginDownloadStatistics,+ parsePluginUsageStatistics,+ PLUGIN_API_SCHEMA_VERSION,+} from "../delivery.js";++// Copied byte-for-byte from the server's frozen S1 fixture, not reconstructed from client types.+const fixture = JSON.parse(+ readFileSync(+ new URL("../../../../docs/fixtures/plugin-usage.json", import.meta.url),+ "utf8",+ ),+);+const eventIds = fixture.request.events.map(+ (event: { eventId: string }) => event.eventId,+);++it.each(["accepted", "retry", "conflict"])(+ "parses the server %s acknowledgement",+ (name) => {+ expect(parsePluginUsageAck(fixture[name], eventIds)).toEqual(fixture[name]);+ },+);++it("keeps real zero, missing metrics, and download totals independent without requiring installationCount", () => {+ expect(PLUGIN_API_SCHEMA_VERSION).toBe(fixture.schemaVersion);+ for (const name of ["zero", "independent", "unavailable"]) {+ expect(parsePluginUsageStatistics(fixture[name].usageStatistics)).toEqual(+ fixture[name].usageStatistics,+ );+ expect(+ parsePluginDownloadStatistics(fixture[name].downloadStatistics),+ ).toEqual(fixture[name].downloadStatistics);+ expect(+ parsePluginUsageStatistics(fixture[name].usageStatistics)+ ?.installationCount,+ ).toBeUndefined();+ }+});++it("does not treat a storage error envelope as a committed ACK", () => {+ expect(() => parsePluginUsageAck(fixture.retryableError, eventIds)).toThrow();+});diff --git a/packages/plugin-protocol/src/__tests__/usageStatistics.test.ts b/packages/plugin-protocol/src/__tests__/usageStatistics.test.tsindex a614403ca6..b9c6b22bee 100644--- a/packages/plugin-protocol/src/__tests__/usageStatistics.test.ts+++ b/packages/plugin-protocol/src/__tests__/usageStatistics.test.ts@@ -1,27 +1,34 @@import { expect, it } from "vitest";-import {- parsePluginUsageStatistics,- PLUGIN_API_SCHEMA_VERSION,-} from "../delivery.js";-const stats = {- installationCount: "0",- usageCount: "18446744073709551615",- usageCountLast7Days: "20",- asOf: "2026-10-12T00:00:00.000Z",-};-it("keeps real zero and large counters as exact strings without changing protocol v2", () => {+import { parsePluginUsageStatistics, PLUGIN_API_SCHEMA_VERSION } from "../delivery.js";++const asOf = "2026-10-12T00:00:00.000Z";+it("preserves v2, real installation zero, and absence of unsupported statistics", () => {expect(PLUGIN_API_SCHEMA_VERSION).toBe(2);- expect(parsePluginUsageStatistics(stats)).toEqual(stats);-});-it("keeps absent, unsupported, download-only and malformed optional metrics unavailable", () => {- for (const value of [- undefined,- null,- {},- { downloadCount: "400" },- { ...stats, installationCount: 0 },- { ...stats, usageCount: "-1" },- { ...stats, asOf: "invalid" },- ])+ expect(parsePluginUsageStatistics({installationCount: "0", usageCount: "18446744073709551615", usageCountLast7Days: "20", asOf}))+ .toEqual({installationCount: "0", usageCount: "18446744073709551615", usageCountLast7Days: "20", asOf});+ for (const value of [undefined, null, {}, { downloadCount: "400" }, { usageCount: "-1", asOf }])expect(parsePluginUsageStatistics(value)).toBeUndefined();});+it("accepts usage-only servers without inventing an installation count", () => {+ expect(+ parsePluginUsageStatistics({+ usageCount: "0",+ usageCountLast7Days: "0",+ asOf,+ }),+ ).toEqual({ usageCount: "0", usageCountLast7Days: "0", asOf });+});+it("validates each metric independently and preserves exact large counts", () => {+ expect(+ parsePluginUsageStatistics({+ installationCount: -1,+ usageCount: "18446744073709551615",+ usageCountLast7Days: "01",+ asOf,+ }),+ ).toEqual({ usageCount: "18446744073709551615", asOf });+ expect(parsePluginUsageStatistics({ asOf })).toBeUndefined();+ expect(+ parsePluginUsageStatistics({ usageCount: "0", asOf: "invalid" }),+ ).toBeUndefined();+});diff --git a/packages/plugin-protocol/src/delivery.ts b/packages/plugin-protocol/src/delivery.tsindex 233aaf2a40..90111f6b1c 100644--- a/packages/plugin-protocol/src/delivery.ts+++ b/packages/plugin-protocol/src/delivery.ts@@ -116,9 +116,9 @@ export function parsePluginDownloadStatistics(value: unknown): PluginDownloadSta/** Optional, already-authorized audience aggregate. Downloads are not install receipts. */export interface PluginUsageStatistics {- installationCount: string;- usageCount: string;- usageCountLast7Days: string;+ installationCount?: string;+ usageCount?: string;+ usageCountLast7Days?: string;asOf: string;}@@ -127,10 +127,13 @@ export function parsePluginUsageStatistics(value: unknown): PluginUsageStatisticif (!value || typeof value !== 'object' || Array.isArray(value)) return undefined;const raw = value as Record<string, unknown>;const keys = ['installationCount', 'usageCount', 'usageCountLast7Days'] as const;- if (keys.some(key => typeof raw[key] !== 'string' || !/^(0|[1-9][0-9]{0,19})$/.test(raw[key] as string))) return undefined;if (typeof raw.asOf !== 'string' || !/^\d{4}-\d{2}-\d{2}T.*Z$/.test(raw.asOf) || !Number.isFinite(Date.parse(raw.asOf))) return undefined;- return { installationCount: raw.installationCount as string, usageCount: raw.usageCount as string,- usageCountLast7Days: raw.usageCountLast7Days as string, asOf: raw.asOf };+ const result: PluginUsageStatistics = { asOf: raw.asOf };+ for (const key of keys) {+ if (typeof raw[key] === 'string' && /^(0|[1-9][0-9]{0,19})$/.test(raw[key] as string))+ result[key] = raw[key] as string;+ }+ return keys.some(key => result[key] !== undefined) ? result : undefined;}/** Plugin 列表项;只含市场展示和版本对账所需的摘要。 */diff --git a/packages/plugin-protocol/src/index.ts b/packages/plugin-protocol/src/index.tsindex d74cf97218..96f8bcb263 100644--- a/packages/plugin-protocol/src/index.ts+++ b/packages/plugin-protocol/src/index.ts@@ -3,3 +3,4 @@ export * from './routineEvents.js';export * from './recommendations.js';export * from './delivery.js';export * from './memberUpload.js';+export * from './usage.js';diff --git a/packages/plugin-protocol/src/usage.ts b/packages/plugin-protocol/src/usage.tsnew file mode 100644index 0000000000..4da7c42d9b--- /dev/null+++ b/packages/plugin-protocol/src/usage.ts@@ -0,0 +1,57 @@+import { PluginProtocolError } from "./internal/parse.js";++export interface PluginUsageEventInput {+ eventId: string;+ releaseId: string;+ occurredAt: string;+}++export const PLUGIN_USAGE_REJECTION_CODES = [+ "EVENT_ID_CONFLICT",+ "RELEASE_NOT_DELIVERED",+ "OCCURRED_AT_OUT_OF_RANGE",+] as const;++export interface PluginUsageAck {+ accepted: string[];+ duplicate: string[];+ rejected: { eventId: string; code: string }[];+}++/** Acknowledgements only apply to this exact batch. Missing IDs remain pending. */+export function parsePluginUsageAck(+ value: unknown,+ expectedIds: readonly string[],+): PluginUsageAck {+ const fail = (): never => {+ throw new PluginProtocolError("Invalid plugin usage acknowledgement");+ };+ if (!value || typeof value !== "object" || Array.isArray(value))+ return fail();+ const raw = value as Record<string, unknown>;+ const expected = new Set(expectedIds);+ const seen = new Set<string>();+ const id = (value: unknown): string => {+ if (typeof value !== "string" || !expected.has(value) || seen.has(value))+ return fail();+ seen.add(value);+ return value;+ };+ const ids = (value: unknown): string[] => {+ if (!Array.isArray(value) || value.length > expected.size) return fail();+ return value.map(id);+ };+ const accepted = ids(raw.accepted);+ const duplicate = ids(raw.duplicate);+ if (!Array.isArray(raw.rejected) || raw.rejected.length > expected.size)+ return fail();+ const rejected = raw.rejected.map((value: unknown) => {+ if (!value || typeof value !== "object" || Array.isArray(value))+ return fail();+ const row = value as Record<string, unknown>;+ if (typeof row.code !== "string" || !/^[A-Z_]{1,64}$/.test(row.code))+ return fail();+ return { eventId: id(row.eventId), code: row.code };+ });+ return { accepted, duplicate, rejected };+}