Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(agents): record what opened each agent session (#9931)
Eric Hayesc23f1e672627
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.jsonindex 2b41a567ce..b83ed3c6c5 100644--- a/.github/workspace-dep-closures.json+++ b/.github/workspace-dep-closures.json@@ -14477,6 +14477,7 @@"trigger_context": ["crates/bot_id","crates/cowlike",+ "crates/macro_user_id","crates/trigger_context","crates/workspace-hack"],diff --git a/.sqlx/query-404264a37bfb58d17db3dcdf1c036aef6ebecea728487ecdcfbe960d137c4895.json b/.sqlx/query-158ccbb40a502f25d61afe99aeae131e544ac11e18e75be5c7c5ee3bc681653e.jsonsimilarity index 81%rename from .sqlx/query-404264a37bfb58d17db3dcdf1c036aef6ebecea728487ecdcfbe960d137c4895.jsonrename to .sqlx/query-158ccbb40a502f25d61afe99aeae131e544ac11e18e75be5c7c5ee3bc681653e.jsonindex 46d52c254f..1be3188829 100644--- a/.sqlx/query-404264a37bfb58d17db3dcdf1c036aef6ebecea728487ecdcfbe960d137c4895.json+++ b/.sqlx/query-158ccbb40a502f25d61afe99aeae131e544ac11e18e75be5c7c5ee3bc681653e.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT\n id, name, archived_by::TEXT AS \"archived_by?\", archived_at, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, repo_branch, pull_request_url, task_id, source, visibility, workspace, sandbox_size, instructions,\n mcp_scope, mcp_servers, acp_session_id, status,\n status_event_name, agent_session.created_at, modified_at,\n (SELECT jsonb_build_object('type', parent_entity_type, 'id', parent_entity_id)\n FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_parent?: Json<MessageParent>\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\",\n ext.last_run_id AS \"external_last_run_id?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE thread_id = $1\n ORDER BY agent_session.created_at DESC\n ",+ "query": "\n SELECT\n id, name, archived_by::TEXT AS \"archived_by?\", archived_at, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, repo_branch, pull_request_url, task_id, source, visibility, workspace, sandbox_size, instructions,\n mcp_scope, mcp_servers, acp_session_id, status,\n status_event_name, agent_session.created_at, modified_at,\n (SELECT jsonb_build_object('type', parent_entity_type, 'id', parent_entity_id)\n FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_parent?: Json<MessageParent>\",\n (SELECT to_jsonb(origin_row) FROM agent_session_source origin_row\n WHERE origin_row.id = agent_session.source_id)\n AS \"source_row?: Json<source::SourceRow>\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\",\n ext.last_run_id AS \"external_last_run_id?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE thread_id = $1 AND bot_id = $2\n ORDER BY agent_session.created_at DESC\n LIMIT 1\n ","describe": {"columns": [{@@ -140,32 +140,38 @@},{"ordinal": 27,+ "name": "source_row?: Json<source::SourceRow>",+ "type_info": "Jsonb"+ },+ {+ "ordinal": 28,"name": "external_provider?","type_info": "Text"},{- "ordinal": 28,+ "ordinal": 29,"name": "external_id?","type_info": "Text"},{- "ordinal": 29,+ "ordinal": 30,"name": "external_name?","type_info": "Text"},{- "ordinal": 30,+ "ordinal": 31,"name": "external_url?","type_info": "Text"},{- "ordinal": 31,+ "ordinal": 32,"name": "external_last_run_id?","type_info": "Text"}],"parameters": {"Left": [+ "Uuid","Uuid"]},@@ -197,6 +203,7 @@false,false,null,+ null,false,false,true,@@ -204,5 +211,5 @@true]},- "hash": "404264a37bfb58d17db3dcdf1c036aef6ebecea728487ecdcfbe960d137c4895"+ "hash": "158ccbb40a502f25d61afe99aeae131e544ac11e18e75be5c7c5ee3bc681653e"}diff --git a/.sqlx/query-d53caadf901950805aa2f2c46a64a0566227a35b42d7f7de90cc2a42cb69b6d5.json b/.sqlx/query-29d7de13b2503df06c5d753413edea3478914ab2a6914d884f37d59817a6814c.jsonsimilarity index 82%rename from .sqlx/query-d53caadf901950805aa2f2c46a64a0566227a35b42d7f7de90cc2a42cb69b6d5.jsonrename to .sqlx/query-29d7de13b2503df06c5d753413edea3478914ab2a6914d884f37d59817a6814c.jsonindex 540428c95c..0cfc9a01b0 100644--- a/.sqlx/query-d53caadf901950805aa2f2c46a64a0566227a35b42d7f7de90cc2a42cb69b6d5.json+++ b/.sqlx/query-29d7de13b2503df06c5d753413edea3478914ab2a6914d884f37d59817a6814c.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT\n id, name, archived_by::TEXT AS \"archived_by?\", archived_at, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, repo_branch, pull_request_url, task_id, source, visibility, workspace, sandbox_size, instructions,\n mcp_scope, mcp_servers, acp_session_id, status,\n status_event_name, agent_session.created_at, modified_at,\n (SELECT jsonb_build_object('type', parent_entity_type, 'id', parent_entity_id)\n FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_parent?: Json<MessageParent>\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\",\n ext.last_run_id AS \"external_last_run_id?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE id = $1\n ",+ "query": "\n SELECT\n id, name, archived_by::TEXT AS \"archived_by?\", archived_at, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, repo_branch, pull_request_url, task_id, source, visibility, workspace, sandbox_size, instructions,\n mcp_scope, mcp_servers, acp_session_id, status,\n status_event_name, agent_session.created_at, modified_at,\n (SELECT jsonb_build_object('type', parent_entity_type, 'id', parent_entity_id)\n FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_parent?: Json<MessageParent>\",\n (SELECT to_jsonb(origin_row) FROM agent_session_source origin_row\n WHERE origin_row.id = agent_session.source_id)\n AS \"source_row?: Json<source::SourceRow>\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\",\n ext.last_run_id AS \"external_last_run_id?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE thread_id = $1\n ORDER BY agent_session.created_at DESC\n ","describe": {"columns": [{@@ -140,26 +140,31 @@},{"ordinal": 27,+ "name": "source_row?: Json<source::SourceRow>",+ "type_info": "Jsonb"+ },+ {+ "ordinal": 28,"name": "external_provider?","type_info": "Text"},{- "ordinal": 28,+ "ordinal": 29,"name": "external_id?","type_info": "Text"},{- "ordinal": 29,+ "ordinal": 30,"name": "external_name?","type_info": "Text"},{- "ordinal": 30,+ "ordinal": 31,"name": "external_url?","type_info": "Text"},{- "ordinal": 31,+ "ordinal": 32,"name": "external_last_run_id?","type_info": "Text"}@@ -197,6 +202,7 @@false,false,null,+ null,false,false,true,@@ -204,5 +210,5 @@true]},- "hash": "d53caadf901950805aa2f2c46a64a0566227a35b42d7f7de90cc2a42cb69b6d5"+ "hash": "29d7de13b2503df06c5d753413edea3478914ab2a6914d884f37d59817a6814c"}diff --git a/.sqlx/query-fdd57a58314654fb09c01bf2641ae2227c59957cc804e7e56bb2cc7608c387cd.json b/.sqlx/query-2d947f92d175d66f1d993961460700754cb7dd3a7f5fd63fcb31bf4661aedbb6.jsonsimilarity index 72%rename from .sqlx/query-fdd57a58314654fb09c01bf2641ae2227c59957cc804e7e56bb2cc7608c387cd.jsonrename to .sqlx/query-2d947f92d175d66f1d993961460700754cb7dd3a7f5fd63fcb31bf4661aedbb6.jsonindex 7152e483e4..a2d025abdd 100644--- a/.sqlx/query-fdd57a58314654fb09c01bf2641ae2227c59957cc804e7e56bb2cc7608c387cd.json+++ b/.sqlx/query-2d947f92d175d66f1d993961460700754cb7dd3a7f5fd63fcb31bf4661aedbb6.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n INSERT INTO agent_session (\n id, owner_id, thread_id, originating_message_id, bot_id, model,\n harness, repo_url, workspace, sandbox_size, instructions,\n acp_session_id, status, status_event_name, egress_token_hash,\n mcp_scope, mcp_servers, repo_branch, for_warming, source, visibility\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21)\n RETURNING\n id, name, archived_by::TEXT AS \"archived_by?\", archived_at, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, repo_branch, pull_request_url, task_id, source, visibility, workspace, sandbox_size, instructions,\n mcp_scope, mcp_servers, acp_session_id, status,\n status_event_name, created_at, modified_at,\n (SELECT jsonb_build_object('type', parent_entity_type, 'id', parent_entity_id)\n FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_parent?: Json<MessageParent>\",\n -- A row being created cannot have an external identity yet.\n NULL::TEXT AS \"external_provider?\", NULL::TEXT AS \"external_id?\",\n NULL::TEXT AS \"external_name?\", NULL::TEXT AS \"external_url?\",\n NULL::TEXT AS \"external_last_run_id?\"\n ",+ "query": "\n INSERT INTO agent_session (\n id, owner_id, thread_id, originating_message_id, bot_id, model,\n harness, repo_url, workspace, sandbox_size, instructions,\n acp_session_id, status, status_event_name, egress_token_hash,\n mcp_scope, mcp_servers, repo_branch, for_warming, source, visibility, source_id\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22)\n RETURNING\n id, name, archived_by::TEXT AS \"archived_by?\", archived_at, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, repo_branch, pull_request_url, task_id, source, visibility, workspace, sandbox_size, instructions,\n mcp_scope, mcp_servers, acp_session_id, status,\n status_event_name, created_at, modified_at,\n (SELECT jsonb_build_object('type', parent_entity_type, 'id', parent_entity_id)\n FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_parent?: Json<MessageParent>\",\n (SELECT to_jsonb(origin_row) FROM agent_session_source origin_row\n WHERE origin_row.id = agent_session.source_id)\n AS \"source_row?: Json<source::SourceRow>\",\n -- A row being created cannot have an external identity yet.\n NULL::TEXT AS \"external_provider?\", NULL::TEXT AS \"external_id?\",\n NULL::TEXT AS \"external_name?\", NULL::TEXT AS \"external_url?\",\n NULL::TEXT AS \"external_last_run_id?\"\n ","describe": {"columns": [{@@ -140,26 +140,31 @@},{"ordinal": 27,+ "name": "source_row?: Json<source::SourceRow>",+ "type_info": "Jsonb"+ },+ {+ "ordinal": 28,"name": "external_provider?","type_info": "Text"},{- "ordinal": 28,+ "ordinal": 29,"name": "external_id?","type_info": "Text"},{- "ordinal": 29,+ "ordinal": 30,"name": "external_name?","type_info": "Text"},{- "ordinal": 30,+ "ordinal": 31,"name": "external_url?","type_info": "Text"},{- "ordinal": 31,+ "ordinal": 32,"name": "external_last_run_id?","type_info": "Text"}@@ -186,7 +191,8 @@"Text","Bool","Text",- "Text"+ "Text",+ "Uuid"]},"nullable": [@@ -221,8 +227,9 @@null,null,null,+ null,null]},- "hash": "fdd57a58314654fb09c01bf2641ae2227c59957cc804e7e56bb2cc7608c387cd"+ "hash": "2d947f92d175d66f1d993961460700754cb7dd3a7f5fd63fcb31bf4661aedbb6"}diff --git a/.sqlx/query-1edf28fd90647dd3866022069d81e713044bf23dbecfb2bbba03c5f753d261d5.json b/.sqlx/query-3e0ef56c499402bea93f73468915ef3d0655d5dd7c314fa831bb7122d03eef74.jsonsimilarity index 56%rename from .sqlx/query-1edf28fd90647dd3866022069d81e713044bf23dbecfb2bbba03c5f753d261d5.jsonrename to .sqlx/query-3e0ef56c499402bea93f73468915ef3d0655d5dd7c314fa831bb7122d03eef74.jsonindex a0253ea0cf..08d6e43f75 100644--- a/.sqlx/query-1edf28fd90647dd3866022069d81e713044bf23dbecfb2bbba03c5f753d261d5.json+++ b/.sqlx/query-3e0ef56c499402bea93f73468915ef3d0655d5dd7c314fa831bb7122d03eef74.json@@ -1,12 +1,17 @@{"db_name": "PostgreSQL",- "query": "\n DELETE FROM agent_session\n WHERE id = $1\n RETURNING share_permission_id\n ",+ "query": "\n DELETE FROM agent_session\n WHERE id = $1\n RETURNING share_permission_id, source_id\n ","describe": {"columns": [{"ordinal": 0,"name": "share_permission_id","type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "source_id",+ "type_info": "Uuid"}],"parameters": {@@ -15,8 +20,9 @@]},"nullable": [+ true,true]},- "hash": "1edf28fd90647dd3866022069d81e713044bf23dbecfb2bbba03c5f753d261d5"+ "hash": "3e0ef56c499402bea93f73468915ef3d0655d5dd7c314fa831bb7122d03eef74"}diff --git a/.sqlx/query-1705afe309999f1db7e64edb339e1e6014de714cc911f06cbd86136927b8f695.json b/.sqlx/query-6cbaf981c5a213ee89ba925a0e7ea91739244e895ee491f5860b232d4913ce5f.jsonsimilarity index 82%rename from .sqlx/query-1705afe309999f1db7e64edb339e1e6014de714cc911f06cbd86136927b8f695.jsonrename to .sqlx/query-6cbaf981c5a213ee89ba925a0e7ea91739244e895ee491f5860b232d4913ce5f.jsonindex 7459168886..1f6f4a56ee 100644--- a/.sqlx/query-1705afe309999f1db7e64edb339e1e6014de714cc911f06cbd86136927b8f695.json+++ b/.sqlx/query-6cbaf981c5a213ee89ba925a0e7ea91739244e895ee491f5860b232d4913ce5f.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT\n id, name, archived_by::TEXT AS \"archived_by?\", archived_at, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, repo_branch, pull_request_url, task_id, source, visibility, workspace, sandbox_size, instructions,\n mcp_scope, mcp_servers, acp_session_id, status,\n status_event_name, agent_session.created_at, modified_at,\n (SELECT jsonb_build_object('type', parent_entity_type, 'id', parent_entity_id)\n FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_parent?: Json<MessageParent>\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\",\n ext.last_run_id AS \"external_last_run_id?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE egress_token_hash = $1\n ",+ "query": "\n SELECT\n id, name, archived_by::TEXT AS \"archived_by?\", archived_at, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, repo_branch, pull_request_url, task_id, source, visibility, workspace, sandbox_size, instructions,\n mcp_scope, mcp_servers, acp_session_id, status,\n status_event_name, agent_session.created_at, modified_at,\n (SELECT jsonb_build_object('type', parent_entity_type, 'id', parent_entity_id)\n FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_parent?: Json<MessageParent>\",\n (SELECT to_jsonb(origin_row) FROM agent_session_source origin_row\n WHERE origin_row.id = agent_session.source_id)\n AS \"source_row?: Json<source::SourceRow>\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\",\n ext.last_run_id AS \"external_last_run_id?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE egress_token_hash = $1\n ","describe": {"columns": [{@@ -140,26 +140,31 @@},{"ordinal": 27,+ "name": "source_row?: Json<source::SourceRow>",+ "type_info": "Jsonb"+ },+ {+ "ordinal": 28,"name": "external_provider?","type_info": "Text"},{- "ordinal": 28,+ "ordinal": 29,"name": "external_id?","type_info": "Text"},{- "ordinal": 29,+ "ordinal": 30,"name": "external_name?","type_info": "Text"},{- "ordinal": 30,+ "ordinal": 31,"name": "external_url?","type_info": "Text"},{- "ordinal": 31,+ "ordinal": 32,"name": "external_last_run_id?","type_info": "Text"}@@ -197,6 +202,7 @@false,false,null,+ null,false,false,true,@@ -204,5 +210,5 @@true]},- "hash": "1705afe309999f1db7e64edb339e1e6014de714cc911f06cbd86136927b8f695"+ "hash": "6cbaf981c5a213ee89ba925a0e7ea91739244e895ee491f5860b232d4913ce5f"}diff --git a/.sqlx/query-3e96728df6cb61241dd71ac527ba5201894ce9255c5e2070de586da8a03ab3c8.json b/.sqlx/query-766e544146a730dfc9eeea9a5cf130cbd0fd67e5c65f4610caa5ea1f9342096c.jsonsimilarity index 81%rename from .sqlx/query-3e96728df6cb61241dd71ac527ba5201894ce9255c5e2070de586da8a03ab3c8.jsonrename to .sqlx/query-766e544146a730dfc9eeea9a5cf130cbd0fd67e5c65f4610caa5ea1f9342096c.jsonindex 3a866476af..0079b21b36 100644--- a/.sqlx/query-3e96728df6cb61241dd71ac527ba5201894ce9255c5e2070de586da8a03ab3c8.json+++ b/.sqlx/query-766e544146a730dfc9eeea9a5cf130cbd0fd67e5c65f4610caa5ea1f9342096c.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT\n id, name, archived_by::TEXT AS \"archived_by?\", archived_at, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, repo_branch, pull_request_url, task_id, source, visibility, workspace, sandbox_size, instructions,\n mcp_scope, mcp_servers, acp_session_id, status,\n status_event_name, agent_session.created_at, modified_at,\n (SELECT jsonb_build_object('type', parent_entity_type, 'id', parent_entity_id)\n FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_parent?: Json<MessageParent>\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\",\n ext.last_run_id AS \"external_last_run_id?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE owner_id = $1 AND visibility <> 'hidden'\n ORDER BY agent_session.created_at DESC, id DESC\n LIMIT $2\n ",+ "query": "\n SELECT\n id, name, archived_by::TEXT AS \"archived_by?\", archived_at, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, repo_branch, pull_request_url, task_id, source, visibility, workspace, sandbox_size, instructions,\n mcp_scope, mcp_servers, acp_session_id, status,\n status_event_name, agent_session.created_at, modified_at,\n (SELECT jsonb_build_object('type', parent_entity_type, 'id', parent_entity_id)\n FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_parent?: Json<MessageParent>\",\n (SELECT to_jsonb(origin_row) FROM agent_session_source origin_row\n WHERE origin_row.id = agent_session.source_id)\n AS \"source_row?: Json<source::SourceRow>\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\",\n ext.last_run_id AS \"external_last_run_id?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE owner_id = $1 AND visibility <> 'hidden'\n ORDER BY agent_session.created_at DESC, id DESC\n LIMIT $2\n ","describe": {"columns": [{@@ -140,26 +140,31 @@},{"ordinal": 27,+ "name": "source_row?: Json<source::SourceRow>",+ "type_info": "Jsonb"+ },+ {+ "ordinal": 28,"name": "external_provider?","type_info": "Text"},{- "ordinal": 28,+ "ordinal": 29,"name": "external_id?","type_info": "Text"},{- "ordinal": 29,+ "ordinal": 30,"name": "external_name?","type_info": "Text"},{- "ordinal": 30,+ "ordinal": 31,"name": "external_url?","type_info": "Text"},{- "ordinal": 31,+ "ordinal": 32,"name": "external_last_run_id?","type_info": "Text"}@@ -198,6 +203,7 @@false,false,null,+ null,false,false,true,@@ -205,5 +211,5 @@true]},- "hash": "3e96728df6cb61241dd71ac527ba5201894ce9255c5e2070de586da8a03ab3c8"+ "hash": "766e544146a730dfc9eeea9a5cf130cbd0fd67e5c65f4610caa5ea1f9342096c"}diff --git a/.sqlx/query-79ee591afb708176f37d4e82b76cfefc62c0aaf2c67f7fa9212c9108a32b6ae0.json b/.sqlx/query-79ee591afb708176f37d4e82b76cfefc62c0aaf2c67f7fa9212c9108a32b6ae0.jsonnew file mode 100644index 0000000000..b790233627--- /dev/null+++ b/.sqlx/query-79ee591afb708176f37d4e82b76cfefc62c0aaf2c67f7fa9212c9108a32b6ae0.json@@ -0,0 +1,27 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO agent_session_source (\n id, kind, actor_user_id, actor_bot_id, on_behalf_of_user_id, acting_session_id,\n root_user_id, root_routine_id, message_id, task_id, project_id, routine_id,\n routine_firing, event_id\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Text",+ "Uuid",+ "Text",+ "Uuid",+ "Text",+ "Uuid",+ "Uuid",+ "Text",+ "Uuid",+ "Uuid",+ "Text",+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "79ee591afb708176f37d4e82b76cfefc62c0aaf2c67f7fa9212c9108a32b6ae0"+}diff --git a/.sqlx/query-7b0ec9246e4f42c5d097d6b23f6a053f865f07d625cb7e119190cd3722f2aea3.json b/.sqlx/query-7b0ec9246e4f42c5d097d6b23f6a053f865f07d625cb7e119190cd3722f2aea3.jsonnew file mode 100644index 0000000000..6fcf2afa38--- /dev/null+++ b/.sqlx/query-7b0ec9246e4f42c5d097d6b23f6a053f865f07d625cb7e119190cd3722f2aea3.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "DELETE FROM agent_session_source WHERE id = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "7b0ec9246e4f42c5d097d6b23f6a053f865f07d625cb7e119190cd3722f2aea3"+}diff --git a/.sqlx/query-9945a1e7de9236c5ed8a1f9f883114ad05f7b97b8f45588ee8e176fdf11cc3db.json b/.sqlx/query-9945a1e7de9236c5ed8a1f9f883114ad05f7b97b8f45588ee8e176fdf11cc3db.jsonnew file mode 100644index 0000000000..6bbe3b2155--- /dev/null+++ b/.sqlx/query-9945a1e7de9236c5ed8a1f9f883114ad05f7b97b8f45588ee8e176fdf11cc3db.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE agent_session SET source_id = $2 WHERE id = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "9945a1e7de9236c5ed8a1f9f883114ad05f7b97b8f45588ee8e176fdf11cc3db"+}diff --git a/.sqlx/query-aac9a77951f06fc164c5ed1ec2b608b9691894b3003f854c9b9f139d0a0740bd.json b/.sqlx/query-aac9a77951f06fc164c5ed1ec2b608b9691894b3003f854c9b9f139d0a0740bd.jsondeleted file mode 100644index 941dd3f3e4..0000000000--- a/.sqlx/query-aac9a77951f06fc164c5ed1ec2b608b9691894b3003f854c9b9f139d0a0740bd.json+++ /dev/null@@ -1,137 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT id, owner, name, schedule, kind, timezone, task, claimed, created_at,\n updated_at, next_run_at, enabled, trigger_type, event_filters,\n configuration_revision, event_activated_at, trigger_config, run_visibility, template_id,\n description\n FROM scheduled_action\n WHERE enabled AND trigger_type IN ('cron', 'multiple') AND next_run_at IS NOT NULL\n AND (claimed IS NULL OR claimed < $1)\n ORDER BY next_run_at ASC, id ASC\n LIMIT $2\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "id",- "type_info": "Uuid"- },- {- "ordinal": 1,- "name": "owner",- "type_info": "Text"- },- {- "ordinal": 2,- "name": "name",- "type_info": "Text"- },- {- "ordinal": 3,- "name": "schedule",- "type_info": "Text"- },- {- "ordinal": 4,- "name": "kind",- "type_info": "Text"- },- {- "ordinal": 5,- "name": "timezone",- "type_info": "Text"- },- {- "ordinal": 6,- "name": "task",- "type_info": "Jsonb"- },- {- "ordinal": 7,- "name": "claimed",- "type_info": "Timestamptz"- },- {- "ordinal": 8,- "name": "created_at",- "type_info": "Timestamptz"- },- {- "ordinal": 9,- "name": "updated_at",- "type_info": "Timestamptz"- },- {- "ordinal": 10,- "name": "next_run_at",- "type_info": "Timestamptz"- },- {- "ordinal": 11,- "name": "enabled",- "type_info": "Bool"- },- {- "ordinal": 12,- "name": "trigger_type",- "type_info": "Text"- },- {- "ordinal": 13,- "name": "event_filters",- "type_info": "Jsonb"- },- {- "ordinal": 14,- "name": "configuration_revision",- "type_info": "Int8"- },- {- "ordinal": 15,- "name": "event_activated_at",- "type_info": "Timestamptz"- },- {- "ordinal": 16,- "name": "trigger_config",- "type_info": "Jsonb"- },- {- "ordinal": 17,- "name": "run_visibility",- "type_info": "Text"- },- {- "ordinal": 18,- "name": "template_id",- "type_info": "Uuid"- },- {- "ordinal": 19,- "name": "description",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Timestamptz",- "Int8"- ]- },- "nullable": [- false,- false,- false,- true,- false,- true,- false,- true,- false,- false,- true,- false,- false,- true,- false,- true,- true,- false,- true,- false- ]- },- "hash": "aac9a77951f06fc164c5ed1ec2b608b9691894b3003f854c9b9f139d0a0740bd"-}diff --git a/.sqlx/query-11b0bebd59aee078ab9696f6c8aa80c855950b58c28a14f250ae31022c259743.json b/.sqlx/query-c1cfe39f4d7d3210c1ada5712d7559ee980e20fe1a2ccf7f27160009a4cddf42.jsonsimilarity index 83%rename from .sqlx/query-11b0bebd59aee078ab9696f6c8aa80c855950b58c28a14f250ae31022c259743.jsonrename to .sqlx/query-c1cfe39f4d7d3210c1ada5712d7559ee980e20fe1a2ccf7f27160009a4cddf42.jsonindex 245ffc7277..670ac939e9 100644--- a/.sqlx/query-11b0bebd59aee078ab9696f6c8aa80c855950b58c28a14f250ae31022c259743.json+++ b/.sqlx/query-c1cfe39f4d7d3210c1ada5712d7559ee980e20fe1a2ccf7f27160009a4cddf42.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT\n id, name, archived_by::TEXT AS \"archived_by?\", archived_at, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, repo_branch, pull_request_url, task_id, source, visibility, workspace, sandbox_size, instructions,\n mcp_scope, mcp_servers, acp_session_id, status,\n status_event_name, agent_session.created_at, modified_at,\n (SELECT jsonb_build_object('type', parent_entity_type, 'id', parent_entity_id)\n FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_parent?: Json<MessageParent>\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\",\n ext.last_run_id AS \"external_last_run_id?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE thread_id = $1 AND bot_id = $2\n ORDER BY agent_session.created_at DESC\n LIMIT 1\n ",+ "query": "\n SELECT\n id, name, archived_by::TEXT AS \"archived_by?\", archived_at, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, repo_branch, pull_request_url, task_id, source, visibility, workspace, sandbox_size, instructions,\n mcp_scope, mcp_servers, acp_session_id, status,\n status_event_name, agent_session.created_at, modified_at,\n (SELECT jsonb_build_object('type', parent_entity_type, 'id', parent_entity_id)\n FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_parent?: Json<MessageParent>\",\n (SELECT to_jsonb(origin_row) FROM agent_session_source origin_row\n WHERE origin_row.id = agent_session.source_id)\n AS \"source_row?: Json<source::SourceRow>\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\",\n ext.last_run_id AS \"external_last_run_id?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE id = $1\n ","describe": {"columns": [{@@ -140,33 +140,37 @@},{"ordinal": 27,+ "name": "source_row?: Json<source::SourceRow>",+ "type_info": "Jsonb"+ },+ {+ "ordinal": 28,"name": "external_provider?","type_info": "Text"},{- "ordinal": 28,+ "ordinal": 29,"name": "external_id?","type_info": "Text"},{- "ordinal": 29,+ "ordinal": 30,"name": "external_name?","type_info": "Text"},{- "ordinal": 30,+ "ordinal": 31,"name": "external_url?","type_info": "Text"},{- "ordinal": 31,+ "ordinal": 32,"name": "external_last_run_id?","type_info": "Text"}],"parameters": {"Left": [- "Uuid","Uuid"]},@@ -198,6 +202,7 @@false,false,null,+ null,false,false,true,@@ -205,5 +210,5 @@true]},- "hash": "11b0bebd59aee078ab9696f6c8aa80c855950b58c28a14f250ae31022c259743"+ "hash": "c1cfe39f4d7d3210c1ada5712d7559ee980e20fe1a2ccf7f27160009a4cddf42"}diff --git a/Cargo.lock b/Cargo.lockindex 097758eb09..98a1e88078 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -817,6 +817,7 @@ dependencies = ["tracing","tracing-opentelemetry","tracing-subscriber",+ "trigger_context","url","uuid","workspace-hack",@@ -21067,8 +21068,10 @@ version = "0.1.0"dependencies = ["bot_id","chrono",+ "macro_user_id","serde","serde_json",+ "utoipa","uuid","workspace-hack",]@@ -22273,6 +22276,7 @@ dependencies = ["tokio-retry","tower 0.5.3","tracing",+ "trigger_context","url","utoipa","uuid",diff --git a/apps/web/src/lib/core/component/AI/component/tool/ReadAgentSession.test.tsx b/apps/web/src/lib/core/component/AI/component/tool/ReadAgentSession.test.tsxindex d42b095ac2..e04ba26397 100644--- a/apps/web/src/lib/core/component/AI/component/tool/ReadAgentSession.test.tsx+++ b/apps/web/src/lib/core/component/AI/component/tool/ReadAgentSession.test.tsx@@ -24,6 +24,7 @@ it('expands the conversation and preserves the failure when text was truncated',archivedAt: null,harness: 'in-memory',model: 'test',+ origin: { origin: 'unknown' },status: 'disconnected',totalMessages: 2,truncated: true,diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentActor.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentActor.tsnew file mode 100644index 0000000000..60fad5308d--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentActor.ts@@ -0,0 +1,21 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */+import type { BotId } from './botId';+import type { Lineage } from './lineage';+import type { MacroUserIdStr } from './macroUserIdStr';++/**+ * An agent acting for a person.+ */+export interface AgentActor {+ /** The agent. */+ bot: BotId;+ /** Where the agent's own work came from. */+ lineage: Lineage;+ /** The person it acts for. */+ on_behalf_of: MacroUserIdStr;+}diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionResponse.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionResponse.tsindex ef8c9594ef..e7cd0bb8e4 100644--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionResponse.ts+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionResponse.ts@@ -18,6 +18,7 @@ import type { AgentSessionResponseThreadId } from './agentSessionResponseThreadIimport type { AgentSessionResponseThreadParent } from './agentSessionResponseThreadParent';import type { SandboxSize } from './sandboxSize';import type { SessionStatusDto } from './sessionStatusDto';+import type { TriggerOrigin } from './triggerOrigin';/*** Response body describing an agent session.@@ -52,6 +53,9 @@ at creation. Absent otherwise, so existing payloads are unchanged. */modifiedAt: string;/** User-facing session name. */name: string;+ /** What opened the session: who or what started it, and what it is about.+`unknown` when nothing recorded it. */+ origin?: TriggerOrigin;/** The exact message that invoked the bot, if any. */originatingMessageId?: AgentSessionResponseOriginatingMessageId;/** The user who created and owns the session. */diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/caller.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/caller.tsnew file mode 100644index 0000000000..2c4f691d71--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/caller.ts@@ -0,0 +1,13 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */+import type { CallerOneOf } from './callerOneOf';+import type { CallerOneOfThree } from './callerOneOfThree';++/**+ * Who did something that opened a session.+ */+export type Caller = CallerOneOf | CallerOneOfThree;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/callerOneOf.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/callerOneOf.tsnew file mode 100644index 0000000000..220130a46f--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/callerOneOf.ts@@ -0,0 +1,17 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */+import type { CallerOneOfType } from './callerOneOfType';+import type { MacroUserIdStr } from './macroUserIdStr';++/**+ * A person.+ */+export type CallerOneOf = {+ type: CallerOneOfType;+ /** Who. */+ user: MacroUserIdStr;+};diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/callerOneOfThree.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/callerOneOfThree.tsnew file mode 100644index 0000000000..0af1e6b2a3--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/callerOneOfThree.ts@@ -0,0 +1,13 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */+import type { AgentActor } from './agentActor';+import type { CallerOneOfThreeAllOf } from './callerOneOfThreeAllOf';++/**+ * An agent, which always acts for a person on a path that opens a session.+ */+export type CallerOneOfThree = AgentActor & CallerOneOfThreeAllOf;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/callerOneOfThreeAllOf.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/callerOneOfThreeAllOf.tsnew file mode 100644index 0000000000..c84670adcb--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/callerOneOfThreeAllOf.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */+import type { CallerOneOfThreeAllOfType } from './callerOneOfThreeAllOfType';++export type CallerOneOfThreeAllOf = {+ type: CallerOneOfThreeAllOfType;+};diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/callerOneOfThreeAllOfType.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/callerOneOfThreeAllOfType.tsnew file mode 100644index 0000000000..82deccd849--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/callerOneOfThreeAllOfType.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */++export type CallerOneOfThreeAllOfType =+ (typeof CallerOneOfThreeAllOfType)[keyof typeof CallerOneOfThreeAllOfType];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const CallerOneOfThreeAllOfType = {+ agent: 'agent',+} as const;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/callerOneOfType.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/callerOneOfType.tsnew file mode 100644index 0000000000..2b557f0ea3--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/callerOneOfType.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */++export type CallerOneOfType =+ (typeof CallerOneOfType)[keyof typeof CallerOneOfType];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const CallerOneOfType = {+ person: 'person',+} as const;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.tsindex 53a526471a..a2943eeafd 100644--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts@@ -32,6 +32,7 @@ export * from './agentActionOneOfSevenAllOfType';export * from './agentActivityCursor';export * from './agentActivityPage';export * from './agentActivityPageNextCursor';+export * from './agentActor';export * from './agentConfigKindDto';export * from './agentConfigKindDtoOneOf';export * from './agentConfigKindDtoOneOfThree';@@ -126,6 +127,12 @@ export * from './calendarSuggestionsStartAssumption';export * from './calendarSuggestionsTitle';export * from './callConnectedTool';export * from './callConnectedToolArguments';+export * from './caller';+export * from './callerOneOf';+export * from './callerOneOfThree';+export * from './callerOneOfThreeAllOf';+export * from './callerOneOfThreeAllOfType';+export * from './callerOneOfType';export * from './callSearchSuggestions';export * from './callSearchSuggestionsQuery';export * from './callSearchSuggestionsStatus';@@ -266,6 +273,11 @@ export * from './inputSuggestionsOneOfSevenIntent';export * from './inputSuggestionsOneOfThree';export * from './inputSuggestionsOneOfThreeIntent';export * from './intentScore';+export * from './lineage';+export * from './lineageOneOf';+export * from './lineageOneOfThree';+export * from './lineageOneOfThreeType';+export * from './lineageOneOfType';export * from './linkShare';export * from './listAgentRepositoryBranchesParams';export * from './loadAgentModelsRequest';@@ -275,6 +287,7 @@ export * from './loadAgentModelsResponseCurrentModel';export * from './logDirectionDto';export * from './logFrameDto';export * from './logFrameDtoContent';+export * from './macroUserIdStr';export * from './messageParent';export * from './messageParentOneOf';export * from './messageParentOneOfFive';@@ -353,6 +366,18 @@ export * from './reviewRecordAllOfTwo';export * from './reviewRecordAllOfTwoDecision';export * from './reviewRecordAllOfTwoExecutionId';export * from './reviewRecordAllOfTwoPresentedAt';+export * from './root';+export * from './rootOneOf';+export * from './rootOneOfThree';+export * from './rootOneOfThreeType';+export * from './rootOneOfType';+export * from './routineCause';+export * from './routineCauseOneOf';+export * from './routineCauseOneOfFive';+export * from './routineCauseOneOfFiveType';+export * from './routineCauseOneOfThree';+export * from './routineCauseOneOfThreeType';+export * from './routineCauseOneOfType';export * from './sandboxSize';export * from './sandboxSizeBody';export * from './searchConnectedAppToolsParams';@@ -415,6 +440,23 @@ export * from './taskSuggestionsTitle';export * from './toolActor';export * from './toolApprovalAnswerDto';export * from './toolApprovalStatusDto';+export * from './triggerOrigin';+export * from './triggerOriginOneOf';+export * from './triggerOriginOneOfFive';+export * from './triggerOriginOneOfFiveOrigin';+export * from './triggerOriginOneOfNine';+export * from './triggerOriginOneOfNineOrigin';+export * from './triggerOriginOneOfOnefive';+export * from './triggerOriginOneOfOnefiveOrigin';+export * from './triggerOriginOneOfOneone';+export * from './triggerOriginOneOfOneoneOrigin';+export * from './triggerOriginOneOfOnethree';+export * from './triggerOriginOneOfOnethreeOrigin';+export * from './triggerOriginOneOfOrigin';+export * from './triggerOriginOneOfSeven';+export * from './triggerOriginOneOfSevenOrigin';+export * from './triggerOriginOneOfThree';+export * from './triggerOriginOneOfThreeOrigin';export * from './unlinkAgentSessionPullRequestParams';export * from './updateChannelSharePermission';export * from './updateChannelSharePermissionAccessLevel';diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/lineage.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/lineage.tsnew file mode 100644index 0000000000..144bb75137--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/lineage.ts@@ -0,0 +1,13 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */+import type { LineageOneOf } from './lineageOneOf';+import type { LineageOneOfThree } from './lineageOneOfThree';++/**+ * Where an acting agent's work came from.+ */+export type Lineage = LineageOneOf | LineageOneOfThree;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/lineageOneOf.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/lineageOneOf.tsnew file mode 100644index 0000000000..00d6735e77--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/lineageOneOf.ts@@ -0,0 +1,20 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */++import type { LineageOneOfType } from './lineageOneOfType';+import type { Root } from './root';++/**+ * The session the agent acted from, and so where the chain started.+ */+export type LineageOneOf = {+ /** The first non-agent cause of its work. */+ root: Root;+ /** The acting session. */+ session: string;+ type: LineageOneOfType;+};diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/lineageOneOfThree.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/lineageOneOfThree.tsnew file mode 100644index 0000000000..dba5a76e19--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/lineageOneOfThree.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */+import type { LineageOneOfThreeType } from './lineageOneOfThreeType';++/**+ * An agent acted, but its session was not captured.+ */+export type LineageOneOfThree = {+ type: LineageOneOfThreeType;+};diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/lineageOneOfThreeType.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/lineageOneOfThreeType.tsnew file mode 100644index 0000000000..c35d37aed1--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/lineageOneOfThreeType.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */++export type LineageOneOfThreeType =+ (typeof LineageOneOfThreeType)[keyof typeof LineageOneOfThreeType];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const LineageOneOfThreeType = {+ unattributed: 'unattributed',+} as const;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/lineageOneOfType.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/lineageOneOfType.tsnew file mode 100644index 0000000000..8e9e577e7b--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/lineageOneOfType.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */++export type LineageOneOfType =+ (typeof LineageOneOfType)[keyof typeof LineageOneOfType];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const LineageOneOfType = {+ session: 'session',+} as const;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/macroUserIdStr.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/macroUserIdStr.tsnew file mode 100644index 0000000000..4c0b240e85--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/macroUserIdStr.ts@@ -0,0 +1,8 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */++export type MacroUserIdStr = string;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/root.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/root.tsnew file mode 100644index 0000000000..b5218d2639--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/root.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */+import type { RootOneOf } from './rootOneOf';+import type { RootOneOfThree } from './rootOneOfThree';++/**+ * The first non-agent cause. An agent cannot be one, so a chain always ends+at a person or a routine.+ */+export type Root = RootOneOf | RootOneOfThree;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/rootOneOf.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/rootOneOf.tsnew file mode 100644index 0000000000..1df0dbb055--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/rootOneOf.ts@@ -0,0 +1,18 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */++import type { MacroUserIdStr } from './macroUserIdStr';+import type { RootOneOfType } from './rootOneOfType';++/**+ * A person.+ */+export type RootOneOf = {+ type: RootOneOfType;+ /** Who. */+ user: MacroUserIdStr;+};diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/rootOneOfThree.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/rootOneOfThree.tsnew file mode 100644index 0000000000..6acc2a0613--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/rootOneOfThree.ts@@ -0,0 +1,16 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */+import type { RootOneOfThreeType } from './rootOneOfThreeType';++/**+ * A routine.+ */+export type RootOneOfThree = {+ /** The routine. */+ routine: string;+ type: RootOneOfThreeType;+};diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/rootOneOfThreeType.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/rootOneOfThreeType.tsnew file mode 100644index 0000000000..ac1ff6d98c--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/rootOneOfThreeType.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */++export type RootOneOfThreeType =+ (typeof RootOneOfThreeType)[keyof typeof RootOneOfThreeType];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const RootOneOfThreeType = {+ routine: 'routine',+} as const;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/rootOneOfType.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/rootOneOfType.tsnew file mode 100644index 0000000000..dbc100f295--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/rootOneOfType.ts@@ -0,0 +1,13 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */++export type RootOneOfType = (typeof RootOneOfType)[keyof typeof RootOneOfType];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const RootOneOfType = {+ person: 'person',+} as const;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/routineCause.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/routineCause.tsnew file mode 100644index 0000000000..ac59af1276--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/routineCause.ts@@ -0,0 +1,17 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */+import type { RoutineCauseOneOf } from './routineCauseOneOf';+import type { RoutineCauseOneOfFive } from './routineCauseOneOfFive';+import type { RoutineCauseOneOfThree } from './routineCauseOneOfThree';++/**+ * What made a routine fire.+ */+export type RoutineCause =+ | RoutineCauseOneOf+ | RoutineCauseOneOfThree+ | RoutineCauseOneOfFive;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/routineCauseOneOf.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/routineCauseOneOf.tsnew file mode 100644index 0000000000..67259fa4f2--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/routineCauseOneOf.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */+import type { RoutineCauseOneOfType } from './routineCauseOneOfType';++/**+ * One of its schedules came due.+ */+export type RoutineCauseOneOf = {+ type: RoutineCauseOneOfType;+};diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/routineCauseOneOfFive.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/routineCauseOneOfFive.tsnew file mode 100644index 0000000000..9551acff91--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/routineCauseOneOfFive.ts@@ -0,0 +1,16 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */+import type { RoutineCauseOneOfFiveType } from './routineCauseOneOfFiveType';++/**+ * An event it watches happened.+ */+export type RoutineCauseOneOfFive = {+ /** The event. */+ event_id: string;+ type: RoutineCauseOneOfFiveType;+};diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/routineCauseOneOfFiveType.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/routineCauseOneOfFiveType.tsnew file mode 100644index 0000000000..09a7adfb06--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/routineCauseOneOfFiveType.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */++export type RoutineCauseOneOfFiveType =+ (typeof RoutineCauseOneOfFiveType)[keyof typeof RoutineCauseOneOfFiveType];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const RoutineCauseOneOfFiveType = {+ event: 'event',+} as const;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/routineCauseOneOfThree.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/routineCauseOneOfThree.tsnew file mode 100644index 0000000000..2251c36a85--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/routineCauseOneOfThree.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */+import type { RoutineCauseOneOfThreeType } from './routineCauseOneOfThreeType';++/**+ * Its owner started it by hand.+ */+export type RoutineCauseOneOfThree = {+ type: RoutineCauseOneOfThreeType;+};diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/routineCauseOneOfThreeType.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/routineCauseOneOfThreeType.tsnew file mode 100644index 0000000000..eb748f7e10--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/routineCauseOneOfThreeType.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */++export type RoutineCauseOneOfThreeType =+ (typeof RoutineCauseOneOfThreeType)[keyof typeof RoutineCauseOneOfThreeType];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const RoutineCauseOneOfThreeType = {+ manual: 'manual',+} as const;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/routineCauseOneOfType.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/routineCauseOneOfType.tsnew file mode 100644index 0000000000..9d0e4eff45--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/routineCauseOneOfType.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */++export type RoutineCauseOneOfType =+ (typeof RoutineCauseOneOfType)[keyof typeof RoutineCauseOneOfType];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const RoutineCauseOneOfType = {+ scheduled: 'scheduled',+} as const;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/triggerOrigin.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/triggerOrigin.tsnew file mode 100644index 0000000000..98b6664d21--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/triggerOrigin.ts@@ -0,0 +1,27 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */+import type { TriggerOriginOneOf } from './triggerOriginOneOf';+import type { TriggerOriginOneOfFive } from './triggerOriginOneOfFive';+import type { TriggerOriginOneOfNine } from './triggerOriginOneOfNine';+import type { TriggerOriginOneOfOnefive } from './triggerOriginOneOfOnefive';+import type { TriggerOriginOneOfOneone } from './triggerOriginOneOfOneone';+import type { TriggerOriginOneOfOnethree } from './triggerOriginOneOfOnethree';+import type { TriggerOriginOneOfSeven } from './triggerOriginOneOfSeven';+import type { TriggerOriginOneOfThree } from './triggerOriginOneOfThree';++/**+ * What opened a session.+ */+export type TriggerOrigin =+ | TriggerOriginOneOf+ | TriggerOriginOneOfThree+ | TriggerOriginOneOfFive+ | TriggerOriginOneOfSeven+ | TriggerOriginOneOfNine+ | TriggerOriginOneOfOneone+ | TriggerOriginOneOfOnethree+ | TriggerOriginOneOfOnefive;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/triggerOriginOneOf.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/triggerOriginOneOf.tsnew file mode 100644index 0000000000..c2c02c469c--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/triggerOriginOneOf.ts@@ -0,0 +1,19 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */+import type { Caller } from './caller';+import type { TriggerOriginOneOfOrigin } from './triggerOriginOneOfOrigin';++/**+ * A message mentioned the agent.+ */+export type TriggerOriginOneOf = {+ /** Who posted it. */+ by: Caller;+ /** The message. */+ message_id: string;+ origin: TriggerOriginOneOfOrigin;+};diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/triggerOriginOneOfFive.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/triggerOriginOneOfFive.tsnew file mode 100644index 0000000000..dc47e117a2--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/triggerOriginOneOfFive.ts@@ -0,0 +1,19 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */+import type { Caller } from './caller';+import type { TriggerOriginOneOfFiveOrigin } from './triggerOriginOneOfFiveOrigin';++/**+ * The agent was added to a task's assignees.+ */+export type TriggerOriginOneOfFive = {+ /** Who assigned it. */+ by: Caller;+ origin: TriggerOriginOneOfFiveOrigin;+ /** The task. */+ task: string;+};diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/triggerOriginOneOfFiveOrigin.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/triggerOriginOneOfFiveOrigin.tsnew file mode 100644index 0000000000..eb45a31169--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/triggerOriginOneOfFiveOrigin.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */++export type TriggerOriginOneOfFiveOrigin =+ (typeof TriggerOriginOneOfFiveOrigin)[keyof typeof TriggerOriginOneOfFiveOrigin];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const TriggerOriginOneOfFiveOrigin = {+ task_assigned: 'task_assigned',+} as const;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/triggerOriginOneOfNine.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/triggerOriginOneOfNine.tsnew file mode 100644index 0000000000..f40fb0f90c--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/triggerOriginOneOfNine.ts@@ -0,0 +1,17 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */+import type { MacroUserIdStr } from './macroUserIdStr';+import type { TriggerOriginOneOfNineOrigin } from './triggerOriginOneOfNineOrigin';++/**+ * A person opened the session directly, from the composer.+ */+export type TriggerOriginOneOfNine = {+ /** Who opened it. */+ by: MacroUserIdStr;+ origin: TriggerOriginOneOfNineOrigin;+};diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/triggerOriginOneOfNineOrigin.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/triggerOriginOneOfNineOrigin.tsnew file mode 100644index 0000000000..420612fbd5--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/triggerOriginOneOfNineOrigin.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */++export type TriggerOriginOneOfNineOrigin =+ (typeof TriggerOriginOneOfNineOrigin)[keyof typeof TriggerOriginOneOfNineOrigin];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const TriggerOriginOneOfNineOrigin = {+ requested: 'requested',+} as const;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/triggerOriginOneOfOnefive.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/triggerOriginOneOfOnefive.tsnew file mode 100644index 0000000000..5b3e9fbdac--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/triggerOriginOneOfOnefive.ts@@ -0,0 +1,15 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */+import type { TriggerOriginOneOfOnefiveOrigin } from './triggerOriginOneOfOnefiveOrigin';++/**+ * Not known: an unclaimed warm session, a producer that predates this+record, or a kind this build does not know.+ */+export type TriggerOriginOneOfOnefive = {+ origin: TriggerOriginOneOfOnefiveOrigin;+};diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/triggerOriginOneOfOnefiveOrigin.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/triggerOriginOneOfOnefiveOrigin.tsnew file mode 100644index 0000000000..7428f04e67--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/triggerOriginOneOfOnefiveOrigin.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */++export type TriggerOriginOneOfOnefiveOrigin =+ (typeof TriggerOriginOneOfOnefiveOrigin)[keyof typeof TriggerOriginOneOfOnefiveOrigin];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const TriggerOriginOneOfOnefiveOrigin = {+ unknown: 'unknown',+} as const;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/triggerOriginOneOfOneone.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/triggerOriginOneOfOneone.tsnew file mode 100644index 0000000000..490590c620--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/triggerOriginOneOfOneone.ts@@ -0,0 +1,18 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */+import type { MacroUserIdStr } from './macroUserIdStr';+import type { TriggerOriginOneOfOneoneOrigin } from './triggerOriginOneOfOneoneOrigin';++/**+ * A tool handed the agent work. The tool knows only whose authority it+runs under, not which agent called it.+ */+export type TriggerOriginOneOfOneone = {+ /** The user whose authority the work runs under. */+ on_behalf_of: MacroUserIdStr;+ origin: TriggerOriginOneOfOneoneOrigin;+};diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/triggerOriginOneOfOneoneOrigin.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/triggerOriginOneOfOneoneOrigin.tsnew file mode 100644index 0000000000..6b42bbde30--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/triggerOriginOneOfOneoneOrigin.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */++export type TriggerOriginOneOfOneoneOrigin =+ (typeof TriggerOriginOneOfOneoneOrigin)[keyof typeof TriggerOriginOneOfOneoneOrigin];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const TriggerOriginOneOfOneoneOrigin = {+ dispatched: 'dispatched',+} as const;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/triggerOriginOneOfOnethree.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/triggerOriginOneOfOnethree.tsnew file mode 100644index 0000000000..0a91a00d78--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/triggerOriginOneOfOnethree.ts@@ -0,0 +1,19 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */+import type { RoutineCause } from './routineCause';+import type { TriggerOriginOneOfOnethreeOrigin } from './triggerOriginOneOfOnethreeOrigin';++/**+ * A routine fired. Its owner owns the session, so the owner is not repeated.+ */+export type TriggerOriginOneOfOnethree = {+ /** What made it fire. */+ firing: RoutineCause;+ origin: TriggerOriginOneOfOnethreeOrigin;+ /** The routine. */+ routine: string;+};diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/triggerOriginOneOfOnethreeOrigin.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/triggerOriginOneOfOnethreeOrigin.tsnew file mode 100644index 0000000000..d1d503ce5f--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/triggerOriginOneOfOnethreeOrigin.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */++export type TriggerOriginOneOfOnethreeOrigin =+ (typeof TriggerOriginOneOfOnethreeOrigin)[keyof typeof TriggerOriginOneOfOnethreeOrigin];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const TriggerOriginOneOfOnethreeOrigin = {+ routine: 'routine',+} as const;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/triggerOriginOneOfOrigin.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/triggerOriginOneOfOrigin.tsnew file mode 100644index 0000000000..b3726dde7f--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/triggerOriginOneOfOrigin.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */++export type TriggerOriginOneOfOrigin =+ (typeof TriggerOriginOneOfOrigin)[keyof typeof TriggerOriginOneOfOrigin];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const TriggerOriginOneOfOrigin = {+ mentioned: 'mentioned',+} as const;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/triggerOriginOneOfSeven.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/triggerOriginOneOfSeven.tsnew file mode 100644index 0000000000..925e5bf142--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/triggerOriginOneOfSeven.ts@@ -0,0 +1,21 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */+import type { Caller } from './caller';+import type { TriggerOriginOneOfSevenOrigin } from './triggerOriginOneOfSevenOrigin';++/**+ * The task joined a project, and inherited the project's agents.+ */+export type TriggerOriginOneOfSeven = {+ /** Who added the task to the project. */+ by: Caller;+ origin: TriggerOriginOneOfSevenOrigin;+ /** The project. */+ project: string;+ /** The task. */+ task: string;+};diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/triggerOriginOneOfSevenOrigin.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/triggerOriginOneOfSevenOrigin.tsnew file mode 100644index 0000000000..04de9dfd39--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/triggerOriginOneOfSevenOrigin.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */++export type TriggerOriginOneOfSevenOrigin =+ (typeof TriggerOriginOneOfSevenOrigin)[keyof typeof TriggerOriginOneOfSevenOrigin];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const TriggerOriginOneOfSevenOrigin = {+ project_inherited: 'project_inherited',+} as const;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/triggerOriginOneOfThree.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/triggerOriginOneOfThree.tsnew file mode 100644index 0000000000..62f894d430--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/triggerOriginOneOfThree.ts@@ -0,0 +1,19 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */+import type { MacroUserIdStr } from './macroUserIdStr';+import type { TriggerOriginOneOfThreeOrigin } from './triggerOriginOneOfThreeOrigin';++/**+ * A person wrote in their private conversation with the agent.+ */+export type TriggerOriginOneOfThree = {+ /** Who wrote. */+ by: MacroUserIdStr;+ /** The message. */+ message_id: string;+ origin: TriggerOriginOneOfThreeOrigin;+};diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/triggerOriginOneOfThreeOrigin.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/triggerOriginOneOfThreeOrigin.tsnew file mode 100644index 0000000000..2781a186f6--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/triggerOriginOneOfThreeOrigin.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */++export type TriggerOriginOneOfThreeOrigin =+ (typeof TriggerOriginOneOfThreeOrigin)[keyof typeof TriggerOriginOneOfThreeOrigin];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const TriggerOriginOneOfThreeOrigin = {+ conversation: 'conversation',+} as const;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/openapi.json b/apps/web/src/lib/service-clients/service-agent-harness/openapi.jsonindex d8e4ff473a..5922091edb 100644--- a/apps/web/src/lib/service-clients/service-agent-harness/openapi.json+++ b/apps/web/src/lib/service-clients/service-agent-harness/openapi.json@@ -3893,6 +3893,25 @@}}},+ "AgentActor": {+ "type": "object",+ "description": "An agent acting for a person.",+ "required": ["bot", "on_behalf_of", "lineage"],+ "properties": {+ "bot": {+ "$ref": "#/components/schemas/BotId",+ "description": "The agent."+ },+ "lineage": {+ "$ref": "#/components/schemas/Lineage",+ "description": "Where the agent's own work came from."+ },+ "on_behalf_of": {+ "$ref": "#/components/schemas/MacroUserIdStr",+ "description": "The person it acts for."+ }+ }+ },"AgentConfigKindDto": {"oneOf": [{@@ -4611,6 +4630,10 @@"type": "string","description": "User-facing session name."},+ "origin": {+ "$ref": "#/components/schemas/TriggerOrigin",+ "description": "What opened the session: who or what started it, and what it is about.\n`unknown` when nothing recorded it."+ },"originatingMessageId": {"type": ["string", "null"],"format": "uuid",@@ -4889,6 +4912,45 @@},"additionalProperties": false},+ "Caller": {+ "oneOf": [+ {+ "type": "object",+ "description": "A person.",+ "required": ["user", "type"],+ "properties": {+ "type": {+ "type": "string",+ "enum": ["person"]+ },+ "user": {+ "$ref": "#/components/schemas/MacroUserIdStr",+ "description": "Who."+ }+ }+ },+ {+ "allOf": [+ {+ "$ref": "#/components/schemas/AgentActor",+ "description": "An agent, which always acts for a person on a path that opens a session."+ },+ {+ "type": "object",+ "required": ["type"],+ "properties": {+ "type": {+ "type": "string",+ "enum": ["agent"]+ }+ }+ }+ ],+ "description": "An agent, which always acts for a person on a path that opens a session."+ }+ ],+ "description": "Who did something that opened a session."+ },"CapabilityHarnessDto": {"type": "string","description": "Harness names accepted by the capability-discovery endpoint.",@@ -6273,6 +6335,42 @@}}},+ "Lineage": {+ "oneOf": [+ {+ "type": "object",+ "description": "The session the agent acted from, and so where the chain started.",+ "required": ["session", "root", "type"],+ "properties": {+ "root": {+ "$ref": "#/components/schemas/Root",+ "description": "The first non-agent cause of its work."+ },+ "session": {+ "type": "string",+ "format": "uuid",+ "description": "The acting session."+ },+ "type": {+ "type": "string",+ "enum": ["session"]+ }+ }+ },+ {+ "type": "object",+ "description": "An agent acted, but its session was not captured.",+ "required": ["type"],+ "properties": {+ "type": {+ "type": "string",+ "enum": ["unattributed"]+ }+ }+ }+ ],+ "description": "Where an acting agent's work came from."+ },"LinkShare": {"type": "string","description": "Defines who can access an item through its share link.",@@ -6336,6 +6434,9 @@}}},+ "MacroUserIdStr": {+ "type": "string"+ },"MessageParent": {"oneOf": [{@@ -7097,6 +7198,85 @@],"description": "Full UI record, fetched outside the model context."},+ "Root": {+ "oneOf": [+ {+ "type": "object",+ "description": "A person.",+ "required": ["user", "type"],+ "properties": {+ "type": {+ "type": "string",+ "enum": ["person"]+ },+ "user": {+ "$ref": "#/components/schemas/MacroUserIdStr",+ "description": "Who."+ }+ }+ },+ {+ "type": "object",+ "description": "A routine.",+ "required": ["routine", "type"],+ "properties": {+ "routine": {+ "type": "string",+ "format": "uuid",+ "description": "The routine."+ },+ "type": {+ "type": "string",+ "enum": ["routine"]+ }+ }+ }+ ],+ "description": "The first non-agent cause. An agent cannot be one, so a chain always ends\nat a person or a routine."+ },+ "RoutineCause": {+ "oneOf": [+ {+ "type": "object",+ "description": "One of its schedules came due.",+ "required": ["type"],+ "properties": {+ "type": {+ "type": "string",+ "enum": ["scheduled"]+ }+ }+ },+ {+ "type": "object",+ "description": "Its owner started it by hand.",+ "required": ["type"],+ "properties": {+ "type": {+ "type": "string",+ "enum": ["manual"]+ }+ }+ },+ {+ "type": "object",+ "description": "An event it watches happened.",+ "required": ["event_id", "type"],+ "properties": {+ "event_id": {+ "type": "string",+ "format": "uuid",+ "description": "The event."+ },+ "type": {+ "type": "string",+ "enum": ["event"]+ }+ }+ }+ ],+ "description": "What made a routine fire."+ },"SandboxSize": {"type": "string","description": "Named compute tier for a managed sandbox.\n\nThe API and database store the name. CPU, RAM, and disk live in\n`crates/agent_harness/sandbox_sizes.json`.",@@ -7589,6 +7769,155 @@"description": "Where a held tool call stands once answered.","enum": ["pending", "approved", "denied", "cancelled", "expired"]},+ "TriggerOrigin": {+ "oneOf": [+ {+ "type": "object",+ "description": "A message mentioned the agent.",+ "required": ["by", "message_id", "origin"],+ "properties": {+ "by": {+ "$ref": "#/components/schemas/Caller",+ "description": "Who posted it."+ },+ "message_id": {+ "type": "string",+ "format": "uuid",+ "description": "The message."+ },+ "origin": {+ "type": "string",+ "enum": ["mentioned"]+ }+ }+ },+ {+ "type": "object",+ "description": "A person wrote in their private conversation with the agent.",+ "required": ["by", "message_id", "origin"],+ "properties": {+ "by": {+ "$ref": "#/components/schemas/MacroUserIdStr",+ "description": "Who wrote."+ },+ "message_id": {+ "type": "string",+ "format": "uuid",+ "description": "The message."+ },+ "origin": {+ "type": "string",+ "enum": ["conversation"]+ }+ }+ },+ {+ "type": "object",+ "description": "The agent was added to a task's assignees.",+ "required": ["by", "task", "origin"],+ "properties": {+ "by": {+ "$ref": "#/components/schemas/Caller",+ "description": "Who assigned it."+ },+ "origin": {+ "type": "string",+ "enum": ["task_assigned"]+ },+ "task": {+ "type": "string",+ "description": "The task."+ }+ }+ },+ {+ "type": "object",+ "description": "The task joined a project, and inherited the project's agents.",+ "required": ["by", "task", "project", "origin"],+ "properties": {+ "by": {+ "$ref": "#/components/schemas/Caller",+ "description": "Who added the task to the project."+ },+ "origin": {+ "type": "string",+ "enum": ["project_inherited"]+ },+ "project": {+ "type": "string",+ "format": "uuid",+ "description": "The project."+ },+ "task": {+ "type": "string",+ "description": "The task."+ }+ }+ },+ {+ "type": "object",+ "description": "A person opened the session directly, from the composer.",+ "required": ["by", "origin"],+ "properties": {+ "by": {+ "$ref": "#/components/schemas/MacroUserIdStr",+ "description": "Who opened it."+ },+ "origin": {+ "type": "string",+ "enum": ["requested"]+ }+ }+ },+ {+ "type": "object",+ "description": "A tool handed the agent work. The tool knows only whose authority it\nruns under, not which agent called it.",+ "required": ["on_behalf_of", "origin"],+ "properties": {+ "on_behalf_of": {+ "$ref": "#/components/schemas/MacroUserIdStr",+ "description": "The user whose authority the work runs under."+ },+ "origin": {+ "type": "string",+ "enum": ["dispatched"]+ }+ }+ },+ {+ "type": "object",+ "description": "A routine fired. Its owner owns the session, so the owner is not repeated.",+ "required": ["routine", "firing", "origin"],+ "properties": {+ "firing": {+ "$ref": "#/components/schemas/RoutineCause",+ "description": "What made it fire."+ },+ "origin": {+ "type": "string",+ "enum": ["routine"]+ },+ "routine": {+ "type": "string",+ "format": "uuid",+ "description": "The routine."+ }+ }+ },+ {+ "type": "object",+ "description": "Not known: an unclaimed warm session, a producer that predates this\nrecord, or a kind this build does not know.",+ "required": ["origin"],+ "properties": {+ "origin": {+ "type": "string",+ "enum": ["unknown"]+ }+ }+ }+ ],+ "description": "What opened a session."+ },"UpdateChannelSharePermission": {"type": "object","required": ["operation", "channelId"],diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.tsindex 8c4d9b4d99..4f23d4cdcb 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts@@ -14320,6 +14320,7 @@ export const SessionConversation = z.object({harness: z.string(),model: z.string(),status: z.string(),+ origin: z.any(),messages: z.array(z.object({turn: z.number().int().gte(0),diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.tsindex d8f3428757..287887e104 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts@@ -13376,6 +13376,12 @@ export interface SessionConversation {* Last runtime status.*/status: string;+ /**+ * What opened the session: who or what started it, and what it is about.+ */+ origin: {+ [k: string]: unknown;+ };/*** Messages in the requested turn, or the latest messages, oldest first.*/diff --git a/crates/agent_harness/src/domain/model/session_origin.rs b/crates/agent_harness/src/domain/model/session_origin.rsindex a8d3240f75..b2965b44cb 100644--- a/crates/agent_harness/src/domain/model/session_origin.rs+++ b/crates/agent_harness/src/domain/model/session_origin.rs@@ -3,7 +3,7 @@use agent_runtime_protocol::domain::action::{AgentAction, PromptAttachment};use macro_user_id::user_id::MacroUserIdStr;use macro_uuid::Uuid;-use trigger_context::TriggerContext;+use trigger_context::{TriggerContext, TriggerOrigin};use super::{AnnounceOrigin, ReplyPlacement};@@ -32,6 +32,9 @@ pub struct MentionOrigin {/// Why the agent was called, as the trigger read it.#[serde(default, skip_serializing_if = "Option::is_none")]pub context: Option<TriggerContext>,+ /// What opened the session, stored with it.+ #[serde(default, skip_serializing_if = "TriggerOrigin::is_unknown")]+ pub trigger_origin: TriggerOrigin,}/// A task assignment that starts a session without a user-authored mention.@@ -48,6 +51,9 @@ pub struct TaskAssignmentOrigin {/// The task, who assigned it, and how, as the trigger read it.#[serde(default, skip_serializing_if = "Option::is_none")]pub context: Option<TriggerContext>,+ /// What opened the session, stored with it.+ #[serde(default, skip_serializing_if = "TriggerOrigin::is_unknown")]+ pub trigger_origin: TriggerOrigin,}/// The event that opens a managed session.@@ -93,6 +99,13 @@ impl SessionOrigin {}}+ pub(crate) fn trigger_origin(&self) -> &TriggerOrigin {+ match self {+ Self::Mention(origin) => &origin.trigger_origin,+ Self::TaskAssignment(origin) => &origin.trigger_origin,+ }+ }+pub(crate) fn kind(&self) -> &'static str {match self {Self::Mention(_) => "mention",diff --git a/crates/agent_harness/src/domain/model/session_origin/test.rs b/crates/agent_harness/src/domain/model/session_origin/test.rsindex 6bbe84f297..ca0c3b5a36 100644--- a/crates/agent_harness/src/domain/model/session_origin/test.rs+++ b/crates/agent_harness/src/domain/model/session_origin/test.rs@@ -8,6 +8,7 @@ fn actor() -> MacroUserIdStr<'static> {#[test]fn existing_mention_commands_keep_their_wire_shape_and_reply_behavior() {let mention = MentionOrigin {+ trigger_origin: trigger_context::TriggerOrigin::Unknown,reply_placement: Default::default(),parent: MessageParent::Channel(Uuid::from_u128(1)),thread_id: Uuid::from_u128(2),@@ -34,6 +35,7 @@ fn existing_mention_commands_keep_their_wire_shape_and_reply_behavior() {#[test]fn assignments_remain_distinct_after_command_serialization() {let origin = SessionOrigin::TaskAssignment(TaskAssignmentOrigin {+ trigger_origin: trigger_context::TriggerOrigin::Unknown,parent: MessageParent::parse("document", "task-1").unwrap(),discussion_id: Uuid::from_u128(4),actor: actor(),diff --git a/crates/agent_harness/src/domain/ports/test.rs b/crates/agent_harness/src/domain/ports/test.rsindex db212432d7..4e4b6f3874 100644--- a/crates/agent_harness/src/domain/ports/test.rs+++ b/crates/agent_harness/src/domain/ports/test.rs@@ -30,6 +30,7 @@ fn owner() -> MacroUserIdStr<'static> {fn params(id: AgentSessionId) -> CreateAgentSessionParams {CreateAgentSessionParams {+ origin: trigger_context::TriggerOrigin::Unknown,purpose: agent_session::domain::model::SessionPurpose::Standalone,repo_branch: None,id,diff --git a/crates/agent_harness/src/domain/service/open.rs b/crates/agent_harness/src/domain/service/open.rsindex b798916352..f343b60630 100644--- a/crates/agent_harness/src/domain/service/open.rs+++ b/crates/agent_harness/src/domain/service/open.rs@@ -127,6 +127,7 @@ where// Mint the session MCP credential when an authenticated// runtime binds, and rotate it on each subsequent binding.egress_token_hash: None,+ origin: request.origin,// The thread linkage is the caller's claim, not an observed// mention; it must not grant the channel anything.})@@ -517,6 +518,7 @@ where// advertised, for as long as the session lives.mcp_servers: runtime.mcp_servers.clone(),egress_token_hash: Some(egress.session_token_hash),+ origin: origin.trigger_origin().clone(),// This open came from an observed trigger event.}).await?;diff --git a/crates/agent_harness/src/domain/service/test.rs b/crates/agent_harness/src/domain/service/test.rsindex 39b7788ae8..02dcd96ba2 100644--- a/crates/agent_harness/src/domain/service/test.rs+++ b/crates/agent_harness/src/domain/service/test.rs@@ -110,6 +110,7 @@ fn open_command() -> OpenSession {mcp_servers: AgentMcpServers::OwnerConnections,},origin: SessionOrigin::Mention(MentionOrigin {+ trigger_origin: trigger_context::TriggerOrigin::Unknown,reply_placement: Default::default(),parent: MessageParent::Channel(macro_uuid::generate_uuid_v7()),thread_id,@@ -828,6 +829,7 @@ async fn disconnected_session_of(agent_session::domain::ports::AgentSessionRepo::create(repo,CreateAgentSessionParams {+ origin: trigger_context::TriggerOrigin::Unknown,purpose: agent_session::domain::model::SessionPurpose::Standalone,repo_branch: None,id,@@ -3017,6 +3019,7 @@ async fn a_prompt_through_control_resumes_a_disconnected_session() {fn open_external_request(workspace: &str) -> OpenExternalAgentSession {OpenExternalAgentSession {+ origin: trigger_context::TriggerOrigin::Unknown,id: None,profile: None,instructions: None,@@ -3319,6 +3322,7 @@ async fn a_managed_session_opens_as_the_managed_default_bot() {let session = service.open_managed_session(agent_session::domain::ports::OpenManagedSession {+ origin: trigger_context::TriggerOrigin::Unknown,id: None,repo_url: None,repo_branch: None,@@ -3566,6 +3570,7 @@ async fn managed_open_composes_its_prompt_without_channel_context() {let result = service.open_managed_session(OpenManagedSession {+ origin: trigger_context::TriggerOrigin::Unknown,id: None,repo_url: None,repo_branch: None,@@ -3603,6 +3608,7 @@ async fn open_managed_session_spawns_at_the_users_default_size() {.expect("the user default should persist");let open = service.open_managed_session(OpenManagedSession {+ origin: trigger_context::TriggerOrigin::Unknown,id: None,repo_url: None,repo_branch: None,@@ -3647,6 +3653,7 @@ async fn open_external_session_refuses_a_bot_owner() {let error = service.open_external_session(OpenExternalAgentSession {+ origin: trigger_context::TriggerOrigin::Unknown,id: Some(id),owner: model_owner::Owner::Bot(BotId::TEST_A),..open_external_request("/srv/agent")@@ -3672,6 +3679,7 @@ async fn open_managed_session_refuses_a_bot_owner() {let error = service.open_managed_session(OpenManagedSession {+ origin: trigger_context::TriggerOrigin::Unknown,id: Some(id),repo_url: None,repo_branch: None,@@ -4468,6 +4476,7 @@ mod lifecycle_events {async fn codex_named_session_provisions_egress_without_advertising_mcp() {let (service, repo, containers, _, _) = harness();let open = service.open_managed_session(OpenManagedSession {+ origin: trigger_context::TriggerOrigin::Unknown,id: None,repo_url: None,repo_branch: None,@@ -4524,6 +4533,7 @@ async fn a_managed_open_delivers_its_first_prompt_under_the_callers_id() {let (service, repo, containers, _, _) = harness();let action_id = AgentActionId::mint();let open = service.open_managed_session(OpenManagedSession {+ origin: trigger_context::TriggerOrigin::Unknown,id: None,repo_url: None,repo_branch: None,@@ -4655,6 +4665,7 @@ impl crate::domain::ports::ReachableRepositories for SelectedRepositories {async fn a_chosen_model_is_the_session_model_from_creation() {let (service, repo, containers, _, _) = harness();let open = service.open_managed_session(OpenManagedSession {+ origin: trigger_context::TriggerOrigin::Unknown,id: None,repo_url: None,repo_branch: None,@@ -4686,6 +4697,7 @@ async fn a_chosen_model_is_the_session_model_from_creation() {async fn a_chosen_model_is_selected_on_a_runtime_that_does_not_read_the_row() {let (service, _, containers, _, _) = harness();let open = service.open_managed_session(OpenManagedSession {+ origin: trigger_context::TriggerOrigin::Unknown,id: None,repo_url: None,repo_branch: None,@@ -4726,6 +4738,7 @@ async fn a_chosen_model_is_selected_on_a_runtime_that_does_not_read_the_row() {async fn a_managed_persona_profile_applies_unless_overridden() {let (service, repo, containers, _, _) = harness();let open = service.open_managed_session(OpenManagedSession {+ origin: trigger_context::TriggerOrigin::Unknown,id: None,repo_url: None,repo_branch: None,@@ -4764,6 +4777,7 @@ async fn a_managed_persona_profile_applies_unless_overridden() {async fn a_managed_persona_profile_is_used_when_nothing_overrides_it() {let (service, repo, containers, _, _) = harness();let open = service.open_managed_session(OpenManagedSession {+ origin: trigger_context::TriggerOrigin::Unknown,id: None,repo_url: None,repo_branch: None,@@ -4810,6 +4824,7 @@ async fn a_repository_without_a_persona_opens_as_cursor() {"https://github.com/macro-inc/macro",])));let open = service.open_managed_session(OpenManagedSession {+ origin: trigger_context::TriggerOrigin::Unknown,id: None,repo_url: Some("https://github.com/macro-inc/macro".into()),repo_branch: None,@@ -4845,6 +4860,7 @@ async fn a_repository_without_a_persona_opens_as_cursor() {async fn a_cursor_managed_session_is_always_stamped_cursor() {let (service, repo, containers, _, _) = harness();let open = service.open_managed_session(OpenManagedSession {+ origin: trigger_context::TriggerOrigin::Unknown,id: None,repo_url: None,repo_branch: None,@@ -4897,6 +4913,7 @@ async fn a_repository_for_a_persona_that_cannot_take_one_is_refused_by_name() {fn explicit_cursor_request() -> OpenManagedSession {OpenManagedSession {+ origin: trigger_context::TriggerOrigin::Unknown,id: None,owner: model_owner::Owner::User(sender()),instructions: None,diff --git a/crates/agent_harness/src/domain/service/test/chat_reply.rs b/crates/agent_harness/src/domain/service/test/chat_reply.rsindex 7656017dcd..8de3f22661 100644--- a/crates/agent_harness/src/domain/service/test/chat_reply.rs+++ b/crates/agent_harness/src/domain/service/test/chat_reply.rs@@ -21,6 +21,7 @@ fn chat_open_command() -> OpenSession {fn assignment_open_command() -> OpenSession {let mut command = chat_open_command();command.origin = SessionOrigin::TaskAssignment(TaskAssignmentOrigin {+ trigger_origin: trigger_context::TriggerOrigin::Unknown,parent: messages::domain::models::MessageParent::parse("document", "task-1").unwrap(),discussion_id: macro_uuid::generate_uuid_v7(),actor: sender(),diff --git a/crates/agent_harness/src/domain/service/test/coding_preferences.rs b/crates/agent_harness/src/domain/service/test/coding_preferences.rsindex f4ff4f0a28..54170a886c 100644--- a/crates/agent_harness/src/domain/service/test/coding_preferences.rs+++ b/crates/agent_harness/src/domain/service/test/coding_preferences.rs@@ -34,6 +34,7 @@ fn assignment_command(kind: AgentKind, harness: &str) -> OpenSession {command.runtime.harness = harness.to_owned();command.runtime.instructions = "Persona.".to_owned();command.origin = SessionOrigin::TaskAssignment(TaskAssignmentOrigin {+ trigger_origin: trigger_context::TriggerOrigin::Unknown,parent: MessageParent::parse("document", "task-1").unwrap(),discussion_id: macro_uuid::generate_uuid_v7(),actor: sender(),@@ -185,6 +186,7 @@ async fn a_managed_open_ends_with_both_workflows() {service.open_managed_session(OpenManagedSession {+ origin: trigger_context::TriggerOrigin::Unknown,id: Some(id),repo_url: None,repo_branch: None,@@ -214,6 +216,7 @@ async fn an_external_open_ends_with_the_tasks_workflow() {let session = service.open_external_session(OpenExternalAgentSession {+ origin: trigger_context::TriggerOrigin::Unknown,instructions: Some("Ad hoc.".to_owned()),..open_external_request("/srv/agent")})diff --git a/crates/agent_harness/src/domain/service/test/quota.rs b/crates/agent_harness/src/domain/service/test/quota.rsindex 228c85eb1c..c26716fadb 100644--- a/crates/agent_harness/src/domain/service/test/quota.rs+++ b/crates/agent_harness/src/domain/service/test/quota.rs@@ -53,6 +53,7 @@ async fn session(agent_session::domain::ports::AgentSessionRepo::create(repo,CreateAgentSessionParams {+ origin: trigger_context::TriggerOrigin::Unknown,purpose: agent_session::domain::model::SessionPurpose::Standalone,id,owner_id: owner,@@ -120,6 +121,7 @@ async fn denied_or_unavailable_trigger_open_has_no_side_effects() {for origin in [open.origin.clone(),SessionOrigin::TaskAssignment(crate::domain::model::TaskAssignmentOrigin {+ trigger_origin: trigger_context::TriggerOrigin::Unknown,parent: MessageParent::parse("document", "assigned-task").unwrap(),discussion_id: macro_uuid::generate_uuid_v7(),actor: staff_sender(),@@ -176,6 +178,7 @@ async fn managed_open_checks_quota_before_provisioning_without_an_initial_promptlet id = AgentSessionId::new();let result = service.open_managed_session(OpenManagedSession {+ origin: trigger_context::TriggerOrigin::Unknown,id: Some(id),owner: Owner::User(sender()),repo_url: None,diff --git a/crates/agent_harness/src/domain/service/test/reopen.rs b/crates/agent_harness/src/domain/service/test/reopen.rsindex d5eb05ffaf..36ba652233 100644--- a/crates/agent_harness/src/domain/service/test/reopen.rs+++ b/crates/agent_harness/src/domain/service/test/reopen.rs@@ -8,6 +8,7 @@ async fn codex_session(agent_session::domain::ports::AgentSessionRepo::create(repo,CreateAgentSessionParams {+ origin: trigger_context::TriggerOrigin::Unknown,purpose: agent_session::domain::model::SessionPurpose::Standalone,repo_branch: None,id,diff --git a/crates/agent_harness/src/domain/service/test/warm.rs b/crates/agent_harness/src/domain/service/test/warm.rsindex 0d256815de..a08a72cf81 100644--- a/crates/agent_harness/src/domain/service/test/warm.rs+++ b/crates/agent_harness/src/domain/service/test/warm.rs@@ -13,6 +13,7 @@ impl agent_session::domain::warm::WarmSessionLifecycle for WarmLifecycleStub {_bot: BotId,_model: &'a str,_instructions: Option<&'a str>,+ _origin: &'a trigger_context::TriggerOrigin,) -> std::pin::Pin<Box<dyn std::future::Future<Output = agent_session::domain::error::Result<WarmClaim>>@@ -133,6 +134,7 @@ async fn warming_initializes_without_a_prompt_or_visible_created_event() {assert!(signals.lifecycle.published().is_empty());let claimed = service.open_managed_session(OpenManagedSession {+ origin: trigger_context::TriggerOrigin::Unknown,id: Some(id),owner: model_owner::Owner::User(sender()),prompt: None,@@ -188,6 +190,7 @@ async fn a_warm_claim_delivers_its_first_prompt_under_the_callers_id() {let action_id = AgentActionId::mint();service.open_managed_session(OpenManagedSession {+ origin: trigger_context::TriggerOrigin::Unknown,id: Some(id),owner: model_owner::Owner::User(sender()),prompt: Some(FirstPrompt {@@ -280,6 +283,7 @@ async fn a_missed_warm_claim_records_why_on_the_open_span() {);let session = service.open_managed_session(OpenManagedSession {+ origin: trigger_context::TriggerOrigin::Unknown,id: Some(AgentSessionId::new()),owner: model_owner::Owner::User(sender()),prompt: None,@@ -333,6 +337,7 @@ async fn an_open_without_a_client_id_records_that_no_warm_id_was_sent() {);let session = service.open_managed_session(OpenManagedSession {+ origin: trigger_context::TriggerOrigin::Unknown,id: None,owner: model_owner::Owner::User(sender()),prompt: None,@@ -415,6 +420,7 @@ async fn a_routine_run_opens_its_own_session_instead_of_claiming_a_warm_one() {);let session = service.open_managed_session(OpenManagedSession {+ origin: trigger_context::TriggerOrigin::Unknown,id: Some(AgentSessionId::new()),owner: model_owner::Owner::User(sender()),prompt: None,diff --git a/crates/agent_harness/src/domain/service/warm.rs b/crates/agent_harness/src/domain/service/warm.rsindex 58787e5473..aafccc73b7 100644--- a/crates/agent_harness/src/domain/service/warm.rs+++ b/crates/agent_harness/src/domain/service/warm.rs@@ -192,6 +192,7 @@ wherebot_id,&model,instructions.as_deref(),+ &request.origin,).await?,),@@ -290,6 +291,7 @@ whereinstructions,mcp_servers,egress_token_hash: Some(egress.session_token_hash),+ origin: request.origin,}).instrument(tracing::info_span!("agent.init.persist", agent.session.id = %session_id)).await?;@@ -448,6 +450,7 @@ wherereservations.insert(id, (owner.clone(), Instant::now()));}let request = OpenManagedSession {+ origin: trigger_context::TriggerOrigin::Unknown,id: Some(id),owner,prompt: None,diff --git a/crates/agent_harness/src/domain/trigger_router.rs b/crates/agent_harness/src/domain/trigger_router.rsindex 5a8166322e..fecc9ca4bc 100644--- a/crates/agent_harness/src/domain/trigger_router.rs+++ b/crates/agent_harness/src/domain/trigger_router.rs@@ -61,6 +61,10 @@ pub fn route_agent_trigger(runtime: Option<AgentRuntimeConfig>,links: &StaticFileLinks,) -> Result<RoutedTrigger, Skipped> {+ let trigger_origin = match &event {+ AgentTriggerTopicEvent::New(new) => new.origin(),+ AgentTriggerTopicEvent::Existing(_) => trigger_context::TriggerOrigin::Unknown,+ };match event {AgentTriggerTopicEvent::New(NewAgentSessionEvent::ConversationMessage(event)) => {let Some(runtime) = runtime else {@@ -82,6 +86,7 @@ pub fn route_agent_trigger(bot_id: event.bot_id,runtime,origin: SessionOrigin::Mention(MentionOrigin {+ trigger_origin,reply_placement: super::model::ReplyPlacement::Timeline,parent: event.message.parent,thread_id: event.message.thread_id.unwrap_or(event.message.message_id),@@ -104,6 +109,7 @@ pub fn route_agent_trigger(bot_id: assigned.bot_id,runtime,origin: SessionOrigin::TaskAssignment(TaskAssignmentOrigin {+ trigger_origin,// The task travels in the context; the prompt is only// what to do with it. Events from producers that// predate the context carry the whole brief instead.@@ -142,6 +148,7 @@ pub fn route_agent_trigger(bot_id,runtime,origin: SessionOrigin::Mention(MentionOrigin {+ trigger_origin,reply_placement: Default::default(),parent: message.parent,// A top-level mention roots its own thread; a mentiondiff --git a/crates/agent_harness/src/inbound/kafka/test.rs b/crates/agent_harness/src/inbound/kafka/test.rsindex 87a03c7b28..82486476c1 100644--- a/crates/agent_harness/src/inbound/kafka/test.rs+++ b/crates/agent_harness/src/inbound/kafka/test.rs@@ -330,6 +330,7 @@ fn a_document_mention_opens_and_follows_up_on_its_document() {fn assigned_to_task() -> AgentTriggerTopicEvent {AgentTriggerTopicEvent::New(NewAgentSessionEvent::AssignedToTask(AgentAssignedToTaskEvent {+ origin: trigger_context::TriggerOrigin::Unknown,bot_id: BotId::TEST_A,parent: document(),discussion_id: Uuid::from_u128(2),diff --git a/crates/agent_harness/src/outbound/conversation_turns/test.rs b/crates/agent_harness/src/outbound/conversation_turns/test.rsindex 2fd4e4747e..76c8da6e81 100644--- a/crates/agent_harness/src/outbound/conversation_turns/test.rs+++ b/crates/agent_harness/src/outbound/conversation_turns/test.rs@@ -72,6 +72,7 @@ async fn setup(pool: PgPool) -> (PgConversationTurnStore, AgentSessionId, Uuid,mcp_servers: agent_session::domain::model::AgentMcpServers::OwnerConnections,},origin: crate::domain::model::SessionOrigin::Mention(MentionOrigin {+ trigger_origin: trigger_context::TriggerOrigin::Unknown,reply_placement: ReplyPlacement::Timeline,parent: messages::domain::models::MessageParent::Channel(channel),thread_id: source,diff --git a/crates/agent_harness/src/outbound/cursor/manager/test.rs b/crates/agent_harness/src/outbound/cursor/manager/test.rsindex e6b6c04dae..386e2c3d54 100644--- a/crates/agent_harness/src/outbound/cursor/manager/test.rs+++ b/crates/agent_harness/src/outbound/cursor/manager/test.rs@@ -83,6 +83,7 @@ impl AgentSessionRepo for StubSessions {async fn get(&self, id: AgentSessionId) -> SessionResult<AgentSession> {Ok(AgentSession {+ origin: Default::default(),repo_branch: self.repo_branch.clone(),id,owner_id: model_owner::Owner::User(diff --git a/crates/agent_harness/src/outbound/routing/test.rs b/crates/agent_harness/src/outbound/routing/test.rsindex c0ab0ff253..9b5f96f593 100644--- a/crates/agent_harness/src/outbound/routing/test.rs+++ b/crates/agent_harness/src/outbound/routing/test.rs@@ -135,6 +135,7 @@ impl AgentSessionRepo for FixedBotSessions {async fn get(&self, id: AgentSessionId) -> SessionResult<AgentSession> {Ok(AgentSession {+ origin: Default::default(),repo_branch: None,pull_request_url: None,task_id: None,diff --git a/crates/agent_inmem/Cargo.toml b/crates/agent_inmem/Cargo.tomlindex a5f4cacca8..bf5f7b0f7b 100644--- a/crates/agent_inmem/Cargo.toml+++ b/crates/agent_inmem/Cargo.toml@@ -71,3 +71,4 @@ opentelemetry_sdk = { workspace = true, features = ["testing", "trace"] }tracing-opentelemetry = { workspace = true }tracing-subscriber = { workspace = true }tokio = { workspace = true, features = ["macros", "rt-multi-thread", "time", "test-util"] }+trigger_context = { path = "../trigger_context" }diff --git a/crates/agent_inmem/src/outbound/manager/test.rs b/crates/agent_inmem/src/outbound/manager/test.rsindex ff1ae287e1..df6df52dc3 100644--- a/crates/agent_inmem/src/outbound/manager/test.rs+++ b/crates/agent_inmem/src/outbound/manager/test.rs@@ -254,6 +254,7 @@ async fn a_prompt_runs_end_to_end_through_the_real_session_machine() {let id = AgentSessionId::new();sessions.create_session(CreateAgentSessionParams {+ origin: trigger_context::TriggerOrigin::Unknown,purpose: agent_session::domain::model::SessionPurpose::Standalone,repo_branch: None,id,@@ -400,6 +401,7 @@ async fn manager_admission_rejects_turns_without_wedging_the_session() {let id = AgentSessionId::new();sessions.create_session(CreateAgentSessionParams {+ origin: trigger_context::TriggerOrigin::Unknown,purpose: agent_session::domain::model::SessionPurpose::Standalone,repo_branch: None,id,@@ -500,6 +502,7 @@ async fn a_restarted_manager_rebuilds_the_conversation_from_the_log() {let id = AgentSessionId::new();sessions.create_session(CreateAgentSessionParams {+ origin: trigger_context::TriggerOrigin::Unknown,purpose: agent_session::domain::model::SessionPurpose::Standalone,repo_branch: None,id,@@ -657,6 +660,7 @@ async fn instructions_reach_every_turn_including_after_a_reattach() {let id = AgentSessionId::new();sessions.create_session(CreateAgentSessionParams {+ origin: trigger_context::TriggerOrigin::Unknown,purpose: agent_session::domain::model::SessionPurpose::Standalone,repo_branch: None,id,@@ -733,6 +737,7 @@ async fn a_session_without_instructions_hands_the_engine_none() {let id = AgentSessionId::new();sessions.create_session(CreateAgentSessionParams {+ origin: trigger_context::TriggerOrigin::Unknown,purpose: agent_session::domain::model::SessionPurpose::Standalone,repo_branch: None,id,@@ -797,6 +802,7 @@ async fn identity_reaches_every_turn_including_after_a_reattach() {let id = AgentSessionId::new();sessions.create_session(CreateAgentSessionParams {+ origin: trigger_context::TriggerOrigin::Unknown,purpose: agent_session::domain::model::SessionPurpose::Standalone,repo_branch: None,id,diff --git a/crates/agent_inmem/src/outbound/manager/test/summary.rs b/crates/agent_inmem/src/outbound/manager/test/summary.rsindex c27b820106..da38dd0558 100644--- a/crates/agent_inmem/src/outbound/manager/test/summary.rs+++ b/crates/agent_inmem/src/outbound/manager/test/summary.rs@@ -111,6 +111,7 @@ async fn a_restarted_manager_reads_a_summary_in_place_of_the_turns_it_covered()let id = AgentSessionId::new();sessions.create_session(CreateAgentSessionParams {+ origin: trigger_context::TriggerOrigin::Unknown,purpose: agent_session::domain::model::SessionPurpose::Standalone,repo_branch: None,id,diff --git a/crates/agent_session/AGENTS.md b/crates/agent_session/AGENTS.mdindex 5e1f1c4f84..abae4921a0 100644--- a/crates/agent_session/AGENTS.md+++ b/crates/agent_session/AGENTS.md@@ -130,6 +130,14 @@ through `set_name` clears it, so a name a person chose is never replaced.## Gotchas+- What opened a session is an `agent_session_source` row, referenced by+ `agent_session.source_id` and written in the transaction that writes the session+ (`outbound/postgres/source.rs`). It holds references only, as+ `trigger_context::TriggerOrigin`. Null means unknown: a session older than this,+ an unclaimed warm session, or an older runtime. It describes a session; `source`+ and `visibility` decide what happens to it, and a runtime's claim never sets them.+ Whoever can view a session reads its origin: `AgentSessionResponse`, the SDK's+ `AgentSession.origin()`, and `ReadAgentSession`.- Where a session is shown is `agent_session.visibility` (`listed`,`unlisted`, `hidden`), set at creation and changed later only by warmclaims and the DM-context backfill (`list_visibility.rs`).diff --git a/crates/agent_session/Cargo.toml b/crates/agent_session/Cargo.tomlindex 4e501d3c48..4633189d02 100644--- a/crates/agent_session/Cargo.toml+++ b/crates/agent_session/Cargo.toml@@ -43,7 +43,7 @@ outbound = []# OpenAPI schemas for the vocabulary that reaches an HTTP boundary: the# router's DTOs, and the lifecycle events the webhook union carries.-schema = ["activity/schema", "dep:utoipa", "agent_runtime_protocol/utoipa", "macro_user_id/schema"]+schema = ["activity/schema", "dep:utoipa", "agent_runtime_protocol/utoipa", "macro_user_id/schema", "trigger_context/schema"]# Mock and in-memory port implementations, for crates that test against this one.test-utils = ["dep:mockall", "agent_fold/test-utils"]diff --git a/crates/agent_session/src/bin/seed_jsonl.rs b/crates/agent_session/src/bin/seed_jsonl.rsindex 0374ed203b..4ad821bfaa 100644--- a/crates/agent_session/src/bin/seed_jsonl.rs+++ b/crates/agent_session/src/bin/seed_jsonl.rs@@ -250,6 +250,7 @@ async fn seed(args: &Args) -> Result<(), SeedError> {let session = AgentSessionRepo::create(&repo,CreateAgentSessionParams {+ origin: trigger_context::TriggerOrigin::Unknown,purpose: agent_session::domain::model::SessionPurpose::Standalone,repo_branch: None,id: session_id,diff --git a/crates/agent_session/src/domain/coding_agents.rs b/crates/agent_session/src/domain/coding_agents.rsindex c35323ef7c..36bb37f9e3 100644--- a/crates/agent_session/src/domain/coding_agents.rs+++ b/crates/agent_session/src/domain/coding_agents.rs@@ -246,6 +246,9 @@ impl<Directory: CodingAgentDirectory, Sessions: RoutineSessions, Updates: Codingsession_id,source: SessionSource::Agent,visibility: SessionVisibility::Listed,+ origin: trigger_context::TriggerOrigin::Dispatched {+ on_behalf_of: command.user_id.clone(),+ },}).await.map_err(failed)?;diff --git a/crates/agent_session/src/domain/model.rs b/crates/agent_session/src/domain/model.rsindex afbc8cb081..f3cb229c1f 100644--- a/crates/agent_session/src/domain/model.rs+++ b/crates/agent_session/src/domain/model.rs@@ -357,6 +357,9 @@ pub struct CreateAgentSessionParams {/// replayed from a recording, or created without a sandbox, has nothing to/// store here.pub egress_token_hash: Option<String>,+ /// What opened the session, written with the session's row. `Unknown`+ /// writes nothing: an unclaimed warm session has no cause yet.+ pub origin: trigger_context::TriggerOrigin,}/// Who or what archived a session.@@ -428,6 +431,8 @@ pub struct AgentSession {pub task_id: Option<String>,/// Who started the session.pub source: SessionSource,+ /// What opened the session. `Unknown` when nothing recorded it.+ pub origin: trigger_context::TriggerOrigin,/// Where the session is shown.pub visibility: SessionVisibility,/// Directory the harness runs in, snapshotted at creation. The sessiondiff --git a/crates/agent_session/src/domain/ports.rs b/crates/agent_session/src/domain/ports.rsindex 2139737504..55510588dc 100644--- a/crates/agent_session/src/domain/ports.rs+++ b/crates/agent_session/src/domain/ports.rs@@ -133,6 +133,8 @@ pub struct RequestedExternalSession {pub source: SessionSource,/// Whether a routine run is listed; a person's session always is.pub visibility: SessionVisibility,+ /// What opened the session, told to the runtime on the event.+ pub origin: trigger_context::TriggerOrigin,}/// Validate the base branch supported by external repository provisioning.@@ -297,6 +299,9 @@ pub struct OpenExternalAgentSession {pub thread: Option<SessionThread>,/// Instructions the session's runtime works under, when any were stated.pub instructions: Option<String>,+ /// What opened the session, as the runtime was told on the trigger event.+ /// A description only: it never decides visibility or notifications.+ pub origin: trigger_context::TriggerOrigin,}/// Everything needed to open a session the server hosts itself.@@ -333,6 +338,8 @@ pub struct OpenManagedSession {pub source: SessionSource,/// Whether a routine run is listed; a person's session always is.pub visibility: SessionVisibility,+ /// What opened the session.+ pub origin: trigger_context::TriggerOrigin,}/// The prompt a managed session opens with, delivered as soon as it can run.diff --git a/crates/agent_session/src/domain/read.rs b/crates/agent_session/src/domain/read.rsindex c6b2a13386..24742a5180 100644--- a/crates/agent_session/src/domain/read.rs+++ b/crates/agent_session/src/domain/read.rs@@ -37,6 +37,9 @@ pub struct SessionConversation {pub model: String,/// Last runtime status.pub status: String,+ /// What opened the session: who or what started it, and what it is about.+ #[cfg_attr(feature = "ai_tools", schemars(with = "serde_json::Value"))]+ pub origin: trigger_context::TriggerOrigin,/// Messages in the requested turn, or the latest messages, oldest first.pub messages: Vec<SessionConversationMessage>,/// Number of messages matching the requested turn before bounding.@@ -152,6 +155,7 @@ fn conversation(archived_at: session.archived.map(|archive| archive.at),harness: session.harness.clone(),model: session.model.clone(),+ origin: session.origin.clone(),status: match &session.status {super::model::SessionStatus::Event(event) => event.as_str().to_string(),status => status.as_ref().to_string(),diff --git a/crates/agent_session/src/domain/routines/models.rs b/crates/agent_session/src/domain/routines/models.rsindex 8cd225c2ee..ab3697e4e6 100644--- a/crates/agent_session/src/domain/routines/models.rs+++ b/crates/agent_session/src/domain/routines/models.rs@@ -44,6 +44,12 @@ pub struct PrepareRoutineSession {/// schedulers omit it along with `source`.#[serde(default)]pub visibility: SessionVisibility,+ /// What opened the session. Older schedulers omit it.+ #[serde(+ default,+ skip_serializing_if = "trigger_context::TriggerOrigin::is_unknown"+ )]+ pub origin: trigger_context::TriggerOrigin,}/// A verified, persisted session ready for its first prompt.diff --git a/crates/agent_session/src/domain/routines/service.rs b/crates/agent_session/src/domain/routines/service.rsindex 5fa0b74c6f..82cee642ae 100644--- a/crates/agent_session/src/domain/routines/service.rs+++ b/crates/agent_session/src/domain/routines/service.rs@@ -185,6 +185,7 @@ wheremodel: selection.model.clone(),source: command.source,visibility: command.visibility,+ origin: command.origin,}).await}@@ -198,6 +199,7 @@ wheremodel: selection.model.clone(),source: command.source,visibility: command.visibility,+ origin: command.origin,}).await}diff --git a/crates/agent_session/src/domain/routines/service/test.rs b/crates/agent_session/src/domain/routines/service/test.rsindex 537ba0cbf8..d9e33247b2 100644--- a/crates/agent_session/src/domain/routines/service/test.rs+++ b/crates/agent_session/src/domain/routines/service/test.rs@@ -273,6 +273,7 @@ impl Fixture {fn prepare(&self) -> PrepareRoutineSession {PrepareRoutineSession {+ origin: trigger_context::TriggerOrigin::Unknown,selection: self.selection(),session_id: self.session.id,source: SessionSource::Routine,@@ -331,6 +332,7 @@ async fn external_preparation_uses_requested_identity_and_model() {assert_eq!(requests.as_slice(),&[RequestedExternalSession {+ origin: trigger_context::TriggerOrigin::Unknown,repo_url: None,session_id: fx.session.id,bot_id: fx.session.bot_id,@@ -626,6 +628,7 @@ async fn a_routine_app_must_be_connected_to_save_and_to_run() {assert_eq!(fx.service.prepare(PrepareRoutineSession {+ origin: trigger_context::TriggerOrigin::Unknown,selection,..fx.prepare()})diff --git a/crates/agent_session/src/domain/warm.rs b/crates/agent_session/src/domain/warm.rsindex 5bbc00af62..a2d311b890 100644--- a/crates/agent_session/src/domain/warm.rs+++ b/crates/agent_session/src/domain/warm.rs@@ -51,6 +51,7 @@ pub trait WarmSessionLifecycle: Send + Sync {bot: BotId,model: &'a str,instructions: Option<&'a str>,+ origin: &'a trigger_context::TriggerOrigin,) -> Pin<Box<dyn Future<Output = Result<WarmClaim>> + Send + 'a>>;/// Mark expired hidden sessions disconnected, returning ids for routed deletion./// Claimed sessions are never selected. Work is bounded per sweep.diff --git a/crates/agent_session/src/inbound/axum_router.rs b/crates/agent_session/src/inbound/axum_router.rsindex 7a8d8949bb..071825b1ef 100644--- a/crates/agent_session/src/inbound/axum_router.rs+++ b/crates/agent_session/src/inbound/axum_router.rs@@ -654,6 +654,10 @@ pub struct AgentSessionResponse {pub acp_session_id: Option<String>,/// The session's status.pub status: SessionStatusDto,+ /// What opened the session: who or what started it, and what it is about.+ /// `unknown` when nothing recorded it.+ #[serde(default)]+ pub origin: trigger_context::TriggerOrigin,/// The external provider serving this session, when one does. Absent for/// sandboxed sessions, so existing payloads are byte-identical.#[serde(default, skip_serializing_if = "Option::is_none")]@@ -725,6 +729,7 @@ impl AgentSessionResponse {acp_session_id: session.acp_session_id.map(|id| id.to_string()),external: session.external.map(Into::into),status: session.status.into(),+ origin: session.origin,created_at: session.created_at,modified_at: session.modified_at,}@@ -1917,6 +1922,15 @@ pub struct CreateAgentSessionRequest {/// a session is a control action instead, and reads as one in its/// transcript.pub model: Option<String>,+ /// What opened the session, copied from the trigger event by the runtime+ /// answering it. Honored only from a harness, and only as a description.+ /// Internal to runtimes, so not part of the public API.+ #[serde(+ default,+ skip_serializing_if = "trigger_context::TriggerOrigin::is_unknown"+ )]+ #[schema(ignore)]+ pub origin: trigger_context::TriggerOrigin,}/// The triggering mention on a create request.@@ -2278,6 +2292,14 @@ pub async fn create_agent_session_handler<return Err(CreateSessionApiError::MixedSessionShape);}let owner = resolve_owner(&caller.authorization, None, state.non_user_owners)?;+ // Only a person's own request is the composer; a bot's is an API call+ // nothing yet says the reason for.+ let origin = match (&caller.authorization, owner.as_user()) {+ (UserBotOrHarnessAuthorization::User(_), Some(by)) => {+ trigger_context::TriggerOrigin::Requested { by: by.clone() }+ }+ _ => trigger_context::TriggerOrigin::Unknown,+ };let profile = if let Some(bot_id) = request.bot_id {let selected =persona_for_owner(state.bots.as_ref(), BotId::new_from_uuid(bot_id), &owner)@@ -2337,6 +2359,7 @@ pub async fn create_agent_session_handler<model: request.model.filter(|model| !model.trim().is_empty()),source: SessionSource::User,visibility: SessionVisibility::Listed,+ origin,}).await?;return Ok((@@ -2371,6 +2394,7 @@ pub async fn create_agent_session_handler<model: request.model.filter(|model| !model.trim().is_empty()),source: SessionSource::User,visibility: SessionVisibility::Listed,+ origin,}).await?;return Ok((@@ -2454,6 +2478,12 @@ pub async fn create_agent_session_handler<owner,thread: thread.clone(),instructions,+ origin: match &caller.authorization {+ UserBotOrHarnessAuthorization::Harness(_) => request.origin,+ UserBotOrHarnessAuthorization::User(_) | UserBotOrHarnessAuthorization::Bot(_) => {+ trigger_context::TriggerOrigin::Unknown+ }+ },}).await{diff --git a/crates/agent_session/src/inbound/axum_router/test.rs b/crates/agent_session/src/inbound/axum_router/test.rsindex 6b372c867e..c4df1a9a67 100644--- a/crates/agent_session/src/inbound/axum_router/test.rs+++ b/crates/agent_session/src/inbound/axum_router/test.rs@@ -221,6 +221,7 @@ impl SessionOpener for RecordingOpener {) -> crate::domain::error::Result<AgentSession> {session_owner_user(&request.owner)?;let session = AgentSession {+ origin: Default::default(),repo_branch: None,pull_request_url: None,task_id: None,@@ -261,6 +262,7 @@ impl SessionOpener for RecordingOpener {.as_ref().map_or(BotId::TEST_B, |selected| selected.bot_id);let session = AgentSession {+ origin: Default::default(),repo_branch: None,pull_request_url: None,task_id: None,@@ -480,6 +482,7 @@ impl ExternalSessionRequester for RecordingRequester {));}let session = AgentSession {+ origin: Default::default(),repo_branch: None,pull_request_url: None,task_id: None,diff --git a/crates/agent_session/src/inbound/axum_router/test/read.rs b/crates/agent_session/src/inbound/axum_router/test/read.rsindex dc5ffdb36e..b002e8496b 100644--- a/crates/agent_session/src/inbound/axum_router/test/read.rs+++ b/crates/agent_session/src/inbound/axum_router/test/read.rs@@ -13,6 +13,7 @@ async fn view_router_with_log(log: Vec<crate::domain::model::AgentSessionLog>) -let repo = InMemoryAgentSessionRepo::new();repo.extend_log(log);repo.create(CreateAgentSessionParams {+ origin: trigger_context::TriggerOrigin::Unknown,purpose: crate::domain::model::SessionPurpose::Standalone,repo_branch: None,id: AgentSessionId::TEST_A,diff --git a/crates/agent_session/src/outbound/postgres.rs b/crates/agent_session/src/outbound/postgres.rsindex 3464e575a5..34378f2eac 100644--- a/crates/agent_session/src/outbound/postgres.rs+++ b/crates/agent_session/src/outbound/postgres.rs@@ -16,6 +16,7 @@ mod queue;mod recovery;mod session_task;mod sharing;+mod source;mod turn_state;mod work_registration;mod working_branch;@@ -310,6 +311,7 @@ struct AgentSessionRow {pull_request_url: Option<String>,task_id: Option<String>,source: String,+ source_row: Option<Json<source::SourceRow>>,visibility: String,workspace: String,sandbox_size: String,@@ -365,6 +367,10 @@ impl TryFrom<AgentSessionRow> for AgentSession {.source.parse().map_err(|_| anyhow::anyhow!("unknown agent_session source {:?}", row.source))?,+ origin: row+ .source_row+ .map(|Json(source)| source.into_origin())+ .unwrap_or_default(),visibility: row.visibility.parse().map_err(|_| {anyhow::anyhow!("unknown agent_session visibility {:?}", row.visibility)})?,@@ -412,6 +418,7 @@ impl<B: BotFacts + 'static> AgentSessionRepo for PgAgentSessionRepo<B> {instructions,mcp_servers,egress_token_hash,+ origin,} = params;let mcp_servers_json = serde_json::to_value(mcp_servers.servers()).context("serialize agent session mcp servers")?;@@ -440,6 +447,7 @@ impl<B: BotFacts + 'static> AgentSessionRepo for PgAgentSessionRepo<B> {return Err(AgentSessionError::UnknownOwner);}+ let source_id = source::insert_source(&mut transaction, &origin).await?;let (status, status_event_name) = status_columns(&SessionStatus::NoMessages);let conversation = sqlx::query_scalar!("SELECT EXISTS (SELECT 1 FROM agent_conversation_sessions WHERE session_id = $1) AS \"exists!\"",@@ -461,9 +469,9 @@ impl<B: BotFacts + 'static> AgentSessionRepo for PgAgentSessionRepo<B> {id, owner_id, thread_id, originating_message_id, bot_id, model,harness, repo_url, workspace, sandbox_size, instructions,acp_session_id, status, status_event_name, egress_token_hash,- mcp_scope, mcp_servers, repo_branch, for_warming, source, visibility+ mcp_scope, mcp_servers, repo_branch, for_warming, source, visibility, source_id)- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22)RETURNINGid, name, archived_by::TEXT AS "archived_by?", archived_at, owner_id, thread_id, originating_message_id, bot_id,model, harness, repo_url, repo_branch, pull_request_url, task_id, source, visibility, workspace, sandbox_size, instructions,@@ -472,6 +480,9 @@ impl<B: BotFacts + 'static> AgentSessionRepo for PgAgentSessionRepo<B> {(SELECT jsonb_build_object('type', parent_entity_type, 'id', parent_entity_id)FROM comms_messages WHERE id = agent_session.thread_id)AS "thread_parent?: Json<MessageParent>",+ (SELECT to_jsonb(origin_row) FROM agent_session_source origin_row+ WHERE origin_row.id = agent_session.source_id)+ AS "source_row?: Json<source::SourceRow>",-- A row being created cannot have an external identity yet.NULL::TEXT AS "external_provider?", NULL::TEXT AS "external_id?",NULL::TEXT AS "external_name?", NULL::TEXT AS "external_url?",@@ -498,6 +509,7 @@ impl<B: BotFacts + 'static> AgentSessionRepo for PgAgentSessionRepo<B> {warm,<&str>::from(purpose.source()),<&str>::from(visibility),+ source_id,).fetch_one(&mut *transaction).await@@ -604,6 +616,9 @@ impl<B: BotFacts + 'static> AgentSessionRepo for PgAgentSessionRepo<B> {(SELECT jsonb_build_object('type', parent_entity_type, 'id', parent_entity_id)FROM comms_messages WHERE id = agent_session.thread_id)AS "thread_parent?: Json<MessageParent>",+ (SELECT to_jsonb(origin_row) FROM agent_session_source origin_row+ WHERE origin_row.id = agent_session.source_id)+ AS "source_row?: Json<source::SourceRow>",ext.provider AS "external_provider?", ext.external_id AS "external_id?",ext.external_name AS "external_name?", ext.external_url AS "external_url?",ext.last_run_id AS "external_last_run_id?"@@ -711,6 +726,9 @@ impl<B: BotFacts + 'static> AgentSessionRepo for PgAgentSessionRepo<B> {(SELECT jsonb_build_object('type', parent_entity_type, 'id', parent_entity_id)FROM comms_messages WHERE id = agent_session.thread_id)AS "thread_parent?: Json<MessageParent>",+ (SELECT to_jsonb(origin_row) FROM agent_session_source origin_row+ WHERE origin_row.id = agent_session.source_id)+ AS "source_row?: Json<source::SourceRow>",ext.provider AS "external_provider?", ext.external_id AS "external_id?",ext.external_name AS "external_name?", ext.external_url AS "external_url?",ext.last_run_id AS "external_last_run_id?"@@ -752,6 +770,9 @@ impl<B: BotFacts + 'static> AgentSessionRepo for PgAgentSessionRepo<B> {(SELECT jsonb_build_object('type', parent_entity_type, 'id', parent_entity_id)FROM comms_messages WHERE id = agent_session.thread_id)AS "thread_parent?: Json<MessageParent>",+ (SELECT to_jsonb(origin_row) FROM agent_session_source origin_row+ WHERE origin_row.id = agent_session.source_id)+ AS "source_row?: Json<source::SourceRow>",ext.provider AS "external_provider?", ext.external_id AS "external_id?",ext.external_name AS "external_name?", ext.external_url AS "external_url?",ext.last_run_id AS "external_last_run_id?"@@ -786,6 +807,9 @@ impl<B: BotFacts + 'static> AgentSessionRepo for PgAgentSessionRepo<B> {(SELECT jsonb_build_object('type', parent_entity_type, 'id', parent_entity_id)FROM comms_messages WHERE id = agent_session.thread_id)AS "thread_parent?: Json<MessageParent>",+ (SELECT to_jsonb(origin_row) FROM agent_session_source origin_row+ WHERE origin_row.id = agent_session.source_id)+ AS "source_row?: Json<source::SourceRow>",ext.provider AS "external_provider?", ext.external_id AS "external_id?",ext.external_name AS "external_name?", ext.external_url AS "external_url?",ext.last_run_id AS "external_last_run_id?"@@ -822,6 +846,9 @@ impl<B: BotFacts + 'static> AgentSessionRepo for PgAgentSessionRepo<B> {(SELECT jsonb_build_object('type', parent_entity_type, 'id', parent_entity_id)FROM comms_messages WHERE id = agent_session.thread_id)AS "thread_parent?: Json<MessageParent>",+ (SELECT to_jsonb(origin_row) FROM agent_session_source origin_row+ WHERE origin_row.id = agent_session.source_id)+ AS "source_row?: Json<source::SourceRow>",ext.provider AS "external_provider?", ext.external_id AS "external_id?",ext.external_name AS "external_name?", ext.external_url AS "external_url?",ext.last_run_id AS "external_last_run_id?"@@ -1402,7 +1429,7 @@ impl<B: BotFacts + 'static> AgentSessionRepo for PgAgentSessionRepo<B> {r#"DELETE FROM agent_sessionWHERE id = $1- RETURNING share_permission_id+ RETURNING share_permission_id, source_id"#,id.as_uuid(),)@@ -1410,6 +1437,10 @@ impl<B: BotFacts + 'static> AgentSessionRepo for PgAgentSessionRepo<B> {.await.context("failed to delete agent session")?;+ if let Some(source_id) = permission.as_ref().and_then(|row| row.source_id) {+ source::delete_source(&mut transaction, source_id).await?;+ }+if let Some(permission_id) = permission.and_then(|row| row.share_permission_id) {sqlx::query!(r#"DELETE FROM "SharePermission" WHERE id = $1"#,diff --git a/crates/agent_session/src/outbound/postgres/source.rs b/crates/agent_session/src/outbound/postgres/source.rsnew file mode 100644index 0000000000..0df861577d--- /dev/null+++ b/crates/agent_session/src/outbound/postgres/source.rs@@ -0,0 +1,294 @@+//! What opened a session: one `agent_session_source` row per session, written+//! in the transaction that writes the session itself.++use super::*;+use trigger_context::TriggerOrigin;+use trigger_context::origin::{AgentActor, Caller, Lineage, Root, RoutineCause};++#[cfg(test)]+mod test;++/// A stored source, read back into the enum. The table's constraints admit+/// only rows that map, so one that does not is logged and reads as unknown+/// rather than failing every read of its session.+#[derive(Debug, serde::Deserialize)]+pub(super) struct SourceRow {+ id: Uuid,+ kind: String,+ actor_user_id: Option<MacroUserIdStr<'static>>,+ actor_bot_id: Option<Uuid>,+ on_behalf_of_user_id: Option<MacroUserIdStr<'static>>,+ acting_session_id: Option<Uuid>,+ root_user_id: Option<MacroUserIdStr<'static>>,+ root_routine_id: Option<Uuid>,+ message_id: Option<Uuid>,+ task_id: Option<String>,+ project_id: Option<Uuid>,+ routine_id: Option<Uuid>,+ routine_firing: Option<String>,+ event_id: Option<Uuid>,+}++impl SourceRow {+ pub(super) fn into_origin(self) -> TriggerOrigin {+ let id = self.id;+ self.origin().unwrap_or_else(|| {+ tracing::warn!(source_id = %id, "agent session source does not map to an origin");+ TriggerOrigin::Unknown+ })+ }++ fn caller(&self) -> Option<Caller> {+ match (&self.actor_user_id, self.actor_bot_id) {+ (Some(user), None) => Some(Caller::Person { user: user.clone() }),+ (None, Some(bot)) => Some(Caller::Agent(AgentActor {+ bot: BotId::new_from_uuid(bot),+ on_behalf_of: self.on_behalf_of_user_id.clone()?,+ lineage: self.lineage()?,+ })),+ _ => None,+ }+ }++ fn lineage(&self) -> Option<Lineage> {+ let Some(session) = self.acting_session_id else {+ return Some(Lineage::Unattributed);+ };+ let root = match (&self.root_user_id, self.root_routine_id) {+ (Some(user), None) => Root::Person { user: user.clone() },+ (None, Some(routine)) => Root::Routine { routine },+ _ => return None,+ };+ Some(Lineage::Session { session, root })+ }++ fn origin(&self) -> Option<TriggerOrigin> {+ Some(match self.kind.as_str() {+ "mentioned" => TriggerOrigin::Mentioned {+ by: self.caller()?,+ message_id: self.message_id?,+ },+ "conversation" => TriggerOrigin::Conversation {+ by: self.actor_user_id.clone()?,+ message_id: self.message_id?,+ },+ "task_assigned" => TriggerOrigin::TaskAssigned {+ by: self.caller()?,+ task: self.task_id.clone()?,+ },+ "project_inherited" => TriggerOrigin::ProjectInherited {+ by: self.caller()?,+ task: self.task_id.clone()?,+ project: self.project_id?,+ },+ "requested" => TriggerOrigin::Requested {+ by: self.actor_user_id.clone()?,+ },+ "dispatched" => TriggerOrigin::Dispatched {+ on_behalf_of: self.on_behalf_of_user_id.clone()?,+ },+ "routine" => TriggerOrigin::Routine {+ routine: self.routine_id?,+ firing: match self.routine_firing.as_deref()? {+ "scheduled" => RoutineCause::Scheduled,+ "manual" => RoutineCause::Manual,+ "event" => RoutineCause::Event {+ event_id: self.event_id?,+ },+ _ => return None,+ },+ },+ _ => return None,+ })+ }+}++/// A [`TriggerOrigin`] as the table's columns. The table's constraints repeat+/// the enum's invariants.+#[derive(Default)]+struct SourceColumns {+ actor_user_id: Option<String>,+ actor_bot_id: Option<Uuid>,+ on_behalf_of_user_id: Option<String>,+ acting_session_id: Option<Uuid>,+ root_user_id: Option<String>,+ root_routine_id: Option<Uuid>,+ message_id: Option<Uuid>,+ task_id: Option<String>,+ project_id: Option<Uuid>,+ routine_id: Option<Uuid>,+ routine_firing: Option<&'static str>,+ event_id: Option<Uuid>,+}++impl SourceColumns {+ fn with_caller(mut self, caller: &Caller) -> Self {+ match caller {+ Caller::Person { user } => {+ self.actor_user_id = Some(user.as_ref().to_owned());+ }+ Caller::Agent(AgentActor {+ bot,+ on_behalf_of,+ lineage,+ }) => {+ self.actor_bot_id = Some(bot.as_uuid());+ self.on_behalf_of_user_id = Some(on_behalf_of.as_ref().to_owned());+ if let Lineage::Session { session, root } = lineage {+ self.acting_session_id = Some(*session);+ match root {+ Root::Person { user } => {+ self.root_user_id = Some(user.as_ref().to_owned());+ }+ Root::Routine { routine } => {+ self.root_routine_id = Some(*routine);+ }+ }+ }+ }+ }+ self+ }+}++/// The row's `kind` and columns, or nothing for an origin that is not known.+fn source_columns(origin: &TriggerOrigin) -> Option<(&'static str, SourceColumns)> {+ let columns = SourceColumns::default();+ Some(match origin {+ TriggerOrigin::Mentioned { by, message_id } => (+ "mentioned",+ SourceColumns {+ message_id: Some(*message_id),+ ..columns+ }+ .with_caller(by),+ ),+ TriggerOrigin::Conversation { by, message_id } => (+ "conversation",+ SourceColumns {+ actor_user_id: Some(by.as_ref().to_owned()),+ message_id: Some(*message_id),+ ..columns+ },+ ),+ TriggerOrigin::TaskAssigned { by, task } => (+ "task_assigned",+ SourceColumns {+ task_id: Some(task.clone()),+ ..columns+ }+ .with_caller(by),+ ),+ TriggerOrigin::ProjectInherited { by, task, project } => (+ "project_inherited",+ SourceColumns {+ task_id: Some(task.clone()),+ project_id: Some(*project),+ ..columns+ }+ .with_caller(by),+ ),+ TriggerOrigin::Requested { by } => (+ "requested",+ SourceColumns {+ actor_user_id: Some(by.as_ref().to_owned()),+ ..columns+ },+ ),+ TriggerOrigin::Dispatched { on_behalf_of } => (+ "dispatched",+ SourceColumns {+ on_behalf_of_user_id: Some(on_behalf_of.as_ref().to_owned()),+ ..columns+ },+ ),+ TriggerOrigin::Routine { routine, firing } => {+ let (routine_firing, event_id) = match firing {+ RoutineCause::Scheduled => ("scheduled", None),+ RoutineCause::Manual => ("manual", None),+ RoutineCause::Event { event_id } => ("event", Some(*event_id)),+ };+ (+ "routine",+ SourceColumns {+ routine_id: Some(*routine),+ routine_firing: Some(routine_firing),+ event_id,+ ..columns+ },+ )+ }+ TriggerOrigin::Unknown => return None,+ })+}++/// Write a session's source, returning the id its row references.+pub(super) async fn insert_source(+ transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,+ origin: &TriggerOrigin,+) -> Result<Option<Uuid>> {+ let Some((kind, columns)) = source_columns(origin) else {+ return Ok(None);+ };+ let id = macro_uuid::generate_uuid_v7();+ sqlx::query!(+ r#"+ INSERT INTO agent_session_source (+ id, kind, actor_user_id, actor_bot_id, on_behalf_of_user_id, acting_session_id,+ root_user_id, root_routine_id, message_id, task_id, project_id, routine_id,+ routine_firing, event_id+ )+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)+ "#,+ id,+ kind,+ columns.actor_user_id,+ columns.actor_bot_id,+ columns.on_behalf_of_user_id,+ columns.acting_session_id,+ columns.root_user_id,+ columns.root_routine_id,+ columns.message_id,+ columns.task_id,+ columns.project_id,+ columns.routine_id,+ columns.routine_firing,+ columns.event_id,+ )+ .execute(&mut **transaction)+ .await+ .context("failed to write agent session source")?;+ Ok(Some(id))+}++/// Give a session that exists without a source its source.+pub(super) async fn link_source(+ transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,+ session: AgentSessionId,+ origin: &TriggerOrigin,+) -> Result<()> {+ let Some(source_id) = insert_source(transaction, origin).await? else {+ return Ok(());+ };+ sqlx::query!(+ "UPDATE agent_session SET source_id = $2 WHERE id = $1",+ session.as_uuid(),+ source_id,+ )+ .execute(&mut **transaction)+ .await+ .context("failed to link agent session source")?;+ Ok(())+}++/// Remove the source of a session being deleted, after the session's row.+pub(super) async fn delete_source(+ transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,+ source_id: Uuid,+) -> Result<()> {+ sqlx::query!("DELETE FROM agent_session_source WHERE id = $1", source_id)+ .execute(&mut **transaction)+ .await+ .context("failed to delete agent session source")?;+ Ok(())+}diff --git a/crates/agent_session/src/outbound/postgres/source/test.rs b/crates/agent_session/src/outbound/postgres/source/test.rsnew file mode 100644index 0000000000..46d754dc01--- /dev/null+++ b/crates/agent_session/src/outbound/postgres/source/test.rs@@ -0,0 +1,173 @@+use super::super::test::{create_test_bot, new_session, test_repo};+use super::*;+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use trigger_context::origin::Caller;++fn user() -> MacroUserIdStr<'static> {+ MacroUserIdStr::try_from_email("[email protected]").unwrap()+}++async fn stored_kind(pool: &PgPool, session: AgentSessionId) -> Option<String> {+ sqlx::query_scalar!(+ r#"+ SELECT source.kind+ FROM agent_session session+ JOIN agent_session_source source ON source.id = session.source_id+ WHERE session.id = $1+ "#,+ session.as_uuid(),+ )+ .fetch_optional(pool)+ .await+ .unwrap()+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_session_is_created_with_its_source_and_deleted_with_it(pool: PgPool) {+ let repo = test_repo(&pool);+ let bot = create_test_bot(&pool).await;+ let message_id = macro_uuid::generate_uuid_v7();+ let session = AgentSessionRepo::create(+ &repo,+ CreateAgentSessionParams {+ origin: TriggerOrigin::Mentioned {+ by: Caller::Person { user: user() },+ message_id,+ },+ ..new_session(bot, None, None)+ },+ )+ .await+ .unwrap();++ assert_eq!(+ stored_kind(&pool, session.id).await.as_deref(),+ Some("mentioned")+ );+ assert_eq!(+ AgentSessionRepo::get(&repo, session.id)+ .await+ .unwrap()+ .origin,+ TriggerOrigin::Mentioned {+ by: Caller::Person { user: user() },+ message_id,+ }+ );+ let stored_message = sqlx::query_scalar!(+ "SELECT message_id FROM agent_session_source WHERE message_id = $1",+ message_id,+ )+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(stored_message, Some(message_id));++ AgentSessionRepo::delete(&repo, session.id).await.unwrap();++ let remaining = sqlx::query_scalar!(+ r#"SELECT COUNT(*) AS "count!" FROM agent_session_source WHERE message_id = $1"#,+ message_id,+ )+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(remaining, 0);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_failed_session_create_leaves_no_source(pool: PgPool) {+ let repo = test_repo(&pool);+ let bot = create_test_bot(&pool).await;+ let existing = AgentSessionRepo::create(&repo, new_session(bot, None, None))+ .await+ .unwrap();++ let refused = AgentSessionRepo::create(+ &repo,+ CreateAgentSessionParams {+ id: existing.id,+ origin: TriggerOrigin::Requested { by: user() },+ ..new_session(bot, None, None)+ },+ )+ .await;++ assert!(refused.is_err());+ let sources = sqlx::query_scalar!(r#"SELECT COUNT(*) AS "count!" FROM agent_session_source"#)+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(sources, 0);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn an_unknown_origin_stores_nothing(pool: PgPool) {+ let repo = test_repo(&pool);+ let bot = create_test_bot(&pool).await;++ let session = AgentSessionRepo::create(&repo, new_session(bot, None, None))+ .await+ .unwrap();++ assert_eq!(stored_kind(&pool, session.id).await, None);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn the_table_refuses_an_origin_the_enum_cannot_express(pool: PgPool) {+ let routine_with_a_person = sqlx::query!(+ r#"+ INSERT INTO agent_session_source (id, kind, routine_id, routine_firing, actor_user_id)+ VALUES ($1, 'routine', $2, 'manual', 'macro|[email protected]')+ "#,+ macro_uuid::generate_uuid_v7(),+ macro_uuid::generate_uuid_v7(),+ )+ .execute(&pool)+ .await;+ assert!(routine_with_a_person.is_err());++ let scheduled_with_an_event = sqlx::query!(+ r#"+ INSERT INTO agent_session_source (id, kind, routine_id, routine_firing, event_id)+ VALUES ($1, 'routine', $2, 'scheduled', $3)+ "#,+ macro_uuid::generate_uuid_v7(),+ macro_uuid::generate_uuid_v7(),+ macro_uuid::generate_uuid_v7(),+ )+ .execute(&pool)+ .await;+ assert!(scheduled_with_an_event.is_err());+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn an_agent_and_its_lineage_read_back_as_stored(pool: PgPool) {+ let repo = test_repo(&pool);+ let bot = create_test_bot(&pool).await;+ let origin = TriggerOrigin::TaskAssigned {+ by: Caller::Agent(AgentActor {+ bot,+ on_behalf_of: user(),+ lineage: Lineage::Session {+ session: macro_uuid::generate_uuid_v7(),+ root: Root::Routine {+ routine: macro_uuid::generate_uuid_v7(),+ },+ },+ }),+ task: "task-1".to_owned(),+ };++ let session = AgentSessionRepo::create(+ &repo,+ CreateAgentSessionParams {+ origin: origin.clone(),+ ..new_session(bot, None, None)+ },+ )+ .await+ .unwrap();++ assert_eq!(session.origin, origin);+}diff --git a/crates/agent_session/src/outbound/postgres/test.rs b/crates/agent_session/src/outbound/postgres/test.rsindex 2606481744..2df054c3cd 100644--- a/crates/agent_session/src/outbound/postgres/test.rs+++ b/crates/agent_session/src/outbound/postgres/test.rs@@ -97,6 +97,7 @@ pub(super) fn new_session(originating_message_id: Option<Uuid>,) -> CreateAgentSessionParams {CreateAgentSessionParams {+ origin: trigger_context::TriggerOrigin::Unknown,purpose: crate::domain::model::SessionPurpose::Standalone,repo_branch: None,id: AgentSessionId::new(),@@ -269,6 +270,7 @@ async fn create_refuses_an_owner_that_is_not_a_user(pool: PgPool) {let repo = test_repo(&pool);let bot_id = create_test_bot(&pool).await;let params = CreateAgentSessionParams {+ origin: trigger_context::TriggerOrigin::Unknown,purpose: crate::domain::model::SessionPurpose::Standalone,owner_id: Owner::Bot(bot_id),..new_session(bot_id, None, None)@@ -327,6 +329,7 @@ async fn create_rejects_an_unknown_user_owner(pool: PgPool) {let repo = test_repo(&pool);let bot_id = create_test_bot(&pool).await;let params = CreateAgentSessionParams {+ origin: trigger_context::TriggerOrigin::Unknown,purpose: crate::domain::model::SessionPurpose::Standalone,owner_id: Owner::User(user_id("macro|[email protected]")),..new_session(bot_id, None, None)@@ -425,6 +428,7 @@ async fn instructions_round_trip_on_every_read_path(pool: PgPool) {let (_channel_id, thread_id, originating_message_id) =insert_originating_thread_fixture(&pool).await;let params = CreateAgentSessionParams {+ origin: trigger_context::TriggerOrigin::Unknown,purpose: crate::domain::model::SessionPurpose::Standalone,instructions: Some(INSTRUCTIONS.to_owned()),egress_token_hash: Some("token-hash".to_owned()),@@ -480,6 +484,7 @@ async fn mcp_server_selection_round_trips_on_every_read_path(pool: PgPool) {],};let params = CreateAgentSessionParams {+ origin: trigger_context::TriggerOrigin::Unknown,purpose: crate::domain::model::SessionPurpose::Standalone,mcp_servers: selection.clone(),egress_token_hash: Some("mcp-token-hash".to_owned()),@@ -1081,6 +1086,7 @@ async fn recent_for_owner_returns_the_owners_newest_sessions(pool: PgPool) {let someone_else = create_session(&repo,CreateAgentSessionParams {+ origin: trigger_context::TriggerOrigin::Unknown,purpose: crate::domain::model::SessionPurpose::Standalone,owner_id: Owner::User(user_id(OTHER_OWNER)),..new_session(bot_id, None, None)@@ -1397,6 +1403,7 @@ async fn sessions_record_who_started_them_and_where_they_show(pool: PgPool) {let managed = create_session(&repo,CreateAgentSessionParams {+ origin: trigger_context::TriggerOrigin::Unknown,purpose: crate::domain::model::SessionPurpose::Routine {visibility: SessionVisibility::Unlisted,},@@ -1410,6 +1417,7 @@ async fn sessions_record_who_started_them_and_where_they_show(pool: PgPool) {let shown = create_session(&repo,CreateAgentSessionParams {+ origin: trigger_context::TriggerOrigin::Unknown,purpose: crate::domain::model::SessionPurpose::Routine {visibility: SessionVisibility::Listed,},@@ -1422,6 +1430,7 @@ async fn sessions_record_who_started_them_and_where_they_show(pool: PgPool) {let dispatched = create_session(&repo,CreateAgentSessionParams {+ origin: trigger_context::TriggerOrigin::Unknown,purpose: crate::domain::model::SessionPurpose::Dispatched,..new_session(bot_id, None, None)},@@ -3224,9 +3233,17 @@ async fn warm_sessions_are_hidden_and_claimed_only_once_by_the_owner(pool: PgPoo);let other = Owner::User(user_id("macro|[email protected]"));assert_eq!(- WarmSessionLifecycle::claim(&repo, session.id, &other, bot, &session.model, None)- .await- .unwrap(),+ WarmSessionLifecycle::claim(+ &repo,+ session.id,+ &other,+ bot,+ &session.model,+ None,+ &trigger_context::TriggerOrigin::Unknown+ )+ .await+ .unwrap(),WarmClaim::Missed(WarmMissReason::OwnerMismatch));assert_eq!(@@ -3236,7 +3253,8 @@ async fn warm_sessions_are_hidden_and_claimed_only_once_by_the_owner(pool: PgPoo&session.owner_id,bot,"wrong-model",- None+ None,+ &trigger_context::TriggerOrigin::Unknown,).await.unwrap(),@@ -3249,7 +3267,8 @@ async fn warm_sessions_are_hidden_and_claimed_only_once_by_the_owner(pool: PgPoo&session.owner_id,bot,&session.model,- Some("different instructions")+ Some("different instructions"),+ &trigger_context::TriggerOrigin::Unknown,).await.unwrap(),@@ -3262,7 +3281,8 @@ async fn warm_sessions_are_hidden_and_claimed_only_once_by_the_owner(pool: PgPoo&session.owner_id,bot,&session.model,- None+ None,+ &trigger_context::TriggerOrigin::Unknown,).await.unwrap(),@@ -3275,7 +3295,8 @@ async fn warm_sessions_are_hidden_and_claimed_only_once_by_the_owner(pool: PgPoo&session.owner_id,bot,&session.model,- None+ None,+ &trigger_context::TriggerOrigin::Unknown,),WarmSessionLifecycle::claim(&repo,@@ -3283,7 +3304,8 @@ async fn warm_sessions_are_hidden_and_claimed_only_once_by_the_owner(pool: PgPoo&session.owner_id,bot,&session.model,- None+ None,+ &trigger_context::TriggerOrigin::Unknown,),);let mut outcomes = [left.unwrap(), right.unwrap()];@@ -3336,7 +3358,8 @@ async fn expired_warm_sessions_cannot_be_claimed(pool: PgPool) {&session.owner_id,bot,&session.model,- None+ None,+ &trigger_context::TriggerOrigin::Unknown,).await.unwrap(),@@ -3350,7 +3373,8 @@ async fn expired_warm_sessions_cannot_be_claimed(pool: PgPool) {&session.owner_id,bot,&session.model,- None+ None,+ &trigger_context::TriggerOrigin::Unknown,).await.unwrap(),diff --git a/crates/agent_session/src/outbound/postgres/test/user_cleanup.rs b/crates/agent_session/src/outbound/postgres/test/user_cleanup.rsindex 3cd5d5437e..8af66bb93f 100644--- a/crates/agent_session/src/outbound/postgres/test/user_cleanup.rs+++ b/crates/agent_session/src/outbound/postgres/test/user_cleanup.rs@@ -20,6 +20,7 @@ async fn cleanup_batches_remove_all_session_rows_without_a_user_cascade(pool: Pglet other = create_session(&repo,CreateAgentSessionParams {+ origin: trigger_context::TriggerOrigin::Unknown,purpose: crate::domain::model::SessionPurpose::Standalone,owner_id: Owner::User(user_id(OTHER)),..new_session(bot, None, None)diff --git a/crates/agent_session/src/outbound/postgres/warm.rs b/crates/agent_session/src/outbound/postgres/warm.rsindex 5f2bd8f5f9..6565d50ff5 100644--- a/crates/agent_session/src/outbound/postgres/warm.rs+++ b/crates/agent_session/src/outbound/postgres/warm.rs@@ -15,6 +15,7 @@ impl<B: BotFacts + 'static> WarmSessionLifecycle for PgAgentSessionRepo<B> {bot: BotId,model: &'a str,instructions: Option<&'a str>,+ origin: &'a trigger_context::TriggerOrigin,) -> Pin<Box<dyn Future<Output = Result<WarmClaim>> + Send + 'a>> {Box::pin(async move {let user = session_owner_user(owner)?;@@ -93,6 +94,8 @@ impl<B: BotFacts + 'static> WarmSessionLifecycle for PgAgentSessionRepo<B> {upsert_user_history(&mut transaction, user.as_ref(), &id.as_uuid()).await.context("record claimed warm session history")?;+ // A warm row has no cause until someone claims it.+ source::link_source(&mut transaction, id, origin).await?;}transaction.commit().await.context("commit warm claim")?;Ok(claim)diff --git a/crates/agent_session/src/outbound/postgres/warm/test.rs b/crates/agent_session/src/outbound/postgres/warm/test.rsindex 992e4f670d..e6b52adda1 100644--- a/crates/agent_session/src/outbound/postgres/warm/test.rs+++ b/crates/agent_session/src/outbound/postgres/warm/test.rs@@ -53,9 +53,16 @@ async fn dm_contexts_stay_hidden_and_cannot_be_claimed_or_expired(pool: PgPool));assert_eq!(repo.get(id).await.unwrap().id, id);assert_eq!(- repo.claim(id, &dm.owner_id, bot, &dm.model, None)- .await- .unwrap(),+ repo.claim(+ id,+ &dm.owner_id,+ bot,+ &dm.model,+ None,+ &trigger_context::TriggerOrigin::Unknown+ )+ .await+ .unwrap(),WarmClaim::Missed(WarmMissReason::NotWarm));}@@ -78,9 +85,16 @@ async fn dm_contexts_stay_hidden_and_cannot_be_claimed_or_expired(pool: PgPool)let dm = repo.get(id).await.unwrap();assert_eq!(dm.status, SessionStatus::NoMessages);assert_eq!(- repo.claim(id, &dm.owner_id, bot, &dm.model, None)- .await- .unwrap(),+ repo.claim(+ id,+ &dm.owner_id,+ bot,+ &dm.model,+ None,+ &trigger_context::TriggerOrigin::Unknown+ )+ .await+ .unwrap(),WarmClaim::Missed(WarmMissReason::NotWarm));}@@ -262,9 +276,16 @@ async fn an_old_claimant_cannot_leave_a_visible_session_eligible_for_cleanup(poo.await.unwrap();assert_eq!(- repo.claim(session.id, &session.owner_id, bot, &session.model, None)- .await- .unwrap(),+ repo.claim(+ session.id,+ &session.owner_id,+ bot,+ &session.model,+ None,+ &trigger_context::TriggerOrigin::Unknown+ )+ .await+ .unwrap(),WarmClaim::Missed(WarmMissReason::NotWarm));sqlx::query!(diff --git a/crates/agent_session/src/testing.rs b/crates/agent_session/src/testing.rsindex c6dc44a7df..52ee900cd6 100644--- a/crates/agent_session/src/testing.rs+++ b/crates/agent_session/src/testing.rs@@ -204,6 +204,7 @@ impl AgentSessionRepo for InMemoryAgentSessionRepo {async fn create(&self, params: CreateAgentSessionParams) -> Result<AgentSession> {let now = chrono::Utc::now();let session = AgentSession {+ origin: Default::default(),repo_branch: params.repo_branch,pull_request_url: None,task_id: None,@@ -1106,6 +1107,7 @@ impl agent_fold::domain::ports::LogRepo for InMemoryAgentSessionRepo {pub fn test_agent_session(id: AgentSessionId) -> AgentSession {let now = chrono::Utc::now();AgentSession {+ origin: Default::default(),repo_branch: None,pull_request_url: None,task_id: None,diff --git a/crates/agent_trigger/AGENTS.md b/crates/agent_trigger/AGENTS.mdindex 6016a75e1f..0cf88cdbdb 100644--- a/crates/agent_trigger/AGENTS.md+++ b/crates/agent_trigger/AGENTS.md@@ -13,6 +13,9 @@ session that results.— mention detection, admission, and dispatch.- `src/domain/sources.rs`: the trigger sources (explicit mention, implicitreply, task/project assignment).+- `src/domain/broker_events.rs`: the events, and `NewAgentSessionEvent::origin`,+ which says what opened the session (`trigger_context::TriggerOrigin`). Only `New`+ events tell it: a runtime already has the sessions it is following up in.- `src/domain/context.rs`: structured context assembled for the agentprompt (thread history, people, discussion). Message attachments travel oneach `ContextMessage` so the prompt XML and ACP file links can see filesdiff --git a/crates/agent_trigger/src/domain/broker_events.rs b/crates/agent_trigger/src/domain/broker_events.rsindex aaa0295546..aeef524244 100644--- a/crates/agent_trigger/src/domain/broker_events.rs+++ b/crates/agent_trigger/src/domain/broker_events.rs@@ -20,6 +20,8 @@ use messages::domain::models::MessageParent;use serde::{Deserialize, Serialize};use trigger_context::TriggerContext;+use trigger_context::TriggerOrigin;+use trigger_context::origin::{AgentActor, Caller, Lineage};#[cfg(test)]mod test;@@ -81,6 +83,10 @@ pub struct AgentAssignedToTaskEvent {pub actor: macro_user_id::user_id::MacroUserIdStr<'static>,/// Private startup prompt, never posted as a discussion message.pub prompt: String,+ /// Who assigned it, and whether a project's agents were inherited.+ /// `Unknown` on events from producers that predate it.+ #[serde(default, skip_serializing_if = "TriggerOrigin::is_unknown")]+ pub origin: TriggerOrigin,/// Why the agent was called, for whoever composes its prompt. Absent on/// events from producers that predate it.#[serde(default, skip_serializing_if = "Option::is_none")]@@ -94,7 +100,8 @@ pub struct AgentAssignedToTaskEvent {/// Served by the bot's own runtime, which creates the session under the id/// named here so the requester can find it. No prompt: whoever asked/// delivers theirs through the session's control endpoint once it exists,-/// so nothing a user typed travels on this topic.+/// so nothing a user typed travels on this topic. Routines and dispatching+/// tools ask the same way, and `origin` says which it was.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct AgentSessionRequestedEvent {/// The bot the session runs for.@@ -106,6 +113,10 @@ pub struct AgentSessionRequestedEvent {/// Repository selected by the requester, absent on older producers.#[serde(default, skip_serializing_if = "Option::is_none")]pub repo_url: Option<String>,+ /// What asked for the session. `Unknown` on events from producers that+ /// predate it.+ #[serde(default, skip_serializing_if = "TriggerOrigin::is_unknown")]+ pub origin: TriggerOrigin,/// Why the agent was called, for whoever composes its prompt. Absent on/// events from producers that predate it.#[serde(default, skip_serializing_if = "Option::is_none")]@@ -178,6 +189,29 @@ impl NewAgentSessionEvent {}}+ /// What opened this session, for whoever creates it. Mentions and+ /// conversations derive it from the message they carry.+ #[must_use]+ pub fn origin(&self) -> TriggerOrigin {+ match self {+ Self::ConversationMessage(conversation) => {+ match conversation.message.sender.as_user() {+ Some(by) => TriggerOrigin::Conversation {+ by: by.clone(),+ message_id: conversation.message.message_id,+ },+ None => TriggerOrigin::Unknown,+ }+ }+ Self::TopLevelMentioned(_) | Self::Mentioned(_) => match self.mention() {+ Some(mention) => mentioned_origin(&mention.message),+ None => TriggerOrigin::Unknown,+ },+ Self::AssignedToTask(assigned) => assigned.origin.clone(),+ Self::Requested(requested) => requested.origin.clone(),+ }+ }+/// The composer request this event carries, if that is what it is.#[must_use]pub fn requested(&self) -> Option<&AgentSessionRequestedEvent> {@@ -191,6 +225,26 @@ impl NewAgentSessionEvent {}}+/// A mention, attributed to whoever posted it. A bot's post with no invoking+/// user opens nothing, so it has no origin to name.+fn mentioned_origin(message: &MessagePostedMetadata) -> TriggerOrigin {+ let Some(user) = message.invoking_user() else {+ return TriggerOrigin::Unknown;+ };+ let by = match message.sender.as_bot() {+ Some(bot) => Caller::Agent(AgentActor {+ bot: bot.bot_id(),+ on_behalf_of: user,+ lineage: Lineage::Unattributed,+ }),+ None => Caller::Person { user },+ };+ TriggerOrigin::Mentioned {+ by,+ message_id: message.message_id,+ }+}+/// A channel message for a session that already exists, in the channel-only/// shape consumers built before message parents decode.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]diff --git a/crates/agent_trigger/src/domain/broker_events/test.rs b/crates/agent_trigger/src/domain/broker_events/test.rsindex 53f3d96675..8b9fdaec7a 100644--- a/crates/agent_trigger/src/domain/broker_events/test.rs+++ b/crates/agent_trigger/src/domain/broker_events/test.rs@@ -152,6 +152,7 @@ fn task_assignment_round_trips_and_opens_on_its_discussion() {..posted(document(), None)};let assigned = NewAgentSessionEvent::AssignedToTask(AgentAssignedToTaskEvent {+ origin: trigger_context::TriggerOrigin::Unknown,bot_id: BotId::TEST_A,parent: message.parent.clone(),discussion_id: message.message_id,@@ -432,3 +433,51 @@ fn a_conversation_turn_carries_its_trigger_without_the_channel() {assert_eq!(wire["metadata"]["context"]["kind"], "conversation");assert!(wire["metadata"]["context"].get("channel").is_none());}++#[test]+fn a_mention_is_attributed_to_whoever_posted_it() {+ let message = posted(document(), None);+ let by_person = NewAgentSessionEvent::Mentioned(AgentMentionedEvent {+ bot_id: BotId::TEST_A,+ message: message.clone(),+ context: None,+ });+ let TriggerOrigin::Mentioned { by, message_id } = by_person.origin() else {+ panic!("expected a mention");+ };+ assert_eq!(message_id, message.message_id);+ assert!(matches!(by, Caller::Person { .. }));++ let user = MacroUserIdStr::try_from_email("[email protected]").unwrap();+ let by_agent = NewAgentSessionEvent::Mentioned(AgentMentionedEvent {+ bot_id: BotId::TEST_A,+ message: MessagePostedMetadata {+ sender: ChannelSender::new_from_bot(BotId::TEST_B),+ triggered_by: Some(user.as_ref().to_owned()),+ ..message.clone()+ },+ context: None,+ });+ let TriggerOrigin::Mentioned { by, .. } = by_agent.origin() else {+ panic!("expected a mention");+ };+ assert_eq!(+ by,+ Caller::Agent(AgentActor {+ bot: BotId::TEST_B,+ on_behalf_of: user,+ lineage: Lineage::Unattributed,+ })+ );++ let unprompted = NewAgentSessionEvent::Mentioned(AgentMentionedEvent {+ bot_id: BotId::TEST_A,+ message: MessagePostedMetadata {+ sender: ChannelSender::new_from_bot(BotId::TEST_B),+ triggered_by: None,+ ..message+ },+ context: None,+ });+ assert_eq!(unprompted.origin(), TriggerOrigin::Unknown);+}diff --git a/crates/agent_trigger/src/domain/project_assignment/test.rs b/crates/agent_trigger/src/domain/project_assignment/test.rsindex 11778f94d4..340d5cf0e6 100644--- a/crates/agent_trigger/src/domain/project_assignment/test.rs+++ b/crates/agent_trigger/src/domain/project_assignment/test.rs@@ -28,6 +28,7 @@ fn update(project: Option<InitiativeId>,) -> EntityPropertyUpdatedMetadata {EntityPropertyUpdatedMetadata {+ inherited_from_project: None,entity_property_id: Uuid::now_v7(),entity_id: "task".to_owned(),entity_type: PropertyEntityType::Task,diff --git a/crates/agent_trigger/src/domain/service/test.rs b/crates/agent_trigger/src/domain/service/test.rsindex 8edd9afaf3..704f8db125 100644--- a/crates/agent_trigger/src/domain/service/test.rs+++ b/crates/agent_trigger/src/domain/service/test.rs@@ -108,6 +108,7 @@ fn message(mentions: Vec<SimpleMention>) -> MessagePostedMetadata {fn session(id: AgentSessionId, bot_id: BotId) -> AgentSession {AgentSession {+ origin: Default::default(),repo_branch: None,pull_request_url: None,task_id: None,@@ -141,6 +142,7 @@ fn session(id: AgentSessionId, bot_id: BotId) -> AgentSession {/// A session rooted at the test message's thread.fn thread_session(id: AgentSessionId, bot_id: BotId) -> AgentSession {AgentSession {+ origin: Default::default(),thread_id: Some(Uuid::from_u128(3)),originating_message_id: Some(Uuid::from_u128(3)),..session(id, bot_id)diff --git a/crates/agent_trigger/src/domain/sources/test.rs b/crates/agent_trigger/src/domain/sources/test.rsindex eff6a0b84c..8922a18ad6 100644--- a/crates/agent_trigger/src/domain/sources/test.rs+++ b/crates/agent_trigger/src/domain/sources/test.rs@@ -104,6 +104,7 @@ fn a_task_joining_a_project_decodes_as_a_project_addition() {let project = InitiativeId::generate();let user = MacroUserIdStr::try_from_email("[email protected]").unwrap();let event = PropertyMacroEvent::entity_property_updated(EntityPropertyUpdatedMetadata {+ inherited_from_project: None,entity_property_id: Uuid::now_v7(),entity_id: "task-a".to_owned(),entity_type: EntityType::Task,diff --git a/crates/agent_trigger/src/domain/task_assignment.rs b/crates/agent_trigger/src/domain/task_assignment.rsindex faee741a9e..789713803a 100644--- a/crates/agent_trigger/src/domain/task_assignment.rs+++ b/crates/agent_trigger/src/domain/task_assignment.rs@@ -4,7 +4,8 @@ use std::collections::HashSet;use agent_session::domain::error::{AgentSessionError, Result as AgentResult};use chrono::{DateTime, Utc};-use trigger_context::{TaskAssignedContext, TaskSnapshot, TriggerContext};+use trigger_context::origin::{AgentActor, Caller, Lineage};+use trigger_context::{TaskAssignedContext, TaskSnapshot, TriggerContext, TriggerOrigin};use crate::domain::context::PeopleDirectory;use agent_session::domain::ports::AgentSessionRepo;@@ -76,6 +77,8 @@ pub struct TaskAssignment {pub actor: MacroUserIdStr<'static>,/// Agents added by this change, in stable order.pub bots: Vec<BotId>,+ /// Who made the assignment, and how.+ pub origin: TriggerOrigin,}impl TaskAssignment {@@ -95,18 +98,42 @@ impl TaskAssignment {if bots.is_empty() {return None;}+ let actor = updated+ .actor_user_id+ .clone()+ .or_else(|| updated.on_behalf_of.clone())?;Some(Self {event_id,parent: MessageParent::parse("document", &updated.entity_id).ok()?,- actor: updated- .actor_user_id- .clone()- .or_else(|| updated.on_behalf_of.clone())?,+ origin: assignment_origin(updated, actor.clone()),+ actor,bots,})}}+/// `actor` is the user behind the change; the event's own `actor` says whether+/// an agent made it for them.+fn assignment_origin(+ updated: &EntityPropertyUpdatedMetadata,+ actor: MacroUserIdStr<'static>,+) -> TriggerOrigin {+ let acting_bot = updated.actor.as_ref().and_then(|actor| actor.as_bot());+ let by = match acting_bot {+ Some(bot) => Caller::Agent(AgentActor {+ bot: bot.bot_id(),+ on_behalf_of: actor,+ lineage: Lineage::Unattributed,+ }),+ None => Caller::Person { user: actor },+ };+ let task = updated.entity_id.clone();+ match updated.inherited_from_project {+ Some(project) => TriggerOrigin::ProjectInherited { by, task, project },+ None => TriggerOrigin::TaskAssigned { by, task },+ }+}+fn assigned_bots(value: Option<&PropertyValue>) -> HashSet<BotId> {let Some(PropertyValue::EntityRef(references)) = value else {return HashSet::new();@@ -193,6 +220,7 @@ wherediscussion_id: message.id,actor: assignment.actor.clone(),prompt: assignment_prompt(assignment, &brief),+ origin: assignment.origin.clone(),context: Some(context),},));diff --git a/crates/agent_trigger/src/domain/task_assignment/test.rs b/crates/agent_trigger/src/domain/task_assignment/test.rsindex 3ecbabd615..77d6dff775 100644--- a/crates/agent_trigger/src/domain/task_assignment/test.rs+++ b/crates/agent_trigger/src/domain/task_assignment/test.rs@@ -55,6 +55,7 @@ fn value(ids: &[&str]) -> Option<PropertyValue> {fn update() -> EntityPropertyUpdatedMetadata {EntityPropertyUpdatedMetadata {+ inherited_from_project: None,entity_property_id: Uuid::now_v7(),entity_id: "task-1".to_owned(),entity_type: EntityType::Task,@@ -475,3 +476,66 @@ fn assignment_response_ids_are_stable_distinct_uuid_v7s() {assert_eq!(root.get_version_num(), 7);assert_eq!(&root.as_bytes()[..6], &event.as_bytes()[..6]);}++#[test]+fn an_assignment_made_by_a_person_is_theirs() {+ let assignment = TaskAssignment::from_update(Uuid::now_v7(), &update()).unwrap();++ assert_eq!(+ assignment.origin,+ TriggerOrigin::TaskAssigned {+ by: Caller::Person {+ user: MacroUserIdStr::try_from_email("[email protected]").unwrap(),+ },+ task: "task-1".to_owned(),+ }+ );+}++#[test]+fn an_assignment_an_agent_made_for_a_person_names_the_agent() {+ let user = MacroUserIdStr::try_from_email("[email protected]").unwrap();+ let updated = EntityPropertyUpdatedMetadata {+ actor_user_id: None,+ actor: Some(channel_sender::ChannelSender::new_from_bot(BotId::TEST_B)),+ on_behalf_of: Some(user.clone()),+ ..update()+ };++ let assignment = TaskAssignment::from_update(Uuid::now_v7(), &updated).unwrap();++ assert_eq!(assignment.actor, user);+ assert_eq!(+ assignment.origin,+ TriggerOrigin::TaskAssigned {+ by: Caller::Agent(AgentActor {+ bot: BotId::TEST_B,+ on_behalf_of: user,+ lineage: Lineage::Unattributed,+ }),+ task: "task-1".to_owned(),+ }+ );+}++#[test]+fn agents_a_task_inherits_from_its_project_say_so() {+ let project = Uuid::now_v7();+ let updated = EntityPropertyUpdatedMetadata {+ inherited_from_project: Some(project),+ ..update()+ };++ let assignment = TaskAssignment::from_update(Uuid::now_v7(), &updated).unwrap();++ assert_eq!(+ assignment.origin,+ TriggerOrigin::ProjectInherited {+ by: Caller::Person {+ user: MacroUserIdStr::try_from_email("[email protected]").unwrap(),+ },+ task: "task-1".to_owned(),+ project,+ }+ );+}diff --git a/crates/coding_agent_worker/README.md b/crates/coding_agent_worker/README.mdindex 6bf3755b2f..18925dca1a 100644--- a/crates/coding_agent_worker/README.md+++ b/crates/coding_agent_worker/README.md@@ -179,6 +179,14 @@ Transcripts still end its turns. Without a reported session ID, macrod findsCodex's transcript by working directory and start time. Viewer windows(`macrod herdr-pane`) report their own state through OSC 7501.+## What opened a session++Each `New` trigger event says what opened its session+(`NewAgentSessionEvent::origin`). `src/trigger.rs` keeps it on `TriggerWork`, and+`src/dispatch.rs` copies it onto the create request, where the service stores it+with the session. macrod reports only what the event said. The service treats it+as a description, so it never decides a session's visibility or notifications.+## Replies to chat-agent mentionsTrigger prompts use the source channel/document message UUID as the controldiff --git a/crates/coding_agent_worker/src/dispatch.rs b/crates/coding_agent_worker/src/dispatch.rsindex eae2099386..9a8debbc60 100644--- a/crates/coding_agent_worker/src/dispatch.rs+++ b/crates/coding_agent_worker/src/dispatch.rs@@ -136,6 +136,7 @@ impl WorkExecutor for Dispatcher {message_id,content,context,+ origin,} => {let session = AgentSessionId::new_from_uuid(uuid::Uuid::new_v5(&bot.as_uuid(),@@ -188,6 +189,7 @@ impl WorkExecutor for Dispatcher {// Likewise the model: an external session runs on// whatever this runtime is configured with.model: None,+ origin: *origin,};let created = match self.api.create_session(&request, &sender).await {Ok(created) => created,@@ -239,6 +241,7 @@ impl WorkExecutor for Dispatcher {session,bot,sender,+ origin,} => {let workspace = self.workspace_for(session, repo_url.as_deref()).await?;// Same create as a mention, minus the thread: the requester is@@ -258,6 +261,7 @@ impl WorkExecutor for Dispatcher {thread: None,instructions: None,model: None,+ origin,};self.api.create_session(&request, &sender).await?;self.created(session, &sender);diff --git a/crates/coding_agent_worker/src/outbound/agent_session/test.rs b/crates/coding_agent_worker/src/outbound/agent_session/test.rsindex 230d766658..111dbe9bd2 100644--- a/crates/coding_agent_worker/src/outbound/agent_session/test.rs+++ b/crates/coding_agent_worker/src/outbound/agent_session/test.rs@@ -47,6 +47,7 @@ async fn transient_create_retries_keep_identity_and_trigger_controls_keep_source});let sender = MacroUserIdStr::try_from_email("[email protected]").unwrap();let request = CreateAgentSessionRequest {+ origin: trigger_context::TriggerOrigin::Unknown,id: Some(session.as_uuid()),bot_id: Some(bot_id::BotId::TEST_A.as_uuid()),workspace: Some("/workspace".into()),diff --git a/crates/coding_agent_worker/src/trigger.rs b/crates/coding_agent_worker/src/trigger.rsindex d527163332..8e0398173a 100644--- a/crates/coding_agent_worker/src/trigger.rs+++ b/crates/coding_agent_worker/src/trigger.rs@@ -14,7 +14,7 @@ use macro_event_broker::Event;use macro_user_id::user_id::MacroUserIdStr;use macro_uuid::Uuid;use strum::IntoEnumIterator as _;-use trigger_context::TriggerContext;+use trigger_context::{TriggerContext, TriggerOrigin};use webhook::domain::models::WebhookFilter;#[cfg(test)]@@ -47,6 +47,8 @@ pub enum TriggerWork {content: String,/// Why the agent was called, forwarded with the prompt.context: Option<TriggerContext>,+ /// What opened the session, copied onto its create request.+ origin: Box<TriggerOrigin>,},/// Open a session somebody asked for from the composer, under the id/// they are waiting on. No thread, so nothing is announced anywhere;@@ -61,6 +63,8 @@ pub enum TriggerWork {bot: BotId,/// Who asked; owns the session.sender: MacroUserIdStr<'static>,+ /// What opened the session, copied onto its create request.+ origin: TriggerOrigin,},/// Forward a message into a session that already exists, serving it/// first if this daemon is not already. Just the prompt: the harness@@ -100,6 +104,7 @@ pub fn trigger_to_work(event: AgentTriggerTopicEvent) -> Result<TriggerWork, Skibot_id,session_id,owner,+ origin,context: _,},)) => {@@ -109,6 +114,7 @@ pub fn trigger_to_work(event: AgentTriggerTopicEvent) -> Result<TriggerWork, Skisession: session_id,bot: bot_id,sender,+ origin,})}AgentTriggerTopicEvent::New(NewAgentSessionEvent::AssignedToTask(assigned)) => {@@ -127,9 +133,11 @@ pub fn trigger_to_work(event: AgentTriggerTopicEvent) -> Result<TriggerWork, Skithread_id: assigned.discussion_id,message_id: assigned.discussion_id,context: assigned.context,+ origin: Box::new(assigned.origin),})}AgentTriggerTopicEvent::New(event) => {+ let origin = event.origin();let Some(OpeningMention {bot_id,message,@@ -150,6 +158,7 @@ pub fn trigger_to_work(event: AgentTriggerTopicEvent) -> Result<TriggerWork, Skimessage_id: message.message_id,content: message.content,context,+ origin: Box::new(origin),})}AgentTriggerTopicEvent::Existing(event) => {diff --git a/crates/coding_agent_worker/src/trigger/test.rs b/crates/coding_agent_worker/src/trigger/test.rsindex 145954983c..f418c88c07 100644--- a/crates/coding_agent_worker/src/trigger/test.rs+++ b/crates/coding_agent_worker/src/trigger/test.rs@@ -103,6 +103,10 @@ fn document_triggers_become_work_on_the_document() {assert_eq!(trigger_to_work(opened).expect("a document mention is work"),TriggerWork::OpenAndPrompt {+ origin: Box::new(trigger_context::TriggerOrigin::Mentioned {+ by: trigger_context::origin::Caller::Person { user: sender() },+ message_id: Uuid::from_u128(2),+ }),reuse_origin_message: false,bot: bot_id::BotId::TEST_A,sender: sender(),@@ -137,6 +141,7 @@ fn document_triggers_become_work_on_the_document() {fn a_task_assignment_opens_and_prompts_in_the_task_discussion() {let event = AgentTriggerTopicEvent::New(NewAgentSessionEvent::AssignedToTask(AgentAssignedToTaskEvent {+ origin: trigger_context::TriggerOrigin::Unknown,bot_id: BotId::TEST_A,parent: document(),discussion_id: Uuid::from_u128(2),@@ -148,6 +153,7 @@ fn a_task_assignment_opens_and_prompts_in_the_task_discussion() {assert_eq!(trigger_to_work(event).expect("a task assignment is work"),TriggerWork::OpenAndPrompt {+ origin: Box::new(trigger_context::TriggerOrigin::Unknown),reuse_origin_message: true,bot: BotId::TEST_A,sender: sender(),@@ -166,6 +172,10 @@ fn a_mention_becomes_open_and_prompt_rooting_its_own_thread() {assert_eq!(work,TriggerWork::OpenAndPrompt {+ origin: Box::new(trigger_context::TriggerOrigin::Mentioned {+ by: trigger_context::origin::Caller::Person { user: sender() },+ message_id: Uuid::from_u128(2),+ }),reuse_origin_message: false,bot: bot_id::BotId::TEST_A,sender: sender(),@@ -307,3 +317,15 @@ fn attributed_bot_mentions_open_and_prompt_with_the_invoking_user() {matches!(trigger_to_work(follow_up).unwrap(), TriggerWork::PromptExisting { sender: actor, .. } if actor == sender()));}++#[test]+fn a_mention_tells_the_runtime_what_opened_its_session() {+ let Ok(TriggerWork::OpenAndPrompt { origin, .. }) = trigger_to_work(mention("hello")) else {+ panic!("expected a session to open");+ };++ assert!(matches!(+ *origin,+ trigger_context::TriggerOrigin::Mentioned { .. }+ ));+}diff --git a/crates/entity_registry/entity_registry/src/domain/creation_principal.rs b/crates/entity_registry/entity_registry/src/domain/creation_principal.rsindex 9997019dda..79c173c6d4 100644--- a/crates/entity_registry/entity_registry/src/domain/creation_principal.rs+++ b/crates/entity_registry/entity_registry/src/domain/creation_principal.rs@@ -69,8 +69,16 @@ pub fn resolve_creation_principal(non_user_owners: NonUserOwners,) -> Result<CreationPrincipal, CreationPrincipalError> {match authorization {+ // A token signed for an agent still acts as its user, who owns the+ // result, but the agent is who did it.MacroAuthorization::User(user) | MacroAuthorization::Internal(Some(user)) => {- Ok(CreationPrincipal::User(user.macro_user_id.clone()))+ Ok(match user.agent_id {+ Some(bot) => CreationPrincipal::BotForUser {+ bot,+ user: user.macro_user_id.clone(),+ },+ None => CreationPrincipal::User(user.macro_user_id.clone()),+ })}MacroAuthorization::Bot(bot) => resolve_bot(bot, non_user_owners),MacroAuthorization::Internal(None) => Err(CreationPrincipalError::InternalWithoutUser),diff --git a/crates/entity_registry/entity_registry/src/domain/creation_principal/test.rs b/crates/entity_registry/entity_registry/src/domain/creation_principal/test.rsindex 5f1d7414f4..e89758ae28 100644--- a/crates/entity_registry/entity_registry/src/domain/creation_principal/test.rs+++ b/crates/entity_registry/entity_registry/src/domain/creation_principal/test.rs@@ -217,3 +217,20 @@ fn invalid_gate_value_is_rejected() {Err("provided string was not `true` or `false`".to_owned()));}++#[test]+fn a_token_signed_for_an_agent_creates_as_that_agent_for_its_user() {+ let agent = BotId::TEST_A;+ let authorization = MacroAuthorization::User(MacroUserAuthentication {+ agent_id: Some(agent),+ ..user()+ });++ assert_eq!(+ resolve_creation_principal(&authorization, NonUserOwners::Disabled),+ Ok(CreationPrincipal::BotForUser {+ bot: agent,+ user: user_id(),+ })+ );+}diff --git a/crates/macro_db_client/migrations/20261105234841_agent_session_source.sql b/crates/macro_db_client/migrations/20261105234841_agent_session_source.sqlnew file mode 100644index 0000000000..27295a3793--- /dev/null+++ b/crates/macro_db_client/migrations/20261105234841_agent_session_source.sql@@ -0,0 +1,74 @@+-- What opened an agent session, one row per session. Holds only references to users and+-- entities, none of them foreign keys: the record must outlive the message, routine or+-- session it names. A session's delete removes its source in the same transaction.+SET LOCAL lock_timeout = '5s';++CREATE TABLE agent_session_source (+ id UUID PRIMARY KEY,+ kind TEXT NOT NULL,+ -- Who acted: a person, or an agent acting for a person.+ actor_user_id TEXT,+ actor_bot_id UUID,+ on_behalf_of_user_id TEXT,+ -- The session the acting agent ran in, and the first non-agent cause of its work.+ acting_session_id UUID,+ root_user_id TEXT,+ root_routine_id UUID,+ -- What it is about.+ message_id UUID,+ task_id TEXT,+ project_id UUID,+ routine_id UUID,+ routine_firing TEXT,+ event_id UUID,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),++ CONSTRAINT agent_session_source_kind_fields CHECK (+ CASE kind+ WHEN 'mentioned' THEN message_id IS NOT NULL+ WHEN 'conversation' THEN actor_user_id IS NOT NULL AND message_id IS NOT NULL+ WHEN 'task_assigned' THEN task_id IS NOT NULL+ WHEN 'project_inherited' THEN task_id IS NOT NULL AND project_id IS NOT NULL+ WHEN 'requested' THEN actor_user_id IS NOT NULL+ WHEN 'dispatched' THEN on_behalf_of_user_id IS NOT NULL+ WHEN 'routine' THEN routine_id IS NOT NULL AND routine_firing IS NOT NULL+ ELSE false+ END+ ),+ -- Mentions and assignments come from a person or from an agent acting for one.+ CONSTRAINT agent_session_source_actor CHECK (+ kind NOT IN ('mentioned', 'task_assigned', 'project_inherited')+ OR (actor_user_id IS NOT NULL AND actor_bot_id IS NULL AND on_behalf_of_user_id IS NULL)+ OR (actor_user_id IS NULL AND actor_bot_id IS NOT NULL AND on_behalf_of_user_id IS NOT NULL)+ ),+ -- A routine fires on its own; no one acted.+ CONSTRAINT agent_session_source_routine_has_no_actor CHECK (+ kind <> 'routine'+ OR (actor_user_id IS NULL AND actor_bot_id IS NULL AND on_behalf_of_user_id IS NULL)+ ),+ CONSTRAINT agent_session_source_routine_firing CHECK (+ routine_firing IS NULL OR routine_firing IN ('scheduled', 'manual', 'event')+ ),+ CONSTRAINT agent_session_source_event_only_when_fired_by_one CHECK (+ CASE routine_firing+ WHEN 'event' THEN event_id IS NOT NULL+ ELSE event_id IS NULL+ END+ ),+ -- A known acting session has exactly one root; an unknown one has none.+ CONSTRAINT agent_session_source_lineage CHECK (+ (acting_session_id IS NULL AND root_user_id IS NULL AND root_routine_id IS NULL)+ OR (+ acting_session_id IS NOT NULL+ AND actor_bot_id IS NOT NULL+ AND (root_user_id IS NULL) <> (root_routine_id IS NULL)+ )+ )+);++-- Null for sessions that predate this, unclaimed warm sessions, and sessions opened by a+-- runtime too old to report what opened them.+ALTER TABLE agent_session+ ADD COLUMN source_id UUID,+ ADD CONSTRAINT agent_session_source_id_fkey+ FOREIGN KEY (source_id) REFERENCES agent_session_source (id) NOT VALID;diff --git a/crates/macro_db_client/migrations/20261105234842_index_agent_session_source_id.sql b/crates/macro_db_client/migrations/20261105234842_index_agent_session_source_id.sqlnew file mode 100644index 0000000000..676686599b--- /dev/null+++ b/crates/macro_db_client/migrations/20261105234842_index_agent_session_source_id.sql@@ -0,0 +1,5 @@+-- no-transaction+-- Keeps the foreign key check on a source's delete from scanning agent_session.+CREATE INDEX CONCURRENTLY IF NOT EXISTS agent_session_source_id_idx+ON agent_session (source_id)+WHERE source_id IS NOT NULL;diff --git a/crates/macro_db_client/migrations/20261105234843_validate_agent_session_source_id.sql b/crates/macro_db_client/migrations/20261105234843_validate_agent_session_source_id.sqlnew file mode 100644index 0000000000..6e8ca204bd--- /dev/null+++ b/crates/macro_db_client/migrations/20261105234843_validate_agent_session_source_id.sql@@ -0,0 +1,4 @@+-- Run after the column migration releases its exclusive table lock.+SET LOCAL lock_timeout = '5s';++ALTER TABLE agent_session VALIDATE CONSTRAINT agent_session_source_id_fkey;diff --git a/crates/properties/src/domain/activity/test.rs b/crates/properties/src/domain/activity/test.rsindex 158bc9cd82..96a4489c78 100644--- a/crates/properties/src/domain/activity/test.rs+++ b/crates/properties/src/domain/activity/test.rs@@ -20,6 +20,7 @@ fn envelope(event: PropertyTopicEvent) -> Event<PropertyTopicEvent> {fn update(actor: Option<MacroUserIdStr<'static>>) -> EntityPropertyUpdatedMetadata {EntityPropertyUpdatedMetadata {+ inherited_from_project: None,entity_property_id: Uuid::from_u128(4),entity_id: "task-1".to_string(),entity_type: PropertyEntityType::Task,diff --git a/crates/properties/src/domain/events.rs b/crates/properties/src/domain/events.rsindex 45894a6466..e1a50bcda3 100644--- a/crates/properties/src/domain/events.rs+++ b/crates/properties/src/domain/events.rs@@ -126,6 +126,10 @@ pub struct EntityPropertyUpdatedMetadata {/// The outside event behind the change, when an integration made it.#[serde(default, skip_serializing_if = "Option::is_none")]pub source: Option<PropertyChangeSource>,+ /// The project whose agents this change inherited, when a task joining it+ /// made the change rather than someone setting the value.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub inherited_from_project: Option<Uuid>,/// Full value after the update, or `None` when cleared without deleting the row.pub value: Option<PropertyValue>,/// Full value before the update: `None` when the property was newlydiff --git a/crates/properties/src/domain/events/test.rs b/crates/properties/src/domain/events/test.rsindex aaccca0d60..0545a29a75 100644--- a/crates/properties/src/domain/events/test.rs+++ b/crates/properties/src/domain/events/test.rs@@ -155,6 +155,7 @@ fn topic_events(),(PropertyTopicEvent::EntityPropertyUpdated(EntityPropertyUpdatedMetadata {+ inherited_from_project: None,entity_property_id: uuid(ENTITY_PROPERTY_ID),entity_id: ENTITY_ID.to_string(),entity_type: EntityType::Document,diff --git a/crates/properties/src/domain/service_impl.rs b/crates/properties/src/domain/service_impl.rsindex 280a91a001..0ab180ffc9 100644--- a/crates/properties/src/domain/service_impl.rs+++ b/crates/properties/src/domain/service_impl.rs@@ -259,6 +259,7 @@ whereprevious_value: &Option<PropertyValue>,access: &EditReceipt,source: Option<&PropertyChangeSource>,+ inherited_from_project: Option<Uuid>,) -> PropertyMacroEvent {let PublishedEventActors {actor,@@ -274,6 +275,7 @@ whereactor,on_behalf_of,source: source.cloned(),+ inherited_from_project,value: value.clone(),previous_value: previous_value.clone(),updated_at: property.updated_at,@@ -296,6 +298,7 @@ where&mutation.previous_value,access,None,+ None,));}}@@ -472,6 +475,7 @@ wherefor mutation in mutations {self.publish_property_event(PropertyMacroEvent::entity_property_updated(EntityPropertyUpdatedMetadata {+ inherited_from_project: None,entity_property_id: mutation.property.id,entity_id: mutation.property.entity_id.clone(),entity_type: mutation.property.entity_type,@@ -747,6 +751,7 @@ where&None,access,source.as_ref(),+ None,));return Ok(EntityPropertyWithDefinition {property,@@ -795,6 +800,7 @@ where&snapshot.previous_value,access,source.as_ref(),+ None,));Ok(EntityPropertyWithDefinition {@@ -869,6 +875,7 @@ where&mutation.previous_value,task,None,+ Uuid::parse_str(project.entity_id()).ok(),));}Ok(())@@ -935,6 +942,7 @@ where&mutation.previous_value,access,None,+ None,));Ok(())@@ -975,6 +983,7 @@ where&mutation.previous_value,access,None,+ None,));}diff --git a/crates/properties/src/inbound/axum_router/extract.rs b/crates/properties/src/inbound/axum_router/extract.rsindex ac2a858e07..467acee251 100644--- a/crates/properties/src/inbound/axum_router/extract.rs+++ b/crates/properties/src/inbound/axum_router/extract.rs@@ -15,8 +15,8 @@ use axum::{response::{IntoResponse, Response},};use entity_access::domain::models::{- AccessLevel, EditAccessLevel, Entity, EntityAccessAuth, EntityAccessReceipt, EntityPermission,- EntityType as AccessEntityType, RequiredPermission, ViewAccessLevel,+ AccessLevel, BotAccessScope, EditAccessLevel, Entity, EntityAccessAuth, EntityAccessReceipt,+ EntityPermission, EntityType as AccessEntityType, RequiredPermission, ViewAccessLevel,};use entity_access::domain::ports::EntityAccessService;use macro_authorization::{@@ -228,14 +228,31 @@ where.await.map_err(ReceiptRejection::from)?;- let user = authorization.authorization.user.macro_user_id;- let receipt = mint_authenticated_receipt::<EditAccessLevel, A>(- state.entity_access_service.as_ref(),- &user,- ¶ms.entity_id,- target_entity_type(params.entity_type),- )- .await?;+ let user = authorization.authorization.user;+ let entity_type = target_entity_type(params.entity_type);+ // A token signed for an agent writes as that agent on its user's+ // behalf, the way the agent's MCP tools do.+ let receipt = match user.agent_id {+ Some(agent) => state+ .entity_access_service+ .generate_bot_entity_access_receipt::<EditAccessLevel>(+ agent,+ BotAccessScope::user(user.macro_user_id),+ ¶ms.entity_id,+ entity_type,+ )+ .await+ .map_err(|_| PropertiesErr::PermissionDenied)?,+ None => {+ mint_authenticated_receipt::<EditAccessLevel, A>(+ state.entity_access_service.as_ref(),+ &user.macro_user_id,+ ¶ms.entity_id,+ entity_type,+ )+ .await?+ }+ };Ok(Self(receipt))}diff --git a/crates/scheduled_action/src/domain/execution.rs b/crates/scheduled_action/src/domain/execution.rsindex e8ccb31a2f..2a8a062b89 100644--- a/crates/scheduled_action/src/domain/execution.rs+++ b/crates/scheduled_action/src/domain/execution.rs@@ -46,6 +46,8 @@ pub struct ExecutionHandle {pub history: RunHistory,/// What started this run and when, once the runner knows.pub run: Option<RunInfo>,+ /// What fired the routine, for the session this run opens.+ pub firing: Option<trigger_context::origin::RoutineCause>,// Cancellation during admission must not contact a runner that never started.preparation_started: bool,// Started was published, so Stopped must follow even without a transcript.@@ -62,6 +64,7 @@ impl Default for ExecutionHandle {steps: Vec::new(),history: RunHistory::default(),run: None,+ firing: None,preparation_started: false,announced: false,}@@ -379,7 +382,10 @@ where}}let mut ready_tx = Some(ready_tx);- let mut handle = ExecutionHandle::default();+ let mut handle = ExecutionHandle {+ firing: Some(firing.cause()),+ ..ExecutionHandle::default()+ };let result = bounded(deadline, executor.cancellation.cancelled(), async {let resource = executor.prepare(&action, &mut handle).await?;if let Some(ready_tx) = ready_tx.take() {@@ -471,7 +477,10 @@ whererun: &ClaimedEventRun,cancellation: impl Future<Output = ()> + Send,) -> EventExecutionResult {- let mut handle = ExecutionHandle::default();+ let mut handle = ExecutionHandle {+ firing: Some(RoutineRun::Event(&run.run).cause()),+ ..ExecutionHandle::default()+ };let shutdown = async {tokio::select! {_ = self.cancellation.cancelled() => {},diff --git a/crates/scheduled_action/src/domain/ports.rs b/crates/scheduled_action/src/domain/ports.rsindex e656dab0cd..2951c35724 100644--- a/crates/scheduled_action/src/domain/ports.rs+++ b/crates/scheduled_action/src/domain/ports.rs@@ -338,6 +338,17 @@ pub enum RoutineRun<'a> {}impl RoutineRun<'_> {+ pub fn cause(&self) -> trigger_context::origin::RoutineCause {+ use trigger_context::origin::RoutineCause;+ match self {+ Self::Scheduled { .. } => RoutineCause::Scheduled,+ Self::Manual { .. } => RoutineCause::Manual,+ Self::Event(run) => RoutineCause::Event {+ event_id: run.pending.event.event_id().into(),+ },+ }+ }+pub fn event(&self) -> Option<&EventReference> {match self {Self::Event(run) => Some(&run.pending.event),diff --git a/crates/scheduled_action/src/domain/target_runner.rs b/crates/scheduled_action/src/domain/target_runner.rsindex 5da119ea7b..6abd56c296 100644--- a/crates/scheduled_action/src/domain/target_runner.rs+++ b/crates/scheduled_action/src/domain/target_runner.rs@@ -15,7 +15,7 @@ use bot_id::BotId;use bots::domain::models::AgentMcpServer;use macro_user_id::user_id::MacroUserIdStr;use routine_program::AgentStep;-use trigger_context::TriggerContext;+use trigger_context::{TriggerContext, TriggerOrigin};use super::{execution::ExecutionHandle,@@ -66,6 +66,10 @@ impl<Sessions: RoutineSessions> RoutineAgents for TargetRunner<Sessions> {session_id: identity.session_id,source: SessionSource::Routine,visibility: action.run_visibility.into(),+ origin: match (action.id, handle.firing) {+ (Some(routine), Some(firing)) => TriggerOrigin::Routine { routine, firing },+ _ => TriggerOrigin::Unknown,+ },}).await;match prepared {diff --git a/crates/scheduled_action/src/outbound/agent_session_client/test.rs b/crates/scheduled_action/src/outbound/agent_session_client/test.rsindex 7e55f6f289..7658187f47 100644--- a/crates/scheduled_action/src/outbound/agent_session_client/test.rs+++ b/crates/scheduled_action/src/outbound/agent_session_client/test.rs@@ -145,6 +145,7 @@ async fn all_commands_use_internal_auth_and_domain_wire_contract_at_both_prefixe..selection()};let prepare = PrepareRoutineSession {+ origin: trigger_context::TriggerOrigin::Unknown,selection: selection.clone(),session_id: identity.session_id,source: SessionSource::Routine,@@ -252,6 +253,7 @@ async fn typed_sanitized_domain_errors_are_preserved() {let client = AgentSessionClient::new(&server.url, KEY).unwrap();let error = client.prepare(PrepareRoutineSession {+ origin: trigger_context::TriggerOrigin::Unknown,selection: selection(),session_id: identity().session_id,source: SessionSource::User,diff --git a/crates/soup_realtime/src/inbound/kafka_consumer/test.rs b/crates/soup_realtime/src/inbound/kafka_consumer/test.rsindex 75f95b1008..18218e19cb 100644--- a/crates/soup_realtime/src/inbound/kafka_consumer/test.rs+++ b/crates/soup_realtime/src/inbound/kafka_consumer/test.rs@@ -331,6 +331,7 @@ fn sent_chat_messages_refresh_the_soup_model() {#[test]fn task_property_updates_map_to_document_updates() {let event = PropertyTopicEvent::EntityPropertyUpdated(EntityPropertyUpdatedMetadata {+ inherited_from_project: None,entity_property_id: Uuid::now_v7(),entity_id: DOCUMENT_ID.to_string(),entity_type: PropertyEntityType::Task,@@ -461,6 +462,7 @@ fn attributed_initiative_clears_and_other_system_clears_still_refresh_soup() {fn a_cell_edit_updates_the_database_row() {let row = "70000000-0000-0000-0000-000000000001";let event = PropertyTopicEvent::EntityPropertyUpdated(EntityPropertyUpdatedMetadata {+ inherited_from_project: None,entity_property_id: Uuid::from_u128(0xe0000000_0000_0000_0000_000000000001),entity_id: row.to_string(),entity_type: PropertyEntityType::DatabaseRow,@@ -1040,6 +1042,7 @@ fn moving_a_task_between_projects_refreshes_the_task_and_both_projects() {}]))};let event = PropertyTopicEvent::EntityPropertyUpdated(EntityPropertyUpdatedMetadata {+ inherited_from_project: None,entity_property_id: Uuid::now_v7(),entity_id: DOCUMENT_ID.to_string(),entity_type: PropertyEntityType::Task,diff --git a/crates/trigger_context/AGENTS.md b/crates/trigger_context/AGENTS.mdnew file mode 100644index 0000000000..91ac992aaf--- /dev/null+++ b/crates/trigger_context/AGENTS.md@@ -0,0 +1,42 @@+# trigger_context++## What it is++Part of agent sessions: plain data for why an agent was called, shared by+whatever calls an agent, the runtimes that serve it, and the service that composes+its prompt. Plain data so the self-hosted daemon can carry it without the+producers' dependencies.++## Start here++- `src/lib.rs`: `TriggerContext`, the account written for the agent. It carries+ content, and is absent when it could not be read.+- `src/origin.rs`: `TriggerOrigin`, the record of what opened a session. References+ only, known from the source event alone, and stored in `agent_session_source`.++## Scope++- Owns: the vocabulary of both types.+- Not here: rendering a context into a prompt (`services/lexical-service`), storing+ an origin (`agent_session`), or deciding that an agent should run (`agent_trigger`).++## Boundaries++- Depends on: `bot_id`, `macro_user_id`.+- Used by: `agent_trigger`, `agent_session`, `agent_harness`, `scheduled_action`,+ and `coding_agent_worker`.++## Recipes++- Add an origin: a `TriggerOrigin` variant → its producer → `source_columns` in+ `crates/agent_session/src/outbound/postgres/source.rs` → the table's constraints.+ Hold only references to users and entities, and only fields that path always has.++## Checks++- `cargo test -p trigger_context`.++## Gotchas++- Runtimes are not rolled with a deploy, so new fields default on decode, and an+ origin this build does not know decodes as `Unknown`.diff --git a/crates/trigger_context/CLAUDE.md b/crates/trigger_context/CLAUDE.mdnew file mode 120000index 0000000000..47dc3e3d86--- /dev/null+++ b/crates/trigger_context/CLAUDE.md@@ -0,0 +1 @@+AGENTS.md\ No newline at end of filediff --git a/crates/trigger_context/Cargo.toml b/crates/trigger_context/Cargo.tomlindex beea462596..d72d2ede67 100644--- a/crates/trigger_context/Cargo.toml+++ b/crates/trigger_context/Cargo.toml@@ -7,10 +7,16 @@ version = "0.1.0"# Why an agent was called, as it travels from whatever called it to whoever# composes the agent's prompt. Plain data, so the self-hosted daemon and the# session control API can carry it without the producers' dependencies.+[features]+# OpenAPI schema for the origin a session reports through its API.+schema = ["bot_id/schema", "dep:utoipa", "macro_user_id/schema"]+[dependencies]bot_id = { path = "../bot_id" }chrono = { workspace = true, features = ["serde"] }+macro_user_id = { path = "../macro_user_id" }serde = { workspace = true }serde_json = { workspace = true }+utoipa = { workspace = true, optional = true }uuid = { workspace = true, features = ["serde"] }workspace-hack = { version = "0.1", path = "../workspace-hack" }diff --git a/crates/trigger_context/src/lib.rs b/crates/trigger_context/src/lib.rsindex 94852142d4..be5ddf0373 100644--- a/crates/trigger_context/src/lib.rs+++ b/crates/trigger_context/src/lib.rs@@ -12,6 +12,9 @@ use serde::{Deserialize, Serialize};use serde_json::Value;use uuid::Uuid;+pub mod origin;+pub use origin::TriggerOrigin;+#[cfg(test)]mod test;diff --git a/crates/trigger_context/src/origin.rs b/crates/trigger_context/src/origin.rsnew file mode 100644index 0000000000..74908bf804--- /dev/null+++ b/crates/trigger_context/src/origin.rs@@ -0,0 +1,160 @@+//! What opened an agent session.+//!+//! [`crate::TriggerContext`] is written for the agent: it carries content, and+//! it is absent when it could not be read. [`TriggerOrigin`] is the record of+//! the cause: references to users and entities only, known from the source+//! event alone, and stored on the session. Each variant holds exactly the+//! fields that path always has, so what happened and who did it cannot+//! disagree. It describes a session; it grants nothing.++use bot_id::BotId;+use macro_user_id::user_id::MacroUserIdStr;+use serde::{Deserialize, Serialize};+use uuid::Uuid;++#[cfg(test)]+mod test;++/// What opened a session.+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]+#[serde(tag = "origin", rename_all = "snake_case")]+pub enum TriggerOrigin {+ /// A message mentioned the agent.+ Mentioned {+ /// Who posted it.+ by: Caller,+ /// The message.+ message_id: Uuid,+ },+ /// A person wrote in their private conversation with the agent.+ Conversation {+ /// Who wrote.+ by: MacroUserIdStr<'static>,+ /// The message.+ message_id: Uuid,+ },+ /// The agent was added to a task's assignees.+ TaskAssigned {+ /// Who assigned it.+ by: Caller,+ /// The task.+ task: String,+ },+ /// The task joined a project, and inherited the project's agents.+ ProjectInherited {+ /// Who added the task to the project.+ by: Caller,+ /// The task.+ task: String,+ /// The project.+ project: Uuid,+ },+ /// A person opened the session directly, from the composer.+ Requested {+ /// Who opened it.+ by: MacroUserIdStr<'static>,+ },+ /// A tool handed the agent work. The tool knows only whose authority it+ /// runs under, not which agent called it.+ Dispatched {+ /// The user whose authority the work runs under.+ on_behalf_of: MacroUserIdStr<'static>,+ },+ /// A routine fired. Its owner owns the session, so the owner is not repeated.+ Routine {+ /// The routine.+ routine: Uuid,+ /// What made it fire.+ firing: RoutineCause,+ },+ /// Not known: an unclaimed warm session, a producer that predates this+ /// record, or a kind this build does not know.+ #[default]+ #[serde(other)]+ Unknown,+}++impl TriggerOrigin {+ /// Whether nothing is known, which the wire omits.+ #[must_use]+ pub fn is_unknown(&self) -> bool {+ matches!(self, Self::Unknown)+ }+}++/// Who did something that opened a session.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]+#[serde(tag = "type", rename_all = "snake_case")]+pub enum Caller {+ /// A person.+ Person {+ /// Who.+ user: MacroUserIdStr<'static>,+ },+ /// An agent, which always acts for a person on a path that opens a session.+ Agent(AgentActor),+}++/// An agent acting for a person.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]+pub struct AgentActor {+ /// The agent.+ pub bot: BotId,+ /// The person it acts for.+ pub on_behalf_of: MacroUserIdStr<'static>,+ /// Where the agent's own work came from.+ pub lineage: Lineage,+}++/// Where an acting agent's work came from.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]+#[serde(tag = "type", rename_all = "snake_case")]+pub enum Lineage {+ /// The session the agent acted from, and so where the chain started.+ Session {+ /// The acting session.+ session: Uuid,+ /// The first non-agent cause of its work.+ root: Root,+ },+ /// An agent acted, but its session was not captured.+ Unattributed,+}++/// The first non-agent cause. An agent cannot be one, so a chain always ends+/// at a person or a routine.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]+#[serde(tag = "type", rename_all = "snake_case")]+pub enum Root {+ /// A person.+ Person {+ /// Who.+ user: MacroUserIdStr<'static>,+ },+ /// A routine.+ Routine {+ /// The routine.+ routine: Uuid,+ },+}++/// What made a routine fire.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]+#[serde(tag = "type", rename_all = "snake_case")]+pub enum RoutineCause {+ /// One of its schedules came due.+ Scheduled,+ /// Its owner started it by hand.+ Manual,+ /// An event it watches happened.+ Event {+ /// The event.+ event_id: Uuid,+ },+}diff --git a/crates/trigger_context/src/origin/test.rs b/crates/trigger_context/src/origin/test.rsnew file mode 100644index 0000000000..31ce5bc35a--- /dev/null+++ b/crates/trigger_context/src/origin/test.rs@@ -0,0 +1,47 @@+use super::*;++#[test]+fn a_kind_this_build_does_not_know_decodes_as_unknown() {+ let origin: TriggerOrigin =+ serde_json::from_value(serde_json::json!({"origin": "from_the_future", "field": 1}))+ .unwrap();++ assert_eq!(origin, TriggerOrigin::Unknown);+}++#[test]+fn an_agent_task_assignment_reads_back_with_its_lineage() {+ let encoded = serde_json::json!({+ "origin": "task_assigned",+ "task": "task-1",+ "by": {+ "type": "agent",+ "bot": "01a0fd65-0ef7-763f-86ba-f065d75eaa66",+ "on_behalf_of": "macro|[email protected]",+ "lineage": {+ "type": "session",+ "session": "01a1a9da-8e60-7e60-9678-68ce6e69e117",+ "root": {"type": "routine", "routine": "01a1a90c-c2cb-7f25-8b21-0de250451c91"},+ },+ },+ });++ let origin: TriggerOrigin = serde_json::from_value(encoded).unwrap();++ let TriggerOrigin::TaskAssigned {+ by: Caller::Agent(actor),+ ..+ } = origin+ else {+ panic!("expected an agent's assignment");+ };+ let Lineage::Session { root, .. } = actor.lineage else {+ panic!("expected a known session");+ };+ assert_eq!(+ root,+ Root::Routine {+ routine: "01a1a90c-c2cb-7f25-8b21-0de250451c91".parse().unwrap()+ }+ );+}diff --git a/crates/webhook/Cargo.toml b/crates/webhook/Cargo.tomlindex 595dc1f446..a185a27337 100644--- a/crates/webhook/Cargo.toml+++ b/crates/webhook/Cargo.toml@@ -116,6 +116,7 @@ agent_session = { path = "../agent_session", default-features = false, features] }bot_id = { path = "../bot_id", features = ["test-utils"] }channel_sender = { path = "../channel_sender" }+trigger_context = { path = "../trigger_context" }macro_db_migrator = { path = "../macro_db_migrator" }messages = { path = "../messages" }rate_limit = { path = "../rate_limit", default-features = false, features = [diff --git a/crates/webhook/src/domain/ingestion/test.rs b/crates/webhook/src/domain/ingestion/test.rsindex 3b38bd9c59..24a0466b3a 100644--- a/crates/webhook/src/domain/ingestion/test.rs+++ b/crates/webhook/src/domain/ingestion/test.rs@@ -1396,6 +1396,7 @@ fn agent_trigger_requested_event()Event::new(AgentTriggerTopicEvent::New(NewAgentSessionEvent::Requested(AgentSessionRequestedEvent {+ origin: trigger_context::TriggerOrigin::Unknown,repo_url: None,bot_id: bot_id::BotId::new_from_uuid(uuid::Uuid::from_u128(0xB07)),session_id: agent_session::domain::model::AgentSessionId::new_from_uuid(@@ -1488,6 +1489,7 @@ fn agent_trigger_task_assignment_event() -> Event<AgentTriggerTopicEvent> {Event::new(AgentTriggerTopicEvent::New(NewAgentSessionEvent::AssignedToTask(AgentAssignedToTaskEvent {+ origin: trigger_context::TriggerOrigin::Unknown,bot_id: bot_id::BotId::TEST_A,parent: messages::domain::models::MessageParent::parse("document", DOCUMENT_ID).unwrap(),diff --git a/packages/sdk/generated/agent-harness/index.ts b/packages/sdk/generated/agent-harness/index.tsindex e81dd9bfb1..f726ed0f75 100644--- a/packages/sdk/generated/agent-harness/index.ts+++ b/packages/sdk/generated/agent-harness/index.ts@@ -1,4 +1,4 @@// This file is auto-generated by @hey-api/openapi-tsexport { type Options, Sdk } from './sdk.gen';-export type { AccessLevel, ActivityWireRow, AddConnectedMcpServerData, AddConnectedMcpServerErrors, AddConnectedMcpServerResponse, AddConnectedMcpServerResponses, AgentAction, AgentActionId, AgentActivityCursor, AgentActivityPage, AgentConfigKindDto, AgentConfigOptionDto, AgentConfigSelectOptionDto, AgentConversationDto, AgentConversationsDto, AgentConversationSessionDto, AgentConversationTurnDto, AgentMode, AgentModeChoiceRequest, AgentModeChoiceResponse, AgentModelDto, AgentModelsStatusDto, AgentPermissionAction, AgentPromptAction, AgentRepositoriesResponse, AgentRepositoryBranchesResponse, AgentRepositoryDto, AgentRespondElicitationAction, AgentSessionChangesPatchResponse, AgentSessionChangesResponse, AgentSessionFoldedLogResponse, AgentSessionLogEntryDto, AgentSessionLogResponse, AgentSessionPreviewData, AgentSessionPreviewDto, AgentSessionQueueResponse, AgentSessionResponse, AgentSessionsForPullRequestData, AgentSessionsForPullRequestError, AgentSessionsForPullRequestErrors, AgentSessionsForPullRequestResponse, AgentSessionsForPullRequestResponses, AgentSessionsForPullRequestsData, AgentSessionsForPullRequestsError, AgentSessionsForPullRequestsErrors, AgentSessionsForPullRequestsResponse, AgentSessionsForPullRequestsResponses, AgentSetConfigOptionAction, AgentSetModelAction, AiAdmissionErrorBody, AiSuggestions, AnswerAgentSessionToolApprovalData, AnswerAgentSessionToolApprovalError, AnswerAgentSessionToolApprovalErrors, AnswerAgentSessionToolApprovalResponse, AnswerAgentSessionToolApprovalResponses, AnswerToolApprovalRequest, AnswerToolApprovalResponse, AppConnectedRequest, ArchiveCause, AutoArchiveOverridesBody, AutoArchivePreferencesBody, BotId, CalendarSuggestions, CallConnectedAppToolData, CallConnectedAppToolErrors, CallConnectedAppToolResponse, CallConnectedAppToolResponses, CallConnectedTool, CallSearchSuggestions, CapabilityHarnessDto, CaptureAttemptDto, CaptureOutcomeDto, ChangedFileDto, ChangesetDto, ChangesetSourceDto, ChannelSearchSuggestions, ChannelSharePermission, ChooseAgentModeData, ChooseAgentModeErrors, ChooseAgentModeResponse, ChooseAgentModeResponses, ClassifyData, ClassifyErrors, ClassifyInputRequest, ClassifyInputResponse, ClassifyResponse, ClassifyResponses, ClientOptions, CodingPreferencesBody, ConnectedApp, ConnectedAppKind, ConnectedTool, ConnectedToolMatch, ConnectedToolResult, ConnectedToolSearch, ConnectMcpServer, ConnectMcpServerResponse, ConnectorTool, ControlAgentSessionData, ControlAgentSessionError, ControlAgentSessionErrors, ControlAgentSessionResponse, ControlAgentSessionResponses, ControlRequest, ControlResponse, ControlStatusDto, ConversationTurnState, CreateAgentSessionData, CreateAgentSessionError, CreateAgentSessionErrors, CreateAgentSessionRequest, CreateAgentSessionResponse, CreateAgentSessionResponse2, CreateAgentSessionResponses, CreateReview, CreateSessionReviewData, CreateSessionReviewErrors, CreateSessionReviewResponse, CreateSessionReviewResponses, CreateSessionThread, DecideSessionReviewData, DecideSessionReviewErrors, DecideSessionReviewResponse, DecideSessionReviewResponses, DecisionVia, DeleteAgentSessionData, DeleteAgentSessionError, DeleteAgentSessionErrors, DeleteAgentSessionResponses, DiscoverAgentCapabilitiesHandlerData, DiscoverAgentCapabilitiesHandlerErrors, DiscoverAgentCapabilitiesHandlerResponse, DiscoverAgentCapabilitiesHandlerResponses, DiscoverAgentCapabilitiesRequest, DiscoverAgentCapabilitiesResponse, DiscoverConnectedAppsData, DiscoverConnectedAppsErrors, DiscoverConnectedAppsResponse, DiscoverConnectedAppsResponses, DiscoverConnectorsResponse, DiscoveredApp, DiscoveryRequest, DiscoveryResult, DocumentId, EditQueuedActionData, EditQueuedActionError, EditQueuedActionErrors, EditQueuedActionRequest, EditQueuedActionResponse, EditQueuedActionResponses, ElicitationAnswer, ElicitationContentValue, ElicitationRequestId, EmailSearchSuggestions, EmailSuggestions, EntityType, ExecutionActivity, ExecutionId, ExecutionRecord, ExecutionStatus, ExternalSessionResponse, ExtractData, ExtractErrors, ExtractInputRequest, ExtractInputResponse, ExtractResponse, ExtractResponses, FileChangeKindDto, GetAgentAutoArchivePreferencesData, GetAgentAutoArchivePreferencesError, GetAgentAutoArchivePreferencesErrors, GetAgentAutoArchivePreferencesResponse, GetAgentAutoArchivePreferencesResponses, GetAgentCodingPreferencesData, GetAgentCodingPreferencesError, GetAgentCodingPreferencesErrors, GetAgentCodingPreferencesResponse, GetAgentCodingPreferencesResponses, GetAgentSandboxSizeData, GetAgentSandboxSizeError, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponse, GetAgentSandboxSizeResponses, GetAgentSessionActivityData, GetAgentSessionActivityErrors, GetAgentSessionActivityResponse, GetAgentSessionActivityResponses, GetAgentSessionAutoArchiveData, GetAgentSessionAutoArchiveError, GetAgentSessionAutoArchiveErrors, GetAgentSessionAutoArchiveResponse, GetAgentSessionAutoArchiveResponses, GetAgentSessionChangesData, GetAgentSessionChangesError, GetAgentSessionChangesErrors, GetAgentSessionChangesPatchData, GetAgentSessionChangesPatchError, GetAgentSessionChangesPatchErrors, GetAgentSessionChangesPatchResponse, GetAgentSessionChangesPatchResponses, GetAgentSessionChangesResponse, GetAgentSessionChangesResponses, GetAgentSessionData, GetAgentSessionError, GetAgentSessionErrors, GetAgentSessionFoldedLogData, GetAgentSessionFoldedLogError, GetAgentSessionFoldedLogErrors, GetAgentSessionFoldedLogResponse, GetAgentSessionFoldedLogResponses, GetAgentSessionLogData, GetAgentSessionLogError, GetAgentSessionLogErrors, GetAgentSessionLogResponse, GetAgentSessionLogResponses, GetAgentSessionPermissionsData, GetAgentSessionPermissionsError, GetAgentSessionPermissionsErrors, GetAgentSessionPermissionsResponse, GetAgentSessionPermissionsResponses, GetAgentSessionQueueData, GetAgentSessionQueueError, GetAgentSessionQueueErrors, GetAgentSessionQueueResponse, GetAgentSessionQueueResponses, GetAgentSessionResponse, GetAgentSessionResponses, GetCodeExecutionData, GetCodeExecutionErrors, GetCodeExecutionResponse, GetCodeExecutionResponses, GetSessionReviewData, GetSessionReviewErrors, GetSessionReviewResponse, GetSessionReviewResponses, GitRefDto, InputIntent, InputPropertyDefinition, InputPropertySuggestion, InputSuggestions, IntentScore, LinkAgentSessionPullRequestData, LinkAgentSessionPullRequestError, LinkAgentSessionPullRequestErrors, LinkAgentSessionPullRequestResponse, LinkAgentSessionPullRequestResponses, LinkShare, ListAgentConversationsData, ListAgentConversationsErrors, ListAgentConversationsResponse, ListAgentConversationsResponses, ListAgentRepositoriesData, ListAgentRepositoriesErrors, ListAgentRepositoriesResponse, ListAgentRepositoriesResponses, ListAgentRepositoryBranchesData, ListAgentRepositoryBranchesErrors, ListAgentRepositoryBranchesResponse, ListAgentRepositoryBranchesResponses, ListAgentSessionPullRequestsData, ListAgentSessionPullRequestsError, ListAgentSessionPullRequestsErrors, ListAgentSessionPullRequestsResponse, ListAgentSessionPullRequestsResponses, ListAgentWorkRegistrationsData, ListAgentWorkRegistrationsError, ListAgentWorkRegistrationsErrors, ListAgentWorkRegistrationsResponse, ListAgentWorkRegistrationsResponses, ListConnectedAppToolsData, ListConnectedAppToolsErrors, ListConnectedAppToolsResponse, ListConnectedAppToolsResponses, ListExecutionConnectedAppsData, ListExecutionConnectedAppsErrors, ListExecutionConnectedAppsResponse, ListExecutionConnectedAppsResponses, ListExecutionReviewsData, ListExecutionReviewsErrors, ListExecutionReviewsResponse, ListExecutionReviewsResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponse, LoadAgentModelsHandlerResponses, LoadAgentModelsRequest, LoadAgentModelsResponse, LogDirectionDto, LogFrameDto, MessageParent, MessageSuggestions, ModelHarnessDto, MonthlyWeekday, NoteSuggestions, PermissionAnswer, PresentSessionViewData, PresentSessionViewErrors, PresentSessionViewResponse, PresentSessionViewResponses, PresentView, PreviewAgentSessionsData, PreviewAgentSessionsError, PreviewAgentSessionsErrors, PreviewAgentSessionsRequest, PreviewAgentSessionsResponse, PreviewAgentSessionsResponse2, PreviewAgentSessionsResponses, PromptAttachment, PullRequestLinkedSession, PullRequestLinkSource, PullRequestSessions, PullRequestSessionsResponse, PullRequestsSessionsResponse, PullRequestUrl, PullRequestUrls, PutAgentAutoArchivePreferencesData, PutAgentAutoArchivePreferencesError, PutAgentAutoArchivePreferencesErrors, PutAgentAutoArchivePreferencesResponse, PutAgentAutoArchivePreferencesResponses, PutAgentCodingPreferencesData, PutAgentCodingPreferencesError, PutAgentCodingPreferencesErrors, PutAgentCodingPreferencesResponse, PutAgentCodingPreferencesResponses, PutAgentSandboxSizeData, PutAgentSandboxSizeError, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponse, PutAgentSandboxSizeResponses, PutAgentSessionAutoArchiveData, PutAgentSessionAutoArchiveError, PutAgentSessionAutoArchiveErrors, PutAgentSessionAutoArchiveResponse, PutAgentSessionAutoArchiveResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeError, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponse, PutAgentSessionSandboxSizeResponses, QuerySearchSuggestions, QueuedActionDto, RecordedCallStatus, RecordedToolCall, RecurrenceEnd, RecurrenceFrequency, RecurrenceSuggestion, RefreshAgentSessionChangesData, RefreshAgentSessionChangesError, RefreshAgentSessionChangesErrors, RefreshAgentSessionChangesResponse, RefreshAgentSessionChangesResponses, RegisterAgentSessionWorkData, RegisterAgentSessionWorkError, RegisterAgentSessionWorkErrors, RegisterAgentSessionWorkResponse, RegisterAgentSessionWorkResponses, RemoveQueuedActionData, RemoveQueuedActionError, RemoveQueuedActionErrors, RemoveQueuedActionResponse, RemoveQueuedActionResponses, RenameAgentSessionData, RenameAgentSessionError, RenameAgentSessionErrors, RenameAgentSessionRequest, RenameAgentSessionResponse, RenameAgentSessionResponses, ReportAgentSessionAppConnectedData, ReportAgentSessionAppConnectedError, ReportAgentSessionAppConnectedErrors, ReportAgentSessionAppConnectedResponses, RetryAgentConversationTurnData, RetryAgentConversationTurnErrors, RetryAgentConversationTurnRequest, RetryAgentConversationTurnResponse, RetryAgentConversationTurnResponses, ReviewDecision, ReviewDecisionContext, ReviewId, ReviewRecord, SandboxSize, SandboxSizeBody, SearchConnectedAppToolsData, SearchConnectedAppToolsErrors, SearchConnectedAppToolsResponse, SearchConnectedAppToolsResponses, SearchSuggestions, SearchType, SessionAutoArchiveResponse, SessionBot, SessionPullRequestLink, SessionPullRequestsResponse, SessionStatusDto, SetAgentSessionArchivedData, SetAgentSessionArchivedError, SetAgentSessionArchivedErrors, SetAgentSessionArchivedRequest, SetAgentSessionArchivedResponse, SetAgentSessionArchivedResponses, SharePermissionV2, StartFreshAgentConversationData, StartFreshAgentConversationErrors, StartFreshAgentConversationRequest, StartFreshAgentConversationResponse, StartFreshAgentConversationResponses, SteerQueuedActionData, SteerQueuedActionError, SteerQueuedActionErrors, SteerQueuedActionResponse, SteerQueuedActionResponses, TaskSearchSuggestions, TaskSuggestions, ToolActor, ToolApprovalAnswerDto, ToolApprovalStatusDto, UnlinkAgentSessionPullRequestData, UnlinkAgentSessionPullRequestError, UnlinkAgentSessionPullRequestErrors, UnlinkAgentSessionPullRequestResponse, UnlinkAgentSessionPullRequestResponses, UnregisterAgentSessionWorkData, UnregisterAgentSessionWorkError, UnregisterAgentSessionWorkErrors, UnregisterAgentSessionWorkResponse, UnregisterAgentSessionWorkResponses, UpdateAgentSessionPermissionsData, UpdateAgentSessionPermissionsError, UpdateAgentSessionPermissionsErrors, UpdateAgentSessionPermissionsResponse, UpdateAgentSessionPermissionsResponses, UpdateChannelSharePermission, UpdateOperation, UpdateSharePermissionRequestV2, WarmAgentSessionHandlerData, WarmAgentSessionHandlerResponse, WarmAgentSessionHandlerResponses, WarmAgentSessionRequest, WarmAgentSessionResponse, WeekdayCode, WithAgentSessionId, WorkRegistrationResponse } from './types.gen';+export type { AccessLevel, ActivityWireRow, AddConnectedMcpServerData, AddConnectedMcpServerErrors, AddConnectedMcpServerResponse, AddConnectedMcpServerResponses, AgentAction, AgentActionId, AgentActivityCursor, AgentActivityPage, AgentActor, AgentConfigKindDto, AgentConfigOptionDto, AgentConfigSelectOptionDto, AgentConversationDto, AgentConversationsDto, AgentConversationSessionDto, AgentConversationTurnDto, AgentMode, AgentModeChoiceRequest, AgentModeChoiceResponse, AgentModelDto, AgentModelsStatusDto, AgentPermissionAction, AgentPromptAction, AgentRepositoriesResponse, AgentRepositoryBranchesResponse, AgentRepositoryDto, AgentRespondElicitationAction, AgentSessionChangesPatchResponse, AgentSessionChangesResponse, AgentSessionFoldedLogResponse, AgentSessionLogEntryDto, AgentSessionLogResponse, AgentSessionPreviewData, AgentSessionPreviewDto, AgentSessionQueueResponse, AgentSessionResponse, AgentSessionsForPullRequestData, AgentSessionsForPullRequestError, AgentSessionsForPullRequestErrors, AgentSessionsForPullRequestResponse, AgentSessionsForPullRequestResponses, AgentSessionsForPullRequestsData, AgentSessionsForPullRequestsError, AgentSessionsForPullRequestsErrors, AgentSessionsForPullRequestsResponse, AgentSessionsForPullRequestsResponses, AgentSetConfigOptionAction, AgentSetModelAction, AiAdmissionErrorBody, AiSuggestions, AnswerAgentSessionToolApprovalData, AnswerAgentSessionToolApprovalError, AnswerAgentSessionToolApprovalErrors, AnswerAgentSessionToolApprovalResponse, AnswerAgentSessionToolApprovalResponses, AnswerToolApprovalRequest, AnswerToolApprovalResponse, AppConnectedRequest, ArchiveCause, AutoArchiveOverridesBody, AutoArchivePreferencesBody, BotId, CalendarSuggestions, CallConnectedAppToolData, CallConnectedAppToolErrors, CallConnectedAppToolResponse, CallConnectedAppToolResponses, CallConnectedTool, Caller, CallSearchSuggestions, CapabilityHarnessDto, CaptureAttemptDto, CaptureOutcomeDto, ChangedFileDto, ChangesetDto, ChangesetSourceDto, ChannelSearchSuggestions, ChannelSharePermission, ChooseAgentModeData, ChooseAgentModeErrors, ChooseAgentModeResponse, ChooseAgentModeResponses, ClassifyData, ClassifyErrors, ClassifyInputRequest, ClassifyInputResponse, ClassifyResponse, ClassifyResponses, ClientOptions, CodingPreferencesBody, ConnectedApp, ConnectedAppKind, ConnectedTool, ConnectedToolMatch, ConnectedToolResult, ConnectedToolSearch, ConnectMcpServer, ConnectMcpServerResponse, ConnectorTool, ControlAgentSessionData, ControlAgentSessionError, ControlAgentSessionErrors, ControlAgentSessionResponse, ControlAgentSessionResponses, ControlRequest, ControlResponse, ControlStatusDto, ConversationTurnState, CreateAgentSessionData, CreateAgentSessionError, CreateAgentSessionErrors, CreateAgentSessionRequest, CreateAgentSessionResponse, CreateAgentSessionResponse2, CreateAgentSessionResponses, CreateReview, CreateSessionReviewData, CreateSessionReviewErrors, CreateSessionReviewResponse, CreateSessionReviewResponses, CreateSessionThread, DecideSessionReviewData, DecideSessionReviewErrors, DecideSessionReviewResponse, DecideSessionReviewResponses, DecisionVia, DeleteAgentSessionData, DeleteAgentSessionError, DeleteAgentSessionErrors, DeleteAgentSessionResponses, DiscoverAgentCapabilitiesHandlerData, DiscoverAgentCapabilitiesHandlerErrors, DiscoverAgentCapabilitiesHandlerResponse, DiscoverAgentCapabilitiesHandlerResponses, DiscoverAgentCapabilitiesRequest, DiscoverAgentCapabilitiesResponse, DiscoverConnectedAppsData, DiscoverConnectedAppsErrors, DiscoverConnectedAppsResponse, DiscoverConnectedAppsResponses, DiscoverConnectorsResponse, DiscoveredApp, DiscoveryRequest, DiscoveryResult, DocumentId, EditQueuedActionData, EditQueuedActionError, EditQueuedActionErrors, EditQueuedActionRequest, EditQueuedActionResponse, EditQueuedActionResponses, ElicitationAnswer, ElicitationContentValue, ElicitationRequestId, EmailSearchSuggestions, EmailSuggestions, EntityType, ExecutionActivity, ExecutionId, ExecutionRecord, ExecutionStatus, ExternalSessionResponse, ExtractData, ExtractErrors, ExtractInputRequest, ExtractInputResponse, ExtractResponse, ExtractResponses, FileChangeKindDto, GetAgentAutoArchivePreferencesData, GetAgentAutoArchivePreferencesError, GetAgentAutoArchivePreferencesErrors, GetAgentAutoArchivePreferencesResponse, GetAgentAutoArchivePreferencesResponses, GetAgentCodingPreferencesData, GetAgentCodingPreferencesError, GetAgentCodingPreferencesErrors, GetAgentCodingPreferencesResponse, GetAgentCodingPreferencesResponses, GetAgentSandboxSizeData, GetAgentSandboxSizeError, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponse, GetAgentSandboxSizeResponses, GetAgentSessionActivityData, GetAgentSessionActivityErrors, GetAgentSessionActivityResponse, GetAgentSessionActivityResponses, GetAgentSessionAutoArchiveData, GetAgentSessionAutoArchiveError, GetAgentSessionAutoArchiveErrors, GetAgentSessionAutoArchiveResponse, GetAgentSessionAutoArchiveResponses, GetAgentSessionChangesData, GetAgentSessionChangesError, GetAgentSessionChangesErrors, GetAgentSessionChangesPatchData, GetAgentSessionChangesPatchError, GetAgentSessionChangesPatchErrors, GetAgentSessionChangesPatchResponse, GetAgentSessionChangesPatchResponses, GetAgentSessionChangesResponse, GetAgentSessionChangesResponses, GetAgentSessionData, GetAgentSessionError, GetAgentSessionErrors, GetAgentSessionFoldedLogData, GetAgentSessionFoldedLogError, GetAgentSessionFoldedLogErrors, GetAgentSessionFoldedLogResponse, GetAgentSessionFoldedLogResponses, GetAgentSessionLogData, GetAgentSessionLogError, GetAgentSessionLogErrors, GetAgentSessionLogResponse, GetAgentSessionLogResponses, GetAgentSessionPermissionsData, GetAgentSessionPermissionsError, GetAgentSessionPermissionsErrors, GetAgentSessionPermissionsResponse, GetAgentSessionPermissionsResponses, GetAgentSessionQueueData, GetAgentSessionQueueError, GetAgentSessionQueueErrors, GetAgentSessionQueueResponse, GetAgentSessionQueueResponses, GetAgentSessionResponse, GetAgentSessionResponses, GetCodeExecutionData, GetCodeExecutionErrors, GetCodeExecutionResponse, GetCodeExecutionResponses, GetSessionReviewData, GetSessionReviewErrors, GetSessionReviewResponse, GetSessionReviewResponses, GitRefDto, InputIntent, InputPropertyDefinition, InputPropertySuggestion, InputSuggestions, IntentScore, Lineage, LinkAgentSessionPullRequestData, LinkAgentSessionPullRequestError, LinkAgentSessionPullRequestErrors, LinkAgentSessionPullRequestResponse, LinkAgentSessionPullRequestResponses, LinkShare, ListAgentConversationsData, ListAgentConversationsErrors, ListAgentConversationsResponse, ListAgentConversationsResponses, ListAgentRepositoriesData, ListAgentRepositoriesErrors, ListAgentRepositoriesResponse, ListAgentRepositoriesResponses, ListAgentRepositoryBranchesData, ListAgentRepositoryBranchesErrors, ListAgentRepositoryBranchesResponse, ListAgentRepositoryBranchesResponses, ListAgentSessionPullRequestsData, ListAgentSessionPullRequestsError, ListAgentSessionPullRequestsErrors, ListAgentSessionPullRequestsResponse, ListAgentSessionPullRequestsResponses, ListAgentWorkRegistrationsData, ListAgentWorkRegistrationsError, ListAgentWorkRegistrationsErrors, ListAgentWorkRegistrationsResponse, ListAgentWorkRegistrationsResponses, ListConnectedAppToolsData, ListConnectedAppToolsErrors, ListConnectedAppToolsResponse, ListConnectedAppToolsResponses, ListExecutionConnectedAppsData, ListExecutionConnectedAppsErrors, ListExecutionConnectedAppsResponse, ListExecutionConnectedAppsResponses, ListExecutionReviewsData, ListExecutionReviewsErrors, ListExecutionReviewsResponse, ListExecutionReviewsResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponse, LoadAgentModelsHandlerResponses, LoadAgentModelsRequest, LoadAgentModelsResponse, LogDirectionDto, LogFrameDto, MacroUserIdStr, MessageParent, MessageSuggestions, ModelHarnessDto, MonthlyWeekday, NoteSuggestions, PermissionAnswer, PresentSessionViewData, PresentSessionViewErrors, PresentSessionViewResponse, PresentSessionViewResponses, PresentView, PreviewAgentSessionsData, PreviewAgentSessionsError, PreviewAgentSessionsErrors, PreviewAgentSessionsRequest, PreviewAgentSessionsResponse, PreviewAgentSessionsResponse2, PreviewAgentSessionsResponses, PromptAttachment, PullRequestLinkedSession, PullRequestLinkSource, PullRequestSessions, PullRequestSessionsResponse, PullRequestsSessionsResponse, PullRequestUrl, PullRequestUrls, PutAgentAutoArchivePreferencesData, PutAgentAutoArchivePreferencesError, PutAgentAutoArchivePreferencesErrors, PutAgentAutoArchivePreferencesResponse, PutAgentAutoArchivePreferencesResponses, PutAgentCodingPreferencesData, PutAgentCodingPreferencesError, PutAgentCodingPreferencesErrors, PutAgentCodingPreferencesResponse, PutAgentCodingPreferencesResponses, PutAgentSandboxSizeData, PutAgentSandboxSizeError, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponse, PutAgentSandboxSizeResponses, PutAgentSessionAutoArchiveData, PutAgentSessionAutoArchiveError, PutAgentSessionAutoArchiveErrors, PutAgentSessionAutoArchiveResponse, PutAgentSessionAutoArchiveResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeError, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponse, PutAgentSessionSandboxSizeResponses, QuerySearchSuggestions, QueuedActionDto, RecordedCallStatus, RecordedToolCall, RecurrenceEnd, RecurrenceFrequency, RecurrenceSuggestion, RefreshAgentSessionChangesData, RefreshAgentSessionChangesError, RefreshAgentSessionChangesErrors, RefreshAgentSessionChangesResponse, RefreshAgentSessionChangesResponses, RegisterAgentSessionWorkData, RegisterAgentSessionWorkError, RegisterAgentSessionWorkErrors, RegisterAgentSessionWorkResponse, RegisterAgentSessionWorkResponses, RemoveQueuedActionData, RemoveQueuedActionError, RemoveQueuedActionErrors, RemoveQueuedActionResponse, RemoveQueuedActionResponses, RenameAgentSessionData, RenameAgentSessionError, RenameAgentSessionErrors, RenameAgentSessionRequest, RenameAgentSessionResponse, RenameAgentSessionResponses, ReportAgentSessionAppConnectedData, ReportAgentSessionAppConnectedError, ReportAgentSessionAppConnectedErrors, ReportAgentSessionAppConnectedResponses, RetryAgentConversationTurnData, RetryAgentConversationTurnErrors, RetryAgentConversationTurnRequest, RetryAgentConversationTurnResponse, RetryAgentConversationTurnResponses, ReviewDecision, ReviewDecisionContext, ReviewId, ReviewRecord, Root, RoutineCause, SandboxSize, SandboxSizeBody, SearchConnectedAppToolsData, SearchConnectedAppToolsErrors, SearchConnectedAppToolsResponse, SearchConnectedAppToolsResponses, SearchSuggestions, SearchType, SessionAutoArchiveResponse, SessionBot, SessionPullRequestLink, SessionPullRequestsResponse, SessionStatusDto, SetAgentSessionArchivedData, SetAgentSessionArchivedError, SetAgentSessionArchivedErrors, SetAgentSessionArchivedRequest, SetAgentSessionArchivedResponse, SetAgentSessionArchivedResponses, SharePermissionV2, StartFreshAgentConversationData, StartFreshAgentConversationErrors, StartFreshAgentConversationRequest, StartFreshAgentConversationResponse, StartFreshAgentConversationResponses, SteerQueuedActionData, SteerQueuedActionError, SteerQueuedActionErrors, SteerQueuedActionResponse, SteerQueuedActionResponses, TaskSearchSuggestions, TaskSuggestions, ToolActor, ToolApprovalAnswerDto, ToolApprovalStatusDto, TriggerOrigin, UnlinkAgentSessionPullRequestData, UnlinkAgentSessionPullRequestError, UnlinkAgentSessionPullRequestErrors, UnlinkAgentSessionPullRequestResponse, UnlinkAgentSessionPullRequestResponses, UnregisterAgentSessionWorkData, UnregisterAgentSessionWorkError, UnregisterAgentSessionWorkErrors, UnregisterAgentSessionWorkResponse, UnregisterAgentSessionWorkResponses, UpdateAgentSessionPermissionsData, UpdateAgentSessionPermissionsError, UpdateAgentSessionPermissionsErrors, UpdateAgentSessionPermissionsResponse, UpdateAgentSessionPermissionsResponses, UpdateChannelSharePermission, UpdateOperation, UpdateSharePermissionRequestV2, WarmAgentSessionHandlerData, WarmAgentSessionHandlerResponse, WarmAgentSessionHandlerResponses, WarmAgentSessionRequest, WarmAgentSessionResponse, WeekdayCode, WithAgentSessionId, WorkRegistrationResponse } from './types.gen';diff --git a/packages/sdk/generated/agent-harness/types.gen.ts b/packages/sdk/generated/agent-harness/types.gen.tsindex 1f11592494..68f6dbd5a1 100644--- a/packages/sdk/generated/agent-harness/types.gen.ts+++ b/packages/sdk/generated/agent-harness/types.gen.ts@@ -111,6 +111,24 @@ export type AgentActivityPage = {nextCursor?: null | AgentActivityCursor;};+/**+ * An agent acting for a person.+ */+export type AgentActor = {+ /**+ * The agent.+ */+ bot: BotId;+ /**+ * Where the agent's own work came from.+ */+ lineage: Lineage;+ /**+ * The person it acts for.+ */+ on_behalf_of: MacroUserIdStr;+};+/*** Type-specific state for one agent session setting.*/@@ -651,6 +669,11 @@ export type AgentSessionResponse = {* User-facing session name.*/name: string;+ /**+ * What opened the session: who or what started it, and what it is about.+ * `unknown` when nothing recorded it.+ */+ origin?: TriggerOrigin;/*** The exact message that invoked the bot, if any.*/@@ -881,6 +904,19 @@ export type CallSearchSuggestions = {status?: string | null;};+/**+ * Who did something that opened a session.+ */+export type Caller = {+ type: 'person';+ /**+ * Who.+ */+ user: MacroUserIdStr;+} | (AgentActor & {+ type: 'agent';+});+/*** Harness names accepted by the capability-discovery endpoint.*/@@ -1903,6 +1939,23 @@ export type IntentScore = {score: number;};+/**+ * Where an acting agent's work came from.+ */+export type Lineage = {+ /**+ * The first non-agent cause of its work.+ */+ root: Root;+ /**+ * The acting session.+ */+ session: string;+ type: 'session';+} | {+ type: 'unattributed';+};+/*** Defines who can access an item through its share link.*/@@ -1968,6 +2021,8 @@ export type LogFrameDto = {direction: LogDirectionDto;};+export type MacroUserIdStr = string;+/*** The entity whose permissions and lifecycle govern a message.*/@@ -2479,6 +2534,39 @@ export type ReviewRecord = {updatedAt: number;};+/**+ * The first non-agent cause. An agent cannot be one, so a chain always ends+ * at a person or a routine.+ */+export type Root = {+ type: 'person';+ /**+ * Who.+ */+ user: MacroUserIdStr;+} | {+ /**+ * The routine.+ */+ routine: string;+ type: 'routine';+};++/**+ * What made a routine fire.+ */+export type RoutineCause = {+ type: 'scheduled';+} | {+ type: 'manual';+} | {+ /**+ * The event.+ */+ event_id: string;+ type: 'event';+};+/*** Named compute tier for a managed sandbox.*@@ -2719,6 +2807,79 @@ export type ToolApprovalAnswerDto = 'approve' | 'approve_and_remember' | 'deny'*/export type ToolApprovalStatusDto = 'pending' | 'approved' | 'denied' | 'cancelled' | 'expired';+/**+ * What opened a session.+ */+export type TriggerOrigin = {+ /**+ * Who posted it.+ */+ by: Caller;+ /**+ * The message.+ */+ message_id: string;+ origin: 'mentioned';+} | {+ /**+ * Who wrote.+ */+ by: MacroUserIdStr;+ /**+ * The message.+ */+ message_id: string;+ origin: 'conversation';+} | {+ /**+ * Who assigned it.+ */+ by: Caller;+ origin: 'task_assigned';+ /**+ * The task.+ */+ task: string;+} | {+ /**+ * Who added the task to the project.+ */+ by: Caller;+ origin: 'project_inherited';+ /**+ * The project.+ */+ project: string;+ /**+ * The task.+ */+ task: string;+} | {+ /**+ * Who opened it.+ */+ by: MacroUserIdStr;+ origin: 'requested';+} | {+ /**+ * The user whose authority the work runs under.+ */+ on_behalf_of: MacroUserIdStr;+ origin: 'dispatched';+} | {+ /**+ * What made it fire.+ */+ firing: RoutineCause;+ origin: 'routine';+ /**+ * The routine.+ */+ routine: string;+} | {+ origin: 'unknown';+};+export type UpdateChannelSharePermission = {accessLevel?: null | AccessLevel;/**diff --git a/packages/sdk/specs/agent-harness.json b/packages/sdk/specs/agent-harness.jsonindex d8e4ff473a..5922091edb 100644--- a/packages/sdk/specs/agent-harness.json+++ b/packages/sdk/specs/agent-harness.json@@ -3893,6 +3893,25 @@}}},+ "AgentActor": {+ "type": "object",+ "description": "An agent acting for a person.",+ "required": ["bot", "on_behalf_of", "lineage"],+ "properties": {+ "bot": {+ "$ref": "#/components/schemas/BotId",+ "description": "The agent."+ },+ "lineage": {+ "$ref": "#/components/schemas/Lineage",+ "description": "Where the agent's own work came from."+ },+ "on_behalf_of": {+ "$ref": "#/components/schemas/MacroUserIdStr",+ "description": "The person it acts for."+ }+ }+ },"AgentConfigKindDto": {"oneOf": [{@@ -4611,6 +4630,10 @@"type": "string","description": "User-facing session name."},+ "origin": {+ "$ref": "#/components/schemas/TriggerOrigin",+ "description": "What opened the session: who or what started it, and what it is about.\n`unknown` when nothing recorded it."+ },"originatingMessageId": {"type": ["string", "null"],"format": "uuid",@@ -4889,6 +4912,45 @@},"additionalProperties": false},+ "Caller": {+ "oneOf": [+ {+ "type": "object",+ "description": "A person.",+ "required": ["user", "type"],+ "properties": {+ "type": {+ "type": "string",+ "enum": ["person"]+ },+ "user": {+ "$ref": "#/components/schemas/MacroUserIdStr",+ "description": "Who."+ }+ }+ },+ {+ "allOf": [+ {+ "$ref": "#/components/schemas/AgentActor",+ "description": "An agent, which always acts for a person on a path that opens a session."+ },+ {+ "type": "object",+ "required": ["type"],+ "properties": {+ "type": {+ "type": "string",+ "enum": ["agent"]+ }+ }+ }+ ],+ "description": "An agent, which always acts for a person on a path that opens a session."+ }+ ],+ "description": "Who did something that opened a session."+ },"CapabilityHarnessDto": {"type": "string","description": "Harness names accepted by the capability-discovery endpoint.",@@ -6273,6 +6335,42 @@}}},+ "Lineage": {+ "oneOf": [+ {+ "type": "object",+ "description": "The session the agent acted from, and so where the chain started.",+ "required": ["session", "root", "type"],+ "properties": {+ "root": {+ "$ref": "#/components/schemas/Root",+ "description": "The first non-agent cause of its work."+ },+ "session": {+ "type": "string",+ "format": "uuid",+ "description": "The acting session."+ },+ "type": {+ "type": "string",+ "enum": ["session"]+ }+ }+ },+ {+ "type": "object",+ "description": "An agent acted, but its session was not captured.",+ "required": ["type"],+ "properties": {+ "type": {+ "type": "string",+ "enum": ["unattributed"]+ }+ }+ }+ ],+ "description": "Where an acting agent's work came from."+ },"LinkShare": {"type": "string","description": "Defines who can access an item through its share link.",@@ -6336,6 +6434,9 @@}}},+ "MacroUserIdStr": {+ "type": "string"+ },"MessageParent": {"oneOf": [{@@ -7097,6 +7198,85 @@],"description": "Full UI record, fetched outside the model context."},+ "Root": {+ "oneOf": [+ {+ "type": "object",+ "description": "A person.",+ "required": ["user", "type"],+ "properties": {+ "type": {+ "type": "string",+ "enum": ["person"]+ },+ "user": {+ "$ref": "#/components/schemas/MacroUserIdStr",+ "description": "Who."+ }+ }+ },+ {+ "type": "object",+ "description": "A routine.",+ "required": ["routine", "type"],+ "properties": {+ "routine": {+ "type": "string",+ "format": "uuid",+ "description": "The routine."+ },+ "type": {+ "type": "string",+ "enum": ["routine"]+ }+ }+ }+ ],+ "description": "The first non-agent cause. An agent cannot be one, so a chain always ends\nat a person or a routine."+ },+ "RoutineCause": {+ "oneOf": [+ {+ "type": "object",+ "description": "One of its schedules came due.",+ "required": ["type"],+ "properties": {+ "type": {+ "type": "string",+ "enum": ["scheduled"]+ }+ }+ },+ {+ "type": "object",+ "description": "Its owner started it by hand.",+ "required": ["type"],+ "properties": {+ "type": {+ "type": "string",+ "enum": ["manual"]+ }+ }+ },+ {+ "type": "object",+ "description": "An event it watches happened.",+ "required": ["event_id", "type"],+ "properties": {+ "event_id": {+ "type": "string",+ "format": "uuid",+ "description": "The event."+ },+ "type": {+ "type": "string",+ "enum": ["event"]+ }+ }+ }+ ],+ "description": "What made a routine fire."+ },"SandboxSize": {"type": "string","description": "Named compute tier for a managed sandbox.\n\nThe API and database store the name. CPU, RAM, and disk live in\n`crates/agent_harness/sandbox_sizes.json`.",@@ -7589,6 +7769,155 @@"description": "Where a held tool call stands once answered.","enum": ["pending", "approved", "denied", "cancelled", "expired"]},+ "TriggerOrigin": {+ "oneOf": [+ {+ "type": "object",+ "description": "A message mentioned the agent.",+ "required": ["by", "message_id", "origin"],+ "properties": {+ "by": {+ "$ref": "#/components/schemas/Caller",+ "description": "Who posted it."+ },+ "message_id": {+ "type": "string",+ "format": "uuid",+ "description": "The message."+ },+ "origin": {+ "type": "string",+ "enum": ["mentioned"]+ }+ }+ },+ {+ "type": "object",+ "description": "A person wrote in their private conversation with the agent.",+ "required": ["by", "message_id", "origin"],+ "properties": {+ "by": {+ "$ref": "#/components/schemas/MacroUserIdStr",+ "description": "Who wrote."+ },+ "message_id": {+ "type": "string",+ "format": "uuid",+ "description": "The message."+ },+ "origin": {+ "type": "string",+ "enum": ["conversation"]+ }+ }+ },+ {+ "type": "object",+ "description": "The agent was added to a task's assignees.",+ "required": ["by", "task", "origin"],+ "properties": {+ "by": {+ "$ref": "#/components/schemas/Caller",+ "description": "Who assigned it."+ },+ "origin": {+ "type": "string",+ "enum": ["task_assigned"]+ },+ "task": {+ "type": "string",+ "description": "The task."+ }+ }+ },+ {+ "type": "object",+ "description": "The task joined a project, and inherited the project's agents.",+ "required": ["by", "task", "project", "origin"],+ "properties": {+ "by": {+ "$ref": "#/components/schemas/Caller",+ "description": "Who added the task to the project."+ },+ "origin": {+ "type": "string",+ "enum": ["project_inherited"]+ },+ "project": {+ "type": "string",+ "format": "uuid",+ "description": "The project."+ },+ "task": {+ "type": "string",+ "description": "The task."+ }+ }+ },+ {+ "type": "object",+ "description": "A person opened the session directly, from the composer.",+ "required": ["by", "origin"],+ "properties": {+ "by": {+ "$ref": "#/components/schemas/MacroUserIdStr",+ "description": "Who opened it."+ },+ "origin": {+ "type": "string",+ "enum": ["requested"]+ }+ }+ },+ {+ "type": "object",+ "description": "A tool handed the agent work. The tool knows only whose authority it\nruns under, not which agent called it.",+ "required": ["on_behalf_of", "origin"],+ "properties": {+ "on_behalf_of": {+ "$ref": "#/components/schemas/MacroUserIdStr",+ "description": "The user whose authority the work runs under."+ },+ "origin": {+ "type": "string",+ "enum": ["dispatched"]+ }+ }+ },+ {+ "type": "object",+ "description": "A routine fired. Its owner owns the session, so the owner is not repeated.",+ "required": ["routine", "firing", "origin"],+ "properties": {+ "firing": {+ "$ref": "#/components/schemas/RoutineCause",+ "description": "What made it fire."+ },+ "origin": {+ "type": "string",+ "enum": ["routine"]+ },+ "routine": {+ "type": "string",+ "format": "uuid",+ "description": "The routine."+ }+ }+ },+ {+ "type": "object",+ "description": "Not known: an unclaimed warm session, a producer that predates this\nrecord, or a kind this build does not know.",+ "required": ["origin"],+ "properties": {+ "origin": {+ "type": "string",+ "enum": ["unknown"]+ }+ }+ }+ ],+ "description": "What opened a session."+ },"UpdateChannelSharePermission": {"type": "object","required": ["operation", "channelId"],diff --git a/packages/sdk/src/entities/agent-sessions/agent-session.ts b/packages/sdk/src/entities/agent-sessions/agent-session.tsindex 490d8f6294..e97707c1d2 100644--- a/packages/sdk/src/entities/agent-sessions/agent-session.ts+++ b/packages/sdk/src/entities/agent-sessions/agent-session.ts@@ -31,6 +31,7 @@ import {sessionActivity,} from './activity';import { CodeExecution } from './code-execution';+import { type SessionOrigin, sessionOrigin } from './origin';import { QueuedAction } from './queued-action';import { type CreateReviewOptions, SessionReview } from './review';import { ToolApproval } from './tool-approval';@@ -278,6 +279,19 @@ export class AgentSession extends MacroEntity<AgentSessionResponse> {/** The session's user-facing display name. */readonly name = this.field('name');+ /**+ * What opened the session: who or what started it, and what it is about.+ * Readable by anyone who can view the session, including other agents.+ */+ async origin(): Promise<SessionOrigin> {+ const detail = await this.detail.get();+ return sessionOrigin(+ this.client,+ detail.origin ?? { origin: 'unknown' },+ detail.threadChannelId ?? undefined,+ );+ }+/*** Who archived the session, making it read-only: `'user'`,* `'pull_request_merged'` or `'runtime_closed'`. `undefined` while it is notdiff --git a/packages/sdk/src/entities/agent-sessions/origin.ts b/packages/sdk/src/entities/agent-sessions/origin.tsnew file mode 100644index 0000000000..a8cad5f17a--- /dev/null+++ b/packages/sdk/src/entities/agent-sessions/origin.ts@@ -0,0 +1,171 @@+import type { TriggerOrigin } from '../../../generated/agent-harness/types.gen';+import type { MacroClient } from '../../utils/client';+import { Agent } from '../agents/agent';+import { Message } from '../channels/message';+import { Initiative } from '../initiatives/initiative';+import { Routine } from '../routines/routine';+import { Task } from '../tasks/task';+import { User } from '../users/user';+import { AgentSession } from './agent-session';++/** The first non-agent cause of an agent's work. */+export type SessionOriginRoot =+ | { type: 'person'; user: User }+ | { type: 'routine'; routine: Routine };++/** Where an acting agent's own work came from. */+export type SessionOriginLineage =+ | {+ type: 'session';+ /** The session the agent acted from. */+ session: AgentSession;+ /** Where the chain of agents started. */+ root: SessionOriginRoot;+ }+ /** An agent acted, but its session was not captured. */+ | { type: 'unattributed' };++/** Who did something that opened a session. */+export type SessionOriginCaller =+ | { type: 'person'; user: User }+ | {+ type: 'agent';+ /** The agent that acted. */+ agent: Agent;+ /** The person it acted for. */+ onBehalfOf: User;+ /** Where the agent's own work came from. */+ lineage: SessionOriginLineage;+ };++/** What opened a session. */+export type SessionOrigin =+ /** A message mentioned the agent. `message` is set for channel messages. */+ | { kind: 'mentioned'; by: SessionOriginCaller; message?: Message }+ /** A person wrote in their private conversation with the agent. */+ | { kind: 'conversation'; by: User; message?: Message }+ /** The agent was added to a task's assignees. */+ | { kind: 'task_assigned'; by: SessionOriginCaller; task: Task }+ /** The task joined a project, and inherited the project's agents. */+ | {+ kind: 'project_inherited';+ by: SessionOriginCaller;+ task: Task;+ project: Initiative;+ }+ /** A person opened the session directly, from the composer. */+ | { kind: 'requested'; by: User }+ /** A tool handed the agent work, under this user's authority. */+ | { kind: 'dispatched'; onBehalfOf: User }+ /** A routine fired. */+ | {+ kind: 'routine';+ routine: Routine;+ firing: 'scheduled' | 'manual' | 'event';+ }+ /** Nothing recorded it: an older session, or an unclaimed warm one. */+ | { kind: 'unknown' };++type RawCaller = Extract<TriggerOrigin, { origin: 'mentioned' }>['by'];++type RawLineage = Extract<RawCaller, { type: 'agent' }>['lineage'];++function originLineage(+ client: MacroClient,+ lineage: RawLineage,+): SessionOriginLineage {+ if (lineage.type === 'unattributed') {+ return { type: 'unattributed' };+ }++ return {+ type: 'session',+ session: AgentSession.byId(client, lineage.session),+ root:+ lineage.root.type === 'person'+ ? { type: 'person', user: User.byId(client, lineage.root.user) }+ : {+ type: 'routine',+ routine: Routine.byId(client, lineage.root.routine),+ },+ };+}++function originCaller(+ client: MacroClient,+ caller: RawCaller,+): SessionOriginCaller {+ if (caller.type === 'person') {+ return { type: 'person', user: User.byId(client, caller.user) };+ }++ return {+ type: 'agent',+ agent: Agent.byId(client, caller.bot),+ onBehalfOf: User.byId(client, caller.on_behalf_of),+ lineage: originLineage(client, caller.lineage),+ };+}++/**+ * A session's origin as handles. A message handle needs its channel, which is+ * the session's own thread channel; other parents leave `message` unset.+ */+export function sessionOrigin(+ client: MacroClient,+ origin: TriggerOrigin,+ channelId: string | undefined,+): SessionOrigin {+ const message = (id: string) =>+ channelId ? Message.byId(client, channelId, id) : undefined;++ switch (origin.origin) {+ case 'mentioned':+ return {+ kind: 'mentioned',+ by: originCaller(client, origin.by),+ message: message(origin.message_id),+ };++ case 'conversation':+ return {+ kind: 'conversation',+ by: User.byId(client, origin.by),+ message: message(origin.message_id),+ };++ case 'task_assigned':+ return {+ kind: 'task_assigned',+ by: originCaller(client, origin.by),+ task: Task.byId(client, origin.task),+ };++ case 'project_inherited':+ return {+ kind: 'project_inherited',+ by: originCaller(client, origin.by),+ task: Task.byId(client, origin.task),+ project: Initiative.byId(client, origin.project),+ };++ case 'requested':+ return { kind: 'requested', by: User.byId(client, origin.by) };++ case 'dispatched':+ return {+ kind: 'dispatched',+ onBehalfOf: User.byId(client, origin.on_behalf_of),+ };++ case 'routine':+ return {+ kind: 'routine',+ routine: Routine.byId(client, origin.routine),+ firing: origin.firing.type,+ };++ case 'unknown':+ return { kind: 'unknown' };+ }+}diff --git a/packages/sdk/src/macro.ts b/packages/sdk/src/macro.tsindex 70c98d98e2..619e724a9a 100644--- a/packages/sdk/src/macro.ts+++ b/packages/sdk/src/macro.ts@@ -300,6 +300,12 @@ export {AgentConversation,ConversationTurn,} from './entities/agent-sessions/conversation';+export type {+ SessionOrigin,+ SessionOriginCaller,+ SessionOriginLineage,+ SessionOriginRoot,+} from './entities/agent-sessions/origin';export type {CreateReviewOptions,ReviewCalendarDraft,diff --git a/packages/sdk/tests/agent-session-origin.test.ts b/packages/sdk/tests/agent-session-origin.test.tsnew file mode 100644index 0000000000..d4e436b497--- /dev/null+++ b/packages/sdk/tests/agent-session-origin.test.ts@@ -0,0 +1,81 @@+import { describe, expect, test } from 'bun:test';+import { sessionOrigin } from '../src/entities/agent-sessions/origin';+import type { MacroClient } from '../src/utils/client';++// Handles are lazy, so mapping never touches the network.+const client = {} as MacroClient;++const user = 'macro|[email protected]';+const bot = '01a00000-0000-7000-8000-0000000000b7';+const routine = '01a00000-0000-7000-8000-00000000000c';+const channel = '01a00000-0000-7000-8000-000000000001';++describe('sessionOrigin', () => {+ test('a task an agent assigned traces back to the routine behind it', () => {+ const origin = sessionOrigin(+ client,+ {+ origin: 'task_assigned',+ task: 'task-1',+ by: {+ type: 'agent',+ bot,+ on_behalf_of: user,+ lineage: {+ type: 'session',+ session: '01a00000-0000-7000-8000-00000000000a',+ root: { type: 'routine', routine },+ },+ },+ },+ undefined,+ );++ if (origin.kind !== 'task_assigned' || origin.by.type !== 'agent') {+ throw new Error('expected an agent task assignment');+ }+ expect(origin.task.id).toBe('task-1');+ expect(origin.by.agent.id).toBe(bot);+ if (+ origin.by.lineage.type !== 'session' ||+ origin.by.lineage.root.type !== 'routine'+ ) {+ throw new Error('expected a known lineage');+ }+ expect(origin.by.lineage.root.routine.id).toBe(routine);+ });++ test('a mention has a message handle only in a channel', () => {+ const raw = {+ origin: 'mentioned',+ message_id: '01a00000-0000-7000-8000-000000000003',+ by: { type: 'person', user },+ } as const;++ const inChannel = sessionOrigin(client, raw, channel);+ const elsewhere = sessionOrigin(client, raw, undefined);++ expect(inChannel).toMatchObject({ kind: 'mentioned' });+ expect(inChannel.kind === 'mentioned' && inChannel.message?.id).toBe(+ raw.message_id,+ );+ expect(elsewhere.kind === 'mentioned' && elsewhere.message).toBeUndefined();+ });++ test('a routine reports what fired it', () => {+ const origin = sessionOrigin(+ client,+ {+ origin: 'routine',+ routine,+ firing: {+ type: 'event',+ event_id: '01a00000-0000-7000-8000-00000000000e',+ },+ },+ undefined,+ );++ expect(origin).toMatchObject({ kind: 'routine', firing: 'event' });+ });+});diff --git a/services/agent_harness_service/src/external_session_requests.rs b/services/agent_harness_service/src/external_session_requests.rsindex 1827548d12..e390d3695e 100644--- a/services/agent_harness_service/src/external_session_requests.rs+++ b/services/agent_harness_service/src/external_session_requests.rs@@ -49,6 +49,7 @@ whererepo_url: request.repo_url,session_id,owner: request.owner.as_ref().to_owned(),+ origin: request.origin,// The requester's prompt follows through the session's control// endpoint, from the app; nothing composes it with this event.context: None,diff --git a/services/search_processing_service/src/inbound/kafka_consumer/test.rs b/services/search_processing_service/src/inbound/kafka_consumer/test.rsindex 9327ca1c56..761a4a2a18 100644--- a/services/search_processing_service/src/inbound/kafka_consumer/test.rs+++ b/services/search_processing_service/src/inbound/kafka_consumer/test.rs@@ -1257,6 +1257,7 @@ fn property_event_cases() -> Vec<(PropertyTopicEvent, PropertyEventDescription<'),(PropertyTopicEvent::EntityPropertyUpdated(EntityPropertyUpdatedMetadata {+ inherited_from_project: None,entity_property_id: ENTITY_PROPERTY_ID,entity_id: PROPERTY_ENTITY_ID.to_string(),entity_type: EntityType::Document,