Skip to content

armgit / cindy

Public Imported from GitHub
0

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

feat(plugins): 复用普通任务与协同生命周期接口

Dashe9c277c558bf
diff --git a/apps/desktop/drizzle/0116_happy_eternity.sql b/apps/desktop/drizzle/0116_happy_eternity.sql
new file mode 100644
index 0000000000..b98018c9f3
--- /dev/null
+++ b/apps/desktop/drizzle/0116_happy_eternity.sql
@@ -0,0 +1,14 @@
+CREATE TABLE `plugin_task_requests` (
+ `id` text PRIMARY KEY NOT NULL,
+ `plugin_id` text NOT NULL,
+ `operation` text NOT NULL,
+ `target_id` text NOT NULL,
+ `request_key` text NOT NULL,
+ `fingerprint` text NOT NULL,
+ `payload` text NOT NULL,
+ `revision` integer DEFAULT 0 NOT NULL,
+ `created_at` integer NOT NULL
+);
+--> statement-breakpoint
+CREATE UNIQUE INDEX `plugin_task_request_key` ON `plugin_task_requests` (`plugin_id`,`operation`,`target_id`,`request_key`);--> statement-breakpoint
+CREATE INDEX `plugin_task_target` ON `plugin_task_requests` (`target_id`,`plugin_id`);
\ No newline at end of file
diff --git a/apps/desktop/drizzle/meta/0116_snapshot.json b/apps/desktop/drizzle/meta/0116_snapshot.json
new file mode 100644
index 0000000000..8440ad1d4e
--- /dev/null
+++ b/apps/desktop/drizzle/meta/0116_snapshot.json
@@ -0,0 +1,6206 @@
+{
+ "version": "6",
+ "dialect": "sqlite",
+ "id": "d2e315ce-363f-44ef-bd5e-04b2564ac625",
+ "prevId": "5d2dd28a-3d32-448d-8bbb-000d29541d1e",
+ "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": {}
+ },
+ "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_lifecycle_events": {
+ "name": "bot_lifecycle_events",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bot_id": {
+ "name": "bot_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "event_type": {
+ "name": "event_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "payload_json": {
+ "name": "payload_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_bot_lifecycle_events_bot_created": {
+ "name": "idx_bot_lifecycle_events_bot_created",
+ "columns": [
+ "bot_id",
+ "created_at"
+ ],
+ "isUnique": false
+ },
+ "idx_bot_lifecycle_events_session_created": {
+ "name": "idx_bot_lifecycle_events_session_created",
+ "columns": [
+ "session_id",
+ "created_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "bot_lifecycle_events_bot_id_bot_profiles_id_fk": {
+ "name": "bot_lifecycle_events_bot_id_bot_profiles_id_fk",
+ "tableFrom": "bot_lifecycle_events",
+ "tableTo": "bot_profiles",
+ "columnsFrom": [
+ "bot_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "bot_lifecycle_events_session_id_sessions_id_fk": {
+ "name": "bot_lifecycle_events_session_id_sessions_id_fk",
+ "tableFrom": "bot_lifecycle_events",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "bot_profile_versions": {
+ "name": "bot_profile_versions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bot_id": {
+ "name": "bot_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "version": {
+ "name": "version",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "identity_source": {
+ "name": "identity_source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "capabilities_json": {
+ "name": "capabilities_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_bot_profile_versions_bot_version": {
+ "name": "uniq_bot_profile_versions_bot_version",
+ "columns": [
+ "bot_id",
+ "version"
+ ],
+ "isUnique": true
+ },
+ "idx_bot_profile_versions_bot_created": {
+ "name": "idx_bot_profile_versions_bot_created",
+ "columns": [
+ "bot_id",
+ "created_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "bot_profile_versions_bot_id_bot_profiles_id_fk": {
+ "name": "bot_profile_versions_bot_id_bot_profiles_id_fk",
+ "tableFrom": "bot_profile_versions",
+ "tableTo": "bot_profiles",
+ "columnsFrom": [
+ "bot_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "bot_profiles": {
+ "name": "bot_profiles",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "display_name": {
+ "name": "display_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "avatar": {
+ "name": "avatar",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'🤖'"
+ },
+ "avatar_color": {
+ "name": "avatar_color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'violet'"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'active'"
+ },
+ "hidden_at": {
+ "name": "hidden_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pinned_at": {
+ "name": "pinned_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "attention_reason": {
+ "name": "attention_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "attention_at": {
+ "name": "attention_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "current_version": {
+ "name": "current_version",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 1
+ },
+ "canonical_session_id": {
+ "name": "canonical_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_bot_profiles_status_updated": {
+ "name": "idx_bot_profiles_status_updated",
+ "columns": [
+ "status",
+ "updated_at"
+ ],
+ "isUnique": false
+ },
+ "idx_bot_profiles_canonical_session": {
+ "name": "idx_bot_profiles_canonical_session",
+ "columns": [
+ "canonical_session_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "bot_profiles_canonical_session_id_sessions_id_fk": {
+ "name": "bot_profiles_canonical_session_id_sessions_id_fk",
+ "tableFrom": "bot_profiles",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "canonical_session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "bot_runtime_snapshots": {
+ "name": "bot_runtime_snapshots",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bot_id": {
+ "name": "bot_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "profile_version": {
+ "name": "profile_version",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "working_dir": {
+ "name": "working_dir",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "memory_scope_key": {
+ "name": "memory_scope_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "configured_json": {
+ "name": "configured_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "resolved_json": {
+ "name": "resolved_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "prepared_at": {
+ "name": "prepared_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "applied_at": {
+ "name": "applied_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "failed_at": {
+ "name": "failed_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "failure_json": {
+ "name": "failure_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_bot_runtime_snapshots_bot_prepared": {
+ "name": "idx_bot_runtime_snapshots_bot_prepared",
+ "columns": [
+ "bot_id",
+ "prepared_at"
+ ],
+ "isUnique": false
+ },
+ "idx_bot_runtime_snapshots_session_prepared": {
+ "name": "idx_bot_runtime_snapshots_session_prepared",
+ "columns": [
+ "session_id",
+ "prepared_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "bot_runtime_snapshots_bot_id_bot_profiles_id_fk": {
+ "name": "bot_runtime_snapshots_bot_id_bot_profiles_id_fk",
+ "tableFrom": "bot_runtime_snapshots",
+ "tableTo": "bot_profiles",
+ "columnsFrom": [
+ "bot_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "bot_runtime_snapshots_session_id_sessions_id_fk": {
+ "name": "bot_runtime_snapshots_session_id_sessions_id_fk",
+ "tableFrom": "bot_runtime_snapshots",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "bot_session_links": {
+ "name": "bot_session_links",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bot_id": {
+ "name": "bot_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "profile_version": {
+ "name": "profile_version",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 1
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "route_key": {
+ "name": "route_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "archived_at": {
+ "name": "archived_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_bot_session_links_session": {
+ "name": "uniq_bot_session_links_session",
+ "columns": [
+ "session_id"
+ ],
+ "isUnique": true
+ },
+ "uniq_bot_session_links_canonical_per_bot": {
+ "name": "uniq_bot_session_links_canonical_per_bot",
+ "columns": [
+ "bot_id"
+ ],
+ "isUnique": true,
+ "where": "\"bot_session_links\".\"role\" = 'canonical'"
+ },
+ "idx_bot_session_links_bot_role": {
+ "name": "idx_bot_session_links_bot_role",
+ "columns": [
+ "bot_id",
+ "role"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "bot_session_links_bot_id_bot_profiles_id_fk": {
+ "name": "bot_session_links_bot_id_bot_profiles_id_fk",
+ "tableFrom": "bot_session_links",
+ "tableTo": "bot_profiles",
+ "columnsFrom": [
+ "bot_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "bot_session_links_session_id_sessions_id_fk": {
+ "name": "bot_session_links_session_id_sessions_id_fk",
+ "tableFrom": "bot_session_links",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "custom_mcp_servers": {
+ "name": "custom_mcp_servers",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "transport": {
+ "name": "transport",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "url": {
+ "name": "url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "headers": {
+ "name": "headers",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "sort_order": {
+ "name": "sort_order",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_custom_mcp_servers_sort_order": {
+ "name": "idx_custom_mcp_servers_sort_order",
+ "columns": [
+ "sort_order"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "custom_providers": {
+ "name": "custom_providers",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "runtimes": {
+ "name": "runtimes",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "auth": {
+ "name": "auth",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "sort_order": {
+ "name": "sort_order",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_custom_providers_sort_order": {
+ "name": "idx_custom_providers_sort_order",
+ "columns": [
+ "sort_order"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "daily_model_usage": {
+ "name": "daily_model_usage",
+ "columns": {
+ "day": {
+ "name": "day",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "model": {
+ "name": "model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "cost_usd": {
+ "name": "cost_usd",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "cost_amount": {
+ "name": "cost_amount",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "cost_currency": {
+ "name": "cost_currency",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'USD'"
+ },
+ "cost_is_approximate": {
+ "name": "cost_is_approximate",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "input_tokens": {
+ "name": "input_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "output_tokens": {
+ "name": "output_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "cache_read_tokens": {
+ "name": "cache_read_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "cache_create_tokens": {
+ "name": "cache_create_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "daily_model_usage_day_agent_kind_model_cost_currency_pk": {
+ "columns": [
+ "day",
+ "agent_kind",
+ "model",
+ "cost_currency"
+ ],
+ "name": "daily_model_usage_day_agent_kind_model_cost_currency_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "daily_session_usage": {
+ "name": "daily_session_usage",
+ "columns": {
+ "day": {
+ "name": "day",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tokens": {
+ "name": "tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "daily_session_usage_day_session_id_pk": {
+ "columns": [
+ "day",
+ "session_id"
+ ],
+ "name": "daily_session_usage_day_session_id_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "daily_spend": {
+ "name": "daily_spend",
+ "columns": {
+ "day": {
+ "name": "day",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "cost_usd": {
+ "name": "cost_usd",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "cost_amount": {
+ "name": "cost_amount",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "cost_currency": {
+ "name": "cost_currency",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'USD'"
+ },
+ "cost_is_approximate": {
+ "name": "cost_is_approximate",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "daily_spend_day_cost_currency_pk": {
+ "columns": [
+ "day",
+ "cost_currency"
+ ],
+ "name": "daily_spend_day_cost_currency_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "device_link_ownership": {
+ "name": "device_link_ownership",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "owner_id": {
+ "name": "owner_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "owner_pid": {
+ "name": "owner_pid",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "owner_label": {
+ "name": "owner_label",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "heartbeat_at": {
+ "name": "heartbeat_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "embedding_jobs": {
+ "name": "embedding_jobs",
+ "columns": {
+ "rowid": {
+ "name": "rowid",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "source_id": {
+ "name": "source_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "chunk_index": {
+ "name": "chunk_index",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "model_id": {
+ "name": "model_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "vec_table": {
+ "name": "vec_table",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "attempts": {
+ "name": "attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "last_error": {
+ "name": "last_error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "scheduled_at": {
+ "name": "scheduled_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "locked_at": {
+ "name": "locked_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_embedding_jobs_natural": {
+ "name": "uniq_embedding_jobs_natural",
+ "columns": [
+ "source",
+ "source_id",
+ "chunk_index",
+ "model_id"
+ ],
+ "isUnique": true
+ },
+ "idx_embedding_jobs_status_scheduled": {
+ "name": "idx_embedding_jobs_status_scheduled",
+ "columns": [
+ "status",
+ "scheduled_at"
+ ],
+ "isUnique": false
+ },
+ "idx_embedding_jobs_source_id": {
+ "name": "idx_embedding_jobs_source_id",
+ "columns": [
+ "source",
+ "source_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "embedding_meta": {
+ "name": "embedding_meta",
+ "columns": {
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "ghost_cards": {
+ "name": "ghost_cards",
+ "columns": {
+ "call_id": {
+ "name": "call_id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ghost_id": {
+ "name": "ghost_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "html": {
+ "name": "html",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "height": {
+ "name": "height",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "v": {
+ "name": "v",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 1
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "ghost_cards_updated_at_idx": {
+ "name": "ghost_cards_updated_at_idx",
+ "columns": [
+ "updated_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "hook_group_context_cursors": {
+ "name": "hook_group_context_cursors",
+ "columns": {
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "cursor_key": {
+ "name": "cursor_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "cursor_id": {
+ "name": "cursor_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "hook_group_context_cursors_updated_at_idx": {
+ "name": "hook_group_context_cursors_updated_at_idx",
+ "columns": [
+ "updated_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "hook_group_context_cursors_provider_cursor_key_pk": {
+ "columns": [
+ "provider",
+ "cursor_key"
+ ],
+ "name": "hook_group_context_cursors_provider_cursor_key_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "hook_group_message_stats": {
+ "name": "hook_group_message_stats",
+ "columns": {
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "row_count": {
+ "name": "row_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "text_bytes": {
+ "name": "text_bytes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "hook_group_messages": {
+ "name": "hook_group_messages",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "chat_id": {
+ "name": "chat_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "thread_id": {
+ "name": "thread_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "message_id": {
+ "name": "message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "chat_name": {
+ "name": "chat_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "author": {
+ "name": "author",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "is_bot": {
+ "name": "is_bot",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "text": {
+ "name": "text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "file_names": {
+ "name": "file_names",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "sent_at": {
+ "name": "sent_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "hook_group_messages_msg_idx": {
+ "name": "hook_group_messages_msg_idx",
+ "columns": [
+ "provider",
+ "chat_id",
+ "thread_id",
+ "message_id"
+ ],
+ "isUnique": true
+ },
+ "hook_group_messages_window_idx": {
+ "name": "hook_group_messages_window_idx",
+ "columns": [
+ "provider",
+ "chat_id",
+ "thread_id",
+ "id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "im_bindings": {
+ "name": "im_bindings",
+ "columns": {
+ "channel": {
+ "name": "channel",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bot_context_id": {
+ "name": "bot_context_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "scope_key": {
+ "name": "scope_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "target_session_id": {
+ "name": "target_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "attached_at": {
+ "name": "attached_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "attached_via_card_message_id": {
+ "name": "attached_via_card_message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_im_bindings_target": {
+ "name": "idx_im_bindings_target",
+ "columns": [
+ "target_session_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "im_bindings_target_session_id_sessions_id_fk": {
+ "name": "im_bindings_target_session_id_sessions_id_fk",
+ "tableFrom": "im_bindings",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "target_session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "im_bindings_channel_bot_context_id_user_id_scope_key_pk": {
+ "columns": [
+ "channel",
+ "bot_context_id",
+ "user_id",
+ "scope_key"
+ ],
+ "name": "im_bindings_channel_bot_context_id_user_id_scope_key_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "im_notification_origins": {
+ "name": "im_notification_origins",
+ "columns": {
+ "channel": {
+ "name": "channel",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bot_context_id": {
+ "name": "bot_context_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "message_id": {
+ "name": "message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "chat_id": {
+ "name": "chat_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "im_notification_origins_channel_bot_context_id_user_id_message_id_pk": {
+ "columns": [
+ "channel",
+ "bot_context_id",
+ "user_id",
+ "message_id"
+ ],
+ "name": "im_notification_origins_channel_bot_context_id_user_id_message_id_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "media_blobs": {
+ "name": "media_blobs",
+ "columns": {
+ "hash": {
+ "name": "hash",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ext": {
+ "name": "ext",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "mime_type": {
+ "name": "mime_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bytes": {
+ "name": "bytes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "is_cache": {
+ "name": "is_cache",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "last_access_at": {
+ "name": "last_access_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "media_invocations": {
+ "name": "media_invocations",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "owner": {
+ "name": "owner",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "model_id": {
+ "name": "model_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "capability": {
+ "name": "capability",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "guide_revision": {
+ "name": "guide_revision",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "guide_json": {
+ "name": "guide_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "state": {
+ "name": "state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "response_json": {
+ "name": "response_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "media_invocations_owner_created_at_idx": {
+ "name": "media_invocations_owner_created_at_idx",
+ "columns": [
+ "owner",
+ "created_at"
+ ],
+ "isUnique": false
+ },
+ "media_invocations_owner_state_idx": {
+ "name": "media_invocations_owner_state_idx",
+ "columns": [
+ "owner",
+ "state"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "media_refs": {
+ "name": "media_refs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "hash": {
+ "name": "hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ref_kind": {
+ "name": "ref_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ref_id": {
+ "name": "ref_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "origin_session_id": {
+ "name": "origin_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "origin_kind": {
+ "name": "origin_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "origin_id": {
+ "name": "origin_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "label": {
+ "name": "label",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "media_refs_hash_idx": {
+ "name": "media_refs_hash_idx",
+ "columns": [
+ "hash"
+ ],
+ "isUnique": false
+ },
+ "media_refs_ref_idx": {
+ "name": "media_refs_ref_idx",
+ "columns": [
+ "ref_kind",
+ "ref_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "media_refs_hash_media_blobs_hash_fk": {
+ "name": "media_refs_hash_media_blobs_hash_fk",
+ "tableFrom": "media_refs",
+ "tableTo": "media_blobs",
+ "columnsFrom": [
+ "hash"
+ ],
+ "columnsTo": [
+ "hash"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "messages": {
+ "name": "messages",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tool_use_id": {
+ "name": "tool_use_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "agent_meta": {
+ "name": "agent_meta",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "rewind_at": {
+ "name": "rewind_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_messages_session_client": {
+ "name": "uniq_messages_session_client",
+ "columns": [
+ "session_id",
+ "client_id"
+ ],
+ "isUnique": true
+ },
+ "idx_messages_session_created": {
+ "name": "idx_messages_session_created",
+ "columns": [
+ "session_id",
+ "created_at"
+ ],
+ "isUnique": false
+ },
+ "idx_messages_created_at": {
+ "name": "idx_messages_created_at",
+ "columns": [
+ "created_at",
+ "id"
+ ],
+ "isUnique": false
+ },
+ "idx_messages_rewind_at": {
+ "name": "idx_messages_rewind_at",
+ "columns": [
+ "rewind_at"
+ ],
+ "isUnique": false
+ },
+ "idx_messages_active_error_tail": {
+ "name": "idx_messages_active_error_tail",
+ "columns": [
+ "session_id",
+ "created_at"
+ ],
+ "isUnique": false,
+ "where": "\"messages\".\"role\" = 'error' AND \"messages\".\"rewind_at\" IS NULL"
+ }
+ },
+ "foreignKeys": {
+ "messages_session_id_sessions_id_fk": {
+ "name": "messages_session_id_sessions_id_fk",
+ "tableFrom": "messages",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "messages_fts_rows": {
+ "name": "messages_fts_rows",
+ "columns": {
+ "fts_rowid": {
+ "name": "fts_rowid",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "message_id": {
+ "name": "message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "messages_fts_rows_message_id_idx": {
+ "name": "messages_fts_rows_message_id_idx",
+ "columns": [
+ "message_id"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "migration_history": {
+ "name": "migration_history",
+ "columns": {
+ "seq": {
+ "name": "seq",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "file_name": {
+ "name": "file_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "content_hash": {
+ "name": "content_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "applied_at": {
+ "name": "applied_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "migration_meta": {
+ "name": "migration_meta",
+ "columns": {
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "orca_teams": {
+ "name": "orca_teams",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "lead_session_id": {
+ "name": "lead_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'active'"
+ },
+ "completed_at": {
+ "name": "completed_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_active_team_per_lead": {
+ "name": "uniq_active_team_per_lead",
+ "columns": [
+ "lead_session_id"
+ ],
+ "isUnique": true,
+ "where": "\"orca_teams\".\"status\" = 'active'"
+ },
+ "idx_orca_teams_status": {
+ "name": "idx_orca_teams_status",
+ "columns": [
+ "status"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "orca_teams_lead_session_id_sessions_id_fk": {
+ "name": "orca_teams_lead_session_id_sessions_id_fk",
+ "tableFrom": "orca_teams",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "lead_session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "orca_worker_creation_reservations": {
+ "name": "orca_worker_creation_reservations",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "team_id": {
+ "name": "team_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "label": {
+ "name": "label",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_orca_worker_creation_reservations_team_label": {
+ "name": "uniq_orca_worker_creation_reservations_team_label",
+ "columns": [
+ "team_id",
+ "lower(\"label\")"
+ ],
+ "isUnique": true
+ },
+ "idx_orca_worker_creation_reservations_expires_at": {
+ "name": "idx_orca_worker_creation_reservations_expires_at",
+ "columns": [
+ "expires_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "orca_worker_creation_reservations_team_id_orca_teams_id_fk": {
+ "name": "orca_worker_creation_reservations_team_id_orca_teams_id_fk",
+ "tableFrom": "orca_worker_creation_reservations",
+ "tableTo": "orca_teams",
+ "columnsFrom": [
+ "team_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "orca_workers": {
+ "name": "orca_workers",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "team_id": {
+ "name": "team_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'idle'"
+ },
+ "label": {
+ "name": "label",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "worktree_branch": {
+ "name": "worktree_branch",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'developer'"
+ },
+ "focused": {
+ "name": "focused",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "idle_since": {
+ "name": "idle_since",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_orca_workers_session_id": {
+ "name": "uniq_orca_workers_session_id",
+ "columns": [
+ "session_id"
+ ],
+ "isUnique": true
+ },
+ "uniq_orca_workers_team_label": {
+ "name": "uniq_orca_workers_team_label",
+ "columns": [
+ "team_id",
+ "lower(\"label\")"
+ ],
+ "isUnique": true
+ },
+ "uniq_orca_workers_focused_per_team": {
+ "name": "uniq_orca_workers_focused_per_team",
+ "columns": [
+ "team_id"
+ ],
+ "isUnique": true,
+ "where": "\"orca_workers\".\"focused\" = true"
+ },
+ "idx_orca_workers_team_id": {
+ "name": "idx_orca_workers_team_id",
+ "columns": [
+ "team_id"
+ ],
+ "isUnique": false
+ },
+ "idx_orca_workers_status": {
+ "name": "idx_orca_workers_status",
+ "columns": [
+ "status"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "orca_workers_team_id_orca_teams_id_fk": {
+ "name": "orca_workers_team_id_orca_teams_id_fk",
+ "tableFrom": "orca_workers",
+ "tableTo": "orca_teams",
+ "columnsFrom": [
+ "team_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "orca_workers_session_id_sessions_id_fk": {
+ "name": "orca_workers_session_id_sessions_id_fk",
+ "tableFrom": "orca_workers",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "plugin_task_requests": {
+ "name": "plugin_task_requests",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "plugin_id": {
+ "name": "plugin_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "operation": {
+ "name": "operation",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "target_id": {
+ "name": "target_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "request_key": {
+ "name": "request_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "fingerprint": {
+ "name": "fingerprint",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "payload": {
+ "name": "payload",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "revision": {
+ "name": "revision",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "plugin_task_request_key": {
+ "name": "plugin_task_request_key",
+ "columns": [
+ "plugin_id",
+ "operation",
+ "target_id",
+ "request_key"
+ ],
+ "isUnique": true
+ },
+ "plugin_task_target": {
+ "name": "plugin_task_target",
+ "columns": [
+ "target_id",
+ "plugin_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "project_aliases": {
+ "name": "project_aliases",
+ "columns": {
+ "project_key": {
+ "name": "project_key",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "alias": {
+ "name": "alias",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_project_aliases_updated_at": {
+ "name": "idx_project_aliases_updated_at",
+ "columns": [
+ "updated_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "project_automation_consents": {
+ "name": "project_automation_consents",
+ "columns": {
+ "working_dir": {
+ "name": "working_dir",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "consented_at": {
+ "name": "consented_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "config_hash": {
+ "name": "config_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "recent_workdirs": {
+ "name": "recent_workdirs",
+ "columns": {
+ "path": {
+ "name": "path",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "last_used_at": {
+ "name": "last_used_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_recent_workdirs_last_used_at": {
+ "name": "idx_recent_workdirs_last_used_at",
+ "columns": [
+ "last_used_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "right_sidebar_tabs": {
+ "name": "right_sidebar_tabs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "position": {
+ "name": "position",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "is_active": {
+ "name": "is_active",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "state": {
+ "name": "state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "right_sidebar_tabs_session_idx": {
+ "name": "right_sidebar_tabs_session_idx",
+ "columns": [
+ "session_id",
+ "position"
+ ],
+ "isUnique": false
+ },
+ "right_sidebar_tabs_subagents_singleton_idx": {
+ "name": "right_sidebar_tabs_subagents_singleton_idx",
+ "columns": [
+ "session_id"
+ ],
+ "isUnique": true,
+ "where": "\"right_sidebar_tabs\".\"kind\" = 'subagents'"
+ },
+ "right_sidebar_tabs_bot_artifacts_singleton_idx": {
+ "name": "right_sidebar_tabs_bot_artifacts_singleton_idx",
+ "columns": [
+ "session_id"
+ ],
+ "isUnique": true,
+ "where": "\"right_sidebar_tabs\".\"kind\" = 'bot-artifacts'"
+ }
+ },
+ "foreignKeys": {
+ "right_sidebar_tabs_session_id_sessions_id_fk": {
+ "name": "right_sidebar_tabs_session_id_sessions_id_fk",
+ "tableFrom": "right_sidebar_tabs",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "schedule_runs": {
+ "name": "schedule_runs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "schedule_id": {
+ "name": "schedule_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "fired_at": {
+ "name": "fired_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "finished_at": {
+ "name": "finished_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "error_msg": {
+ "name": "error_msg",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "cost_usd": {
+ "name": "cost_usd",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "estimated_value_usd": {
+ "name": "estimated_value_usd",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "cost_amount": {
+ "name": "cost_amount",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "estimated_value_amount": {
+ "name": "estimated_value_amount",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "cost_currency": {
+ "name": "cost_currency",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "cost_is_approximate": {
+ "name": "cost_is_approximate",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "cost_attribution": {
+ "name": "cost_attribution",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'legacy'"
+ },
+ "result_text": {
+ "name": "result_text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pre_run_hook_result": {
+ "name": "pre_run_hook_result",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "read_at": {
+ "name": "read_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "heartbeat_at": {
+ "name": "heartbeat_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_schedule_runs_schedule": {
+ "name": "idx_schedule_runs_schedule",
+ "columns": [
+ "schedule_id",
+ "fired_at"
+ ],
+ "isUnique": false
+ },
+ "idx_schedule_runs_running_schedule": {
+ "name": "idx_schedule_runs_running_schedule",
+ "columns": [
+ "schedule_id"
+ ],
+ "isUnique": false,
+ "where": "\"schedule_runs\".\"status\" = 'running'"
+ },
+ "idx_schedule_runs_running_heartbeat": {
+ "name": "idx_schedule_runs_running_heartbeat",
+ "columns": [
+ "heartbeat_at"
+ ],
+ "isUnique": false,
+ "where": "\"schedule_runs\".\"status\" = 'running' AND \"schedule_runs\".\"heartbeat_at\" IS NOT NULL"
+ },
+ "idx_schedule_runs_running_legacy": {
+ "name": "idx_schedule_runs_running_legacy",
+ "columns": [
+ "fired_at"
+ ],
+ "isUnique": false,
+ "where": "\"schedule_runs\".\"status\" = 'running' AND \"schedule_runs\".\"heartbeat_at\" IS NULL"
+ },
+ "idx_schedule_runs_unread_terminal": {
+ "name": "idx_schedule_runs_unread_terminal",
+ "columns": [
+ "schedule_id",
+ "status",
+ "fired_at"
+ ],
+ "isUnique": false,
+ "where": "\"schedule_runs\".\"read_at\" IS NULL AND \"schedule_runs\".\"status\" IN ('success', 'failed', 'aborted', 'interrupted')"
+ },
+ "idx_schedule_runs_session_latest": {
+ "name": "idx_schedule_runs_session_latest",
+ "columns": [
+ "session_id",
+ "fired_at",
+ "id"
+ ],
+ "isUnique": false,
+ "where": "\"schedule_runs\".\"session_id\" IS NOT NULL"
+ }
+ },
+ "foreignKeys": {
+ "schedule_runs_schedule_id_schedules_id_fk": {
+ "name": "schedule_runs_schedule_id_schedules_id_fk",
+ "tableFrom": "schedule_runs",
+ "tableTo": "schedules",
+ "columnsFrom": [
+ "schedule_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "schedule_runs_session_id_sessions_id_fk": {
+ "name": "schedule_runs_session_id_sessions_id_fk",
+ "tableFrom": "schedule_runs",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "schedule_session_latest_runs": {
+ "name": "schedule_session_latest_runs",
+ "columns": {
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "run_id": {
+ "name": "run_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "fired_at": {
+ "name": "fired_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_schedule_session_latest_runs_run": {
+ "name": "idx_schedule_session_latest_runs_run",
+ "columns": [
+ "run_id"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "schedule_session_latest_runs_session_id_sessions_id_fk": {
+ "name": "schedule_session_latest_runs_session_id_sessions_id_fk",
+ "tableFrom": "schedule_session_latest_runs",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "schedule_session_latest_runs_run_id_schedule_runs_id_fk": {
+ "name": "schedule_session_latest_runs_run_id_schedule_runs_id_fk",
+ "tableFrom": "schedule_session_latest_runs",
+ "tableTo": "schedule_runs",
+ "columnsFrom": [
+ "run_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "schedules": {
+ "name": "schedules",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "prompt": {
+ "name": "prompt",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "job_type": {
+ "name": "job_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'prompt'"
+ },
+ "job_config": {
+ "name": "job_config",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "execution_mode": {
+ "name": "execution_mode",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'agent'"
+ },
+ "script_config": {
+ "name": "script_config",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "'user'"
+ },
+ "project_config_id": {
+ "name": "project_config_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "legacy_session_fallback": {
+ "name": "legacy_session_fallback",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'cron'"
+ },
+ "cron_expr": {
+ "name": "cron_expr",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "timezone": {
+ "name": "timezone",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "recurring": {
+ "name": "recurring",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": true
+ },
+ "manual": {
+ "name": "manual",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "interval_ms": {
+ "name": "interval_ms",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "model_agent_kind": {
+ "name": "model_agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "model": {
+ "name": "model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "provider_id": {
+ "name": "provider_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "effort": {
+ "name": "effort",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "fast_mode": {
+ "name": "fast_mode",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "working_dir": {
+ "name": "working_dir",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "workspace_kind": {
+ "name": "workspace_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'project'"
+ },
+ "use_worktree": {
+ "name": "use_worktree",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "target_session_id": {
+ "name": "target_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "persistent_session": {
+ "name": "persistent_session",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "silent_when_idle": {
+ "name": "silent_when_idle",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "pre_run_hook_command": {
+ "name": "pre_run_hook_command",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pre_run_hook_timeout_ms": {
+ "name": "pre_run_hook_timeout_ms",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "skip_log_session_id": {
+ "name": "skip_log_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "notify_desktop": {
+ "name": "notify_desktop",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": true
+ },
+ "notify_feishu": {
+ "name": "notify_feishu",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "notify_wecom_group": {
+ "name": "notify_wecom_group",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'active'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "last_fired_at": {
+ "name": "last_fired_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_finished_at": {
+ "name": "last_finished_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "next_fire_at": {
+ "name": "next_fire_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "expire_at": {
+ "name": "expire_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_schedules_active_next": {
+ "name": "idx_schedules_active_next",
+ "columns": [
+ "status",
+ "next_fire_at"
+ ],
+ "isUnique": false
+ },
+ "idx_schedules_target_session": {
+ "name": "idx_schedules_target_session",
+ "columns": [
+ "target_session_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "schedules_target_session_id_sessions_id_fk": {
+ "name": "schedules_target_session_id_sessions_id_fk",
+ "tableFrom": "schedules",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "target_session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "schedules_skip_log_session_id_sessions_id_fk": {
+ "name": "schedules_skip_log_session_id_sessions_id_fk",
+ "tableFrom": "schedules",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "skip_log_session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "session_goals": {
+ "name": "session_goals",
+ "columns": {
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "objective": {
+ "name": "objective",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'active'"
+ },
+ "budget_tokens": {
+ "name": "budget_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "max_turns": {
+ "name": "max_turns",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "no_progress_limit": {
+ "name": "no_progress_limit",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "turns_used": {
+ "name": "turns_used",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "tokens_used": {
+ "name": "tokens_used",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "no_progress_streak": {
+ "name": "no_progress_streak",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "usage_reset_at": {
+ "name": "usage_reset_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_reason": {
+ "name": "last_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_session_goals_status": {
+ "name": "idx_session_goals_status",
+ "columns": [
+ "status"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "session_goals_session_id_sessions_id_fk": {
+ "name": "session_goals_session_id_sessions_id_fk",
+ "tableFrom": "session_goals",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "session_pr_refs": {
+ "name": "session_pr_refs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "owner": {
+ "name": "owner",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "repo": {
+ "name": "repo",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "pr_number": {
+ "name": "pr_number",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "url": {
+ "name": "url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "first_seen_at": {
+ "name": "first_seen_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "last_seen_at": {
+ "name": "last_seen_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_session_pr_refs": {
+ "name": "uniq_session_pr_refs",
+ "columns": [
+ "session_id",
+ "owner",
+ "repo",
+ "pr_number"
+ ],
+ "isUnique": true
+ },
+ "idx_session_pr_refs_session_last_seen": {
+ "name": "idx_session_pr_refs_session_last_seen",
+ "columns": [
+ "session_id",
+ "last_seen_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "session_pr_refs_session_id_sessions_id_fk": {
+ "name": "session_pr_refs_session_id_sessions_id_fk",
+ "tableFrom": "session_pr_refs",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "session_task_tags": {
+ "name": "session_task_tags",
+ "columns": {
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tag_id": {
+ "name": "tag_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "session_task_tags_tag_idx": {
+ "name": "session_task_tags_tag_idx",
+ "columns": [
+ "tag_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "session_task_tags_session_id_sessions_id_fk": {
+ "name": "session_task_tags_session_id_sessions_id_fk",
+ "tableFrom": "session_task_tags",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "session_task_tags_tag_id_task_tags_id_fk": {
+ "name": "session_task_tags_tag_id_task_tags_id_fk",
+ "tableFrom": "session_task_tags",
+ "tableTo": "task_tags",
+ "columnsFrom": [
+ "tag_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "session_task_tags_session_id_tag_id_pk": {
+ "columns": [
+ "session_id",
+ "tag_id"
+ ],
+ "name": "session_task_tags_session_id_tag_id_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "sessions": {
+ "name": "sessions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'New Maker'"
+ },
+ "working_dir": {
+ "name": "working_dir",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "workspace_kind": {
+ "name": "workspace_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'project'"
+ },
+ "model": {
+ "name": "model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'claude-sonnet-4-6'"
+ },
+ "effort": {
+ "name": "effort",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'high'"
+ },
+ "permission_mode": {
+ "name": "permission_mode",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'ask'"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'active'"
+ },
+ "sdk_session_id": {
+ "name": "sdk_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "total_token_usage": {
+ "name": "total_token_usage",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "total_cost_usd": {
+ "name": "total_cost_usd",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "total_cost_amount": {
+ "name": "total_cost_amount",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "total_cost_currency": {
+ "name": "total_cost_currency",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "total_cost_is_approximate": {
+ "name": "total_cost_is_approximate",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "context_tokens": {
+ "name": "context_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "context_window": {
+ "name": "context_window",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "context_window_runtime": {
+ "name": "context_window_runtime",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "fast_mode": {
+ "name": "fast_mode",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "plan_mode_enabled": {
+ "name": "plan_mode_enabled",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "cleared_at": {
+ "name": "cleared_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pinned_at": {
+ "name": "pinned_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "summary": {
+ "name": "summary",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "provider_id": {
+ "name": "provider_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "user_send_at": {
+ "name": "user_send_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'cc'"
+ },
+ "orca_role": {
+ "name": "orca_role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "parent_session_id": {
+ "name": "parent_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "forked_at_message_id": {
+ "name": "forked_at_message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "worktree_path": {
+ "name": "worktree_path",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'desktop'"
+ },
+ "feishu_open_id": {
+ "name": "feishu_open_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "feishu_bot_app_id": {
+ "name": "feishu_bot_app_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "im_bot_context_id": {
+ "name": "im_bot_context_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "im_user_id": {
+ "name": "im_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "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
+ },
+ "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 file
diff --git a/apps/desktop/drizzle/meta/_journal.json b/apps/desktop/drizzle/meta/_journal.json
index b574885fb8..f76e89c908 100644
--- a/apps/desktop/drizzle/meta/_journal.json
+++ b/apps/desktop/drizzle/meta/_journal.json
@@ -813,6 +813,13 @@
"when": 1790421361685,
"tag": "0115_silky_power_man",
"breakpoints": true
+ },
+ {
+ "idx": 116,
+ "version": "6",
+ "when": 1790435515244,
+ "tag": "0116_happy_eternity",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/taskSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/taskSlot.test.ts
new file mode 100644
index 0000000000..3ba34488e9
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/taskSlot.test.ts
@@ -0,0 +1,86 @@
+import { describe, expect, it, vi } from 'vitest';
+import { handlePluginTaskRequest, validPluginTaskRequest } from '../taskSlot.js';
+import type { InstalledGhost } from '../../../shared/ghost.js';
+
+describe('plugin task pipe', () => {
+ const ghost = { enabled: true, manifest: { agent: { tasks: true } } } as InstalledGhost;
+ it('requires its own declared capability; errand alone grants nothing', async () => {
+ const handler = vi.fn();
+ const result = await handlePluginTaskRequest(
+ 'p',
+ { type: 'tasks-request', kind: 'capabilities' },
+ {
+ getGhost: () => ({ ...ghost, manifest: { ...ghost.manifest, agent: { errand: true } } }),
+ handler,
+ isCurrent: () => true,
+ },
+ );
+ expect(result.ok).toBe(false);
+ expect(handler).not.toHaveBeenCalled();
+ });
+ it.each([
+ { type: 'tasks-request', kind: 'create', requestKey: 'a', title: 't', workingDir: '/private' },
+ {
+ type: 'tasks-request',
+ kind: 'send',
+ taskId: 's',
+ requestKey: 'a',
+ expectedRevision: 1,
+ text: 'hi',
+ permissionMode: 'bypassPermissions',
+ },
+ { type: 'tasks-request', kind: 'list', limit: 1000 },
+ { type: 'tasks-request', kind: 'get', taskId: 's', ghostId: 'other' },
+ { type: 'tasks-request', kind: '__proto__' },
+ ])('rejects unsupported/identity/permission fields', (payload) =>
+ expect(validPluginTaskRequest(payload)).toBe(false),
+ );
+ it('rechecks authorization after async work and redacts internal errors', async () => {
+ let current = true;
+ const result = await handlePluginTaskRequest(
+ 'p',
+ { type: 'tasks-request', kind: 'get', taskId: 't' },
+ {
+ getGhost: () => ghost,
+ isCurrent: () => current,
+ handler: async () => {
+ current = false;
+ return 'secret';
+ },
+ },
+ );
+ expect(result).toMatchObject({ ok: false, error: { code: 'PERMISSION_DENIED' } });
+ const error = await handlePluginTaskRequest(
+ 'p',
+ { type: 'tasks-request', kind: 'get', taskId: 't' },
+ {
+ getGhost: () => ghost,
+ isCurrent: () => true,
+ handler: async () => {
+ throw new Error('/sensitive/path');
+ },
+ },
+ );
+ expect(JSON.stringify(error)).not.toContain('/sensitive/path');
+ });
+});
+
+it('write access can only ask the host for a task, never supply a permission grant',()=>{
+ expect(validPluginTaskRequest({type:'tasks-request',kind:'requestWriteAccess',taskId:'own'})).toBe(true);
+ for(const extra of [{permissionMode:'auto'},{confirmed:true},{ghostId:'other'}]){
+ expect(validPluginTaskRequest({type:'tasks-request',kind:'requestWriteAccess',taskId:'own',...extra})).toBe(false);
+ }
+});
+
+it('collaboration methods accept only an owned task identifier, not permission overrides',()=>{
+ for(const kind of ['startTeam','getTeam']){
+ expect(validPluginTaskRequest({type:'tasks-request',kind,taskId:'own'})).toBe(true);
+ expect(validPluginTaskRequest({type:'tasks-request',kind,taskId:'own',workerPermissionMode:'auto'})).toBe(false);
+ }
+});
+
+it('allows an Auto request but never Full access', () => {
+ expect(validPluginTaskRequest({type:'tasks-request',kind:'requestWriteAccess',taskId:'own',mode:'auto'})).toBe(true);
+ expect(validPluginTaskRequest({type:'tasks-request',kind:'requestWriteAccess',taskId:'own',mode:'bypassPermissions'})).toBe(false);
+});
+
diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.ts
index 215bc6ea9f..1b5cc665f0 100644
--- a/apps/desktop/src/main/cindy-brain/forge.ts
+++ b/apps/desktop/src/main/cindy-brain/forge.ts
@@ -3897,6 +3897,53 @@ const r = await cindy.agent.requestSchedule({
什么时候**不该**用它:一次性的、当场就要结果的事,用快问快答(§4.0.2)或派活取件
(§4.11.1)。这个加档是给"长期定期刷新"用的,每条任务都会反复产生模型费用。
+### 4.11.3 普通任务接口(实验性)
+
+声明 \`"agent": { "tasks": true }\` 后,逻辑页可使用 \`cindy.tasks\`。它是独立权限,
+旧 \`errand\` 声明不自动取得该权限;用户仍可在侧边栏查看和接手这些任务。
+面板通过既有逻辑页通道调用,不获得新的 preload 或内部 IPC 权限。
+
+先调用 \`capabilities()\` 获取实际支持操作。当前仅支持本插件创建的本机普通任务:
+\`create\`、\`get\`、\`list\`、\`send\`、\`getRun\`、\`listRuns\`、\`readMessages\`、\`cancel\`。
+可对自有任务调用 \`startTeam({taskId})\` 启用 Orca 主任务,并用 \`getTeam({taskId})\` 读取实际协同状态。协调主任务需经用户授权 Auto,Worker 自动沿用 Auto。
+在首次派发前调用 \`setTeamPlan({taskId,plan:{concurrency,items}})\`,每项包含\`label, workingDir, route\`。计划冻结后不可改写。
+
+暂不支持选择现有任务、远程/伙伴任务、任意更新配置、归档、队列暂停或事件订阅。
+旧 \`agent.errand\` 接口不变。
+
+\`\`\`js
+// requestWriteAccess({taskId, mode: 'auto'}) 请求宿主原生确认,不能替用户确认。
+// 省略 mode 保留 acceptEdits;Auto 插件主任务的 Worker 使用 Auto,不改全局权限。
+
+const task = await cindy.tasks.create({ requestKey: 'experiment-1-create', title: 'My evaluation' });
+const run = await cindy.tasks.send({ taskId: task.taskId, expectedRevision: task.revision,
+ requestKey: 'experiment-1-send', text: 'Read the project and report your findings.' });
+const status = await cindy.tasks.getRun({ runId: run.runId });
+const page = await cindy.tasks.readMessages({ taskId: task.taskId, limit: 50 });
+// 保存 nextCursor;下一页传 after,不以最后一条 assistant 推断 run 已完成。
+\`\`\`
+
+SDK 成功返回 data,失败抛出带 code 的错误。原始管子响应为 \`{ok:true,data}\` 或
+\`{ok:false,error:{code,message,retryable}}\`。不要将请求键换掉来绕过不确定的派发结果。
+create/send 的 requestKey 持久去重;同键不同内容拒绝。删除后的记录不自动重建。
+请求键及 taskId/runId 需要由插件保存。取消仅作用于该输入,不能停止用户后来的执行。
+
+省略 route 时在接收时解析用户给本插件的 AI 配置;可显式传
+\`{agentKind:'codex',providerId:'...',model:'...',effort:'high',fastMode:false}\`。
+来源/模型/强度必须当前可用,派发前再次核对,不自动改用其它账号。
+工作目录由宿主分配,或沿用用户已在插件设置中选择的目录;不接受任意路径或权限覆盖。
+权限沿用 AI 代办配置,默认只读,禁止 bypassPermissions。
+create 可传 \`isolatedWorkspace:true\`,使用宿主为该任务生成的独立空目录,忽略插件的项目目录偏好。
+返回 workingDir 仅属于本插件创建的任务,可交给插件 Node 进程放入候选项目;不接受插件自报任意目录。
+任务视图同时返回 permissionMode,插件在只读时应明确提示,不能暗中升级权限。
+
+run 的 acceptedConfig 是接收配置,execution 是观测到的原生 instance/generation,
+不冒充完整实际用量/重试清单。outputMessageId 来自产品终态,不是文字猜测。
+没有足够证据的重启/恢复窗口返回 reconciling,不能当 completed、failed 或零分;
+不要自动重发可能已经产生副作用的输入。费用目前 unavailable,绝不以耗时推算。
+实验性接口尚未提供全部恢复路径的最终对账和事件补拉,因此暂不用于无人值守正式评测。
+
+
## 4.12 随包 Node 工作进程与 stdio MCP(node 能力)
插件需要随包代码、CLI、JS 依赖、可复用 worker 状态或 stdio MCP 时,使用顶层
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index dcc0cf0477..5064ac5fbd 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -1,6 +1,7 @@
import { getModelVisibilityOverride, waitForModelVisibilityMirror } from '../maker-host/model-visibility-mirror.js';
import { projectGhostAgentModels } from './ghostAgentModels.js';
import { getDesktopProviderService } from '../maker-host/createDesktopProviderService.js';
+import { handlePluginTaskRequest, type PluginTaskHandler } from './taskSlot.js';
import { registerGhostCardRemoteProvider, persistGhostCardWithRemoteChange } from './cardRemoteResource.js';
import { openDeviceAuthorizationCard, openPluginAuthorizationCard } from '../plugin-oauth/deviceCard.js';
import { t as authorizationText } from '../i18n.js';
@@ -1697,6 +1698,14 @@ export function setGhostSessionRevealer(reveal: ((sessionId: string) => void) |
getGhostErrandSlot().setRevealSession(reveal);
}
+let pluginTaskHandler: PluginTaskHandler | null = null;
+export function setPluginTaskHandler(handler: PluginTaskHandler | null): void { pluginTaskHandler = handler; }
+
+export function isPluginTaskAuthorized(id: string): boolean {
+ const ghost = findAvailableGhost(id);
+ return ghost?.enabled === true && ghost.manifest.agent?.tasks === true;
+}
+
let errandSlotSingleton: GhostErrandSlot | null = null;
/** 派活取件槽单例(agent 槽 errand 加档):资格审/频控/任务表的统一守门点。 */
@@ -7180,6 +7189,13 @@ export function registerGhostIpc(): void {
// 专属 errand 会话跑一轮,最终回复文字取回给插件;任务文本同样只进
// 普通 user 消息。资格审/频控/任务表在 errandSlot,会话与收口在注入
// 的 runner(maker-ipc)。
+ if (type === 'tasks-request') {
+ const owner = getActiveDataOwnerPushStamp();
+ return handlePluginTaskRequest(id, payload, {
+ getGhost: findAvailableGhost, handler: pluginTaskHandler,
+ isCurrent: () => { const current = getActiveDataOwnerPushStamp(); return owner.dataOwnerId === current.dataOwnerId && owner.ownerGeneration === current.ownerGeneration; },
+ });
+ }
if (type === 'agent-errand-request') {
return getGhostErrandSlot().handleRequest(id, payload);
}
diff --git a/apps/desktop/src/main/cindy-brain/taskSlot.ts b/apps/desktop/src/main/cindy-brain/taskSlot.ts
new file mode 100644
index 0000000000..6af1218463
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/taskSlot.ts
@@ -0,0 +1,156 @@
+import type { InstalledGhost } from '../../shared/ghost.js';
+import type { PluginTaskRequest, PluginTaskResult } from '../../shared/pluginTasks.js';
+
+export const PLUGIN_TASK_OPERATIONS = [
+ 'capabilities',
+ 'requestWriteAccess',
+ 'startTeam',
+ 'getTeam',
+ 'setTeamPlan',
+ 'releaseWorker',
+ 'create',
+ 'list',
+ 'get',
+ 'send',
+ 'getRun',
+ 'listRuns',
+ 'cancel',
+ 'readMessages',
+] as const;
+export type PluginTaskHandler = (pluginId: string, request: PluginTaskRequest) => Promise<unknown>;
+const object = (v: unknown): v is Record<string, unknown> =>
+ !!v && typeof v === 'object' && !Array.isArray(v);
+const text = (v: unknown, max: number) =>
+ typeof v === 'string' && v.trim().length > 0 && v.length <= max;
+export function validPluginTaskRequest(value: unknown): value is PluginTaskRequest {
+ if (!object(value) || value.type !== 'tasks-request') return false;
+ const allowed: Record<string, string[]> = {
+ capabilities: [],
+ create: ['requestKey', 'title', 'route', 'isolatedWorkspace'],
+ list: ['after', 'limit'],
+ get: ['taskId'],
+ requestWriteAccess: ['taskId', 'mode'],
+ startTeam: ['taskId'],
+ getTeam: ['taskId'],
+ setTeamPlan: ['taskId', 'plan'],
+ releaseWorker: ['taskId', 'workerId', 'completedAt'],
+ send: ['taskId', 'requestKey', 'expectedRevision', 'text'],
+ getRun: ['runId'],
+ listRuns: ['taskId', 'after', 'limit'],
+ readMessages: ['taskId', 'after', 'limit'],
+ cancel: ['runId', 'requestKey'],
+ };
+ if (typeof value.kind !== 'string' || !Object.hasOwn(allowed, value.kind)) return false;
+ const kind = value.kind;
+ if (Object.keys(value).some((key) => !['type', 'kind', ...allowed[kind]].includes(key)))
+ return false;
+ if (kind === 'requestWriteAccess' && value.mode !== undefined && !['acceptEdits', 'auto'].includes(String(value.mode))) return false;
+ const requires = (key: string) => text(value[key], 128);
+ if (['create', 'send', 'cancel'].includes(value.kind) && !requires('requestKey')) return false;
+ if (['get', 'send', 'listRuns', 'readMessages', 'requestWriteAccess', 'startTeam', 'getTeam', 'setTeamPlan', 'releaseWorker'].includes(value.kind) && !requires('taskId'))
+ return false;
+ if (['getRun', 'cancel'].includes(value.kind) && !requires('runId')) return false;
+ if (value.isolatedWorkspace !== undefined && typeof value.isolatedWorkspace !== 'boolean') return false;
+ if (value.kind === 'create' && !text(value.title, 100)) return false;
+ if (
+ value.kind === 'send' &&
+ (!text(value.text, 32768) ||
+ !Number.isSafeInteger(value.expectedRevision) ||
+ (value.expectedRevision as number) < 0)
+ )
+ return false;
+ if (value.after !== undefined && !text(value.after, 1024)) return false;
+ if (
+ value.limit !== undefined &&
+ (!Number.isInteger(value.limit) || (value.limit as number) < 1 || (value.limit as number) > 100)
+ )
+ return false;
+ if (kind === 'releaseWorker' && (!requires('workerId') || !Number.isSafeInteger(value.completedAt) || (value.completedAt as number) <= 0)) return false;
+ if (kind === 'setTeamPlan') {
+ const p = value.plan;
+ if (!object(p) || Object.keys(p).some(k => !['concurrency','items'].includes(k)) ||
+ (p.concurrency !== null && (!Number.isSafeInteger(p.concurrency) || (p.concurrency as number) < 1)) ||
+ !Array.isArray(p.items) || !p.items.length || p.items.length > 1000) return false;
+ const labels = new Set<string>();
+ for (const item of p.items) {
+ if (!object(item) || Object.keys(item).some(k => !['label','workingDir','route'].includes(k)) ||
+ !text(item.label,32) || !/^[a-z0-9][a-z0-9_-]*$/.test(String(item.label)) || labels.has(String(item.label)) || !text(item.workingDir,4096) ||
+ !validPluginTaskRequest({type:'tasks-request',kind:'create',requestKey:'validate',title:'validate',route:item.route}) || !item.route) return false;
+ labels.add(String(item.label));
+ }
+ }
+ if (value.route !== undefined) {
+ const r = value.route;
+ if (
+ !object(r) ||
+ Object.keys(r).some(
+ (k) => !['agentKind', 'providerId', 'model', 'effort', 'fastMode'].includes(k),
+ )
+ )
+ return false;
+ if (
+ !['cc', 'codex', 'pi'].includes(String(r.agentKind)) ||
+ !text(r.providerId, 128) ||
+ !text(r.model, 256) ||
+ !text(r.effort, 32) ||
+ typeof r.fastMode !== 'boolean'
+ )
+ return false;
+ }
+ return true;
+}
+
+/** Sender binding is performed by the pipe; the payload can never claim a plugin identity. */
+export async function handlePluginTaskRequest(
+ pluginId: string,
+ value: unknown,
+ deps: {
+ getGhost(id: string): InstalledGhost | null;
+ handler: PluginTaskHandler | null;
+ isCurrent: () => boolean;
+ },
+): Promise<PluginTaskResult> {
+ const permitted = () =>
+ deps.isCurrent() &&
+ deps.getGhost(pluginId)?.enabled === true &&
+ deps.getGhost(pluginId)?.manifest.agent?.tasks === true;
+ const error = (code: string, message: string, retryable = false): PluginTaskResult => ({
+ ok: false,
+ error: { code, message, retryable },
+ });
+ if (!permitted()) return error('PERMISSION_DENIED', 'Plugin task capability is unavailable');
+ if (!validPluginTaskRequest(value)) return error('INVALID_REQUEST', 'Invalid task request');
+ if (value.kind === 'capabilities')
+ return {
+ ok: true,
+ data: {
+ version: 1,
+ experimental: true,
+ operations: PLUGIN_TASK_OPERATIONS,
+ targets: ['own-plugin-local-session'],
+ maxPageSize: 100,
+ exactRoute: true,
+ },
+ };
+ if (!deps.handler) return error('HOST_NOT_READY', 'Task service is not ready', true);
+ try {
+ const data = await deps.handler(pluginId, value);
+ if (!permitted()) return error('PERMISSION_DENIED', 'Plugin task capability is unavailable');
+ return { ok: true, data };
+ } catch (err) {
+ // Only explicit public errors cross the sandbox boundary, never internal DB/path errors.
+ if (
+ object(err) &&
+ err.name === 'PluginTaskError' &&
+ typeof err.code === 'string' &&
+ typeof err.message === 'string'
+ ) {
+ return error(err.code, err.message, err.retryable === true);
+ }
+ return error(
+ 'HOST_NOT_READY',
+ 'Task operation could not be confirmed; reuse the same request key',
+ true,
+ );
+ }
+}
diff --git a/apps/desktop/src/main/localDb/chatHistoryReader.ts b/apps/desktop/src/main/localDb/chatHistoryReader.ts
index 1cabb16a7a..d819d35d7a 100644
--- a/apps/desktop/src/main/localDb/chatHistoryReader.ts
+++ b/apps/desktop/src/main/localDb/chatHistoryReader.ts
@@ -324,6 +324,8 @@ export interface GetMessagesParams {
export interface HistoryMessage {
id: string;
+ /** Stable send/terminal identity, distinct from the storage row ID. */
+ clientId?: string;
sessionId: string;
sessionWorkingDir: string | null;
sessionAgentKind: string;
@@ -462,6 +464,7 @@ export async function getMessagesForHistory(
const camel = messageToCamel(r.m);
return {
id: camel.id,
+ clientId: camel.clientId,
sessionId: camel.sessionId,
sessionWorkingDir: r.sWorkingDir,
sessionAgentKind: r.sAgentKind,
diff --git a/apps/desktop/src/main/localDb/ipc/pluginWorkspaceSessions.ts b/apps/desktop/src/main/localDb/ipc/pluginWorkspaceSessions.ts
index 50fcde400c..b4309b1b51 100644
--- a/apps/desktop/src/main/localDb/ipc/pluginWorkspaceSessions.ts
+++ b/apps/desktop/src/main/localDb/ipc/pluginWorkspaceSessions.ts
@@ -168,6 +168,9 @@ export async function createPluginDraftSession(params: {
*/
export async function createGhostErrandSession(params: {
ghostId: string;
+ /** Host-allocated durable task identity; never taken directly from plugin payload. */
+ sessionId?: string;
+ shouldContinue?: () => boolean;
title: string | null;
agentKind?: 'cc' | 'codex' | 'pi';
model?: string;
@@ -179,9 +182,10 @@ export async function createGhostErrandSession(params: {
workingDir?: string;
notifySessionCreated?: (info: { sessionId: string; workdir?: string }) => void;
}): Promise<string> {
+ if (params.shouldContinue && !params.shouldContinue()) throw new Error('Plugin task owner changed');
const db = getDbClient().drizzle;
const now = Date.now();
- const id = randomUUID();
+ const id = params.sessionId ?? randomUUID();
const projectDir = params.workingDir
? (normalizeWorkingDirForStorage(params.workingDir) ?? undefined)
: undefined;
@@ -216,7 +220,9 @@ export async function createGhostErrandSession(params: {
autoInitProjectGit: gitSafety.autoInitProjectGit,
source: 'plugin-errand-session',
});
+ if (params.shouldContinue && !params.shouldContinue()) throw new Error('Plugin task owner changed');
await db.insert(sessions).values(insertRow);
+ if (params.shouldContinue && !params.shouldContinue()) throw new Error('Plugin task owner changed');
if (projectDir && insertRow.workingDir) {
// 项目目录是用户在插件详情页亲手选的,进"最近项目"合理;dialogue 目录
// 是 app 管理的临时间,不进。失败仅日志,不阻断创建。
diff --git a/apps/desktop/src/main/localDb/schema.ts b/apps/desktop/src/main/localDb/schema.ts
index 9b05b2cbbd..d7340fa18e 100644
--- a/apps/desktop/src/main/localDb/schema.ts
+++ b/apps/desktop/src/main/localDb/schema.ts
@@ -2135,3 +2135,19 @@ export const sessionTaskTags = sqliteTable(
byTag: index('session_task_tags_tag_idx').on(t.tagId),
}),
);
+
+/** Plugin attribution/idempotency receipts. Survive Session deletion as tombstones. */
+export const pluginTaskRequests = sqliteTable('plugin_task_requests', {
+ id: text('id').primaryKey(),
+ pluginId: text('plugin_id').notNull(),
+ operation: text('operation', { enum: ['create', 'send'] }).notNull(),
+ targetId: text('target_id').notNull(),
+ requestKey: text('request_key').notNull(),
+ fingerprint: text('fingerprint').notNull(),
+ payload: text('payload').notNull(),
+ revision: integer('revision').notNull().default(0),
+ createdAt: integer('created_at').notNull(),
+}, table => [
+ uniqueIndex('plugin_task_request_key').on(table.pluginId, table.operation, table.targetId, table.requestKey),
+ index('plugin_task_target').on(table.targetId, table.pluginId),
+]);
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
index 382628c715..a1aeddfee7 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
@@ -443,6 +443,7 @@ describe('AgentInputCoordinator Orca priority queue transactions', () => {
closeWorkerSessionIfIdle: async () => true,
hasPendingWorkerInput: async () => false,
hasSendToSessionLock: () => false,
+ withSessionSendLock: async (_sessionId, action) => action(),
archiveWorkerSession: async () => {},
getManualInterrupt: () => manualInterrupt.current,
clearManualInterrupt: () => {
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/orcaLifecycleService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/orcaLifecycleService.test.ts
index c62587a77a..8458a02124 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/orcaLifecycleService.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaLifecycleService.test.ts
@@ -1,6 +1,9 @@
import type { AgentKind } from '@cindy/maker-core';
import { describe, expect, it, vi } from 'vitest';
+// The lifecycle unit owns no credential/runtime I/O.
+vi.mock('../../maker-host/codex-credential-switch.js', () => ({isCredentialModeSwitchBusyError: () => false}));
+
import {
createOrcaLifecycleService,
ORCA_WORKER_READY_MESSAGE,
@@ -977,3 +980,27 @@ describe('enableTeam — 孤儿空团队自动回收 (#3555)', () => {
await expect(first).resolves.toMatchObject({ teamId: 'team-a' });
});
});
+
+
+describe('host-scoped Worker permissions', () => {
+ it.each([undefined, 'bypassPermissions'] as const)('keeps plugin Workers Auto despite global or explicit Full access: %s', async (workerPermissionMode) => {
+ const { deps, service } = createDeps({
+ getActiveTeamByLead: vi.fn(async () => activeTeam()),
+ getWorkerPermissionMode: vi.fn(() => 'bypassPermissions' as const),
+ getWorkerPermissionModeOverride: vi.fn(async () => 'auto' as const),
+ });
+ expect(await service.startTeam({leadSessionId: 'lead-1', workerPermissionMode})).toMatchObject({ok: true, workerPermissionMode: 'auto'});
+ await service.createWorker({leadSessionId: 'lead-1', role: 'worker', label: 'sample', agent: 'codex', workerPermissionMode});
+ expect(deps.createWorkerInTeam).toHaveBeenCalledWith(expect.objectContaining({workerPermissionMode: 'auto'}));
+ expect(deps.setWorkerPermissionMode).not.toHaveBeenCalled();
+ });
+ it('does not create a Worker after host authorization is revoked', async () => {
+ const { deps, service } = createDeps({
+ getActiveTeamByLead: vi.fn(async () => activeTeam()),
+ getWorkerPermissionModeOverride: vi.fn(async () => { throw new Error('permission revoked'); }),
+ });
+ await expect(service.createWorker({leadSessionId: 'lead-1', role: 'worker', label: 'sample', agent: 'codex'})).rejects.toThrow('permission revoked');
+ expect(deps.createWorkerInTeam).not.toHaveBeenCalled();
+ expect(deps.setWorkerPermissionMode).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/orcaTeamService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/orcaTeamService.test.ts
index 24f18e78e2..2a61b90443 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/orcaTeamService.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaTeamService.test.ts
@@ -172,6 +172,7 @@ function createDeps(overrides: Partial<OrcaTeamServiceDeps> = {}) {
}),
hasPendingWorkerInput: vi.fn(async () => false),
hasSendToSessionLock: vi.fn(() => false),
+ withSessionSendLock: async (_id, operation) => operation(),
archiveWorkerSession: vi.fn(async (sessionId) => {
calls.push(`archiveWorkerSession:${sessionId}`);
}),
@@ -2881,3 +2882,31 @@ describe('OrcaTeamService worker queued message control', () => {
});
});
});
+
+it('idle-only archive preserves queued input',async()=>{const {deps,service,setWorker}=createDeps();setWorker(createWorker({status:'done'}));vi.mocked(deps.hasPendingWorkerInput).mockResolvedValue(true);expect((await service.archiveWorker({callerLeadSessionId:'lead-1',workerId:'worker-1',onlyIfIdle:true})).ok).toBe(false);expect(deps.cancelWorkerSessionOperations).not.toHaveBeenCalled();expect(deps.archiveWorkerSession).not.toHaveBeenCalled();});
+it('idle-only archive preserves active runtime',async()=>{const {deps,service,setWorker}=createDeps();setWorker(createWorker({status:'done'}));vi.mocked(deps.closeWorkerSessionIfIdle!).mockResolvedValue(false);expect((await service.archiveWorker({callerLeadSessionId:'lead-1',workerId:'worker-1',onlyIfIdle:true})).ok).toBe(false);expect(deps.archiveWorkerSession).not.toHaveBeenCalled();});
+
+it('idle-only archive rechecks the execution stamp after waiting for the send fence',async()=>{
+ const {deps,service,setWorker}=createDeps();setWorker(createWorker({status:'done'}));
+ let current=true;
+ deps.withSessionSendLock=async (_id,operation)=>{current=false;return operation();};
+ const beforeArchive=async()=>{if(!current)throw new Error('stale completion');};
+ await expect(service.archiveWorker({callerLeadSessionId:'lead-1',workerId:'worker-1',onlyIfIdle:true,beforeArchive})).rejects.toThrow('stale completion');
+ expect(deps.archiveWorkerSession).not.toHaveBeenCalled();expect(deps.cancelWorkerSessionOperations).not.toHaveBeenCalled();
+});
+
+it('release refuses an occupied send fence without waiting for it',async()=>{
+ const {deps,service,setWorker}=createDeps();setWorker(createWorker({status:'done'}));
+ vi.mocked(deps.hasSendToSessionLock).mockReturnValue(true);
+ deps.withSessionSendLock=vi.fn(async (_id,operation)=>operation());
+ expect((await service.archiveWorker({callerLeadSessionId:'lead-1',workerId:'worker-1',onlyIfIdle:true})).ok).toBe(false);
+ expect(deps.withSessionSendLock).not.toHaveBeenCalled();expect(deps.archiveWorkerSession).not.toHaveBeenCalled();
+});
+it('release closes under its own send fence and fails closed on close error',async()=>{
+ const {deps,service,setWorker}=createDeps();setWorker(createWorker({status:'done'}));
+ await service.archiveWorker({callerLeadSessionId:'lead-1',workerId:'worker-1',onlyIfIdle:true});
+ expect(deps.closeWorkerSessionIfIdle).toHaveBeenCalledWith('worker-session-1',true);
+ vi.mocked(deps.archiveWorkerSession).mockClear();vi.mocked(deps.closeWorkerSessionIfIdle).mockRejectedValue(new Error('close failed'));
+ expect((await service.archiveWorker({callerLeadSessionId:'lead-1',workerId:'worker-1',onlyIfIdle:true})).ok).toBe(false);
+ expect(deps.archiveWorkerSession).not.toHaveBeenCalled();
+});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts
index a5be37db74..40d78936d7 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts
@@ -2723,3 +2723,6 @@ describe('SSH remote worker model/provider compatibility gate (R23 P2)', () => {
message: expect.stringContaining('not available for SSH remote workers'),
});
});
+
+it('applies plan limit in atomic reservation',async()=>{const {deps,service}=createDeps({validateCreationPlan:vi.fn(async()=>2)});await service.createWorker({leadSessionId:'lead-1',role:'eval',agent:'codex',label:'sample'});expect(deps.reserveWorkerCreation).toHaveBeenCalledWith(expect.objectContaining({hardLimit:2}));});
+it('rejects invalid plan before reservation',async()=>{const {deps,service}=createDeps({validateCreationPlan:vi.fn(async()=>{throw Error('not pending');})});await expect(service.createWorker({leadSessionId:'lead-1',role:'eval',agent:'codex',label:'sample'})).rejects.toThrow('not pending');expect(deps.reserveWorkerCreation).not.toHaveBeenCalled();expect(deps.bootstrapSession).not.toHaveBeenCalled();});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.ts
new file mode 100644
index 0000000000..cacb8176f9
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.ts
@@ -0,0 +1,308 @@
+import { describe, expect, it, vi } from 'vitest';
+import {
+ createPluginTaskService,
+ type PluginTaskReceipt,
+ type PluginTaskStore,
+ type PluginTaskServiceDeps,
+} from '../pluginTaskService.js';
+import type { PluginTaskView } from '../../../shared/pluginTasks.js';
+
+function fixture() {
+ let seq = 0;
+ let current = true;
+ const rows = new Map<string, PluginTaskReceipt>();
+ const tasks = new Map<string, PluginTaskView>();
+ const copy = <T>(v: T): T => structuredClone(v);
+ const store: PluginTaskStore = {
+ get: async (id) => copy(rows.get(id)),
+ find: async (p, op, t, k) =>
+ copy(
+ [...rows.values()].find(
+ (r) => r.pluginId === p && r.operation === op && r.targetId === t && r.requestKey === k,
+ ),
+ ),
+ list: async (p, op, t, after, limit) =>
+ copy(
+ [...rows.values()]
+ .filter(
+ (r) =>
+ r.pluginId === p &&
+ r.operation === op &&
+ (t === null || r.targetId === t) &&
+ r.id > after,
+ )
+ .slice(0, limit),
+ ),
+ forSession: async (t) =>
+ copy([...rows.values()].filter((r) => r.operation === 'send' && r.targetId === t)),
+ insert: async (r) => {
+ expect(rows.has(r.id)).toBe(false);
+ rows.set(r.id, copy(r));
+ },
+ save: async (r) => {
+ expect(rows.get(r.id)?.revision).toBe(r.revision);
+ rows.set(r.id, copy({ ...r, revision: r.revision + 1 }));
+ },
+ };
+ const route = {
+ agentKind: 'codex' as const,
+ providerId: 'mine',
+ model: 'model',
+ effort: 'high',
+ fastMode: false,
+ };
+ const execution = { instanceId: 'native', generation: 1 };
+ const deps: PluginTaskServiceDeps = {
+ store,
+ assertAuthorized: () => {
+ if (!current) throw new Error('Owner changed');
+ },
+ assertCurrent: () => {
+ if (!current) throw new Error('Owner changed');
+ },
+ id: () => `id-${++seq}`,
+ now: () => 1,
+ resolveRoute: vi.fn(async (_, r) => r ?? route),
+ createSession: vi.fn(async (_, taskId, title, resolvedConfig) => {
+ tasks.set(taskId, { taskId, title, resolvedConfig, revision: 1, status: 'active' });
+ }),
+ readSession: async (id) => copy(tasks.get(id) ?? null),
+ dispatch: vi.fn(async () => ({ ok: true })),
+ inspect: vi.fn(async () => ({ execution: null, pending: [] })),
+ cancel: vi.fn(async () => 'cancelled' as const),
+ };
+ const service = createPluginTaskService(deps);
+ const create = () => service.create('p', { requestKey: 'create', title: 'Test' });
+ const send = async () => {
+ const task = await create();
+ return service.send('p', {
+ taskId: task.taskId,
+ requestKey: 'send',
+ expectedRevision: task.revision,
+ text: 'hello',
+ });
+ };
+ return {
+ service,
+ deps,
+ rows,
+ tasks,
+ route,
+ execution,
+ create,
+ send,
+ switchOwner: () => {
+ current = false;
+ },
+ };
+}
+
+describe('plugin ordinary task receipts', () => {
+ it('binds isolated workspace intent to creation and idempotency', async () => {
+ const f = fixture();
+ const input = { requestKey: 'isolated', title: 'Test', isolatedWorkspace: true };
+ const task = await f.service.create('p', input);
+ expect(f.deps.createSession).toHaveBeenCalledWith('p', task.taskId, 'Test', f.route, true);
+ await f.service.create('p', input);
+ expect(f.deps.createSession).toHaveBeenCalledTimes(1);
+ await expect(f.service.create('p', { ...input, isolatedWorkspace: false }))
+ .rejects.toMatchObject({ code: 'IDEMPOTENCY_CONFLICT' });
+ });
+
+ it('creates once under concurrent retries and rejects conflicting keys', async () => {
+ const f = fixture();
+ const [a, b] = await Promise.all([f.create(), f.create()]);
+ expect(a.taskId).toBe(b.taskId);
+ expect(f.deps.createSession).toHaveBeenCalledTimes(1);
+ await expect(
+ f.service.create('p', { requestKey: 'create', title: 'Different' }),
+ ).rejects.toMatchObject({ code: 'IDEMPOTENCY_CONFLICT' });
+ });
+ it('never exposes another plugin task or run', async () => {
+ const f = fixture();
+ const run = await f.send();
+ await expect(f.service.get('other', run.taskId)).rejects.toMatchObject({
+ code: 'TASK_NOT_FOUND',
+ });
+ await expect(f.service.getRun('other', run.runId)).rejects.toMatchObject({
+ code: 'TASK_NOT_FOUND',
+ });
+ expect((await f.service.list('other')).items).toEqual([]);
+ });
+ it('persists input identity before dispatch and does not replay after restart', async () => {
+ const f = fixture();
+ f.deps.dispatch = vi.fn(async (_, __, clientId) => {
+ expect([...f.rows.values()].some((r) => r.payload.includes(clientId))).toBe(true);
+ throw new Error('Response lost');
+ });
+ const run = await f.send();
+ expect(run.status).toBe('reconciling');
+ const restarted = createPluginTaskService(f.deps);
+ const retry = await restarted.send('p', {
+ taskId: run.taskId,
+ requestKey: 'send',
+ expectedRevision: 1,
+ text: 'hello',
+ });
+ expect(retry.runId).toBe(run.runId);
+ expect(f.deps.dispatch).toHaveBeenCalledTimes(1);
+ });
+ it('rejects stale revision and archived tasks without dispatch', async () => {
+ const f = fixture();
+ const task = await f.create();
+ await expect(
+ f.service.send('p', {
+ taskId: task.taskId,
+ requestKey: 's',
+ expectedRevision: 2,
+ text: 'hi',
+ }),
+ ).rejects.toMatchObject({ code: 'REVISION_CONFLICT' });
+ f.tasks.get(task.taskId)!.status = 'archived';
+ await expect(
+ f.service.send('p', {
+ taskId: task.taskId,
+ requestKey: 's',
+ expectedRevision: 1,
+ text: 'hi',
+ }),
+ ).rejects.toMatchObject({ code: 'TASK_BUSY' });
+ expect(f.deps.dispatch).not.toHaveBeenCalled();
+ });
+ it('binds native acceptance and fences late terminals from old runtime/generation', async () => {
+ const f = fixture();
+ const run = await f.send();
+ await f.service.accept(run.taskId, { clientId: run.inputMessageId }, f.execution);
+ await f.service.settle(run.taskId, { ...f.execution, instanceId: 'old' }, 'completed', 'wrong');
+ expect(JSON.parse(f.rows.get(run.runId)!.payload).status).toBe('running');
+ await f.service.settle(run.taskId, f.execution, 'completed', 'output');
+ await f.service.settle(run.taskId, f.execution, 'failed');
+ expect(await f.service.getRun('p', run.runId)).toMatchObject({
+ status: 'completed',
+ outputMessageId: 'output',
+ });
+ });
+ it('transfers only native recovery aliases to the new execution', async () => {
+ const f = fixture();
+ const run = await f.send();
+ await f.service.accept(run.taskId, { clientId: run.inputMessageId }, f.execution);
+ await f.service.accept(
+ run.taskId,
+ { clientId: 'retry', retrySourceClientId: run.inputMessageId },
+ { ...f.execution, generation: 2 },
+ );
+ await f.service.settle(run.taskId, f.execution, 'failed');
+ expect(JSON.parse(f.rows.get(run.runId)!.payload).execution.generation).toBe(2);
+ });
+ it('cancellation before acceptance prevents a queued input from starting', async () => {
+ const f = fixture();
+ const run = await f.send();
+ expect((await f.service.cancel('p', run.runId)).status).toBe('cancelled');
+ await expect(
+ f.service.accept(run.taskId, { clientId: run.inputMessageId }, f.execution),
+ ).rejects.toMatchObject({ code: 'REQUEST_EXPIRED' });
+ });
+ it('does not convert a completed output into cancellation', async () => {
+ const f = fixture();
+ const run = await f.send();
+ await f.service.accept(run.taskId, { clientId: run.inputMessageId }, f.execution);
+ await f.service.settle(run.taskId, f.execution, 'completed');
+ expect((await f.service.cancel('p', run.runId)).status).toBe('completed');
+ expect(f.deps.cancel).not.toHaveBeenCalled();
+ });
+ it('revalidates exact configuration at vendor boundary', async () => {
+ const f = fixture();
+ const run = await f.send();
+ f.tasks.get(run.taskId)!.resolvedConfig.model = 'other';
+ await expect(
+ f.service.accept(run.taskId, { clientId: run.inputMessageId }, f.execution),
+ ).rejects.toMatchObject({ code: 'ROUTE_UNAVAILABLE' });
+ });
+ it('account switch blocks subsequent work', async () => {
+ const f = fixture();
+ await f.create();
+ f.switchOwner();
+ await expect(f.service.list('p')).rejects.toThrow('Owner changed');
+ });
+ it('does not recreate a deleted task on request replay', async () => {
+ const f = fixture();
+ const task = await f.create();
+ f.tasks.delete(task.taskId);
+ await expect(f.create()).rejects.toMatchObject({ code: 'TASK_NOT_FOUND' });
+ expect(f.deps.createSession).toHaveBeenCalledTimes(1);
+ });
+ it('allows coordinator acceptance and synchronous terminal inside dispatch without a lock cycle', async () => {
+ const f = fixture();
+ f.deps.dispatch = vi.fn(async (_, taskId, clientId) => {
+ await f.service.accept(taskId, { clientId }, f.execution);
+ await f.service.settle(taskId, f.execution, 'completed', 'answer');
+ return { ok: true };
+ });
+ expect(await f.send()).toMatchObject({ status: 'completed', outputMessageId: 'answer' });
+ });
+ it('does not hold the receipt lock while native stop delivers its terminal', async () => {
+ const f = fixture();
+ const run = await f.send();
+ await f.service.accept(run.taskId, { clientId: run.inputMessageId }, f.execution);
+ f.deps.cancel = vi.fn(async () => {
+ await f.service.settle(run.taskId, f.execution, 'completed', 'finished-before-stop');
+ return 'stopping' as const;
+ });
+ expect(await f.service.cancel('p', run.runId)).toMatchObject({
+ status: 'completed',
+ outputMessageId: 'finished-before-stop',
+ });
+ });
+ it('does not block a user retry after the plugin run ended', async () => {
+ const f = fixture();
+ const run = await f.send();
+ await f.service.accept(run.taskId, { clientId: run.inputMessageId }, f.execution);
+ await f.service.settle(run.taskId, f.execution, 'failed');
+ await expect(
+ f.service.accept(
+ run.taskId,
+ { clientId: 'user-retry', retrySourceClientId: run.inputMessageId },
+ { ...f.execution, generation: 2 },
+ ),
+ ).resolves.toBeUndefined();
+ expect(await f.service.getRun('p', run.runId)).toMatchObject({ status: 'failed' });
+ });
+ it('keeps multi-hop recovery aliases but never adopts an unrelated user input', async () => {
+ const f = fixture();
+ const run = await f.send();
+ await f.service.accept(
+ run.taskId,
+ { clientId: 'retry1', retrySourceClientId: run.inputMessageId },
+ f.execution,
+ );
+ await f.service.accept(
+ run.taskId,
+ { clientId: 'retry2', retrySourceClientId: 'retry1' },
+ { ...f.execution, generation: 2 },
+ );
+ await f.service.accept(run.taskId, { clientId: 'user-new' }, { ...f.execution, generation: 3 });
+ await f.service.discard(run.taskId, { clientId: 'retry1' }, 'cancelled');
+ const receipt = JSON.parse(f.rows.get(run.runId)!.payload);
+ expect(receipt.status).toBe('running');
+ expect(receipt.execution.generation).toBe(2);
+ expect(receipt.inputClientIds).toEqual(['retry1', 'retry2']);
+ });
+});
+
+it('permission elevation blocks new sends but preserves inspection of existing work',async()=>{
+ const f=fixture();const task=await f.create();const run=await f.send();
+ f.tasks.set(task.taskId,{...f.tasks.get(task.taskId)!,permissionMode:'bypassPermissions'});
+ expect((await f.service.get('p',task.taskId)).taskId).toBe(task.taskId);
+ expect((await f.service.getRun('p',run.runId)).runId).toBe(run.runId);
+ await expect(f.service.send('p',{taskId:task.taskId,expectedRevision:task.revision,requestKey:'new-send',text:'new'})).rejects.toMatchObject({code:'PERMISSION_DENIED'});
+});
+
+it('freezes owned plan and retains settled labels',async()=>{const f=fixture(),task=await f.create();const plan={concurrency:2,items:[{label:'sample',workingDir:'/answer',route:f.route}]};await f.service.setTeamPlan('p',task.taskId,plan);await f.service.setTeamPlan('p',task.taskId,plan);await expect(f.service.setTeamPlan('other',task.taskId,plan)).rejects.toThrow('Task not found');await expect(f.service.setTeamPlan('p',task.taskId,{...plan,concurrency:3})).rejects.toThrow('immutable');await f.service.settleWorkerLabel('p',task.taskId,'sample');expect(JSON.parse(f.rows.get(task.taskId)!.payload).settledLabels).toEqual(['sample']);});
+
+
+it('rechecks permissions when queued input reaches native dispatch', async () => {
+ const f=fixture(), run=await f.send();
+ f.tasks.get(run.taskId)!.permissionMode='bypassPermissions';
+ await expect(f.service.accept(run.taskId,{clientId:run.inputMessageId},f.execution)).rejects.toMatchObject({code:'PERMISSION_DENIED'});
+ expect(JSON.parse(f.rows.get(run.runId)!.payload).status).toBe('queued');
+});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginWorkerCompletion.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginWorkerCompletion.test.ts
new file mode 100644
index 0000000000..9835c5eb24
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginWorkerCompletion.test.ts
@@ -0,0 +1,7 @@
+import {describe, it, expect} from 'vitest';
+import {pluginWorkerCompletedAt} from '../pluginWorkerCompletion.js';
+const final = {status:'idle',working:false,queued:0,paused:false,startedAt:100,endedAt:200,anchor:{role:'assistant',createdAt:190,agentMeta:'{"turnCompleted":true}'}};
+describe('released Worker completion',()=>{
+ it('recovers a released final turn from host metadata',()=>expect(pluginWorkerCompletedAt(final)).toBe(200));
+ it.each([{working:true},{queued:1},{paused:true},{status:'error'},{startedAt:210},{clearedAt:195},{anchor:{...final.anchor,role:'user'}},{anchor:{...final.anchor,agentMeta:'{}'}},{anchor:{...final.anchor,agentMeta:'{"turnCompleted":false}'}},{anchor:{...final.anchor,agentMeta:'{"turnCompleted":true,"parentUuid":"child"}'}}])('does not infer completion from idle or old/report text: %j',patch=>expect(pluginWorkerCompletedAt({...final,...patch})).toBeNull());
+});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionExecutionOwnership.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionExecutionOwnership.test.ts
new file mode 100644
index 0000000000..8eebd7bc04
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionExecutionOwnership.test.ts
@@ -0,0 +1,72 @@
+import { describe, expect, it, vi } from 'vitest';
+import {
+ controlOwnedSessionExecution,
+ isSameSessionExecution,
+ withdrawOwnedSessionInputs,
+} from '../sessionExecutionOwnership.js';
+
+describe('ordinary Session execution ownership', () => {
+ it('requires both instance and generation', () => {
+ expect(
+ isSameSessionExecution(
+ { instanceId: 'a', generation: 1 },
+ { instanceId: 'b', generation: 1 },
+ ),
+ ).toBe(false);
+ expect(
+ isSameSessionExecution(
+ { instanceId: 'a', generation: 2 },
+ { instanceId: 'a', generation: 1 },
+ ),
+ ).toBe(false);
+ expect(isSameSessionExecution(null, null)).toBe(false);
+ });
+ it('rechecks after acquiring the restart lock', async () => {
+ let owned = true;
+ const operation = vi.fn();
+ expect(
+ await controlOwnedSessionExecution({
+ sessionId: 's',
+ matches: () => owned,
+ withSessionLock: async (_, fn) => {
+ owned = false;
+ await fn();
+ },
+ operation,
+ }),
+ ).toBe(false);
+ expect(operation).not.toHaveBeenCalled();
+ });
+ it('restores cold queues and only withdraws owned inputs and recovery aliases', async () => {
+ const remove = vi.fn();
+ const flush = vi.fn();
+ let restored = false;
+ await withdrawOwnedSessionInputs({
+ sessionId: 's',
+ owns: (id) => id === 'owned',
+ flush,
+ queue: {
+ ensureQueueRestored: async () => {
+ restored = true;
+ },
+ getQueueControlSnapshot: () => {
+ expect(restored).toBe(true);
+ return {
+ pendingQueue: [
+ { clientId: 'user' },
+ { clientId: 'retry', retrySourceClientId: 'owned' },
+ { clientId: 'clone', supersedesUserClientId: 'owned' },
+ { clientId: 'owned-other' },
+ ],
+ };
+ },
+ remove,
+ },
+ });
+ expect(remove.mock.calls).toEqual([
+ ['s', 'retry'],
+ ['s', 'clone'],
+ ]);
+ expect(flush).toHaveBeenCalledWith('s');
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/botDelegationService.ts b/apps/desktop/src/main/maker-ipc/botDelegationService.ts
index 3c3a8903e3..251d8aaf4e 100644
--- a/apps/desktop/src/main/maker-ipc/botDelegationService.ts
+++ b/apps/desktop/src/main/maker-ipc/botDelegationService.ts
@@ -1,3 +1,4 @@
+import { controlOwnedSessionExecution, isSameSessionExecution, withdrawOwnedSessionInputs } from './sessionExecutionOwnership.js';
import { existsSync, statSync } from 'node:fs';
import type { AgentInputCoordinator } from './agent-input-coordinator.js';
import path from 'node:path';
@@ -94,15 +95,10 @@ export async function discardDelegationQueuedInputs(
delegationId: string,
flush: (sessionId: string) => Promise<void>,
): Promise<void> {
- await queue.ensureQueueRestored(sessionId);
- for (const item of queue.getQueueControlSnapshot(sessionId).pendingQueue) {
- if (isDelegationQueuedInput(delegationId, item.clientId)
- || (item.supersedesUserClientId && isDelegationQueuedInput(delegationId, item.supersedesUserClientId))
- || (item.retrySourceClientId && isDelegationQueuedInput(delegationId, item.retrySourceClientId))) {
- queue.remove(sessionId, item.clientId);
- }
- }
- await flush(sessionId);
+ await withdrawOwnedSessionInputs({
+ sessionId, queue, flush,
+ owns: clientId => isDelegationQueuedInput(delegationId, clientId),
+ });
}
export interface BotDelegationServiceDeps {
@@ -445,7 +441,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {
const sameExecution = (sessionId: string, expected: DelegationExecutionReceipt | null | undefined): boolean => {
if (!deps.readSessionExecution) return true;
const current = deps.readSessionExecution(sessionId);
- return !!expected && current?.instanceId === expected.instanceId && current.generation === expected.generation;
+ return isSameSessionExecution(current, expected);
};
const matchesDelegatedExecution = (row: DelegationRow, allowIdle = false): boolean => {
@@ -460,16 +456,13 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {
};
const controlDelegatedExecution = async (row: DelegationRow, operation: () => Promise<void>, allowIdle = false): Promise<boolean> => {
- if (!row.childSessionId || !matchesDelegatedExecution(row, allowIdle)) return false;
- let applied = false;
- const guarded = async () => {
- if (!matchesDelegatedExecution(row, allowIdle)) return;
- await operation();
- applied = true;
- };
- if (deps.withSessionLock) await deps.withSessionLock(row.childSessionId, guarded);
- else await guarded();
- return applied;
+ if (!row.childSessionId) return false;
+ return controlOwnedSessionExecution({
+ sessionId: row.childSessionId,
+ matches: () => matchesDelegatedExecution(row, allowIdle),
+ withSessionLock: deps.withSessionLock,
+ operation,
+ });
};
// Store only a native turn actually accepted for this delegation run. A later
diff --git a/apps/desktop/src/main/maker-ipc/orcaLifecycleService.ts b/apps/desktop/src/main/maker-ipc/orcaLifecycleService.ts
index 2a5f07ef04..bc7ae81e20 100644
--- a/apps/desktop/src/main/maker-ipc/orcaLifecycleService.ts
+++ b/apps/desktop/src/main/maker-ipc/orcaLifecycleService.ts
@@ -87,6 +87,8 @@ export interface OrcaLifecycleDeps {
/** #3555:active team 是否为初始化中断遗留的孤儿(零 worker 行且无存活创建 reservation)。 */
isOrphanedTeamInit(teamId: string): Promise<boolean>;
getWorkerPermissionMode(): OrcaWorkerPermissionMode;
+ /** Host-authorized per-lead policy; never changes the global creation preference. */
+ getWorkerPermissionModeOverride?(leadSessionId: string): Promise<OrcaWorkerPermissionMode | undefined>;
setWorkerPermissionMode(workerPermissionMode: OrcaWorkerPermissionMode): void;
createWorkerInTeam(params: OrcaWorkerCreateInTeamParams): Promise<OrcaWorkerCreationResult>;
dispatchWorkerTask(params: {
@@ -183,9 +185,12 @@ export function createOrcaLifecycleService(deps: OrcaLifecycleDeps): OrcaLifecyc
const initializingTeamIds = new Set<string>();
const dispatchSource = 'maker-ipc/collab';
- function workerPermissionModeForCreate(
+ async function workerPermissionModeForCreate(
+ leadSessionId: string,
explicitMode: OrcaWorkerPermissionMode | undefined,
- ): OrcaWorkerPermissionMode {
+ ): Promise<OrcaWorkerPermissionMode> {
+ const override = await deps.getWorkerPermissionModeOverride?.(leadSessionId);
+ if (override !== undefined) return override;
if (explicitMode === undefined) return deps.getWorkerPermissionMode();
const resolved = resolveOrcaWorkerPermissionMode(explicitMode);
deps.setWorkerPermissionMode(resolved);
@@ -228,7 +233,7 @@ export function createOrcaLifecycleService(deps: OrcaLifecycleDeps): OrcaLifecyc
return { ok: false, errorCode: 'NOT_FOUND', message: 'no active team for this lead' };
}
const initialTask = hasNonEmptyInitialTask(params.initialTask) ? params.initialTask : undefined;
- const workerPermissionMode = workerPermissionModeForCreate(params.workerPermissionMode);
+ const workerPermissionMode = await workerPermissionModeForCreate(params.leadSessionId, params.workerPermissionMode);
const created = await deps.createWorkerInTeam({
...params,
teamId: team.id,
@@ -315,7 +320,7 @@ export function createOrcaLifecycleService(deps: OrcaLifecycleDeps): OrcaLifecyc
}
async function startTeam(params: OrcaStartTeamParams): Promise<OrcaStartTeamResult> {
- const workerPermissionMode = workerPermissionModeForCreate(params.workerPermissionMode);
+ const workerPermissionMode = await workerPermissionModeForCreate(params.leadSessionId, params.workerPermissionMode);
const existing = await deps.getActiveTeamByLead(params.leadSessionId);
if (existing) {
try {
@@ -339,7 +344,7 @@ export function createOrcaLifecycleService(deps: OrcaLifecycleDeps): OrcaLifecyc
}
async function enableTeam(params: OrcaEnableTeamParams): Promise<OrcaEnableTeamResult> {
- const workerPermissionMode = workerPermissionModeForCreate(params.workerPermissionMode);
+ const workerPermissionMode = await workerPermissionModeForCreate(params.leadSessionId, params.workerPermissionMode);
const normalized = normalizeEnableParams(params);
const validationFailure = validateEnableParams(normalized);
if (validationFailure) return validationFailure;
diff --git a/apps/desktop/src/main/maker-ipc/orcaTeamService.ts b/apps/desktop/src/main/maker-ipc/orcaTeamService.ts
index 381f304328..ea3486984d 100644
--- a/apps/desktop/src/main/maker-ipc/orcaTeamService.ts
+++ b/apps/desktop/src/main/maker-ipc/orcaTeamService.ts
@@ -238,11 +238,12 @@ export interface OrcaTeamServiceDeps {
cancelWorkerSessionOperations(sessionId: string): Promise<void>;
closeWorkerSession(sessionId: string): Promise<void>;
/** 与 Session.send reservation 原子互斥;false 表示 direct send/turn 已先取得会话。 */
- closeWorkerSessionIfIdle(sessionId: string): Promise<boolean>;
+ closeWorkerSessionIfIdle(sessionId: string, sendLockHeld?: boolean): Promise<boolean>;
/** pending / dispatch-boundary / recovery 输入任一存在时返回 true。 */
hasPendingWorkerInput(sessionId: string): Promise<boolean>;
/** send_to_session 的恢复/直发锁覆盖 bootstrap 到 Session.send reservation 的窗口。 */
hasSendToSessionLock(sessionId: string): boolean;
+ withSessionSendLock<T>(sessionId: string, operation: () => Promise<T>): Promise<T>;
archiveWorkerSession(sessionId: string): Promise<void>;
getManualInterrupt(sessionId: string): OrcaManualInterruptSnapshot | null;
clearManualInterrupt(sessionId: string): void;
@@ -340,7 +341,7 @@ export interface OrcaTeamService {
expectedStatus?: 'done';
}): Promise<OrcaOkResult>;
/** 外部调用边界:按 caller lead 校验 worker 可见性。 */
- archiveWorker(params: { callerLeadSessionId: string; workerId: string }): Promise<OrcaOkResult>;
+ archiveWorker(params: { callerLeadSessionId: string; workerId: string; onlyIfIdle?: boolean; beforeArchive?: () => Promise<void> }): Promise<OrcaOkResult>;
/** 外部调用边界:列出目标 worker 输入队列中的排队消息(lead 自己的条目含正文)。 */
listWorkerQueuedMessages(params: {
callerLeadSessionId: string;
@@ -1223,16 +1224,26 @@ export function createOrcaTeamService(deps: OrcaTeamServiceDeps): OrcaTeamServic
async function archiveWorker(params: {
callerLeadSessionId: string;
workerId: string;
+ onlyIfIdle?: boolean;
+ beforeArchive?: () => Promise<void>;
}): Promise<OrcaOkResult> {
+ const perform = async (): Promise<OrcaOkResult> => {
const found = await resolveWorkerRef(params.callerLeadSessionId, params.workerId);
if (!found.ok) return workerRefFailureForControl(params.workerId, found);
const { link, worker } = found;
+ const archive = async (): Promise<OrcaOkResult> => {
+ await params.beforeArchive?.();
+ if (params.onlyIfIdle) {
+ if ((activeWorkerDispatches.get(worker.id) ?? 0)>0 || await deps.hasPendingWorkerInput(worker.sessionId) || !await closeWorkerSessionIfIdleBestEffort(worker.sessionId,'releaseWorker',true)) return {ok:false,errorCode:'WORKER_STATE_CHANGED',message:'Worker has active or queued input'};
+ if (await deps.hasPendingWorkerInput(worker.sessionId)) return {ok:false,errorCode:'WORKER_STATE_CHANGED',message:'Worker has queued input'};
+ }
clearRuntimeState(worker.sessionId);
deps.forgetWorkerSession?.(worker.sessionId);
deferredDoneAcknowledgements.delete(worker.id);
await deps.cancelWorkerSessionOperations(worker.sessionId);
await closeWorkerSessionBestEffort(worker.sessionId, 'archiveWorker');
+ await params.beforeArchive?.();
await deps.archiveWorkerSession(worker.sessionId);
// The archived status is the admission barrier for new Host work. Cancel
// once more after publishing it to catch a build that registered between
@@ -1241,6 +1252,13 @@ export function createOrcaTeamService(deps: OrcaTeamServiceDeps): OrcaTeamServic
await deps.updateWorkerStatus(worker.id, 'done');
deps.broadcastOrcaWorkerChanged(link.leadSessionId);
return { ok: true, workerId: worker.id };
+ };
+ // Never wait for a send while holding the Worker transition: send acceptance
+ // also needs this transition. Check and reserve synchronously (no await).
+ if (params.onlyIfIdle && deps.hasSendToSessionLock(worker.sessionId)) return {ok:false,errorCode:'WORKER_STATE_CHANGED',message:'Worker has a send in progress'};
+ return params.onlyIfIdle ? deps.withSessionSendLock(worker.sessionId, archive) : archive();
+ };
+ return params.onlyIfIdle ? withWorkerTransition(params.workerId,perform) : perform();
}
/** 排队消息 source 判定:worker 队列里 orca 条目只可能来自其 lead(通信拓扑为 Lead↔Worker)。 */
@@ -1476,15 +1494,16 @@ export function createOrcaTeamService(deps: OrcaTeamServiceDeps): OrcaTeamServic
async function closeWorkerSessionIfIdleBestEffort(
sessionId: string,
owner: string,
+ sendLockHeld = false,
): Promise<boolean> {
try {
- return await deps.closeWorkerSessionIfIdle(sessionId);
+ return await (sendLockHeld ? deps.closeWorkerSessionIfIdle(sessionId, true) : deps.closeWorkerSessionIfIdle(sessionId));
} catch (err) {
deps.log.warn(`${owner}: close idle worker session failed`, {
sessionId,
err: err instanceof Error ? err.message : String(err),
});
- return true;
+ return false;
}
}
diff --git a/apps/desktop/src/main/maker-ipc/orcaWorkerCreationService.ts b/apps/desktop/src/main/maker-ipc/orcaWorkerCreationService.ts
index e3b346bab7..75bbfb21ba 100644
--- a/apps/desktop/src/main/maker-ipc/orcaWorkerCreationService.ts
+++ b/apps/desktop/src/main/maker-ipc/orcaWorkerCreationService.ts
@@ -208,6 +208,7 @@ export interface OrcaWorkerCreationDeps {
getActiveTeamByLead(leadSessionId: string): Promise<OrcaTeamSnapshot | null>;
listWorkersByLead(leadSessionId: string): Promise<OrcaWorkerListSnapshot[]>;
isActiveWorkerStatus(status: OrcaWorkerStatus): boolean;
+ validateCreationPlan?(params: OrcaWorkerCreateInTeamParams): Promise<number | null | undefined>;
readCollaborationSettings(): { workerSoftLimit: number; workerHardLimit: number };
getLeadSessionRow(leadSessionId: string): Promise<OrcaLeadSessionSnapshot | null>;
getWorkerDefaults(agent: AgentKind): OrcaWorkerDefaultsSnapshot;
@@ -624,7 +625,9 @@ export function createOrcaWorkerCreationService(deps: OrcaWorkerCreationDeps): O
return { ok: false, errorCode: 'DUPLICATE_LABEL', message: `label "${label.value}" already used in this team` };
}
- const settings = deps.readCollaborationSettings();
+ const planLimit = await deps.validateCreationPlan?.(params);
+ const settings = {...deps.readCollaborationSettings()};
+ if (planLimit != null) settings.workerHardLimit = Math.min(settings.workerHardLimit, planLimit);
const activeCount = existing.filter((worker) => deps.isActiveWorkerStatus(worker.status)).length;
if (activeCount >= settings.workerHardLimit) {
return {
diff --git a/apps/desktop/src/main/maker-ipc/pluginTaskService.ts b/apps/desktop/src/main/maker-ipc/pluginTaskService.ts
new file mode 100644
index 0000000000..9be1656dbe
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/pluginTaskService.ts
@@ -0,0 +1,398 @@
+import { createHash, randomUUID } from 'node:crypto';
+import type { PluginTaskRoute, PluginTaskRun, PluginTaskView, PluginTeamPlan } from '../../shared/pluginTasks.js';
+import {
+ isSameSessionExecution,
+ queuedInputBelongsTo,
+ type OwnedQueuedInput,
+ type SessionExecutionIdentity,
+} from './sessionExecutionOwnership.js';
+
+export interface PluginTaskReceipt {
+ id: string;
+ pluginId: string;
+ operation: 'create' | 'send';
+ targetId: string;
+ requestKey: string;
+ fingerprint: string;
+ payload: string;
+ revision: number;
+ createdAt: number;
+}
+export interface PluginTaskStore {
+ get(id: string): Promise<PluginTaskReceipt | undefined>;
+ find(
+ pluginId: string,
+ operation: string,
+ targetId: string,
+ requestKey: string,
+ ): Promise<PluginTaskReceipt | undefined>;
+ list(
+ pluginId: string,
+ operation: string,
+ targetId: string | null,
+ after: string,
+ limit: number,
+ ): Promise<PluginTaskReceipt[]>;
+ forSession(taskId: string): Promise<PluginTaskReceipt[]>;
+ insert(row: PluginTaskReceipt): Promise<void>;
+ save(row: PluginTaskReceipt): Promise<void>;
+}
+export class PluginTaskError extends Error {
+ constructor(
+ readonly code: string,
+ message: string,
+ readonly retryable = false,
+ ) {
+ super(message);
+ this.name = 'PluginTaskError';
+ }
+}
+const fail = (code: string, message: string): never => {
+ throw new PluginTaskError(code, message);
+};
+const terminal = (run: PluginTaskRun) =>
+ ['completed', 'failed', 'cancelled', 'interrupted'].includes(run.status);
+const ownsInput = (run: PluginTaskRun, value: string) =>
+ value === run.inputMessageId || run.inputClientIds?.includes(value) === true;
+const hash = (data: unknown) => createHash('sha256').update(JSON.stringify(data)).digest('hex');
+export interface PluginTaskServiceDeps {
+ store: PluginTaskStore;
+ /** Bound to the captured account/database epoch and plugin availability. */
+ assertCurrent(): void;
+ assertAuthorized(pluginId: string): void;
+ resolveRoute(pluginId: string, route?: PluginTaskRoute): Promise<PluginTaskRoute>;
+ createSession(
+ pluginId: string,
+ taskId: string,
+ title: string,
+ route: PluginTaskRoute,
+ isolatedWorkspace?: boolean,
+ ): Promise<void>;
+ readSession(taskId: string): Promise<PluginTaskView | null>;
+ dispatch(
+ pluginId: string,
+ taskId: string,
+ clientId: string,
+ text: string,
+ ): Promise<{ ok: boolean; message?: string }>;
+ inspect(
+ taskId: string,
+ ): Promise<{ execution: SessionExecutionIdentity | null; pending: readonly OwnedQueuedInput[] }>;
+ cancel(
+ pluginId: string,
+ taskId: string,
+ inputClientIds: readonly string[],
+ execution?: SessionExecutionIdentity,
+ ): Promise<'cancelled' | 'stopping' | 'stale'>;
+ now?: () => number;
+ id?: () => string;
+}
+
+/** Uses native input/terminal facts. Never infers completion from idle or the latest assistant. */
+export function createPluginTaskService(deps: PluginTaskServiceDeps) {
+ const now = deps.now ?? Date.now;
+ const id = deps.id ?? randomUUID;
+ // One service is retained for a database epoch. Mutations serialize with lifecycle receipts.
+ let tail: Promise<unknown> = Promise.resolve();
+ const exclusive = <T>(fn: () => Promise<T>): Promise<T> => {
+ const result = tail.then(() => {
+ deps.assertCurrent();
+ return fn();
+ });
+ tail = result.catch(() => undefined);
+ return result;
+ };
+ const save = async (row: PluginTaskReceipt, payload: unknown) => {
+ deps.assertCurrent();
+ row.payload = JSON.stringify(payload);
+ await deps.store.save(row);
+ row.revision++;
+ };
+ const ownTask = async (pluginId: string, taskId: string) => {
+ deps.assertAuthorized(pluginId);
+ const receipt = await deps.store.get(taskId);
+ if (!receipt || receipt.pluginId !== pluginId || receipt.operation !== 'create')
+ return fail('TASK_NOT_FOUND', 'Task not found');
+ const view = await deps.readSession(taskId);
+ if (!view || view.status === 'deleted') return fail('TASK_NOT_FOUND', 'Task not found');
+ return view;
+ };
+ const ownRun = async (pluginId: string, runId: string) => {
+ const row = await deps.store.get(runId);
+ if (!row || row.pluginId !== pluginId || row.operation !== 'send')
+ return fail('TASK_NOT_FOUND', 'Run not found');
+ await ownTask(pluginId, row.targetId);
+ return row;
+ };
+ const replay = (row: PluginTaskReceipt | undefined, fingerprint: string) => {
+ if (row && row.fingerprint !== fingerprint)
+ fail('IDEMPOTENCY_CONFLICT', 'Request key was used with different input');
+ return row;
+ };
+ const newReceipt = (
+ pluginId: string,
+ operation: 'create' | 'send',
+ targetId: string,
+ requestKey: string,
+ fingerprint: string,
+ payload: unknown,
+ receiptId = id(),
+ ): PluginTaskReceipt => ({
+ id: receiptId,
+ pluginId,
+ operation,
+ targetId,
+ requestKey,
+ fingerprint,
+ payload: JSON.stringify(payload),
+ revision: 0,
+ createdAt: now(),
+ });
+ const reconcile = async (row: PluginTaskReceipt): Promise<PluginTaskRun> => {
+ const run = JSON.parse(row.payload) as PluginTaskRun;
+ if (terminal(run)) return run;
+ const observed = await deps.inspect(run.taskId);
+ if (
+ observed.pending.some((item) => queuedInputBelongsTo(item, (value) => ownsInput(run, value)))
+ )
+ return run;
+ if (isSameSessionExecution(observed.execution, run.execution)) return run;
+ // Lack of a terminal is not success. Never replay an ambiguously dispatched input.
+ run.status = 'reconciling';
+ run.error =
+ 'No matching live execution or pending input; inspect the task before sending a new request.';
+ return run;
+ };
+ return {
+ create: (
+ pluginId: string,
+ request: { requestKey: string; title: string; route?: PluginTaskRoute; isolatedWorkspace?: boolean },
+ ) =>
+ exclusive(async () => {
+ deps.assertAuthorized(pluginId);
+ const fingerprint = hash([request.title, request.route ?? null, ...(request.isolatedWorkspace ? [true] : [])]);
+ let row = replay(
+ await deps.store.find(pluginId, 'create', '', request.requestKey),
+ fingerprint,
+ );
+ if (row) {
+ // Do not recreate a deleted/ambiguous task on replay.
+ return ownTask(pluginId, row.id);
+ }
+ const route = await deps.resolveRoute(pluginId, request.route);
+ deps.assertCurrent();
+ const taskId = id();
+ row = newReceipt(
+ pluginId,
+ 'create',
+ '',
+ request.requestKey,
+ fingerprint,
+ { route, title: request.title },
+ taskId,
+ );
+ await deps.store.insert(row);
+ deps.assertCurrent();
+ await deps.createSession(pluginId, taskId, request.title, route, request.isolatedWorkspace);
+ return ownTask(pluginId, taskId);
+ }),
+ setTeamPlan: (pluginId: string, taskId: string, plan: PluginTeamPlan) => exclusive(async () => {
+ await ownTask(pluginId,taskId);
+ const row = (await deps.store.get(taskId))!;
+ const data = JSON.parse(row.payload);
+ if (data.teamPlan && hash(data.teamPlan) !== hash(plan)) return fail('IDEMPOTENCY_CONFLICT', 'Team plan is immutable');
+ deps.assertAuthorized(pluginId);
+ await save(row,{...data,teamPlan:plan});
+ return {ok:true};
+ }),
+ settleWorkerLabel: (pluginId: string, taskId: string, label: string) => exclusive(async () => {
+ await ownTask(pluginId,taskId);
+ const row = (await deps.store.get(taskId))!;
+ const data = JSON.parse(row.payload);
+ if (!data.teamPlan?.items.some((x: {label:string})=>x.label===label)) return fail('INVALID_REQUEST','Worker is not in team plan');
+ await save(row,{...data,settledLabels:[...new Set([...(data.settledLabels||[]),label])]});
+ }),
+ get: (pluginId: string, taskId: string) => exclusive(() => ownTask(pluginId, taskId)),
+ list: (pluginId: string, after = '', limit = 50) =>
+ exclusive(async () => {
+ deps.assertAuthorized(pluginId);
+ const rows = await deps.store.list(pluginId, 'create', null, after, limit);
+ const items = [];
+ for (const row of rows) {
+ const view = await deps.readSession(row.id);
+ if (view && view.status !== 'deleted') items.push(view);
+ }
+ return { items, nextCursor: rows.length === limit ? rows.at(-1)!.id : null };
+ }),
+ send: async (
+ pluginId: string,
+ request: { taskId: string; requestKey: string; expectedRevision: number; text: string },
+ ): Promise<PluginTaskRun> => {
+ const prepared = await exclusive(async () => {
+ const view = await ownTask(pluginId, request.taskId);
+ const fingerprint = hash([request.text, request.expectedRevision]);
+ const previous = replay(
+ await deps.store.find(pluginId, 'send', request.taskId, request.requestKey),
+ fingerprint,
+ );
+ if (previous)
+ return { run: JSON.parse(previous.payload) as PluginTaskRun, dispatch: false };
+ if (view.permissionMode === 'bypassPermissions') return fail('PERMISSION_DENIED', 'Task permission exceeds plugin dispatch policy');
+ if (view.status !== 'active')
+ return fail('TASK_BUSY', 'Archived tasks cannot accept input');
+ if (view.revision !== request.expectedRevision)
+ return fail('REVISION_CONFLICT', 'Task configuration changed');
+ await deps.resolveRoute(pluginId, view.resolvedConfig);
+ const runId = id();
+ const run: PluginTaskRun = {
+ runId,
+ taskId: view.taskId,
+ inputMessageId: `plugin-task:${runId}`,
+ status: 'queued',
+ acceptedAt: now(),
+ acceptedConfig: view.resolvedConfig,
+ usage: { status: 'unavailable', reason: 'Per-input usage has not been reconciled.' },
+ };
+ deps.assertAuthorized(pluginId);
+ await deps.store.insert(
+ newReceipt(pluginId, 'send', view.taskId, request.requestKey, fingerprint, run, runId),
+ );
+ return { run, dispatch: true };
+ });
+ if (!prepared.dispatch) return prepared.run;
+ let failure: 'failed' | 'reconciling' | undefined;
+ // Never hold the receipt lock while entering Session dispatch/control. The
+ // coordinator awaits accept() before vendor dispatch under its own lock.
+ try {
+ deps.assertAuthorized(pluginId);
+ const outcome = await deps.dispatch(
+ pluginId,
+ prepared.run.taskId,
+ prepared.run.inputMessageId,
+ request.text,
+ );
+ if (!outcome.ok) failure = 'failed';
+ } catch {
+ failure = 'reconciling';
+ }
+ return exclusive(async () => {
+ const row = await ownRun(pluginId, prepared.run.runId);
+ const run = JSON.parse(row.payload) as PluginTaskRun;
+ // A synchronous native terminal wins over a delayed dispatch response.
+ if (failure && !terminal(run) && run.status === 'queued') {
+ run.status = failure;
+ run.error =
+ failure === 'failed'
+ ? 'Input was not accepted by the host.'
+ : 'Dispatch outcome is unknown; this request will not be replayed.';
+ await save(row, run);
+ }
+ return run;
+ });
+ },
+ getRun: async (pluginId: string, runId: string) =>
+ reconcile(await exclusive(() => ownRun(pluginId, runId))),
+ listRuns: async (pluginId: string, taskId: string, after = '', limit = 50) => {
+ const rows = await exclusive(async () => {
+ await ownTask(pluginId, taskId);
+ return deps.store.list(pluginId, 'send', taskId, after, limit);
+ });
+ const items = await Promise.all(rows.map(reconcile));
+ deps.assertCurrent();
+ deps.assertAuthorized(pluginId);
+ return { items, nextCursor: rows.length === limit ? rows.at(-1)!.id : null };
+ },
+ cancel: async (pluginId: string, runId: string): Promise<PluginTaskRun> => {
+ const prepared = await exclusive(async () => {
+ const row = await ownRun(pluginId, runId);
+ const run = JSON.parse(row.payload) as PluginTaskRun;
+ if (terminal(run)) return run;
+ deps.assertAuthorized(pluginId);
+ run.status = 'stopping';
+ await save(row, run);
+ return run;
+ });
+ if (terminal(prepared)) return prepared;
+ deps.assertAuthorized(pluginId);
+ const outcome = await deps.cancel(
+ pluginId,
+ prepared.taskId,
+ [prepared.inputMessageId, ...(prepared.inputClientIds ?? [])],
+ prepared.execution,
+ );
+ return exclusive(async () => {
+ const row = await ownRun(pluginId, runId);
+ const run = JSON.parse(row.payload) as PluginTaskRun;
+ if (terminal(run)) return run;
+ run.status = outcome === 'stale' ? 'reconciling' : outcome;
+ if (outcome === 'cancelled') run.completedAt = now();
+ await save(row, run);
+ return run;
+ });
+ },
+ /** Awaited before vendor dispatch. Aliases are native recovery provenance, never caller input. */
+ accept: (taskId: string, item: OwnedQueuedInput, execution: SessionExecutionIdentity) =>
+ exclusive(async () => {
+ for (const row of await deps.store.forSession(taskId)) {
+ const run = JSON.parse(row.payload) as PluginTaskRun;
+ if (!queuedInputBelongsTo(item, (clientId) => ownsInput(run, clientId))) continue;
+ if (terminal(run) || run.status === 'stopping') {
+ if (
+ item.clientId !== run.inputMessageId &&
+ !run.inputClientIds?.includes(item.clientId)
+ )
+ continue;
+ return fail('REQUEST_EXPIRED', 'Input was already settled');
+ }
+ const view = await ownTask(row.pluginId, taskId);
+ if (view.permissionMode === 'bypassPermissions') return fail('PERMISSION_DENIED', 'Task permission exceeds plugin dispatch policy');
+ if (hash(view.resolvedConfig) !== hash(run.acceptedConfig))
+ return fail('ROUTE_UNAVAILABLE', 'Accepted route changed before dispatch');
+ await deps.resolveRoute(row.pluginId, run.acceptedConfig);
+ run.inputClientIds = [...new Set([...(run.inputClientIds ?? []), item.clientId])];
+ run.execution = execution;
+ run.status = 'running';
+ await save(row, run);
+ }
+ }),
+ settle: (
+ taskId: string,
+ execution: SessionExecutionIdentity,
+ status: 'completed' | 'failed',
+ outputMessageId?: string,
+ ) =>
+ exclusive(async () => {
+ for (const row of await deps.store.forSession(taskId)) {
+ const run = JSON.parse(row.payload) as PluginTaskRun;
+ if (terminal(run) || !isSameSessionExecution(run.execution, execution)) continue;
+ run.status = status;
+ run.completedAt = now();
+ if (outputMessageId) run.outputMessageId = outputMessageId;
+ await save(row, run);
+ }
+ }),
+ discard: (taskId: string, item: OwnedQueuedInput, status: 'cancelled' | 'failed') =>
+ exclusive(async () => {
+ for (const row of await deps.store.forSession(taskId)) {
+ const run = JSON.parse(row.payload) as PluginTaskRun;
+ if (terminal(run) || !queuedInputBelongsTo(item, (value) => ownsInput(run, value)))
+ continue;
+ // A late queue cleanup for an older accepted input cannot settle a
+ // newer recovery attempt. Unknown aliases still represent rejection
+ // before acceptance and must be settled by the coordinator.
+ const latestAccepted = run.inputClientIds?.at(-1);
+ if (
+ run.execution &&
+ latestAccepted &&
+ ownsInput(run, item.clientId) &&
+ item.clientId !== latestAccepted
+ )
+ continue;
+ run.status = status;
+ run.completedAt = now();
+ await save(row, run);
+ }
+ }),
+ };
+}
+export type PluginTaskService = ReturnType<typeof createPluginTaskService>;
diff --git a/apps/desktop/src/main/maker-ipc/pluginTaskStore.ts b/apps/desktop/src/main/maker-ipc/pluginTaskStore.ts
new file mode 100644
index 0000000000..1510534968
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/pluginTaskStore.ts
@@ -0,0 +1,57 @@
+import { and, asc, eq, gt } from 'drizzle-orm';
+import type { DbClient } from '../localDb/client/DbClient.js';
+import { pluginTaskRequests } from '../localDb/schema.js';
+import type { PluginTaskStore } from './pluginTaskService.js';
+
+/** Captures the DB handle once, so a delayed operation never switches accounts. */
+export function createPluginTaskStore(db: DbClient): PluginTaskStore {
+ const table = pluginTaskRequests;
+ return {
+ get: async (id) => (await db.drizzle.select().from(table).where(eq(table.id, id)).limit(1))[0],
+ find: async (pluginId, operation, targetId, requestKey) =>
+ (
+ await db.drizzle
+ .select()
+ .from(table)
+ .where(
+ and(
+ eq(table.pluginId, pluginId),
+ eq(table.operation, operation as 'create' | 'send'),
+ eq(table.targetId, targetId),
+ eq(table.requestKey, requestKey),
+ ),
+ )
+ .limit(1)
+ )[0],
+ list: (pluginId, operation, targetId, after, limit) =>
+ db.drizzle
+ .select()
+ .from(table)
+ .where(
+ and(
+ eq(table.pluginId, pluginId),
+ eq(table.operation, operation as 'create' | 'send'),
+ targetId === null ? undefined : eq(table.targetId, targetId),
+ gt(table.id, after),
+ ),
+ )
+ .orderBy(asc(table.id))
+ .limit(limit),
+ forSession: (taskId) =>
+ db.drizzle
+ .select()
+ .from(table)
+ .where(and(eq(table.operation, 'send'), eq(table.targetId, taskId))),
+ insert: async (row) => {
+ await db.drizzle.insert(table).values(row);
+ },
+ save: async (row) => {
+ const result = await db.drizzle
+ .update(table)
+ .set({ payload: row.payload, revision: row.revision + 1 })
+ .where(and(eq(table.id, row.id), eq(table.revision, row.revision)))
+ .returning({ id: table.id });
+ if (!result.length) throw new Error('Plugin task receipt revision conflict');
+ },
+ };
+}
diff --git a/apps/desktop/src/main/maker-ipc/pluginWorkerCompletion.ts b/apps/desktop/src/main/maker-ipc/pluginWorkerCompletion.ts
new file mode 100644
index 0000000000..abf08a46d2
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/pluginWorkerCompletion.ts
@@ -0,0 +1,14 @@
+/** Recover a released Worker only from the host-stamped final turn, never report text. */
+export function pluginWorkerCompletedAt(input: {
+ status: string; working: boolean; queued: number; paused: boolean;
+ startedAt: number | null; endedAt: number | null; clearedAt?: number | null;
+ anchor?: {role: string; createdAt: number; agentMeta: string | null};
+}): number | null {
+ if (input.working || input.queued !== 0 || input.paused || !['idle', 'done'].includes(input.status)) return null;
+ const {startedAt, endedAt, anchor} = input;
+ if (!startedAt || !endedAt || endedAt < startedAt || !anchor || anchor.role !== 'assistant' || anchor.createdAt < startedAt || anchor.createdAt > endedAt || anchor.createdAt <= (input.clearedAt ?? 0)) return null;
+ try {
+ const meta = JSON.parse(anchor.agentMeta ?? '{}');
+ return meta?.turnCompleted === true && !meta.parentUuid ? endedAt : null;
+ } catch { return null; }
+}
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index f3a293f77f..10685d949c 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -1,3 +1,10 @@
+import { createPluginTaskService, PluginTaskError, type PluginTaskService } from './pluginTaskService.js';
+import { pluginWorkerCompletedAt } from './pluginWorkerCompletion.js';
+import { createPluginTaskStore } from './pluginTaskStore.js';
+import { controlOwnedSessionExecution, isSameSessionExecution, withdrawOwnedSessionInputs } from './sessionExecutionOwnership.js';
+import { setPluginTaskHandler, isPluginTaskAuthorized } from '../cindy-brain/index.js';
+import type { PluginTaskRoute } from '../../shared/pluginTasks.js';
+import { createHash as pluginTaskConfigHash } from 'node:crypto';
import { createBotMessageTransport } from './botMessageTransport.js';
import { setBotRemoteMessageService } from './botRemoteMessageReceiver.js';
import { handleListDevices, defaultDeps as deviceDirectoryDeps } from '../device-link/ipc.js';
@@ -70,6 +77,7 @@ import type {
} from '@cindy/maker-core';
import {
effectiveSourceIdForModel,
+ isModelSelectableForNewRoute,
buildUserProvider,
mergeDiscoveredRuntimeModels,
findCatalogModel,
@@ -94,7 +102,7 @@ import {
DL_SESSION_REFERENCE_CAPABILITY_CHANNEL,
readInputDeliveryClientIds,
} from '@cindy/device-link';
-import { and, desc, eq, gte, inArray, isNull, lt, sql } from 'drizzle-orm';
+import { and, asc, desc, eq, gte, inArray, isNull, lt, sql } from 'drizzle-orm';
import { applyScheduledModelSelection, ScheduledModelSelectionBusyError, type ScheduledModelSelection, type ScheduledModelSelectionLease } from './scheduledModelSelection';
import { app, BrowserWindow, dialog, ipcMain, shell, type IpcMainInvokeEvent } from 'electron';
import {
@@ -395,6 +403,7 @@ import {
messages,
orcaTeams,
orcaWorkers,
+ orcaWorkerCreationReservations,
sessions,
} from '../localDb/schema.js';
import { nextBotModelRoute, normalizeBotModelChain } from '../../shared/botModelChain.js';
@@ -1159,6 +1168,7 @@ import {
} from '../cindy-brain/index.js';
import {
readGhostErrandConfig,
+ writeGhostErrandConfig,
readGhostErrandSessionId,
writeGhostErrandSessionId,
} from '../cindy-brain/errandPrefsStore.js';
@@ -1167,7 +1177,7 @@ import {
resolveGhostUserHookModel,
withGhostUserHookModel,
} from '../cindy-brain/subscriptionGateway.js';
-import { createGhostErrandRunner } from './ghostErrandRunner.js';
+import { createGhostErrandRunner, clampErrandPermissionMode } from './ghostErrandRunner.js';
import {
createGhostErrandSession,
createPluginDraftSession,
@@ -4539,6 +4549,13 @@ const sessionBindings = createSessionBindingLifecycle<WiredSession, WiredSession
},
});
+let pluginTaskServiceForCurrentOwner: (() => PluginTaskService) | null = null;
+function notePluginTaskLifecycle(operation: (service: PluginTaskService) => Promise<unknown>): void {
+ if (!pluginTaskServiceForCurrentOwner) return;
+ try { void operation(pluginTaskServiceForCurrentOwner()).catch(() => log.warn('Plugin task receipt update failed')); }
+ catch { /* Database is unavailable during logout/startup; never switch to another owner. */ }
+}
+
function isCurrentProductTurnFailureOwner(owner: ProductTurnFailureOwner): boolean {
const bound = sessionBindings.getSession(owner.sessionId);
// A closed owner may still receive its renderer's final deferred-persist IPC.
@@ -4572,6 +4589,7 @@ async function interruptProductTurn(
deferredProductTurnFailureGate.clear(owner);
if (!isCurrentProductTurnFailureOwner(owner)) return;
}
+ if (owner) notePluginTaskLifecycle(service => service.settle(sessionId, owner, 'failed'));
await interruptUpstreamMergeTurn(sessionId);
}
@@ -4618,6 +4636,9 @@ function cleanupClosedSessionRuntime(session: WiredSession): void {
// operation. Capturing these services when wiring a Session would freeze the
// pre-initialization or previous runtime value for later events.
const sessionEventDependencies: SessionEventDependencies = {
+ onPluginTaskTerminal: (sessionId, execution, outcome, outputMessageId) => {
+ notePluginTaskLifecycle(service => service.settle(sessionId, execution, outcome, outputMessageId));
+ },
onSuccessfulProductTurn: finishProductTurn,
onUnsuccessfulProductTurn: interruptProductTurn,
deferUnsuccessfulProductTurn: (owner) => deferredProductTurnFailureGate.defer(owner),
@@ -8858,6 +8879,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
createDefaults?: SendToSessionCreateDefaults;
/** 安全调用方可要求新会话不比来源会话拥有更高的权限。 */
inheritSourcePermissionMode?: boolean;
+ /** Host-owned durable inputs use the coordinator even when idle. */
+ forceQueue?: boolean;
}): Promise<SendToSessionInternalResult> {
const {
targetSessionId,
@@ -9214,7 +9237,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
// Pending selections also need the canonical send transaction: it consumes the intent,
// then refreshes queued createOpts from DB before starting the target harness.
// enqueue does not await dispatch, so the drain can acquire this lock after we return.
- if (explicitClientId?.startsWith('bot-dm:') || explicitClientId?.startsWith('bot-authorization-resume:') || inputCoordinator.shouldQueueNewTurn(targetSessionId) || agentSwitchPending.get(targetSessionId)) {
+ if (params.forceQueue || explicitClientId?.startsWith('bot-dm:') || explicitClientId?.startsWith('bot-authorization-resume:') || inputCoordinator.shouldQueueNewTurn(targetSessionId) || agentSwitchPending.get(targetSessionId)) {
lockStage = 'enqueue-queued-message';
const qClientId = explicitClientId ?? createId();
await enqueueSendToSessionMessage({
@@ -10082,6 +10105,287 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
// 这里注入真实执行链——专属会话确保/统一投递/turn 收口。投递仍走
// sendToSessionInternal 这一条主机通路(消息落库、进程拉起与用户亲发一致);
// 收口复用 hook-control 的 observeHookTurn(与飞书 bot 同一套 turn 观察语义)。
+ // One receipt service per account/database epoch. No mutable current-DB lookup
+ // is retained by an asynchronous task request.
+ let pluginTaskEpoch: ReturnType<typeof getCurrentDbClientSnapshot> = null;
+ let pluginTasks: PluginTaskService | null = null;
+ pluginTaskServiceForCurrentOwner = () => {
+ const snapshot = getCurrentDbClientSnapshot();
+ if (!snapshot) throw new PluginTaskError('HOST_NOT_READY', 'Task storage is unavailable', true);
+ if (pluginTaskEpoch === snapshot && pluginTasks) return pluginTasks;
+ const assertCurrent = () => {
+ if (getCurrentDbClientSnapshot() !== snapshot) throw new PluginTaskError('PERMISSION_DENIED', 'Account changed');
+ };
+ const assertPlugin = (pluginId: string) => {
+ assertCurrent();
+ if (!isPluginTaskAuthorized(pluginId)) throw new PluginTaskError('PERMISSION_DENIED', 'Plugin task capability is unavailable');
+ };
+ const routeUnavailable = (): never => { throw new PluginTaskError('ROUTE_UNAVAILABLE', 'The selected provider, model or effort is unavailable'); };
+ const resolveRoute = async (pluginId: string, requested?: PluginTaskRoute): Promise<PluginTaskRoute> => {
+ assertPlugin(pluginId);
+ const cfg = readGhostErrandConfig(pluginId);
+ const agentKind = requested?.agentKind ?? cfg.agentKind ?? 'cc';
+ const defaults = getWorkerDefaultsFromNewMaker(agentKind === 'cc' ? 'claude-code' : agentKind);
+ const modelId = requested?.model ?? cfg.model ?? defaults.model;
+ if (!modelId) return routeUnavailable();
+ const providers = await getDesktopProviderService().listProviders({ allowSideEffects: false, catalog: getActiveCatalog() });
+ assertPlugin(pluginId);
+ const providerId = requested?.providerId ?? cfg.providerId ?? defaults.providerId ?? effectiveSourceIdForModel(providers, null, modelId, agentKind === 'cc' ? 'claude-code' : agentKind);
+ const provider = providers.find(p => p.id === providerId && p.connected && !p.suspended && !p.removed);
+ const model = findCatalogModel(provider, modelId, agentKind === 'cc' ? 'claude-code' : agentKind, { exact: true });
+ if (!provider || !model || !isModelSelectableForNewRoute(model, { userProvider: provider.source === 'user' })) return routeUnavailable();
+ const effort = requested?.effort ?? cfg.effort ?? defaults.effort ?? model.defaultEffort ?? 'high';
+ const fastMode = requested?.fastMode ?? cfg.fastMode ?? defaults.fastMode ?? false;
+ if (!model.efforts.some(e => e === effort)) return routeUnavailable();
+ if (fastMode && model.supportsFastMode !== true) return routeUnavailable();
+ return { agentKind, providerId: provider.id, model: modelId, effort, fastMode };
+ };
+ const readExecution = (taskId: string) => {
+ const live = maker.getSession(taskId);
+ return live && (live.isTurnRunning() || live.getTurnControlSnapshot().pendingInteractionCount > 0) ? { instanceId: live.instanceId, generation: live.getTurnGeneration() } : null;
+ };
+ pluginTaskEpoch = snapshot;
+ pluginTasks = createPluginTaskService({
+ store: createPluginTaskStore(snapshot.client), assertCurrent, assertAuthorized: assertPlugin, resolveRoute,
+ createSession: async (pluginId, taskId, title, route, isolatedWorkspace) => {
+ assertPlugin(pluginId);
+ const cfg = readGhostErrandConfig(pluginId);
+ await createGhostErrandSession({
+ ghostId: pluginId, sessionId: taskId, title, ...route,
+ permissionMode: clampErrandPermissionMode(cfg.permissionMode),
+ ...(!isolatedWorkspace && cfg.workingDir ? { workingDir: cfg.workingDir } : {}),
+ shouldContinue: () => getCurrentDbClientSnapshot() === snapshot && isPluginTaskAuthorized(pluginId),
+ notifySessionCreated: ({ sessionId, workdir }) => {
+ notifyGhostSessionEvent('created', { sessionId, workdir });
+ broadcastSessionCreated(sessionId);
+ },
+ });
+ },
+ readSession: async taskId => {
+ assertCurrent();
+ const [row] = await snapshot.client.drizzle.select().from(sessions).where(eq(sessions.id, taskId)).limit(1);
+ assertCurrent();
+ if (!row || row.source !== 'plugin' || row.remoteHostId || (row.orcaRole && row.orcaRole !== 'lead') || !['cc', 'codex', 'pi'].includes(row.agentKind)) return null;
+ const resolvedConfig: PluginTaskRoute = { agentKind: row.agentKind as PluginTaskRoute['agentKind'], providerId: row.providerId ?? '', model: row.model, effort: row.effort, fastMode: row.fastMode };
+ const revision = Number.parseInt(pluginTaskConfigHash('sha256').update(JSON.stringify([resolvedConfig, row.permissionMode, row.planModeEnabled, row.workingDir, row.status, row.orcaRole])).digest('hex').slice(0, 12), 16);
+ return { taskId, title: row.title, status: row.status, revision, resolvedConfig, workingDir: row.workingDir ?? undefined, permissionMode: row.permissionMode };
+ },
+ dispatch: async (pluginId, taskId, clientId, text) => {
+ assertPlugin(pluginId);
+ const outcome = await sendToSessionInternal({ targetSessionId: taskId, clientId, message: text, forceQueue: true, onAccepted: () => assertPlugin(pluginId) });
+ await awaitAgentInputQueueSnapshotPersistence(taskId);
+ assertCurrent();
+ return outcome;
+ },
+ inspect: async taskId => {
+ assertCurrent(); await inputCoordinator.ensureQueueRestored(taskId); assertCurrent();
+ if (!inputCoordinator.isQueueRestored(taskId)) throw new PluginTaskError('HOST_NOT_READY', 'Task queue is restoring', true);
+ return { execution: readExecution(taskId), pending: inputCoordinator.getQueueControlSnapshot(taskId).pendingQueue };
+ },
+ cancel: async (pluginId, taskId, inputClientIds, execution) => {
+ assertPlugin(pluginId);
+ await inputCoordinator.ensureQueueRestored(taskId);
+ assertCurrent();
+ if (!inputCoordinator.isQueueRestored(taskId)) throw new PluginTaskError('HOST_NOT_READY', 'Task queue is restoring', true);
+ await withdrawOwnedSessionInputs({ sessionId: taskId, queue: inputCoordinator, owns: value => { assertPlugin(pluginId); return inputClientIds.includes(value); }, flush: awaitAgentInputQueueSnapshotPersistence });
+ assertCurrent();
+ if (!execution) return 'cancelled';
+ let stopped = false;
+ const applied = await controlOwnedSessionExecution({
+ sessionId: taskId, withSessionLock: withSessionRestartLock,
+ matches: () => getCurrentDbClientSnapshot() === snapshot && isPluginTaskAuthorized(pluginId) && isSameSessionExecution(readExecution(taskId), execution),
+ operation: async () => {
+ assertPlugin(pluginId);
+ resetAutomaticRecoveryForExplicitStop(taskId);
+ contextOverflowRolloverHolder?.cancelRecovery(taskId);
+ const outcome = await sessionControlService.stopSessionTurn({ targetSessionId: taskId });
+ if (!outcome.ok) throw new PluginTaskError('UNSUPPORTED_CAPABILITY', 'Execution does not support stopping');
+ stopped = outcome.status === 'no-active-turn';
+ },
+ });
+ return applied ? (stopped ? 'stale' : 'stopping') : 'stale';
+ },
+ });
+ return pluginTasks;
+ };
+ const startOrcaTeamForCaller = async (leadSessionId: string, workerPermissionMode?: OrcaWorkerPermissionMode, assertCurrent?: () => Promise<void>) => {
+ try {
+ await assertLeadCollabProjectEnabled(leadSessionId);
+ return await startOrcaTeamWithPermissionGate(
+ { leadSessionId, workerPermissionMode },
+ {
+ getCurrentWorkerPermissionMode: getWorkerPermissionModeFromCreationPrefs,
+ requestFullAccessConfirmation: (sessionId) =>
+ orcaWorkerPermissionConfirmBridge.request(sessionId, {
+ title: t('newChat.chatInput.fullAccessConfirmation.title'),
+ description: `${t('newChat.chatInput.fullAccessConfirmation.description')} ${t('newChat.chatInput.fullAccessConfirmation.note')}`,
+ }),
+ startTeam: async (params) => { await assertCurrent?.(); return orcaLifecycleService.startTeam(params); },
+ },
+ );
+ } catch (err) {
+ return {
+ ok: false as const,
+ errorCode:
+ err instanceof Error && (err as unknown as { code?: string }).code
+ ? (err as unknown as { code: string }).code
+ : 'INTERNAL',
+ message: err instanceof Error ? err.message : String(err),
+ };
+ }
+ };
+ const pluginPermissionRequests = new Set<string>();
+ setPluginTaskHandler(async (pluginId, request) => {
+ const service = pluginTaskServiceForCurrentOwner!();
+ switch (request.kind) {
+ case 'requestWriteAccess': {
+ const snapshot = getCurrentDbClientSnapshot();
+ const task = await service.get(pluginId, request.taskId);
+ const mode = request.mode ?? 'acceptEdits';
+ const cfg = readGhostErrandConfig(pluginId);
+ if (mode === 'acceptEdits' ? task.permissionMode !== 'plan' : task.permissionMode === 'auto' && cfg.permissionMode === 'auto') return { granted: true, task };
+ if (pluginPermissionRequests.size) throw new PluginTaskError('TASK_BUSY', 'A permission request is already open');
+ const before = JSON.stringify(cfg);
+ const assertIdle = async () => {
+ if (mode === 'acceptEdits' && (await service.listRuns(pluginId, task.taskId)).items.length) throw new PluginTaskError('TASK_BUSY', 'Only an unstarted task can request write access');
+ const live = maker.getSession(task.taskId);
+ if (live?.isTurnRunning() || live?.getTurnControlSnapshot().pendingInteractionCount || inputCoordinator.getQueueControlSnapshot(task.taskId).pendingQueue.length) throw new PluginTaskError('TASK_BUSY', 'Wait for the current turn before changing permission');
+ };
+ await assertIdle();
+ pluginPermissionRequests.add(pluginId);
+ try {
+ const result = await dialog.showMessageBox({
+ type: 'question', title: t(mode === 'auto' ? 'pluginTaskWriteAccess.autoTitle' : 'pluginTaskWriteAccess.title'),
+ message: t(mode === 'auto' ? 'pluginTaskWriteAccess.autoMessage' : 'pluginTaskWriteAccess.message').replace('{{name}}', getInstalledGhostName(pluginId) ?? pluginId),
+ detail: t(mode === 'auto' ? 'pluginTaskWriteAccess.autoDetail' : 'pluginTaskWriteAccess.detail'),
+ buttons: [t('pluginTaskWriteAccess.allow'), t('pluginTaskWriteAccess.cancel')], defaultId: 1, cancelId: 1,
+ });
+ if (result.response !== 0) return { granted: false };
+ if (snapshot !== getCurrentDbClientSnapshot() || before !== JSON.stringify(readGhostErrandConfig(pluginId))) throw new PluginTaskError('PERMISSION_DENIED', 'Account or permission settings changed');
+ const fresh = await service.get(pluginId, task.taskId);
+ if (fresh.revision !== task.revision) throw new PluginTaskError('TASK_BUSY', 'Task changed while awaiting permission');
+ await assertIdle();
+ const live = maker.getSession(task.taskId);
+ if (live) await live.setPermissionMode(mode);
+ try {
+ if (snapshot !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED', 'Account changed');
+ const saved = await snapshot!.client.tx('bots.persistSessionPermission', {sessionId: task.taskId, mode});
+ if (!saved.updated) throw new PluginTaskError('TASK_NOT_FOUND', 'Task not found');
+ } catch (error) {
+ if (live) await live.setPermissionMode(task.permissionMode as Parameters<typeof live.setPermissionMode>[0]).catch(() => undefined);
+ throw error;
+ }
+ if (snapshot !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED', 'Account changed');
+ await service.get(pluginId, task.taskId);
+ if (mode === 'auto' || clampErrandPermissionMode(cfg.permissionMode) === 'plan') writeGhostErrandConfig(pluginId, {...cfg, permissionMode: mode});
+ broadcastSessionPatched(task.taskId, {permissionMode: mode});
+ return { granted: true, task: await service.get(pluginId, task.taskId) };
+ } finally { pluginPermissionRequests.delete(pluginId); }
+ }
+ case 'startTeam': {
+ const epoch = getCurrentDbClientSnapshot();
+ const task = await service.get(pluginId, request.taskId);
+ if (task.permissionMode === 'plan' || task.permissionMode === 'bypassPermissions') throw new PluginTaskError('PERMISSION_DENIED', 'Coordinator requires an allowed execution permission');
+ const result = await startOrcaTeamForCaller(task.taskId, undefined, async () => {
+ if (epoch !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED', 'Account changed');
+ const fresh = await service.get(pluginId, task.taskId);
+ if (fresh.revision !== task.revision) throw new PluginTaskError('STALE_REVISION', 'Task changed during confirmation');
+ });
+ if (epoch !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED', 'Account changed');
+ await service.get(pluginId, task.taskId);
+ return result;
+ }
+ case 'setTeamPlan': return service.setTeamPlan(pluginId, request.taskId, request.plan);
+ case 'releaseWorker': {
+ const epoch = getCurrentDbClientSnapshot();
+ await service.get(pluginId,request.taskId);
+ if (!epoch) throw new PluginTaskError('HOST_NOT_READY','Task storage unavailable',true);
+ const [record] = await epoch.client.drizzle.select({id:orcaWorkers.id,sessionId:orcaWorkers.sessionId,label:orcaWorkers.label}).from(orcaWorkers).innerJoin(orcaTeams,eq(orcaWorkers.teamId,orcaTeams.id)).where(and(eq(orcaWorkers.id,request.workerId),eq(orcaTeams.leadSessionId,request.taskId))).limit(1);
+ if (epoch !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED','Account changed');
+ await service.get(pluginId,request.taskId);
+ if (!record) throw new PluginTaskError('TASK_NOT_FOUND','Worker not found');
+ const [row] = await epoch.client.drizzle.select().from(sessions).where(eq(sessions.id,record.sessionId)).limit(1);
+ if (!row || row.status === 'deleted') throw new PluginTaskError('TASK_NOT_FOUND','Worker not found');
+ const validate = async () => {
+ if (epoch !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED','Account changed');
+ await service.get(pluginId,request.taskId);
+ const [fresh] = await epoch.client.drizzle.select().from(sessions).where(eq(sessions.id,record.sessionId)).limit(1);
+ if (epoch !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED','Account changed');
+ if (!fresh || fresh.lastTurnEndedAt !== request.completedAt || (fresh.activeTurnStartedAt ?? 0) > request.completedAt) throw new PluginTaskError('STALE_REVISION','Worker execution changed');
+ };
+ if (row.status === 'archived') {
+ await validate();
+ await service.settleWorkerLabel(pluginId,request.taskId,record.label!);
+ return {ok:true,workerId:record.id};
+ }
+ const result = await orcaTeamService.archiveWorker({callerLeadSessionId:request.taskId,workerId:record.id,onlyIfIdle:true,beforeArchive:validate});
+ if (result.ok) await service.settleWorkerLabel(pluginId,request.taskId,record.label!);
+ return result;
+ }
+ case 'getTeam': {
+ const epoch = getCurrentDbClientSnapshot();
+ if (!epoch) throw new PluginTaskError('HOST_NOT_READY', 'Task storage unavailable', true);
+ await service.get(pluginId, request.taskId);
+ const team = await getOrcaWorkspaceInfoReadOnly(createOrcaDiagnosticsDeps(), request.taskId);
+ if (!team.ok) throw new PluginTaskError('HOST_NOT_READY', 'Collaboration state unavailable', true);
+ const records = await listWorkersByLead(request.taskId);
+ const workers = await Promise.all(team.workers.map(async worker => {
+ const [row] = await epoch!.client.drizzle.select().from(sessions).where(eq(sessions.id, worker.session_id)).limit(1);
+ const safeMeta = sql`CASE WHEN json_valid(${messages.agentMeta}) THEN ${messages.agentMeta} ELSE '{}' END`;
+ const [anchor] = await epoch.client.drizzle.select({role:messages.role, createdAt:messages.createdAt, agentMeta:messages.agentMeta}).from(messages)
+ .where(and(eq(messages.sessionId, worker.session_id), isNull(messages.rewindAt), inArray(messages.role, ['user', 'assistant']), sql`json_extract(${safeMeta}, '$.parentUuid') IS NULL`))
+ .orderBy(desc(messages.createdAt), desc(messages.id)).limit(1);
+ const [firstInput] = await epoch.client.drizzle.select({at:messages.createdAt}).from(messages).where(and(eq(messages.sessionId,worker.session_id),eq(messages.role,'user'),isNull(messages.rewindAt))).orderBy(asc(messages.createdAt)).limit(1);
+ const [firstActivity] = await epoch.client.drizzle.select({at:messages.createdAt}).from(messages).where(and(eq(messages.sessionId,worker.session_id),inArray(messages.role,['assistant','thinking','tool_use']),gte(messages.createdAt,firstInput?.at??row?.createdAt??0),isNull(messages.rewindAt))).orderBy(asc(messages.createdAt)).limit(1);
+ const restoredCompletion = pluginWorkerCompletedAt({status:worker.status, working:worker.is_working, queued:worker.queued_count, paused:worker.queue_paused, startedAt:row?.activeTurnStartedAt ?? null, endedAt:row?.lastTurnEndedAt ?? null, clearedAt:row?.clearedAt, anchor});
+ const completedAt = restoredCompletion ?? (worker.status === 'done' && !worker.is_working && worker.queued_count === 0 && !worker.queue_paused ? records.find(r=>r.id===worker.worker_id)?.updatedAt : null);
+ return {...worker, acceptedAt:firstInput?.at, startedAt:firstActivity?.at, timingBasis:'host-message-window', createdAt:row?.createdAt, lastTurnStartedAt:row?.activeTurnStartedAt, lastTurnEndedAt:row?.lastTurnEndedAt, waitingForUser:!!maker.getSession(worker.session_id)?.getTurnControlSnapshot().pendingInteractionCount, usage: {scope:'session-total', tokens:row?.totalTokenUsage ?? null, costUSD:row?.totalCostCurrency === 'USD' && row.totalCostAmount > 0 ? row.totalCostAmount : null, approximate:row?.totalCostIsApproximate ?? false, reason:row?.totalCostCurrency === 'USD' && row.totalCostAmount > 0 ? null : 'No confirmed USD cost; subscription value and other currencies are not a bill'}, status:completedAt ? 'done' : worker.status, permissionMode:row?.permissionMode, providerId:row?.providerId, fastMode:row?.fastMode, completedAt};
+ }));
+ if (epoch !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED', 'Account changed');
+ await service.get(pluginId, request.taskId);
+ const live = maker.getSession(request.taskId);
+ const [leadRow] = await epoch.client.drizzle.select().from(sessions).where(eq(sessions.id,request.taskId)).limit(1);
+ const reservations = team.workflow ? await epoch.client.drizzle.select({id:orcaWorkerCreationReservations.id}).from(orcaWorkerCreationReservations).where(and(eq(orcaWorkerCreationReservations.teamId,team.workflow.workflow_id),gte(orcaWorkerCreationReservations.expiresAt,Date.now()))) : [];
+ const occupiedSlots=workers.length+reservations.length;
+ const planRow = await createPluginTaskStore(epoch.client).get(request.taskId);
+ const plan = planRow ? JSON.parse(planRow.payload).teamPlan : undefined;
+ if (epoch !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED','Account changed');
+ await service.get(pluginId,request.taskId);
+ const hardLimit = Math.min(readCollaborationSettings().workerHardLimit, plan?.concurrency ?? Infinity);
+ return {...team, capacity:{hardLimit,occupiedSlots,remainingSlots:Math.max(0,hardLimit-occupiedSlots),advisory:true}, coordinatorUsage:{scope:'session-total',tokens:leadRow?.totalTokenUsage ?? null,costUSD:leadRow?.totalCostCurrency==='USD' && leadRow.totalCostAmount>0 ? leadRow.totalCostAmount : null, approximate:leadRow?.totalCostIsApproximate ?? false}, workers, waitingForUser:!!live && live.getTurnControlSnapshot().pendingInteractionCount > 0, leadWorking:(!!live && (live.isTurnRunning() || live.getTurnControlSnapshot().pendingInteractionCount > 0)) || inputCoordinator.getQueueControlSnapshot(request.taskId).pendingQueue.length > 0};
+ }
+ case 'create': return service.create(pluginId, request);
+ case 'get': return service.get(pluginId, request.taskId);
+ case 'list': return service.list(pluginId, request.after, request.limit);
+ case 'send': return service.send(pluginId, request);
+ case 'readMessages': {
+ const snapshot = getCurrentDbClientSnapshot();
+ await service.get(pluginId, request.taskId);
+ if (snapshot !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED', 'Account changed');
+ if (!snapshot) throw new PluginTaskError('HOST_NOT_READY', 'Task storage is unavailable', true);
+ let cursor: { createdAt: number; id: string; rowid?: number } | null = null;
+ if (request.after) {
+ try {
+ cursor = JSON.parse(request.after);
+ if (!cursor || typeof cursor.id !== 'string' || !Number.isSafeInteger(cursor.createdAt)
+ || (cursor.rowid !== undefined && !Number.isSafeInteger(cursor.rowid))) throw new Error('Invalid cursor');
+ } catch { throw new PluginTaskError('INVALID_REQUEST', 'Invalid message cursor'); }
+ }
+ await drainPersistQueue();
+ if (getCurrentDbClientSnapshot() !== snapshot) throw new PluginTaskError('PERMISSION_DENIED', 'Account changed');
+ const page = await getMessagesForHistory({ sessionIds: [request.taskId], workdir: null, fromMs: null, toMs: null,
+ agentKind: null, roles: null, includeRewound: false, limit: request.limit ?? 50, cursor, order: 'asc' });
+ if (getCurrentDbClientSnapshot() !== snapshot) throw new PluginTaskError('PERMISSION_DENIED', 'Account changed');
+ return { items: page.items.map(({ id, clientId, role, content, createdAt }) => ({ id: clientId ?? id, role, content, createdAt })),
+ nextCursor: page.nextCursor ? JSON.stringify(page.nextCursor) : null };
+ }
+ case 'getRun': return service.getRun(pluginId, request.runId);
+ case 'listRuns': return service.listRuns(pluginId, request.taskId, request.after, request.limit);
+ case 'cancel': return service.cancel(pluginId, request.runId);
+ default: throw new PluginTaskError('UNSUPPORTED_CAPABILITY', 'Task operation is unavailable');
+ }
+ });
+
setGhostErrandRunner(
createGhostErrandRunner({
readConfig: readGhostErrandConfig,
@@ -10833,6 +11137,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
};
const orcaTeamService = createOrcaTeamService({
+ withSessionSendLock: withSendToSessionLock,
getWorkerLinkBySessionId: (workerSessionId) => getWorkerLink({ workerSessionId }),
getWorkerLinkByWorkerId: (workerId) => getWorkerLink({ workerId }),
listWorkersByLead,
@@ -10859,8 +11164,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
}
await maker.closeSession(sessionId);
},
- closeWorkerSessionIfIdle: async (sessionId) => {
- if (sendToSessionLocks.has(sessionId)) return false;
+ closeWorkerSessionIfIdle: async (sessionId, sendLockHeld = false) => {
+ if (!sendLockHeld && sendToSessionLocks.has(sessionId)) return false;
const sess = maker.getSession(sessionId);
return sess ? sess.closeIfIdle() : true;
},
@@ -11047,6 +11352,21 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
listWorkersByLead,
isActiveWorkerStatus,
readCollaborationSettings,
+ validateCreationPlan: async params => {
+ const epoch = getCurrentDbClientSnapshot();
+ if (!epoch) throw new PluginTaskError('HOST_NOT_READY','Task storage unavailable');
+ const receipt = await createPluginTaskStore(epoch.client).get(params.leadSessionId);
+ if (!receipt || receipt.operation !== 'create') return undefined;
+ await pluginTaskServiceForCurrentOwner!().get(receipt.pluginId,params.leadSessionId);
+ if (epoch !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED','Account changed');
+ const data = JSON.parse(receipt.payload);
+ if (!data.teamPlan) return undefined; // Existing plugins retain their original behavior.
+ const item = data.teamPlan.items.find((x: {label:string})=>x.label===params.label);
+ if (!item || data.settledLabels?.includes(params.label)) throw new PluginTaskError('INVALID_REQUEST','Worker is not pending in the registered plan');
+ const route = item.route;
+ if (params.workingDir!==item.workingDir || params.model!==route.model || params.providerId!==route.providerId || params.effort!==route.effort || params.fast!==route.fastMode || params.agent!==(route.agentKind==='cc'?'claude-code':route.agentKind)) throw new PluginTaskError('INVALID_REQUEST','Worker configuration differs from registered plan');
+ return data.teamPlan.concurrency;
+ },
getLeadSessionRow: async (leadSessionId) => {
const db = getDbClient().drizzle;
const [leadRow] = await db
@@ -11146,6 +11466,19 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
isOrphanedTeamInit,
createActiveTeam: async (leadSessionId) => createActiveTeam({ leadSessionId }),
getWorkerPermissionMode: getWorkerPermissionModeFromCreationPrefs,
+ getWorkerPermissionModeOverride: async (leadSessionId) => {
+ const epoch = getCurrentDbClientSnapshot();
+ if (!epoch) throw new PluginTaskError('HOST_NOT_READY', 'Task storage unavailable', true);
+ const receipt = await createPluginTaskStore(epoch.client).get(leadSessionId);
+ if (!receipt || receipt.operation !== 'create') return undefined;
+ const task = await pluginTaskServiceForCurrentOwner!().get(receipt.pluginId, leadSessionId);
+ if (epoch !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED', 'Account changed');
+ // Plugin tasks never inherit an unrelated global Full access preference.
+ if (task.permissionMode !== 'auto' || readGhostErrandConfig(receipt.pluginId).permissionMode !== 'auto') {
+ throw new PluginTaskError('PERMISSION_DENIED', 'Authorize Auto for the plugin coordinator before creating Workers');
+ }
+ return 'auto';
+ },
setWorkerPermissionMode: applyWorkerPermissionModePreference,
createWorkerInTeam: (params) => orcaWorkerCreationService.createWorkerInTeam(params),
dispatchWorkerTask: (params) => orcaTeamService.dispatchWorkerTask(params),
@@ -12225,32 +12558,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
updateWorkerQueuedMessage: (params) => orcaTeamService.updateWorkerQueuedMessage(params),
cancelWorkerQueuedMessage: (params) => orcaTeamService.cancelWorkerQueuedMessage(params),
mergeWorkerQueuedMessages: (params) => orcaTeamService.mergeWorkerQueuedMessages(params),
- startTeam: async ({ leadSessionId, workerPermissionMode }) => {
- try {
- await assertLeadCollabProjectEnabled(leadSessionId);
- return await startOrcaTeamWithPermissionGate(
- { leadSessionId, workerPermissionMode },
- {
- getCurrentWorkerPermissionMode: getWorkerPermissionModeFromCreationPrefs,
- requestFullAccessConfirmation: (sessionId) =>
- orcaWorkerPermissionConfirmBridge.request(sessionId, {
- title: t('newChat.chatInput.fullAccessConfirmation.title'),
- description: `${t('newChat.chatInput.fullAccessConfirmation.description')} ${t('newChat.chatInput.fullAccessConfirmation.note')}`,
- }),
- startTeam: (params) => orcaLifecycleService.startTeam(params),
- },
- );
- } catch (err) {
- return {
- ok: false,
- errorCode:
- err instanceof Error && (err as unknown as { code?: string }).code
- ? (err as unknown as { code: string }).code
- : 'INTERNAL',
- message: err instanceof Error ? err.message : String(err),
- };
- }
- },
+ startTeam: ({ leadSessionId, workerPermissionMode }) => startOrcaTeamForCaller(leadSessionId, workerPermissionMode),
createWorker: async (params) => {
try {
await assertLeadCollabProjectEnabled(params.leadSessionId);
@@ -14136,6 +14444,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
// pending auto-bridge 副作用必须先于 turn 启动完成;失败仍吞错落日志,不拦派发。
await orcaInterAgentDispatcher.runQueuedOrcaInterAgentAcceptedCallback(sessionId, item);
await botDelegationServiceHolder?.acceptQueuedSessionInput(sessionId, item.clientId, item.supersedesUserClientId, restoredFromSnapshot, item.retrySourceClientId);
+ const pluginTaskSession = maker.getSession(sessionId);
+ if (pluginTaskSession && pluginTaskServiceForCurrentOwner) {
+ await pluginTaskServiceForCurrentOwner().accept(sessionId, item, { instanceId: pluginTaskSession.instanceId, generation: pluginTaskSession.getTurnGeneration() });
+ }
},
onUserMessagePersisting: (sessionId, item) => {
markQueuedAttachmentPersistenceStarted(sessionId, item.clientId);
@@ -14243,6 +14555,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
publishUiSessionIntervention(sessionId);
},
onRejectedUserTurn: (sessionId, item) => {
+ notePluginTaskLifecycle(service => service.discard(sessionId, item, 'failed'));
welcomeDispatchReceipts.settle(sessionId, item.clientId, false);
rollbackAgentIslandUserPrompt(sessionId, item.clientId, 'rejected');
// Auto-resume items have an exact-token cleanup boundary below. Keep
@@ -14283,6 +14596,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
},
// 队列项未派发即被丢弃(stop/remove/clearSession) → 释放暂存的 accepted 副作用, 防回调表泄漏。
onDiscardedQueuedMessage: (sessionId, item) => {
+ notePluginTaskLifecycle(service => service.discard(sessionId, item, 'cancelled'));
if (item.durableDelivery === true) {
void saveCancelledInputDelivery(sessionId, item.clientId).catch((error) => {
log.warn('input delivery cancellation persistence failed', { sessionId, error: String(error) });
diff --git a/apps/desktop/src/main/maker-ipc/sessionEventTerminal.ts b/apps/desktop/src/main/maker-ipc/sessionEventTerminal.ts
index 4aa3ff782d..15e16b41e5 100644
--- a/apps/desktop/src/main/maker-ipc/sessionEventTerminal.ts
+++ b/apps/desktop/src/main/maker-ipc/sessionEventTerminal.ts
@@ -50,6 +50,7 @@ import {
type ProductTurnFailureOwner,
} from './productTurnFailureOwner.js';
export interface FinishSessionTerminalEventDeps {
+ readonly onPluginTaskTerminal?: (sessionId: string, execution: { instanceId: string; generation: number }, outcome: 'completed' | 'failed', outputMessageId?: string) => void;
readonly onSuccessfulProductTurn?: (
sessionId: string,
owner?: ProductTurnFailureOwner,
@@ -535,6 +536,12 @@ export function finishSessionTerminalEvent(
...(item.supersedesUserClientId ? [item.supersedesUserClientId] : []),
...(item.retrySourceClientId ? [item.retrySourceClientId] : []),
]) ?? [];
+ if (typeof event.sessionTurnGeneration === 'number' && !recoveryOwnsUnsuccessfulBoundary && !autoResumeSuppressesPersist) {
+ deps.onPluginTaskTerminal?.(session.id, {
+ instanceId: event.sessionInstanceId ?? session.instanceId,
+ generation: event.sessionTurnGeneration,
+ }, unsuccessfulBoundary ? 'failed' : 'completed', turnAssistantPersistId ?? undefined);
+ }
void (async () => {
try {
const doneData = event.data as {
diff --git a/apps/desktop/src/main/maker-ipc/sessionExecutionOwnership.ts b/apps/desktop/src/main/maker-ipc/sessionExecutionOwnership.ts
new file mode 100644
index 0000000000..fcb6236b33
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/sessionExecutionOwnership.ts
@@ -0,0 +1,71 @@
+/** Shared by callers of ordinary Sessions; never grants caller authorization. */
+export interface SessionExecutionIdentity {
+ instanceId: string;
+ generation: number;
+}
+
+export function isSameSessionExecution(
+ current: SessionExecutionIdentity | null | undefined,
+ expected: SessionExecutionIdentity | null | undefined,
+): boolean {
+ return (
+ !!current &&
+ !!expected &&
+ current.instanceId === expected.instanceId &&
+ current.generation === expected.generation
+ );
+}
+
+/** Recheck inside the native restart fence: the Session may change while waiting. */
+export async function controlOwnedSessionExecution(params: {
+ sessionId: string;
+ matches: () => boolean;
+ withSessionLock?: (sessionId: string, operation: () => Promise<void>) => Promise<void>;
+ operation: () => Promise<void>;
+}): Promise<boolean> {
+ if (!params.matches()) return false;
+ let applied = false;
+ const guarded = async () => {
+ if (!params.matches()) return;
+ await params.operation();
+ applied = true;
+ };
+ if (params.withSessionLock) await params.withSessionLock(params.sessionId, guarded);
+ else await guarded();
+ return applied;
+}
+
+export interface OwnedQueuedInput {
+ clientId: string;
+ supersedesUserClientId?: string;
+ retrySourceClientId?: string;
+}
+
+/** Recovery aliases retain the original input's ownership, not a Session-wide grant. */
+export function queuedInputBelongsTo(
+ item: OwnedQueuedInput,
+ owns: (clientId: string) => boolean,
+): boolean {
+ return [item.clientId, item.supersedesUserClientId, item.retrySourceClientId].some(
+ (id) => typeof id === 'string' && owns(id),
+ );
+}
+
+/** Ownership is supplied by a trusted adapter (Bot identity or persisted plugin input IDs). */
+export async function withdrawOwnedSessionInputs(params: {
+ sessionId: string;
+ queue: {
+ ensureQueueRestored(sessionId: string): Promise<unknown>;
+ getQueueControlSnapshot(sessionId: string): { pendingQueue: readonly OwnedQueuedInput[] };
+ remove(sessionId: string, clientId: string): unknown;
+ };
+ owns: (clientId: string) => boolean;
+ flush: (sessionId: string) => Promise<void>;
+}): Promise<void> {
+ await params.queue.ensureQueueRestored(params.sessionId);
+ for (const item of params.queue.getQueueControlSnapshot(params.sessionId).pendingQueue) {
+ if (queuedInputBelongsTo(item, params.owns))
+ params.queue.remove(params.sessionId, item.clientId);
+ }
+ await params.flush(params.sessionId);
+}
diff --git a/apps/desktop/src/preload/ghostPreload.ts b/apps/desktop/src/preload/ghostPreload.ts
index a144a3401d..239496b06c 100644
--- a/apps/desktop/src/preload/ghostPreload.ts
+++ b/apps/desktop/src/preload/ghostPreload.ts
@@ -65,6 +65,15 @@ contextBridge.exposeInMainWorld('cindy', {
ipcRenderer.invoke('ghost-pipe:send', { ...req, type: 'fs-request' }),
library: (req: Record<string, unknown>): Promise<unknown> =>
ipcRenderer.invoke('ghost-pipe:send', { ...req, type: 'library-request' }),
+ tasks: Object.fromEntries(
+ ['capabilities', 'requestWriteAccess', 'startTeam', 'getTeam', 'setTeamPlan', 'releaseWorker', 'create', 'list', 'get', 'send', 'getRun', 'listRuns', 'cancel', 'readMessages'].map(kind => [
+ kind, async (req: Record<string, unknown> = {}): Promise<unknown> => {
+ const result = await ipcRenderer.invoke('ghost-pipe:send', { ...req, type: 'tasks-request', kind });
+ if (result?.ok === true) return result.data;
+ throw Object.assign(new Error(result?.error?.message ?? 'Task request failed'), { code: result?.error?.code ?? 'HOST_NOT_READY', retryable: result?.error?.retryable === true });
+ },
+ ]),
+ ),
agent: {
run: (req: Record<string, unknown>): Promise<unknown> =>
ipcRenderer.invoke('ghost-pipe:send', { ...req, type: 'agent-request' }),
diff --git a/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts b/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts
index b9c82a7340..9e60051e69 100644
--- a/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts
+++ b/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts
@@ -314,7 +314,7 @@ export function toGhostPluginDetail(
cindyCapabilities: PINNABLE_CINDY_CATEGORIES.flatMap((category) =>
(manifest.cindy?.[category] ?? []).map((action) => `${category}.${action}`),
),
- hasErrand: manifest.agent?.errand === true,
+ hasErrand: manifest.agent?.errand === true || manifest.agent?.tasks === true,
panelMinWidth: manifest.panel ? (manifest.panel.minWidth ?? 280) : null,
installDir: ghost.dir,
};
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index ad1f6eae8b..d3f9dd6f1b 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -5366,6 +5366,8 @@
"agentUserActionDetail": "Each click permits one turn only, and only in the session that owns the card.",
"agentBackground": "Can automatically start new Agent turns in the background",
"agentBackgroundDetail": "Does not require a click each time, but can only use sessions you previously connected to this plugin. Model charges may apply.",
+ "agentTasks": "Can create and manage its own Cindy tasks",
+ "agentTasksDetail": "Can send messages, read results and stop its own executions. Tasks remain visible to you. Uses this plugin’s AI settings and may incur model charges; does not grant access to other tasks.",
"agentErrand": "Can hand tasks to the Cindy Agent and collect the result",
"agentErrandDetail": "Tasks run in this plugin's dedicated session, always visible in the sidebar and stoppable at any time. Read-only by default; raising the level requires your change in the plugin settings. Model charges may apply.",
"agentSchedule": "Can ask you to create an automation",
@@ -13770,5 +13772,16 @@
"pluginDeviceAuthorization": {
"title": "Authorize Plugin Login",
"description": "Open {{host}} on this device to authorize the plugin running this task. Its credentials stay on the originating device."
+ },
+ "pluginTaskWriteAccess": {
+ "autoTitle": "Enable Auto approval",
+ "autoMessage": "Allow “{{name}}” to use Auto approval?",
+ "autoDetail": "Cindy will review coordinator and Worker actions automatically. Actions requiring confirmation or denied actions still pause. This is not Full access. The choice is saved in plugin AI settings without changing global permissions for other tasks.",
+
+ "title": "Allow this plugin’s AI to edit files?",
+ "message": "Allow the AI in “{{name}}” to edit files and continue?",
+ "detail": "This sets the plugin’s AI permission to Allow edits for future tasks too. A separate working directory is not a system sandbox; commands still follow Cindy permission checks. You can switch back to read-only in the plugin’s AI settings.",
+ "allow": "Allow and continue",
+ "cancel": "Not now"
}
}
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 00dd23a0e2..372dafa053 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -5365,6 +5365,8 @@
"agentUserActionDetail": "1 回のクリックにつき 1 回だけ開始でき、そのカードが属するセッションでのみ使用できます。",
"agentBackground": "バックグラウンドで Agent の新しいターンを自動的に開始できます",
"agentBackgroundDetail": "毎回のクリックは不要ですが、以前このプラグインに関連付けたセッションでのみ使用できます。モデル料金が発生する場合があります。",
+ "agentTasks": "このプラグインの Cindy セッションを作成・管理できます",
+ "agentTasksDetail": "メッセージの送信、結果の読み取り、自身の実行の停止ができます。セッションはユーザーに表示されます。プラグインの AI 設定を使用し、モデル料金が発生する場合があります。他のセッションへのアクセスは許可されません。",
"agentErrand": "Cindy Agent にタスクを任せて結果を受け取れます",
"agentErrandDetail": "タスクはこのプラグイン専用のセッションで実行され、サイドバーから常に確認・停止できます。既定では読み取り専用で、権限の引き上げはプラグイン設定であなた自身が行う必要があります。モデル料金が発生する場合があります。",
"agentSchedule": "自動化の新規作成をあなたに依頼できます",
@@ -13751,5 +13753,15 @@
"pluginDeviceAuthorization": {
"title": "プラグインのログインを認証",
"description": "このデバイスで {{host}} を開き、このタスクを実行するプラグインを認証します。認証情報は認証を開始したデバイスに保存されます。"
+ },
+ "pluginTaskWriteAccess": {
+ "title": "Allow this plugin’s AI to edit files?",
+ "message": "Allow the AI in “{{name}}” to edit files and continue?",
+ "detail": "This sets the plugin’s AI permission to Allow edits for future tasks too. A separate working directory is not a system sandbox; commands still follow Cindy permission checks. You can switch back to read-only in the plugin’s AI settings.",
+ "allow": "Allow and continue",
+ "cancel": "Not now",
+ "autoTitle": "Auto 自動承認を有効化",
+ "autoMessage": "「{{name}}」で Auto 自動承認を使用しますか?",
+ "autoDetail": "主タスクと Worker の操作を Cindy が自動審査します。確認が必要な操作や拒否された操作は停止します。完全アクセスではありません。他のタスクの全体設定は変更しません。"
}
}
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 3f4267d498..deb9ef408c 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -5365,6 +5365,8 @@
"agentUserActionDetail": "클릭 한 번마다 한 번만 시작할 수 있으며, 해당 카드가 속한 세션에서만 사용할 수 있습니다.",
"agentBackground": "백그라운드에서 Agent의 새 작업을 자동으로 시작할 수 있음",
"agentBackgroundDetail": "매번 클릭할 필요는 없지만, 이전에 이 플러그인과 연결한 세션에서만 사용할 수 있습니다. 모델 비용이 발생할 수 있습니다.",
+ "agentTasks": "이 플러그인의 Cindy 세션을 만들고 관리할 수 있음",
+ "agentTasksDetail": "메시지를 보내고 결과를 읽으며 자신의 실행을 중지할 수 있습니다. 세션은 사용자에게 표시됩니다. 플러그인의 AI 설정을 사용하며 모델 비용이 발생할 수 있습니다. 다른 세션에 대한 접근 권한은 부여하지 않습니다.",
"agentErrand": "Cindy Agent에게 작업을 맡기고 결과를 받아올 수 있음",
"agentErrandDetail": "작업은 이 플러그인 전용 세션에서 실행되며, 사이드바에서 언제든 확인하고 중단할 수 있습니다. 기본은 읽기 전용이며, 권한 상향은 플러그인 설정에서 직접 해야 합니다. 모델 비용이 발생할 수 있습니다.",
"agentSchedule": "자동화 새로 만들기를 요청할 수 있음",
@@ -13751,5 +13753,15 @@
"pluginDeviceAuthorization": {
"title": "플러그인 로그인 인증",
"description": "이 기기에서 {{host}}를 열어 이 작업을 실행하는 플러그인을 인증하세요. 인증 정보는 인증을 시작한 기기에 저장됩니다."
+ },
+ "pluginTaskWriteAccess": {
+ "title": "Allow this plugin’s AI to edit files?",
+ "message": "Allow the AI in “{{name}}” to edit files and continue?",
+ "detail": "This sets the plugin’s AI permission to Allow edits for future tasks too. A separate working directory is not a system sandbox; commands still follow Cindy permission checks. You can switch back to read-only in the plugin’s AI settings.",
+ "allow": "Allow and continue",
+ "cancel": "Not now",
+ "autoTitle": "Auto 자동 승인 사용",
+ "autoMessage": "“{{name}}”에 Auto 자동 승인을 허용할까요?",
+ "autoDetail": "Cindy가 주 작업과 Worker 동작을 자동 심사합니다. 확인이 필요하거나 거부된 동작은 일시 중지됩니다. 전체 접근 권한이 아니며 다른 작업의 전역 권한은 변경하지 않습니다."
}
}
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index c1e0087ef8..7cb5edc67b 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -5365,6 +5365,8 @@
"agentUserActionDetail": "每次点击只允许启动一次,并且只能使用这张卡所属的任务。",
"agentBackground": "可在后台自动让 Agent 开始新一轮工作",
"agentBackgroundDetail": "不需要当次点击,但只能使用你曾为这个插件建立过关联的任务,可能产生模型费用。",
+ "agentTasks": "可创建和管理本插件的 Cindy 任务",
+ "agentTasksDetail": "可发送消息、读取结果和停止本插件的执行,任务对你可见。沿用插件的 AI 配置,可能产生模型费用;不授予其他任务的访问权。",
"agentErrand": "可把任务交给 Cindy Agent 代办并取回结果",
"agentErrandDetail": "这些代办会在这个插件的专属任务里进行,你随时可以在侧边栏看到并叫停;默认只能读不能改,要放开需你在插件配置里亲手调整,可能产生模型费用。",
"agentSchedule": "可以请你新建自动化",
@@ -13751,5 +13753,15 @@
"pluginDeviceAuthorization": {
"title": "授权插件登录",
"description": "在这台设备打开 {{host}},为执行此任务的插件授权。凭据保存在发起授权的设备上。"
+ },
+ "pluginTaskWriteAccess": {
+ "autoTitle": "启用 Auto 自动审批",
+ "autoMessage": "允许“{{name}}”使用 Auto 自动审批?",
+ "autoDetail": "主任务和 Worker 的操作将交由 Cindy 自动审批。审批要求人工确认或拒绝时仍会暂停;这不是完全访问。此选择保存到插件 AI 设置,不改变其他任务的全局权限。",
+ "title": "允许插件的 AI 修改文件?",
+ "message": "允许“{{name}}”的 AI 修改文件并继续?",
+ "detail": "将此插件的 AI 权限设为“允许修改”,后续任务沿用此选择。独立作答目录不是系统沙箱;命令仍遵循 Cindy 的权限检查。你可以随时在插件 AI 设置中改回只读。",
+ "allow": "允许并继续",
+ "cancel": "暂不允许"
}
}
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 58c6a7229e..a7b2e86b60 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -5365,6 +5365,8 @@
"agentUserActionDetail": "每次點選只允許啟動一次,並且只能使用這張卡所屬的任務。",
"agentBackground": "可在後臺自動讓 Agent 開始新一輪工作",
"agentBackgroundDetail": "不需要當次點選,但只能使用你曾為這個插件建立過關聯的任務,可能產生模型費用。",
+ "agentTasks": "可建立和管理本插件的 Cindy 任務",
+ "agentTasksDetail": "可傳送訊息、讀取結果和停止本插件的執行,任務對你可見。沿用插件的 AI 配置,可能產生模型費用;不授予其他任務的存取權。",
"agentErrand": "可把任務交給 Cindy Agent 代辦並取回結果",
"agentErrandDetail": "這些代辦會在這個插件的專屬任務裡進行,你隨時可以在側邊欄看到並叫停;預設只能讀不能改,要放開需你在插件配置裡親手調整,可能產生模型費用。",
"agentSchedule": "可以請你新建自動化",
@@ -13751,5 +13753,15 @@
"pluginDeviceAuthorization": {
"title": "授權插件登入",
"description": "在這台裝置開啟 {{host}},為執行此任務的插件授權。憑證保存在發起授權的裝置上。"
+ },
+ "pluginTaskWriteAccess": {
+ "title": "Allow this plugin’s AI to edit files?",
+ "message": "Allow the AI in “{{name}}” to edit files and continue?",
+ "detail": "This sets the plugin’s AI permission to Allow edits for future tasks too. A separate working directory is not a system sandbox; commands still follow Cindy permission checks. You can switch back to read-only in the plugin’s AI settings.",
+ "allow": "Allow and continue",
+ "cancel": "Not now",
+ "autoTitle": "啟用 Auto 自動審批",
+ "autoMessage": "允許「{{name}}」使用 Auto 自動審批?",
+ "autoDetail": "主任務與 Worker 的操作將交由 Cindy 自動審批。需要人工確認或遭拒時仍會暫停;這不是完全存取。此選擇儲存到插件 AI 設定,不變更其他任務的全域權限。"
}
}
diff --git a/apps/desktop/src/shared/__tests__/ghost.tasks.test.ts b/apps/desktop/src/shared/__tests__/ghost.tasks.test.ts
new file mode 100644
index 0000000000..8aa9ca0700
--- /dev/null
+++ b/apps/desktop/src/shared/__tests__/ghost.tasks.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, it } from 'vitest';
+import {
+ ghostManifestToLegacyV2DigestFormat,
+ ghostPermissionItems,
+ validateGhostManifest,
+} from '../ghost.js';
+
+const base = {
+ schemaVersion: 3,
+ minCindyVersion: '0.1.0',
+ id: 'task-test',
+ name: 'Tasks',
+ version: '1.0.0',
+ entry: 'main.js',
+};
+describe('plugin tasks permission compatibility', () => {
+ it('adds a distinct permission without changing old errand permissions', () => {
+ const old = validateGhostManifest({ ...base, agent: { errand: true } });
+ const next = validateGhostManifest({ ...base, agent: { errand: true, tasks: true } });
+ expect(old.ok && next.ok).toBe(true);
+ if (!old.ok || !next.ok) return;
+ const before = ghostPermissionItems(old.manifest);
+ const after = ghostPermissionItems(next.manifest);
+ expect(after.filter((item) => item.key !== 'agent:tasks')).toEqual(before);
+ expect(after.some((item) => item.key === 'agent:tasks')).toBe(true);
+ });
+ it('rejects a non-boolean declaration', () => {
+ expect(validateGhostManifest({ ...base, agent: { tasks: 'yes' } }).ok).toBe(false);
+ });
+ it('keeps the released V2 digest projection frozen', () => {
+ const source = { schemaVersion: 2, slots: ['agent'], agent: { errand: true, tasks: true } };
+ const projected = ghostManifestToLegacyV2DigestFormat(source, source) as typeof source;
+ expect(projected.agent).toEqual({ errand: true });
+ });
+});
diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.ts
index 48514c0602..ce2a6a9f2f 100644
--- a/apps/desktop/src/shared/ghost.ts
+++ b/apps/desktop/src/shared/ghost.ts
@@ -205,6 +205,7 @@ export interface GhostCardNeeds {
export interface GhostAgentNeeds {
background?: boolean;
errand?: boolean;
+ tasks?: boolean;
/**
* schedule = 「可以请你新建自动化任务」(2026-08-04)。
*
@@ -1972,6 +1973,9 @@ export function ghostPermissionItems(manifest: GhostManifest): GhostPermissionIt
detailKey: 'agentErrandDetail',
});
}
+ if (manifest.agent?.tasks === true) {
+ items.unshift({ key: 'agent:tasks', kind: 'agent', labelKey: 'agentTasks', detailKey: 'agentTasksDetail' });
+ }
// 「可以请你新建自动化任务」:独立 key 单列一档。理由同 badge/errand ——
// diffGhostPermissionItems 按 key + detail 比对,若并进任何既有 key,已装插件
// 在更新里新增 schedule 时 added 为空,plugin-market 的扩权复核不会拦,用户会
@@ -4310,20 +4314,24 @@ export function validateGhostManifest(value: unknown): ManifestValidation {
if (agentRaw.errand !== undefined && typeof agentRaw.errand !== 'boolean') {
return { ok: false, reason: 'agent.errand 必须是布尔值' };
}
+ if (agentRaw.tasks !== undefined && typeof agentRaw.tasks !== 'boolean') {
+ return { ok: false, reason: 'agent.tasks must be boolean' };
+ }
if (agentRaw.schedule !== undefined && typeof agentRaw.schedule !== 'boolean') {
return { ok: false, reason: 'agent.schedule 必须是布尔值' };
}
- if (agentRaw.background !== true && agentRaw.errand !== true && agentRaw.schedule !== true && Object.keys(unknownDeclarationFields(agentRaw, ['background', 'errand', 'schedule'])).length === 0) {
+ if (agentRaw.background !== true && agentRaw.errand !== true && agentRaw.schedule !== true && agentRaw.tasks !== true && Object.keys(unknownDeclarationFields(agentRaw, ['background', 'errand', 'schedule', 'tasks'])).length === 0) {
return {
ok: false,
reason:
- 'agent 能力详单只有 background: true / errand: true / schedule: true 三项加档;仅需用户点击触发时请省略 agent 字段',
+ 'agent 能力详单只有 background: true / errand: true / schedule: true / tasks: true 四项加档;仅需用户点击触发时请省略 agent 字段',
};
}
agent = {
- ...unknownDeclarationFields(agentRaw, ['background', 'errand', 'schedule']),
+ ...unknownDeclarationFields(agentRaw, ['background', 'errand', 'schedule', 'tasks']),
...(agentRaw.background === true ? { background: true } : {}),
...(agentRaw.errand === true ? { errand: true } : {}),
+ ...(agentRaw.tasks === true ? { tasks: true } : {}),
...(agentRaw.schedule === true ? { schedule: true } : {}),
};
}
diff --git a/apps/desktop/src/shared/pluginTasks.ts b/apps/desktop/src/shared/pluginTasks.ts
new file mode 100644
index 0000000000..9f3236ad31
--- /dev/null
+++ b/apps/desktop/src/shared/pluginTasks.ts
@@ -0,0 +1,79 @@
+/** Ordinary local Session API. No Bot/Orca identity or permission override is accepted. */
+export interface PluginTaskRoute {
+ agentKind: 'cc' | 'codex' | 'pi';
+ providerId: string;
+ model: string;
+ effort: string;
+ fastMode: boolean;
+}
+export type PluginTaskRunStatus =
+ | 'queued'
+ | 'running'
+ | 'stopping'
+ | 'completed'
+ | 'failed'
+ | 'cancelled'
+ | 'interrupted'
+ | 'reconciling';
+export interface PluginTaskView {
+ taskId: string;
+ title: string;
+ status: 'active' | 'archived' | 'deleted';
+ revision: number;
+ resolvedConfig: PluginTaskRoute;
+ workingDir?: string;
+ permissionMode?: string;
+}
+export interface PluginTaskRun {
+ runId: string;
+ taskId: string;
+ inputMessageId: string;
+ status: PluginTaskRunStatus;
+ acceptedAt: number;
+ acceptedConfig: PluginTaskRoute;
+ execution?: { instanceId: string; generation: number };
+ /** Host-observed retry input aliases; never supplied by the plugin. */
+ inputClientIds?: string[];
+ outputMessageId?: string;
+ completedAt?: number;
+ error?: string;
+ usage: { status: 'unavailable'; reason: string };
+}
+export interface PluginTeamPlan {
+ concurrency: number | null;
+ items: Array<{label: string; workingDir: string; route: PluginTaskRoute}>;
+}
+export type PluginTaskRequest =
+ | { type: 'tasks-request'; kind: 'capabilities' }
+ | {
+ type: 'tasks-request';
+ kind: 'create';
+ requestKey: string;
+ title: string;
+ route?: PluginTaskRoute;
+ isolatedWorkspace?: boolean;
+ }
+ | { type: 'tasks-request'; kind: 'list'; after?: string; limit?: number }
+ | { type: 'tasks-request'; kind: 'get'; taskId: string }
+ | { type: 'tasks-request'; kind: 'startTeam' | 'getTeam'; taskId: string }
+ | { type: 'tasks-request'; kind: 'setTeamPlan'; taskId: string; plan: PluginTeamPlan }
+ | { type: 'tasks-request'; kind: 'releaseWorker'; taskId: string; workerId: string; completedAt: number }
+ | { type: 'tasks-request'; kind: 'requestWriteAccess'; taskId: string; mode?: 'acceptEdits' | 'auto' }
+ | { type: 'tasks-request'; kind: 'readMessages'; taskId: string; after?: string; limit?: number }
+ | {
+ type: 'tasks-request';
+ kind: 'send';
+ taskId: string;
+ requestKey: string;
+ expectedRevision: number;
+ text: string;
+ }
+ | { type: 'tasks-request'; kind: 'getRun'; runId: string }
+ | { type: 'tasks-request'; kind: 'listRuns'; taskId: string; after?: string; limit?: number }
+ | { type: 'tasks-request'; kind: 'cancel'; runId: string; requestKey: string };
+export type PluginTaskResult =
+ | { ok: true; data: unknown }
+ | {
+ ok: false;
+ error: { code: string; message: string; retryable: boolean };
+ };
diff --git a/docs/dev-rules/plugin-task-api-implementation.md b/docs/dev-rules/plugin-task-api-implementation.md
new file mode 100644
index 0000000000..f0350d5948
--- /dev/null
+++ b/docs/dev-rules/plugin-task-api-implementation.md
@@ -0,0 +1,60 @@
+# 插件普通任务接口:第一阶段实现
+
+状态:实验接口,尚未发布。入口为插件逻辑页 `cindy.tasks`,声明 `agent.tasks: true` 后由既有插件权限流程确认。存量 `errand` 声明不自动获得此权限。
+
+## 已接入
+
+- `capabilities/create/list/get/send/getRun/listRuns/readMessages/cancel`。
+- create 可传 isolatedWorkspace:true,由宿主分配独立空作答目录;返回本任务 workingDir 与 permissionMode,插件不能覆盖权限。
+- 创建用户可见的普通本地 Session;工作目录及权限来自用户配置,不接受插件传入绕过权限、任意目录或另一插件身份。
+- 发送走普通输入协调器,使用持久 requestKey 去重和稳定输入 ID;重复请求不会再次启动模型。
+- 指定 provider、model、effort、Fast 必须通过当前目录核验;派发前再次核验,不静默 fallback。
+- 回执独立落库,区分任务、输入执行及原生执行代次;原生终态按 instanceId + generation 结算,不以 idle 或最后一条 assistant 消息猜测完成。
+- 读取限定于本插件创建的任务;返回消息 clientId,分页游标仍使用数据库稳定游标。
+- 取消只撤回自己的排队输入或其原生重试别名;停止前在 Session 锁内再次核对执行身份与插件权限。
+- 请求跨账号切换后不能继续操作新账号数据库。禁用插件后不能继续发送或停止。
+
+## 与伙伴的共用和隔离
+
+`sessionExecutionOwnership.ts` 提供执行身份比较、锁内二次核对、按归属撤回排队输入。伙伴委派与插件任务均使用这套函数。
+
+插件继续复用现有普通 Session 创建、输入协调器、停止服务及产品终态边界。没有创建假伙伴,没有另建模型执行器。伙伴的身份、父子委派规则及专有配置仍由伙伴服务管理。
+
+## 当前限制与后续工作
+
+- 仅本插件创建的本地普通任务;不支持选择既有任务、远端任务或 Bot;自有普通任务可通过 startTeam 成为 Orca Lead。
+- 尚未开放修改/归档任务、队列暂停、事件订阅、逐输入费用与用量。usage 明确返回 unavailable。
+- 回执已经持久化,但完整的重启后终态补账、无输入别名的自动续跑归属尚未闭环。缺少原生证据时返回 reconciling,不重放请求、不报告成功;目前不应作为无人值守正式评测的完成依据。
+- 创建回执落库后若 Session 创建中断,重放不会再建一个任务,可能返回 TASK_NOT_FOUND;尚无自动修复入口。
+- 无推理档位的模型暂不支持;不支持的 route 明确拒绝。
+- cancel 的 requestKey 当前不建立独立账本;同一 run 的终态保持幂等,进行中的重复取消仍可能再次请求原生停止。
+- 评测插件已接入此接口;实际 UI 联调结果另记,未自动启动付费模型。
+
+## 验证边界
+
+服务、执行归属、权限入口、清单兼容、Worker 创建与释放均有定向回归。数据库迁移使用隔离临时数据库验证,不触碰真实用户数据库。完整 UI、真实 provider 执行和重启后的长期恢复仍需发布前验收;不能把模块测试通过解释为无人值守评测已完成。
+
+代码入口:`apps/desktop/src/main/maker-ipc/pluginTaskService.ts`、`pluginTaskStore.ts`、`sessionExecutionOwnership.ts`、`register.ts`;插件入口 `apps/desktop/src/main/cindy-brain/taskSlot.ts` 与 `apps/desktop/src/preload/ghostPreload.ts`。
+
+## 首次修改授权
+
+逻辑页可调用 cindy.tasks.requestWriteAccess({taskId, mode?})。省略 mode 保留旧行为(acceptEdits,仅限未开始执行的任务);mode: auto 请求宿主原生确认,为空闲自有任务及插件后续任务启用 Auto。插件不能替用户确认,不能请求 Full access。拒绝不改状态;账号、配置、任务版本在确认期间改变则拒绝写入。Auto 插件主任务的 Worker 固定使用 Auto,不继承或改写全局 Worker 偏好;授权撤销后拒绝新建。独立目录不是沙箱。返回 granted 与更新后的 task/revision,插件应继续原批次。
+
+### 主任务协调评测
+
+`tasks.startTeam({taskId})` 为本插件拥有的普通任务启用 Orca Lead,复用现有协同入口及 Worker 权限确认。插件不能指定 Worker 权限绕过确认。确认返回后、实际启用前再次校验账号、插件授权、任务配置修订。`tasks.getTeam({taskId})` 只投影所属团队的 Worker 身份、实际模型配置、目录、队列和终态;不会将 Lead 一轮完成解释为整个团队完成。
+
+插件可读取自己任务在权限变化后的状态与执行停止,但新发送拒绝超出插件策略的 full access 任务。既有普通任务的所有权收据在成为 Lead 后继续有效;Worker 不是插件直接控制的普通任务。
+
+评测客户端每批仅创建一个 Lead,答案目录逐份隔离,由 Lead 使用原生 Orca 调度。插件根据 Worker 成员、配置、目录、done 且无活动/队列的状态独立验收。该投影不是逐轮执行账本,不作为精确费用证据。重试先核对既有 Worker;未知归属不得重派或算零分。停止须确认 Lead 停止处理完成和团队不再活动。
+
+getTeam 的 completedAt 可由宿主落盘的 turnCompleted 终态恢复:仅接受当前轮最终顶层 assistant、启动/结束边界吻合、无后续用户输入、无活动/排队/暂停工作。空闲状态或 Worker 报告正文自身不是交卷凭据。投影同时返回实际 permissionMode,供插件诊断。
+
+### 已登记协同计划与释放
+
+`setTeamPlan({taskId,plan:{concurrency,items}})` 在本插件自己的创建收据中冻结计划。每项含唯一 label、workingDir 和精确 route;重复设置必须一致。未登记计划的存量插件沿用原行为。Worker 创建复用原子 reservation,计划上限只可收窄宿主硬上限。已结算 label 持久保留,不因归档再次变成可派发项。
+
+`releaseWorker({taskId,workerId,completedAt})` 仅释放本插件 Lead 内、结束时间仍匹配、无活动/排队输入的 Worker。调用方应先保存交卷快照和评分。复用 Orca 的归档路径、transition 锁和发送锁;持锁后再次核对 completedAt 与归属。已有发送锁时直接拒绝释放,不等待而形成锁反转;只有归档成功才结算 label。拒绝正在发送或运行的 Worker,保留任务历史与作答文件。
+
+`getTeam` 增加包含创建预留的 capacity 快照(advisory;准入仍由创建事务裁决)、逐 Worker 的等待确认状态、首条输入/首条执行消息时间、最近轮结束时间,以及 Worker/Lead 分列的 session-total 用量。`host-message-window` 是可观测作答窗口,不是精确模型计算时长。无确切 USD 金额时返回 null,不把订阅估值或其他币种直接当美元。
+
diff --git a/packages/plugin-protocol/src/manifest.ts b/packages/plugin-protocol/src/manifest.ts
index a681c51af4..e47becccaf 100644
--- a/packages/plugin-protocol/src/manifest.ts
+++ b/packages/plugin-protocol/src/manifest.ts
@@ -208,6 +208,7 @@ export interface GhostCardNeeds {
export interface GhostAgentNeeds {
background?: boolean;
errand?: boolean;
+ tasks?: boolean;
schedule?: boolean;
}
@@ -2934,20 +2935,24 @@ export function validateGhostManifest(value: unknown): ManifestValidation {
if (agentRaw.errand !== undefined && typeof agentRaw.errand !== 'boolean') {
return { ok: false, reason: 'agent.errand 必须是布尔值' };
}
+ if (agentRaw.tasks !== undefined && typeof agentRaw.tasks !== 'boolean') {
+ return { ok: false, reason: 'agent.tasks must be boolean' };
+ }
if (agentRaw.schedule !== undefined && typeof agentRaw.schedule !== 'boolean') {
return { ok: false, reason: 'agent.schedule 必须是布尔值' };
}
- if (agentRaw.background !== true && agentRaw.errand !== true && agentRaw.schedule !== true && Object.keys(unknownDeclarationFields(agentRaw, ['background', 'errand', 'schedule'])).length === 0) {
+ if (agentRaw.background !== true && agentRaw.errand !== true && agentRaw.schedule !== true && agentRaw.tasks !== true && Object.keys(unknownDeclarationFields(agentRaw, ['background', 'errand', 'schedule', 'tasks'])).length === 0) {
return {
ok: false,
reason:
- 'agent 能力详单只有 background: true / errand: true / schedule: true 三项加档;仅需用户点击触发时请省略 agent 字段',
+ 'agent 能力详单只有 background: true / errand: true / schedule: true / tasks: true 四项加档;仅需用户点击触发时请省略 agent 字段',
};
}
agent = {
- ...unknownDeclarationFields(agentRaw, ['background', 'errand', 'schedule']),
+ ...unknownDeclarationFields(agentRaw, ['background', 'errand', 'schedule', 'tasks']),
...(agentRaw.background === true ? { background: true } : {}),
...(agentRaw.errand === true ? { errand: true } : {}),
+ ...(agentRaw.tasks === true ? { tasks: true } : {}),
...(agentRaw.schedule === true ? { schedule: true } : {}),
};
}