Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(agent): gate permission bypass and unify pending interactions (#6194)

Wolf Mermelstein72d621056ee0
diff --git a/.github/workflows/web-app-check-main.yml b/.github/workflows/web-app-check-main.yml
index 9b00519e24..b19980880c 100644
--- a/.github/workflows/web-app-check-main.yml
+++ b/.github/workflows/web-app-check-main.yml
@@ -201,7 +201,7 @@ jobs:
- path-check
if: needs.path-check.outputs.should_run == 'true'
name: Build
- runs-on: namespace-profile-linux-small;overrides.cache-tag=web-ci
+ runs-on: namespace-profile-linux-mid;overrides.cache-tag=web-ci
steps:
- name: Checkout Repo
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10
diff --git a/.sqlx/query-0c9e740da45c30942a9b4dd3806afb6031437c940e2f60cc4231f8707daa3399.json b/.sqlx/query-0c9e740da45c30942a9b4dd3806afb6031437c940e2f60cc4231f8707daa3399.json
new file mode 100644
index 0000000000..a0691aed52
--- /dev/null
+++ b/.sqlx/query-0c9e740da45c30942a9b4dd3806afb6031437c940e2f60cc4231f8707daa3399.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO bots (id, kind, owner_user_id, name, handle, has_agent)\n VALUES ($1, 'owned', $2, 'Bound agent', $3, true)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "0c9e740da45c30942a9b4dd3806afb6031437c940e2f60cc4231f8707daa3399"
+}
diff --git a/.sqlx/query-11eac3a887fa3990adcebdef936eb7ab02937cf53e6003ec8000e86aeae52e68.json b/.sqlx/query-11eac3a887fa3990adcebdef936eb7ab02937cf53e6003ec8000e86aeae52e68.json
new file mode 100644
index 0000000000..ec147e42e9
--- /dev/null
+++ b/.sqlx/query-11eac3a887fa3990adcebdef936eb7ab02937cf53e6003ec8000e86aeae52e68.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO team (id, name, owner_id)\n VALUES ($1, $2, $3)\n ON CONFLICT (id) DO NOTHING\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "11eac3a887fa3990adcebdef936eb7ab02937cf53e6003ec8000e86aeae52e68"
+}
diff --git a/.sqlx/query-12f64bb05648a7305e5bdf0f23f07cd0e52e7b39b61d4b6d6dbcf055cff69cde.json b/.sqlx/query-12f64bb05648a7305e5bdf0f23f07cd0e52e7b39b61d4b6d6dbcf055cff69cde.json
new file mode 100644
index 0000000000..9e44979279
--- /dev/null
+++ b/.sqlx/query-12f64bb05648a7305e5bdf0f23f07cd0e52e7b39b61d4b6d6dbcf055cff69cde.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO harnesses (id, name, owner_user_id, created_by)\n VALUES ($1, 'theirs', $2, $2)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "12f64bb05648a7305e5bdf0f23f07cd0e52e7b39b61d4b6d6dbcf055cff69cde"
+}
diff --git a/.sqlx/query-239210ccb8f59955dbfb234bdb4d0ce122a6b34ddd6885bc17589e0d38f88da1.json b/.sqlx/query-239210ccb8f59955dbfb234bdb4d0ce122a6b34ddd6885bc17589e0d38f88da1.json
new file mode 100644
index 0000000000..3a6c3a6c26
--- /dev/null
+++ b/.sqlx/query-239210ccb8f59955dbfb234bdb4d0ce122a6b34ddd6885bc17589e0d38f88da1.json
@@ -0,0 +1,20 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT count(*) AS \"count!\" FROM harnesses",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "count!",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "239210ccb8f59955dbfb234bdb4d0ce122a6b34ddd6885bc17589e0d38f88da1"
+}
diff --git a/.sqlx/query-29b0f9fb4913bba3bc7960de0f9cb67f3c7c9a9df6d67fb41a4ba9834d7a330f.json b/.sqlx/query-29b0f9fb4913bba3bc7960de0f9cb67f3c7c9a9df6d67fb41a4ba9834d7a330f.json
new file mode 100644
index 0000000000..1b36b3e553
--- /dev/null
+++ b/.sqlx/query-29b0f9fb4913bba3bc7960de0f9cb67f3c7c9a9df6d67fb41a4ba9834d7a330f.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO agent_session (id, owner_id, bot_id, model, harness, workspace)\n VALUES ($1, $2, $3, 'default', 'in-memory', '/workspace')\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "29b0f9fb4913bba3bc7960de0f9cb67f3c7c9a9df6d67fb41a4ba9834d7a330f"
+}
diff --git a/.sqlx/query-2a71491350e271cdae98edcab6314abc10ffdf95660b452bb67c3c9ada3e98b1.json b/.sqlx/query-2a71491350e271cdae98edcab6314abc10ffdf95660b452bb67c3c9ada3e98b1.json
new file mode 100644
index 0000000000..cae974581e
--- /dev/null
+++ b/.sqlx/query-2a71491350e271cdae98edcab6314abc10ffdf95660b452bb67c3c9ada3e98b1.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO agent_configs (bot_id, instructions, harness, default_model, channel_scope, harness_id)\n VALUES ($1, 'prompt', 'macrod', 'default', 'all', $2)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "2a71491350e271cdae98edcab6314abc10ffdf95660b452bb67c3c9ada3e98b1"
+}
diff --git a/.sqlx/query-308407c450a391bd26c2b23bd4b03dca0596ba14972654d7dd2178f47cd4e1dc.json b/.sqlx/query-308407c450a391bd26c2b23bd4b03dca0596ba14972654d7dd2178f47cd4e1dc.json
deleted file mode 100644
index 7952ce2af8..0000000000
--- a/.sqlx/query-308407c450a391bd26c2b23bd4b03dca0596ba14972654d7dd2178f47cd4e1dc.json
+++ /dev/null
@@ -1,28 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT owner_user_id, team_id\n FROM harnesses\n WHERE id = $1 AND deleted_at IS NULL\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "owner_user_id",
- "type_info": "Text"
- },
- {
- "ordinal": 1,
- "name": "team_id",
- "type_info": "Uuid"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid"
- ]
- },
- "nullable": [
- true,
- true
- ]
- },
- "hash": "308407c450a391bd26c2b23bd4b03dca0596ba14972654d7dd2178f47cd4e1dc"
-}
diff --git a/.sqlx/query-3401326e36f2eed91e6ea93bdf8d9f06b2e1d1227a4a8853b42a9ca56176e501.json b/.sqlx/query-3401326e36f2eed91e6ea93bdf8d9f06b2e1d1227a4a8853b42a9ca56176e501.json
new file mode 100644
index 0000000000..85cb1908d0
--- /dev/null
+++ b/.sqlx/query-3401326e36f2eed91e6ea93bdf8d9f06b2e1d1227a4a8853b42a9ca56176e501.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT COUNT(*) AS \"count!\" FROM agent_mcp_servers WHERE bot_id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "count!",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "3401326e36f2eed91e6ea93bdf8d9f06b2e1d1227a4a8853b42a9ca56176e501"
+}
diff --git a/.sqlx/query-3b2dbc5b0affbcf53cfe76fe5210b7e4d96dad61a84d4a87dced9d2f66dc6ff1.json b/.sqlx/query-3b2dbc5b0affbcf53cfe76fe5210b7e4d96dad61a84d4a87dced9d2f66dc6ff1.json
new file mode 100644
index 0000000000..53c3c181dc
--- /dev/null
+++ b/.sqlx/query-3b2dbc5b0affbcf53cfe76fe5210b7e4d96dad61a84d4a87dced9d2f66dc6ff1.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO team (id, name, owner_id) VALUES ($1, 'Team', $2)",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "3b2dbc5b0affbcf53cfe76fe5210b7e4d96dad61a84d4a87dced9d2f66dc6ff1"
+}
diff --git a/.sqlx/query-469a24bfaeb8f3309345777d3ec06f1c32867c385352bb7a568cc1801c23f9e7.json b/.sqlx/query-469a24bfaeb8f3309345777d3ec06f1c32867c385352bb7a568cc1801c23f9e7.json
new file mode 100644
index 0000000000..3b80b3c28f
--- /dev/null
+++ b/.sqlx/query-469a24bfaeb8f3309345777d3ec06f1c32867c385352bb7a568cc1801c23f9e7.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO agent_configs (bot_id, instructions, harness, default_model, channel_scope)\n VALUES ($1, 'prompt', 'in-memory', 'default', 'all')\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "469a24bfaeb8f3309345777d3ec06f1c32867c385352bb7a568cc1801c23f9e7"
+}
diff --git a/.sqlx/query-48bd4e72b43cd79c1200d1ff0c3449002826f5e7cb51a22311649bea6d35e15e.json b/.sqlx/query-48bd4e72b43cd79c1200d1ff0c3449002826f5e7cb51a22311649bea6d35e15e.json
new file mode 100644
index 0000000000..3634f14323
--- /dev/null
+++ b/.sqlx/query-48bd4e72b43cd79c1200d1ff0c3449002826f5e7cb51a22311649bea6d35e15e.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO macro_user (id, username, email, stripe_customer_id)\n VALUES ($1, $2, $2, $3)\n ON CONFLICT (id) DO NOTHING\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "48bd4e72b43cd79c1200d1ff0c3449002826f5e7cb51a22311649bea6d35e15e"
+}
diff --git a/.sqlx/query-5343d5820d16618ef702cebdd513d324060fb473a5215fc7f86896004238155b.json b/.sqlx/query-5343d5820d16618ef702cebdd513d324060fb473a5215fc7f86896004238155b.json
new file mode 100644
index 0000000000..51dd2b0704
--- /dev/null
+++ b/.sqlx/query-5343d5820d16618ef702cebdd513d324060fb473a5215fc7f86896004238155b.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO bots (id, kind, owner_user_id, name, handle, has_agent)\n VALUES ($1, 'owned', $2, 'Other agent', $3, true)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "5343d5820d16618ef702cebdd513d324060fb473a5215fc7f86896004238155b"
+}
diff --git a/.sqlx/query-9cf0d65adf0369dd4429aac0c7b3a01044286c7ab8b1631f80cd98e87f2ba6f4.json b/.sqlx/query-5ecfe393d57f4756dec2fc92bfafe3ebc37f718d33c1206b90925905d12a7025.json
similarity index 52%
rename from .sqlx/query-9cf0d65adf0369dd4429aac0c7b3a01044286c7ab8b1631f80cd98e87f2ba6f4.json
rename to .sqlx/query-5ecfe393d57f4756dec2fc92bfafe3ebc37f718d33c1206b90925905d12a7025.json
index faa11c557f..e4509bcec5 100644
--- a/.sqlx/query-9cf0d65adf0369dd4429aac0c7b3a01044286c7ab8b1631f80cd98e87f2ba6f4.json
+++ b/.sqlx/query-5ecfe393d57f4756dec2fc92bfafe3ebc37f718d33c1206b90925905d12a7025.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n INSERT INTO harnesses (id, kind, name, owner_user_id, team_id, created_by)\n VALUES ($1, 'macrod', $2, $3, $4, $5)\n ",
+ "query": "\n INSERT INTO harnesses (id, kind, name, owner_user_id, team_id, created_by, allow_permission_bypass)\n VALUES ($1, 'macrod', $2, $3, $4, $5, $6)\n ",
"describe": {
"columns": [],
"parameters": {
@@ -9,10 +9,11 @@
"Text",
"Text",
"Uuid",
- "Text"
+ "Text",
+ "Bool"
]
},
"nullable": []
},
- "hash": "9cf0d65adf0369dd4429aac0c7b3a01044286c7ab8b1631f80cd98e87f2ba6f4"
+ "hash": "5ecfe393d57f4756dec2fc92bfafe3ebc37f718d33c1206b90925905d12a7025"
}
diff --git a/.sqlx/query-69e503e7fd0091707b82bb5d7aeb43405c9b9d47b7d9e82864ac74efb8121106.json b/.sqlx/query-69e503e7fd0091707b82bb5d7aeb43405c9b9d47b7d9e82864ac74efb8121106.json
new file mode 100644
index 0000000000..d21c4ca5fb
--- /dev/null
+++ b/.sqlx/query-69e503e7fd0091707b82bb5d7aeb43405c9b9d47b7d9e82864ac74efb8121106.json
@@ -0,0 +1,19 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO agent_session\n (id, owner_id, bot_id, model, harness, workspace, status, status_event_name,\n created_at, modified_at)\n VALUES ($1, $2, $3, 'default', 'macrod', '/workspace', $4, $5,\n now() - make_interval(mins => $6), now() - make_interval(mins => $6))\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Uuid",
+ "Text",
+ "Text",
+ "Int4"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "69e503e7fd0091707b82bb5d7aeb43405c9b9d47b7d9e82864ac74efb8121106"
+}
diff --git a/.sqlx/query-7502dfa03c80d96fdee36b722b560bf2f8d0d3d70a10983dc2179afdb73d6b4d.json b/.sqlx/query-7502dfa03c80d96fdee36b722b560bf2f8d0d3d70a10983dc2179afdb73d6b4d.json
new file mode 100644
index 0000000000..c62fafadfc
--- /dev/null
+++ b/.sqlx/query-7502dfa03c80d96fdee36b722b560bf2f8d0d3d70a10983dc2179afdb73d6b4d.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO team_user (user_id, team_id, team_role)\n VALUES ($1, $2, $3::text::team_role)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "7502dfa03c80d96fdee36b722b560bf2f8d0d3d70a10983dc2179afdb73d6b4d"
+}
diff --git a/.sqlx/query-76b6889b4bf8178dddbfbaa3bb730a68d95ebd4b775c8fc72534681d6ccb8b15.json b/.sqlx/query-76b6889b4bf8178dddbfbaa3bb730a68d95ebd4b775c8fc72534681d6ccb8b15.json
new file mode 100644
index 0000000000..981b19e811
--- /dev/null
+++ b/.sqlx/query-76b6889b4bf8178dddbfbaa3bb730a68d95ebd4b775c8fc72534681d6ccb8b15.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO bots (id, kind, owner_user_id, name, handle, has_agent)\n VALUES ($1, 'owned', $2, 'Unbound agent', $3, true)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "76b6889b4bf8178dddbfbaa3bb730a68d95ebd4b775c8fc72534681d6ccb8b15"
+}
diff --git a/.sqlx/query-462894fae868528fbf10226edf99171a52bdcd0377f40616c3c304ab6a106f25.json b/.sqlx/query-80b0267d335359969f7b8cf44c87fceb9dbe4f8a0952895191d7d75780551c3d.json
similarity index 71%
rename from .sqlx/query-462894fae868528fbf10226edf99171a52bdcd0377f40616c3c304ab6a106f25.json
rename to .sqlx/query-80b0267d335359969f7b8cf44c87fceb9dbe4f8a0952895191d7d75780551c3d.json
index 704ff32bfb..64f331f069 100644
--- a/.sqlx/query-462894fae868528fbf10226edf99171a52bdcd0377f40616c3c304ab6a106f25.json
+++ b/.sqlx/query-80b0267d335359969f7b8cf44c87fceb9dbe4f8a0952895191d7d75780551c3d.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT code, requested_name, host_info, requested_scope, status, created_at,\n expires_at\n FROM harness_pairing_requests\n WHERE code = $1\n ",
+ "query": "\n SELECT code, requested_name, host_info, requested_scope,\n requested_allow_permission_bypass, status, created_at, expires_at\n FROM harness_pairing_requests\n WHERE code = $1\n ",
"describe": {
"columns": [
{
@@ -25,16 +25,21 @@
},
{
"ordinal": 4,
+ "name": "requested_allow_permission_bypass",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 5,
"name": "status",
"type_info": "Text"
},
{
- "ordinal": 5,
+ "ordinal": 6,
"name": "created_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 6,
+ "ordinal": 7,
"name": "expires_at",
"type_info": "Timestamptz"
}
@@ -49,10 +54,11 @@
false,
true,
true,
+ true,
false,
false,
false
]
},
- "hash": "462894fae868528fbf10226edf99171a52bdcd0377f40616c3c304ab6a106f25"
+ "hash": "80b0267d335359969f7b8cf44c87fceb9dbe4f8a0952895191d7d75780551c3d"
}
diff --git a/.sqlx/query-9143f7be1461b1d18f4ab336cb56a6871f22d84c2dd5dfad378a49903b07fc23.json b/.sqlx/query-9143f7be1461b1d18f4ab336cb56a6871f22d84c2dd5dfad378a49903b07fc23.json
new file mode 100644
index 0000000000..2a0291e1ae
--- /dev/null
+++ b/.sqlx/query-9143f7be1461b1d18f4ab336cb56a6871f22d84c2dd5dfad378a49903b07fc23.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO harnesses (id, name, owner_user_id, created_by)\n VALUES ($1, 'mine', $2, $2)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "9143f7be1461b1d18f4ab336cb56a6871f22d84c2dd5dfad378a49903b07fc23"
+}
diff --git a/.sqlx/query-a1685ed15d4c123c062b9a4d41170336cf5fbac50ad448e1451d4b40a5ba6080.json b/.sqlx/query-916cf37a24e7fca2d72e06cf1bcfd65dcac6ba8f4d33c77b677f56d5b1c14171.json
similarity index 71%
rename from .sqlx/query-a1685ed15d4c123c062b9a4d41170336cf5fbac50ad448e1451d4b40a5ba6080.json
rename to .sqlx/query-916cf37a24e7fca2d72e06cf1bcfd65dcac6ba8f4d33c77b677f56d5b1c14171.json
index 2227387659..356c99eff9 100644
--- a/.sqlx/query-a1685ed15d4c123c062b9a4d41170336cf5fbac50ad448e1451d4b40a5ba6080.json
+++ b/.sqlx/query-916cf37a24e7fca2d72e06cf1bcfd65dcac6ba8f4d33c77b677f56d5b1c14171.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n b.id,\n b.kind,\n b.owner_user_id,\n b.team_id,\n b.name,\n b.handle,\n b.description,\n b.avatar_url,\n b.created_by,\n b.created_at,\n b.updated_at,\n b.deleted_at,\n b.has_agent,\n a.instructions,\n a.harness,\n a.harness_id,\n a.default_model,\n a.channel_scope,\n ARRAY(\n SELECT p.channel_id\n FROM comms_channel_participants p\n WHERE p.user_id = 'bot|' || b.id::text\n AND p.left_at IS NULL\n ORDER BY p.channel_id\n ) AS \"channel_ids!\",\n a.mcp_scope,\n ARRAY(\n SELECT m.app_slug\n FROM agent_mcp_servers m\n WHERE m.bot_id = b.id\n ORDER BY m.app_slug\n ) AS \"mcp_app_slugs!\",\n ARRAY(\n SELECT m.server_name\n FROM agent_mcp_servers m\n WHERE m.bot_id = b.id\n ORDER BY m.app_slug\n ) AS \"mcp_server_names!\"\n FROM bots b\n INNER JOIN agent_configs a ON a.bot_id = b.id\n WHERE b.id = $1\n AND b.kind = 'owned'\n AND b.deleted_at IS NULL\n ",
+ "query": "\n SELECT\n b.id,\n b.kind,\n b.owner_user_id,\n b.team_id,\n b.name,\n b.handle,\n b.description,\n b.avatar_url,\n b.created_by,\n b.created_at,\n b.updated_at,\n b.deleted_at,\n b.has_agent,\n a.instructions,\n a.harness,\n a.harness_id,\n a.default_model,\n a.channel_scope,\n a.auto_accept_permissions,\n ARRAY(\n SELECT p.channel_id\n FROM comms_channel_participants p\n WHERE p.user_id = 'bot|' || b.id::text\n AND p.left_at IS NULL\n ORDER BY p.channel_id\n ) AS \"channel_ids!\",\n a.mcp_scope,\n ARRAY(\n SELECT m.app_slug\n FROM agent_mcp_servers m\n WHERE m.bot_id = b.id\n ORDER BY m.app_slug\n ) AS \"mcp_app_slugs!\",\n ARRAY(\n SELECT m.server_name\n FROM agent_mcp_servers m\n WHERE m.bot_id = b.id\n ORDER BY m.app_slug\n ) AS \"mcp_server_names!\"\n FROM bots b\n INNER JOIN agent_configs a ON a.bot_id = b.id\n WHERE b.id = $1\n AND b.kind = 'owned'\n AND b.deleted_at IS NULL\n ",
"describe": {
"columns": [
{
@@ -95,21 +95,26 @@
},
{
"ordinal": 18,
+ "name": "auto_accept_permissions",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 19,
"name": "channel_ids!",
"type_info": "UuidArray"
},
{
- "ordinal": 19,
+ "ordinal": 20,
"name": "mcp_scope",
"type_info": "Text"
},
{
- "ordinal": 20,
+ "ordinal": 21,
"name": "mcp_app_slugs!",
"type_info": "TextArray"
},
{
- "ordinal": 21,
+ "ordinal": 22,
"name": "mcp_server_names!",
"type_info": "TextArray"
}
@@ -138,11 +143,12 @@
true,
false,
false,
+ true,
null,
false,
null,
null
]
},
- "hash": "a1685ed15d4c123c062b9a4d41170336cf5fbac50ad448e1451d4b40a5ba6080"
+ "hash": "916cf37a24e7fca2d72e06cf1bcfd65dcac6ba8f4d33c77b677f56d5b1c14171"
}
diff --git a/.sqlx/query-f24bd1d4434b2306156cd933271e4854c541d13bf5f3d22da5f366bf4b1a8639.json b/.sqlx/query-9b68777f9537afb7bd85558a48098e7fa715b8ea350de181c3c3c092bdc82a3e.json
similarity index 53%
rename from .sqlx/query-f24bd1d4434b2306156cd933271e4854c541d13bf5f3d22da5f366bf4b1a8639.json
rename to .sqlx/query-9b68777f9537afb7bd85558a48098e7fa715b8ea350de181c3c3c092bdc82a3e.json
index 501b81f4c2..80e8dac052 100644
--- a/.sqlx/query-f24bd1d4434b2306156cd933271e4854c541d13bf5f3d22da5f366bf4b1a8639.json
+++ b/.sqlx/query-9b68777f9537afb7bd85558a48098e7fa715b8ea350de181c3c3c092bdc82a3e.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n INSERT INTO harness_pairing_requests\n (id, code, device_secret_hash, requested_name, host_info, requested_scope,\n expires_at)\n VALUES ($1, $2, $3, $4, $5, $6, $7)\n ON CONFLICT (code) DO NOTHING\n ",
+ "query": "\n INSERT INTO harness_pairing_requests\n (id, code, device_secret_hash, requested_name, host_info, requested_scope,\n expires_at, requested_allow_permission_bypass)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8)\n ON CONFLICT (code) DO NOTHING\n ",
"describe": {
"columns": [],
"parameters": {
@@ -11,10 +11,11 @@
"Text",
"Text",
"Text",
- "Timestamptz"
+ "Timestamptz",
+ "Bool"
]
},
"nullable": []
},
- "hash": "f24bd1d4434b2306156cd933271e4854c541d13bf5f3d22da5f366bf4b1a8639"
+ "hash": "9b68777f9537afb7bd85558a48098e7fa715b8ea350de181c3c3c092bdc82a3e"
}
diff --git a/.sqlx/query-bb5f40af2c31290cf842e508fc7affce72ecaf1ba8b9b5d040cec43ba5c0c153.json b/.sqlx/query-9c0a40ee4c671cdcd35dde8f6ef8278e3fc0a72e3f3ac82759719d660b4e4e5d.json
similarity index 76%
rename from .sqlx/query-bb5f40af2c31290cf842e508fc7affce72ecaf1ba8b9b5d040cec43ba5c0c153.json
rename to .sqlx/query-9c0a40ee4c671cdcd35dde8f6ef8278e3fc0a72e3f3ac82759719d660b4e4e5d.json
index 3613de6046..26b3b367ae 100644
--- a/.sqlx/query-bb5f40af2c31290cf842e508fc7affce72ecaf1ba8b9b5d040cec43ba5c0c153.json
+++ b/.sqlx/query-9c0a40ee4c671cdcd35dde8f6ef8278e3fc0a72e3f3ac82759719d660b4e4e5d.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n id, kind, name, owner_user_id, team_id, created_by,\n created_at, updated_at, last_connected_at, last_disconnected_at\n FROM harnesses\n WHERE id = $1 AND deleted_at IS NULL\n ",
+ "query": "\n SELECT\n id, kind, name, owner_user_id, team_id, created_by, allow_permission_bypass,\n created_at, updated_at, last_connected_at, last_disconnected_at\n FROM harnesses\n WHERE id = $1 AND deleted_at IS NULL\n ",
"describe": {
"columns": [
{
@@ -35,21 +35,26 @@
},
{
"ordinal": 6,
+ "name": "allow_permission_bypass",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 7,
"name": "created_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 7,
+ "ordinal": 8,
"name": "updated_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 8,
+ "ordinal": 9,
"name": "last_connected_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 9,
+ "ordinal": 10,
"name": "last_disconnected_at",
"type_info": "Timestamptz"
}
@@ -68,9 +73,10 @@
false,
false,
false,
+ false,
true,
true
]
},
- "hash": "bb5f40af2c31290cf842e508fc7affce72ecaf1ba8b9b5d040cec43ba5c0c153"
+ "hash": "9c0a40ee4c671cdcd35dde8f6ef8278e3fc0a72e3f3ac82759719d660b4e4e5d"
}
diff --git a/.sqlx/query-5ef0fcf615784b75dbd205d642053f5b565c8d2ae1e86a2ee92f99cc32065c1e.json b/.sqlx/query-9d7e5680d328059293deb5a98a029c347df69b980f1c92a07e07c61ae1fea893.json
similarity index 67%
rename from .sqlx/query-5ef0fcf615784b75dbd205d642053f5b565c8d2ae1e86a2ee92f99cc32065c1e.json
rename to .sqlx/query-9d7e5680d328059293deb5a98a029c347df69b980f1c92a07e07c61ae1fea893.json
index 49fee08730..33bb6038a0 100644
--- a/.sqlx/query-5ef0fcf615784b75dbd205d642053f5b565c8d2ae1e86a2ee92f99cc32065c1e.json
+++ b/.sqlx/query-9d7e5680d328059293deb5a98a029c347df69b980f1c92a07e07c61ae1fea893.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n UPDATE agent_configs\n SET instructions = $2,\n harness = $3,\n harness_id = $4,\n default_model = $5,\n channel_scope = $6,\n mcp_scope = $7,\n updated_at = now()\n WHERE bot_id = $1\n ",
+ "query": "\n UPDATE agent_configs\n SET instructions = $2,\n harness = $3,\n harness_id = $4,\n default_model = $5,\n channel_scope = $6,\n mcp_scope = $7,\n auto_accept_permissions = $8,\n updated_at = now()\n WHERE bot_id = $1\n ",
"describe": {
"columns": [],
"parameters": {
@@ -11,10 +11,11 @@
"Uuid",
"Text",
"Text",
- "Text"
+ "Text",
+ "Bool"
]
},
"nullable": []
},
- "hash": "5ef0fcf615784b75dbd205d642053f5b565c8d2ae1e86a2ee92f99cc32065c1e"
+ "hash": "9d7e5680d328059293deb5a98a029c347df69b980f1c92a07e07c61ae1fea893"
}
diff --git a/.sqlx/query-add9f378c7e48521866ded0797002c33631e171900c9fc99e9c70bfd5e09fb74.json b/.sqlx/query-add9f378c7e48521866ded0797002c33631e171900c9fc99e9c70bfd5e09fb74.json
new file mode 100644
index 0000000000..5b214501bc
--- /dev/null
+++ b/.sqlx/query-add9f378c7e48521866ded0797002c33631e171900c9fc99e9c70bfd5e09fb74.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO harnesses (id, name, team_id, created_by)\n VALUES ($1, 'teams', $2, 'macro|[email protected]')\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "add9f378c7e48521866ded0797002c33631e171900c9fc99e9c70bfd5e09fb74"
+}
diff --git a/.sqlx/query-b4fa2a26ca884a6c8a3613ec44bb8291d5fc75bfea7db794ff58446882afd478.json b/.sqlx/query-b4fa2a26ca884a6c8a3613ec44bb8291d5fc75bfea7db794ff58446882afd478.json
new file mode 100644
index 0000000000..8a3067e67f
--- /dev/null
+++ b/.sqlx/query-b4fa2a26ca884a6c8a3613ec44bb8291d5fc75bfea7db794ff58446882afd478.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO harnesses (id, name, owner_user_id, created_by, last_connected_at)\n VALUES ($1, 'mine', $2, $2, now())\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "b4fa2a26ca884a6c8a3613ec44bb8291d5fc75bfea7db794ff58446882afd478"
+}
diff --git a/.sqlx/query-b61cc43a2ea1c9803fb6f7e68afc9bf2e337396d4d35986aeeaeea28b05d3511.json b/.sqlx/query-b61cc43a2ea1c9803fb6f7e68afc9bf2e337396d4d35986aeeaeea28b05d3511.json
new file mode 100644
index 0000000000..4fad7ecd32
--- /dev/null
+++ b/.sqlx/query-b61cc43a2ea1c9803fb6f7e68afc9bf2e337396d4d35986aeeaeea28b05d3511.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO team_user (user_id, team_id, team_role)\n VALUES ($1, $2, $3::text::team_role)\n ON CONFLICT (user_id, team_id) DO NOTHING\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "b61cc43a2ea1c9803fb6f7e68afc9bf2e337396d4d35986aeeaeea28b05d3511"
+}
diff --git a/.sqlx/query-bee8f14659d58b33c71c06209782294887fab648371d0d56fb488cb4093d0995.json b/.sqlx/query-bee8f14659d58b33c71c06209782294887fab648371d0d56fb488cb4093d0995.json
new file mode 100644
index 0000000000..9d33601efa
--- /dev/null
+++ b/.sqlx/query-bee8f14659d58b33c71c06209782294887fab648371d0d56fb488cb4093d0995.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO comms_channel_participants (channel_id, user_id, role)\n VALUES ($1, $2, 'admin'::comms_participant_role)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "bee8f14659d58b33c71c06209782294887fab648371d0d56fb488cb4093d0995"
+}
diff --git a/.sqlx/query-c5d1372ccabff0625eeac4834753c2e732429b4adb66415106637ea0f214643e.json b/.sqlx/query-c5d1372ccabff0625eeac4834753c2e732429b4adb66415106637ea0f214643e.json
new file mode 100644
index 0000000000..7b6dddeb4e
--- /dev/null
+++ b/.sqlx/query-c5d1372ccabff0625eeac4834753c2e732429b4adb66415106637ea0f214643e.json
@@ -0,0 +1,20 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT count(*) AS \"count!\" FROM harness_tokens",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "count!",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "c5d1372ccabff0625eeac4834753c2e732429b4adb66415106637ea0f214643e"
+}
diff --git a/.sqlx/query-52e3880dea11a6285fa0586f87ddd3e2141389f037166868942708cc8c70999a.json b/.sqlx/query-c8d494bfcec68bbcc3da36ae9e69cedfcb520e8463f03f07f33ef9c5c01c8b7e.json
similarity index 60%
rename from .sqlx/query-52e3880dea11a6285fa0586f87ddd3e2141389f037166868942708cc8c70999a.json
rename to .sqlx/query-c8d494bfcec68bbcc3da36ae9e69cedfcb520e8463f03f07f33ef9c5c01c8b7e.json
index baace6bdcc..36a5a131a9 100644
--- a/.sqlx/query-52e3880dea11a6285fa0586f87ddd3e2141389f037166868942708cc8c70999a.json
+++ b/.sqlx/query-c8d494bfcec68bbcc3da36ae9e69cedfcb520e8463f03f07f33ef9c5c01c8b7e.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n INSERT INTO agent_configs (\n bot_id, instructions, harness, harness_id, default_model, channel_scope, mcp_scope\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7)\n ",
+ "query": "\n INSERT INTO agent_configs (\n bot_id, instructions, harness, harness_id, default_model, channel_scope, mcp_scope, auto_accept_permissions\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8)\n ",
"describe": {
"columns": [],
"parameters": {
@@ -11,10 +11,11 @@
"Uuid",
"Text",
"Text",
- "Text"
+ "Text",
+ "Bool"
]
},
"nullable": []
},
- "hash": "52e3880dea11a6285fa0586f87ddd3e2141389f037166868942708cc8c70999a"
+ "hash": "c8d494bfcec68bbcc3da36ae9e69cedfcb520e8463f03f07f33ef9c5c01c8b7e"
}
diff --git a/.sqlx/query-d0538df2f14368486385a50e250cc59f96e560c7f2b3e52aec9414af02f2b10a.json b/.sqlx/query-d0538df2f14368486385a50e250cc59f96e560c7f2b3e52aec9414af02f2b10a.json
new file mode 100644
index 0000000000..09291f5e50
--- /dev/null
+++ b/.sqlx/query-d0538df2f14368486385a50e250cc59f96e560c7f2b3e52aec9414af02f2b10a.json
@@ -0,0 +1,20 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT count(*) AS \"count!\" FROM harness_tokens WHERE revoked_at IS NULL",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "count!",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "d0538df2f14368486385a50e250cc59f96e560c7f2b3e52aec9414af02f2b10a"
+}
diff --git a/.sqlx/query-ca706ffa9077b59f2cfb7b159c25286e43761bede515094d756ae517cb6d6d75.json b/.sqlx/query-d30ffc9d1a8aabb56674f4a0292176684576a144a1dd05b4e6fed48f4e49e3a9.json
similarity index 68%
rename from .sqlx/query-ca706ffa9077b59f2cfb7b159c25286e43761bede515094d756ae517cb6d6d75.json
rename to .sqlx/query-d30ffc9d1a8aabb56674f4a0292176684576a144a1dd05b4e6fed48f4e49e3a9.json
index df12419592..ad20fc9231 100644
--- a/.sqlx/query-ca706ffa9077b59f2cfb7b159c25286e43761bede515094d756ae517cb6d6d75.json
+++ b/.sqlx/query-d30ffc9d1a8aabb56674f4a0292176684576a144a1dd05b4e6fed48f4e49e3a9.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n id, kind, name, owner_user_id, team_id, created_by,\n created_at, updated_at, last_connected_at, last_disconnected_at\n FROM harnesses\n WHERE deleted_at IS NULL\n AND (\n owner_user_id = $1\n OR team_id IN (SELECT team_id FROM team_user WHERE user_id = $1)\n )\n ORDER BY created_at DESC\n ",
+ "query": "\n SELECT\n id, kind, name, owner_user_id, team_id, created_by, allow_permission_bypass,\n created_at, updated_at, last_connected_at, last_disconnected_at\n FROM harnesses\n WHERE deleted_at IS NULL\n AND (\n owner_user_id = $1\n OR team_id IN (SELECT team_id FROM team_user WHERE user_id = $1)\n )\n ORDER BY created_at DESC\n ",
"describe": {
"columns": [
{
@@ -35,21 +35,26 @@
},
{
"ordinal": 6,
+ "name": "allow_permission_bypass",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 7,
"name": "created_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 7,
+ "ordinal": 8,
"name": "updated_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 8,
+ "ordinal": 9,
"name": "last_connected_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 9,
+ "ordinal": 10,
"name": "last_disconnected_at",
"type_info": "Timestamptz"
}
@@ -68,9 +73,10 @@
false,
false,
false,
+ false,
true,
true
]
},
- "hash": "ca706ffa9077b59f2cfb7b159c25286e43761bede515094d756ae517cb6d6d75"
+ "hash": "d30ffc9d1a8aabb56674f4a0292176684576a144a1dd05b4e6fed48f4e49e3a9"
}
diff --git a/.sqlx/query-53568ca36df771ed291dad0d1edf013b45e322d08e5bb0c3c37b3084f459cdb7.json b/.sqlx/query-d6d285adb63e37c4cfcc6dd5f62caad54402d57221a60e4f690571986383ac4a.json
similarity index 60%
rename from .sqlx/query-53568ca36df771ed291dad0d1edf013b45e322d08e5bb0c3c37b3084f459cdb7.json
rename to .sqlx/query-d6d285adb63e37c4cfcc6dd5f62caad54402d57221a60e4f690571986383ac4a.json
index 7dd8b340bd..b4dc61f8e3 100644
--- a/.sqlx/query-53568ca36df771ed291dad0d1edf013b45e322d08e5bb0c3c37b3084f459cdb7.json
+++ b/.sqlx/query-d6d285adb63e37c4cfcc6dd5f62caad54402d57221a60e4f690571986383ac4a.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n b.id,\n b.kind,\n b.owner_user_id,\n b.team_id,\n b.name,\n b.handle,\n b.description,\n b.avatar_url,\n b.created_by,\n b.created_at,\n b.updated_at,\n b.deleted_at,\n b.has_agent,\n a.instructions,\n a.harness,\n a.harness_id,\n a.default_model,\n a.channel_scope,\n ARRAY(\n SELECT p.channel_id\n FROM comms_channel_participants p\n WHERE p.user_id = 'bot|' || b.id::text\n AND p.left_at IS NULL\n ORDER BY p.channel_id\n ) AS \"channel_ids!\",\n a.mcp_scope,\n ARRAY(\n SELECT m.app_slug\n FROM agent_mcp_servers m\n WHERE m.bot_id = b.id\n ORDER BY m.app_slug\n ) AS \"mcp_app_slugs!\",\n ARRAY(\n SELECT m.server_name\n FROM agent_mcp_servers m\n WHERE m.bot_id = b.id\n ORDER BY m.app_slug\n ) AS \"mcp_server_names!\"\n FROM bots b\n INNER JOIN agent_configs a ON a.bot_id = b.id\n WHERE b.kind = 'owned'\n AND b.deleted_at IS NULL\n AND (\n b.owner_user_id = $1\n OR b.team_id IN (\n SELECT team_id FROM team_user WHERE user_id = $1\n )\n OR (\n a.channel_scope = 'selected'\n AND EXISTS (\n SELECT 1\n FROM comms_channel_participants bot_p\n INNER JOIN comms_channel_participants user_p\n ON user_p.channel_id = bot_p.channel_id\n AND user_p.user_id = $1\n AND user_p.left_at IS NULL\n WHERE bot_p.user_id = 'bot|' || b.id::text\n AND bot_p.left_at IS NULL\n )\n )\n )\n ORDER BY b.created_at ASC, b.id ASC\n ",
+ "query": "\n SELECT\n b.id,\n b.kind,\n b.owner_user_id,\n b.team_id,\n b.name,\n b.handle,\n b.description,\n b.avatar_url,\n b.created_by,\n b.created_at,\n b.updated_at,\n b.deleted_at,\n b.has_agent,\n a.instructions,\n a.harness,\n a.harness_id,\n a.default_model,\n a.channel_scope,\n a.auto_accept_permissions,\n ARRAY(\n SELECT p.channel_id\n FROM comms_channel_participants p\n WHERE p.user_id = 'bot|' || b.id::text\n AND p.left_at IS NULL\n ORDER BY p.channel_id\n ) AS \"channel_ids!\",\n a.mcp_scope,\n ARRAY(\n SELECT m.app_slug\n FROM agent_mcp_servers m\n WHERE m.bot_id = b.id\n ORDER BY m.app_slug\n ) AS \"mcp_app_slugs!\",\n ARRAY(\n SELECT m.server_name\n FROM agent_mcp_servers m\n WHERE m.bot_id = b.id\n ORDER BY m.app_slug\n ) AS \"mcp_server_names!\"\n FROM bots b\n INNER JOIN agent_configs a ON a.bot_id = b.id\n WHERE b.kind = 'owned'\n AND b.deleted_at IS NULL\n AND (\n b.owner_user_id = $1\n OR b.team_id IN (\n SELECT team_id FROM team_user WHERE user_id = $1\n )\n OR (\n a.channel_scope = 'selected'\n AND EXISTS (\n SELECT 1\n FROM comms_channel_participants bot_p\n INNER JOIN comms_channel_participants user_p\n ON user_p.channel_id = bot_p.channel_id\n AND user_p.user_id = $1\n AND user_p.left_at IS NULL\n WHERE bot_p.user_id = 'bot|' || b.id::text\n AND bot_p.left_at IS NULL\n )\n )\n )\n ORDER BY b.created_at ASC, b.id ASC\n ",
"describe": {
"columns": [
{
@@ -95,21 +95,26 @@
},
{
"ordinal": 18,
+ "name": "auto_accept_permissions",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 19,
"name": "channel_ids!",
"type_info": "UuidArray"
},
{
- "ordinal": 19,
+ "ordinal": 20,
"name": "mcp_scope",
"type_info": "Text"
},
{
- "ordinal": 20,
+ "ordinal": 21,
"name": "mcp_app_slugs!",
"type_info": "TextArray"
},
{
- "ordinal": 21,
+ "ordinal": 22,
"name": "mcp_server_names!",
"type_info": "TextArray"
}
@@ -138,11 +143,12 @@
true,
false,
false,
+ true,
null,
false,
null,
null
]
},
- "hash": "53568ca36df771ed291dad0d1edf013b45e322d08e5bb0c3c37b3084f459cdb7"
+ "hash": "d6d285adb63e37c4cfcc6dd5f62caad54402d57221a60e4f690571986383ac4a"
}
diff --git a/.sqlx/query-daa0bc442d41e913c848192b36d41aebaebab9284b4a3e5f01c28259003653af.json b/.sqlx/query-daa0bc442d41e913c848192b36d41aebaebab9284b4a3e5f01c28259003653af.json
new file mode 100644
index 0000000000..0a709b4a62
--- /dev/null
+++ b/.sqlx/query-daa0bc442d41e913c848192b36d41aebaebab9284b4a3e5f01c28259003653af.json
@@ -0,0 +1,12 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE harnesses SET last_disconnected_at = now() + interval '1 second'",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": []
+ },
+ "hash": "daa0bc442d41e913c848192b36d41aebaebab9284b4a3e5f01c28259003653af"
+}
diff --git a/.sqlx/query-e276e53d1b162dc479efe8062a1ac365c3400b7c47f5975e1dc8649feb514ed2.json b/.sqlx/query-e276e53d1b162dc479efe8062a1ac365c3400b7c47f5975e1dc8649feb514ed2.json
new file mode 100644
index 0000000000..9330bbede7
--- /dev/null
+++ b/.sqlx/query-e276e53d1b162dc479efe8062a1ac365c3400b7c47f5975e1dc8649feb514ed2.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO macro_user (id, username, email, stripe_customer_id)\n VALUES ($1, $2, $2, $3)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "e276e53d1b162dc479efe8062a1ac365c3400b7c47f5975e1dc8649feb514ed2"
+}
diff --git a/.sqlx/query-e2a9119ecdf92ee9c1afff509209afb89788106d0bd3793444757df3e5013a01.json b/.sqlx/query-e2a9119ecdf92ee9c1afff509209afb89788106d0bd3793444757df3e5013a01.json
new file mode 100644
index 0000000000..ec0cd132c5
--- /dev/null
+++ b/.sqlx/query-e2a9119ecdf92ee9c1afff509209afb89788106d0bd3793444757df3e5013a01.json
@@ -0,0 +1,17 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO harnesses (id, name, owner_user_id, team_id, created_by)\n VALUES ($1, 'test harness', $2, $3, $4)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "e2a9119ecdf92ee9c1afff509209afb89788106d0bd3793444757df3e5013a01"
+}
diff --git a/.sqlx/query-e88fe4be33541cd554f98cfdd4335818f3c56238c8048bb3ccdb5000ace68598.json b/.sqlx/query-e88fe4be33541cd554f98cfdd4335818f3c56238c8048bb3ccdb5000ace68598.json
new file mode 100644
index 0000000000..0e6217e247
--- /dev/null
+++ b/.sqlx/query-e88fe4be33541cd554f98cfdd4335818f3c56238c8048bb3ccdb5000ace68598.json
@@ -0,0 +1,34 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT owner_user_id, team_id, allow_permission_bypass\n FROM harnesses\n WHERE id = $1 AND deleted_at IS NULL\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "owner_user_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "team_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "allow_permission_bypass",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ true,
+ true,
+ false
+ ]
+ },
+ "hash": "e88fe4be33541cd554f98cfdd4335818f3c56238c8048bb3ccdb5000ace68598"
+}
diff --git a/.sqlx/query-ea0bc02ec826150584d7d33b6094598f7fd7b556d897fb37ba6d08e38edf536d.json b/.sqlx/query-ea0bc02ec826150584d7d33b6094598f7fd7b556d897fb37ba6d08e38edf536d.json
new file mode 100644
index 0000000000..15ee478ae4
--- /dev/null
+++ b/.sqlx/query-ea0bc02ec826150584d7d33b6094598f7fd7b556d897fb37ba6d08e38edf536d.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO team_user (user_id, team_id, team_role)\n VALUES ($1, $2, 'member'::team_role)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "ea0bc02ec826150584d7d33b6094598f7fd7b556d897fb37ba6d08e38edf536d"
+}
diff --git a/.sqlx/query-f07c7c14b06831f213fd48fd34dcb05b3fae3ced5e464d75cab227bcc4db6835.json b/.sqlx/query-f07c7c14b06831f213fd48fd34dcb05b3fae3ced5e464d75cab227bcc4db6835.json
new file mode 100644
index 0000000000..f55b5927f0
--- /dev/null
+++ b/.sqlx/query-f07c7c14b06831f213fd48fd34dcb05b3fae3ced5e464d75cab227bcc4db6835.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT digest(convert_to($1, 'UTF8'), 'sha256')",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "digest",
+ "type_info": "Bytea"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "f07c7c14b06831f213fd48fd34dcb05b3fae3ced5e464d75cab227bcc4db6835"
+}
diff --git a/apps/web/justfile b/apps/web/justfile
index e099e88ead..83ab2396ce 100644
--- a/apps/web/justfile
+++ b/apps/web/justfile
@@ -66,10 +66,9 @@ local-email: ensure-cache-wasm
# without it the cache worker's dynamic import 404s at runtime and the
# normalized cache silently degrades to network-only.
#
-# The vite build's chunk-rendering peaks right at node's default ~4GB heap
-# cap, so CI builds flap with "Ineffective mark-compacts near heap limit".
-# Lift the ceiling; peak usage stays the same, it just stops aborting.
-node_heap := "--max-old-space-size=6144"
+# Vite's chunk-rendering can exceed 6GB as the app grows. Leave headroom
+# above that peak; CI builds use the same mid-size runner as preview deploys.
+node_heap := "--max-old-space-size=8192"
build-dev: build-cache-wasm build-agent-fold-wasm
MODE=development NODE_ENV=production NODE_OPTIONS="{{node_heap}}" bun run --bun build
diff --git a/apps/web/src/features/agents-view/components/AgentSessionPane.tsx b/apps/web/src/features/agents-view/components/AgentSessionPane.tsx
index 390c56fc15..550986f554 100644
--- a/apps/web/src/features/agents-view/components/AgentSessionPane.tsx
+++ b/apps/web/src/features/agents-view/components/AgentSessionPane.tsx
@@ -5,15 +5,13 @@ import {
ChangesToggle,
ReviewNotesDock,
} from '@app/features/agent-changes/agent-changes';
+import { AgentSessionProvider } from '@app/features/block-agent/agent-session-provider';
import { AgentComposer } from '@app/features/block-agent/component/AgentComposer';
import { AgentPullRequestChip } from '@app/features/block-agent/component/AgentPullRequestChip';
import { agentSessionTitle } from '@app/features/block-agent/component/AgentSplitHeader';
import { AgentSidePanelSections } from '@app/features/block-agent/component/sidepanel/AgentSidePanelSections';
import { Transcript } from '@app/features/block-agent/component/Transcript';
-import {
- AgentSessionProvider,
- useAgentSession,
-} from '@app/features/block-agent/context/AgentSessionContext';
+import { useAgentSession } from '@app/features/block-agent/context/AgentSessionContext';
import {
forgetPendingSession,
pendingSession,
diff --git a/apps/web/src/features/block-agent/agent-session-provider.tsx b/apps/web/src/features/block-agent/agent-session-provider.tsx
new file mode 100644
index 0000000000..b2ed564d32
--- /dev/null
+++ b/apps/web/src/features/block-agent/agent-session-provider.tsx
@@ -0,0 +1,169 @@
+/** App-facing composition for the agent session and its controllers. */
+
+import { toast } from '@core/component/Toast/Toast';
+import { isCodexBotId } from '@core/constant/codexAgent';
+import { isCursorBotId } from '@core/constant/cursorAgent';
+import { useUserId } from '@core/context/user';
+import { idToDisplayName } from '@core/user/util';
+import { useAgentSessionExternalUrlQuery } from '@queries/agent-session/session';
+import type {
+ AgentAction,
+ AgentSessionResponse,
+} from '@service-agent-harness/generated/schemas';
+import {
+ type Accessor,
+ createEffect,
+ type ParentProps,
+ Suspense,
+} from 'solid-js';
+import { AgentSessionContext } from './context/AgentSessionContext';
+import { createAgentSession } from './context/create-agent-session';
+import {
+ createQueueController,
+ type QueueController,
+} from './context/create-queue-controller';
+import { resolveSessionId } from './context/resolve-session-id';
+import { createInteractionController } from './primitives/create-interaction-controller';
+import type { QuoteInsert } from './ui';
+
+export function AgentSessionProvider(
+ props: ParentProps & {
+ /** The block's id: a session, or a placeholder for one being created. */
+ blockId: string;
+ /** The real id, once known — the block adopts it into the URL. */
+ onSessionId?: (sessionId: string) => void;
+ }
+) {
+ const { sessionId, pending, failed, error } = resolveSessionId(
+ () => props.blockId
+ );
+
+ createEffect(() => {
+ const id = sessionId();
+ if (id && id !== props.blockId) props.onSessionId?.(id);
+ });
+
+ const userId = useUserId();
+ const live = createAgentSession(sessionId, { userId });
+ const turn = () => live.metadata()?.turn ?? 'idle';
+ const served = createQueueController({
+ sessionId,
+ messages: live.messages,
+ });
+ // A row the user removes may be one `sendNext` already showed as sent;
+ // the fold has to forget it too, or it stays a bubble the log never fills.
+ const queue: QueueController = {
+ ...served,
+ remove: (actionId) => {
+ live.retract(actionId);
+ return served.remove(actionId);
+ },
+ };
+ const sendNext = () => {
+ const head = queue.entries()[0];
+ if (!head) return;
+ const action: AgentAction | undefined =
+ head.kind === 'prompt' && head.prompt != null
+ ? { type: 'prompt', prompt: head.prompt }
+ : head.kind === 'compact'
+ ? { type: 'compact' }
+ : undefined;
+ void live.issue({ type: 'stop' })?.then((result) => {
+ if (result.isErr()) live.retract(head.actionId);
+ });
+ if (action) live.expect(head.actionId, action);
+ };
+ const interactions = createInteractionController({
+ sessionId,
+ pending: () => live.metadata()?.pendingInteractions ?? [],
+ canEdit: () => live.session()?.canEdit,
+ issue: live.issue,
+ onFailure: toast.failure,
+ });
+
+ // The transcript's "Reply to this" chip hands selected text to the
+ // composer through here. A plain variable, not a signal: it is only read
+ // at call time, never rendered from.
+ let quoteInsert: QuoteInsert | undefined;
+ const registerQuoteInsert = (insert: QuoteInsert | undefined) => {
+ quoteInsert = insert;
+ };
+ const quoteSelection: QuoteInsert = (text) => quoteInsert?.(text);
+
+ return (
+ <>
+ {/* Nested so a pending poll cannot take the block orchestrator's
+ <Suspense fallback={<LoadingBlock />}> and blank the transcript.
+ The poll component gates on `isSuccess` so it should not suspend;
+ this boundary is the backstop if a read of `query.data` ever does. */}
+ <Suspense fallback={null}>
+ <CloudExternalUrlPoll
+ sessionId={sessionId}
+ session={live.session}
+ applySnapshot={live.applySnapshot}
+ />
+ </Suspense>
+ <AgentSessionContext.Provider
+ value={{
+ userId,
+ displayName: idToDisplayName,
+ sessionId,
+ pending,
+ startupError: error,
+ session: live.session,
+ bot: live.bot,
+ metadata: live.metadata,
+ messages: live.messages,
+ // A create that failed leaves the block with nothing to load, which
+ // is the same dead end for the reader as a load that failed.
+ loadFailed: () => live.loadFailed() || failed(),
+ loadRetryable: live.loadFailed,
+ retryLoad: live.retry,
+ turn,
+ issue: live.issue,
+ sendNext,
+ interactions,
+ queue,
+ quoteSelection,
+ registerQuoteInsert,
+ }}
+ >
+ {props.children}
+ </AgentSessionContext.Provider>
+ </>
+ );
+}
+
+/**
+ * Compensating read for a cloud session whose provider URL arrived after
+ * the feed's snapshot. Lives in its own Suspense so the rest of the block
+ * stays mounted while this query's first fetch is in flight.
+ */
+function CloudExternalUrlPoll(props: {
+ sessionId: Accessor<string | undefined>;
+ session: Accessor<AgentSessionResponse | undefined>;
+ applySnapshot: (session: AgentSessionResponse) => void;
+}) {
+ // Only a loaded cloud session whose provider URL is still missing polls;
+ // everything else passes `undefined`, which disables the query.
+ const query = useAgentSessionExternalUrlQuery(() => {
+ const id = props.sessionId();
+ const session = props.session();
+ if (!id || !session || session.external?.url) return undefined;
+ return isCursorBotId(session.botId) ||
+ isCodexBotId(session.botId) ||
+ session.harness === 'claude-cloud'
+ ? id
+ : undefined;
+ });
+ createEffect(() => {
+ // `query.data` suspends while pending and throws once it errors
+ // (`useFavoritesData`). Gate on success so neither reaches the
+ // orchestrator Suspense / an error boundary.
+ if (!query.isSuccess) return;
+ const snapshot = query.data;
+ if (!snapshot?.external?.url) return;
+ props.applySnapshot(snapshot);
+ });
+ return null;
+}
diff --git a/apps/web/src/features/block-agent/component/AgentComposer.tsx b/apps/web/src/features/block-agent/component/AgentComposer.tsx
index 142ddda793..1f8efe75bf 100644
--- a/apps/web/src/features/block-agent/component/AgentComposer.tsx
+++ b/apps/web/src/features/block-agent/component/AgentComposer.tsx
@@ -11,11 +11,9 @@ import {
uploadInputAttachments,
} from '@channel/Input';
import { toast } from '@core/component/Toast/Toast';
-import { useUserId } from '@core/context/user';
-import { idToDisplayName } from '@core/user/util';
import { uploadFile } from '@core/util/upload';
import type { AgentAction } from '@service-agent-harness/generated/schemas';
-import { type Component, Show } from 'solid-js';
+import { type Component, For, Show } from 'solid-js';
import { useAgentSession } from '../context/AgentSessionContext';
import { changingModel, hasPendingStop } from '../state/control-message';
import {
@@ -27,6 +25,7 @@ import {
QueuedPrompts,
} from '../ui';
import type { AgentModelSelectorProps } from '../ui/AgentModelSelector';
+import { PermissionRequest } from './PermissionRequest';
import { promptActionOf } from './prompt-action';
export function AgentComposer(props: {
@@ -41,7 +40,9 @@ export function AgentComposer(props: {
const Input = props.input ?? AgentInput;
const ModelSelector = props.modelSelector ?? AgentModelSelector;
const {
- elicitation,
+ displayName,
+ userId,
+ interactions,
issue,
loadFailed,
messages,
@@ -52,7 +53,6 @@ export function AgentComposer(props: {
turn,
registerQuoteInsert,
} = useAgentSession();
- const userId = useUserId();
// The fold speculates the action the moment it is issued, so success is
// observed there; only a refusal needs saying here.
@@ -84,6 +84,10 @@ export function AgentComposer(props: {
messages().some((message) => message.pending) &&
!hasPendingStop(messages());
+ const pendingPermissions = () =>
+ interactions.pending().filter((request) => request.kind === 'permission');
+ const pendingElicitation = () =>
+ interactions.pending().some((request) => request.kind === 'elicitation');
// Files dropped, pasted, or picked into the composer. Every one goes to
// the static file service - documents too, not only media - because the
// agent can only reach a file by a URL it can fetch. The chips and the
@@ -121,8 +125,7 @@ export function AgentComposer(props: {
kind: entry.kind,
prompt: entry.prompt ?? undefined,
attachments: entry.attachments,
- queuedBy:
- actor && actor !== userId() ? idToDisplayName(actor) : undefined,
+ queuedBy: actor && actor !== userId() ? displayName(actor) : undefined,
};
});
@@ -144,15 +147,22 @@ export function AgentComposer(props: {
<Show when={resuming()}>
<ComposerNotice text="Waking the agent's sandbox…" active />
</Show>
- <Show when={turn() === 'blocked'}>
+ <Show when={pendingElicitation()}>
<ComposerNotice
text={
- elicitation.canAnswer()
+ interactions.canAnswer()
? 'The agent is waiting for your answer above. Messages sent now are queued.'
: 'The agent is waiting for an editor to answer above. Messages sent now are queued.'
}
/>
</Show>
+ <For each={pendingPermissions()}>
+ {(permission) => (
+ <div class="mb-2 min-w-0">
+ <PermissionRequest request={permission} />
+ </div>
+ )}
+ </For>
<Input
placeholder="Message the agent, @mention anything"
autofocus={props.autofocus}
diff --git a/apps/web/src/features/block-agent/component/AgentMessage.test.tsx b/apps/web/src/features/block-agent/component/AgentMessage.test.tsx
index 29367ade8c..6eba802962 100644
--- a/apps/web/src/features/block-agent/component/AgentMessage.test.tsx
+++ b/apps/web/src/features/block-agent/component/AgentMessage.test.tsx
@@ -92,6 +92,7 @@ const tool = (
});
const permission = (toolCall: string): MessagePart => ({
kind: 'permission',
+ requestId: 'permission-test',
toolCall,
options: [],
outcome: { kind: 'pending' },
diff --git a/apps/web/src/features/block-agent/component/AgentMessage.tsx b/apps/web/src/features/block-agent/component/AgentMessage.tsx
index 4c9eb532e2..9c658a5a16 100644
--- a/apps/web/src/features/block-agent/component/AgentMessage.tsx
+++ b/apps/web/src/features/block-agent/component/AgentMessage.tsx
@@ -75,7 +75,9 @@ function AgentMessagePart(props: {
.with({ kind: 'permission' }, (part) => <PermissionPart part={part} />)
.with({ kind: 'plan' }, (part) => <PlanPart part={part} />)
.with({ kind: 'control' }, (part) => <ControlPart part={part} />)
- .with({ kind: 'elicitation' }, (part) => <ElicitationPart part={part} />)
+ .with({ kind: 'elicitation' }, (part) => (
+ <ElicitationPart part={part} turn={props.message.turn} />
+ ))
.exhaustive();
}
diff --git a/apps/web/src/features/block-agent/component/Block.tsx b/apps/web/src/features/block-agent/component/Block.tsx
index 6a2afb4755..af4503b71b 100644
--- a/apps/web/src/features/block-agent/component/Block.tsx
+++ b/apps/web/src/features/block-agent/component/Block.tsx
@@ -19,10 +19,8 @@ import { blockHandleSignal } from '@core/signal/load';
import { useSearchParams } from '@solidjs/router';
import { EmptyStatePanel } from '@ui';
import { createSignal, Show, useContext } from 'solid-js';
-import {
- AgentSessionProvider,
- useAgentSession,
-} from '../context/AgentSessionContext';
+import { AgentSessionProvider } from '../agent-session-provider';
+import { useAgentSession } from '../context/AgentSessionContext';
import {
ORIGIN_THREAD_DRAWER_ID,
sessionOriginThread,
diff --git a/apps/web/src/features/block-agent/component/PermissionRequest.tsx b/apps/web/src/features/block-agent/component/PermissionRequest.tsx
new file mode 100644
index 0000000000..5f5c9d6558
--- /dev/null
+++ b/apps/web/src/features/block-agent/component/PermissionRequest.tsx
@@ -0,0 +1,46 @@
+import type { PendingPermission } from '@service-agent-fold/generated/types';
+import { useOptionalAgentSession } from '../context/AgentSessionContext';
+import { PermissionCard } from '../ui/PermissionCard';
+import { toolCallDetail, toolLabel } from './parts/shared';
+
+/** Live approval above the composer, with context from the requested tool. */
+export function PermissionRequest(props: { request: PendingPermission }) {
+ const session = useOptionalAgentSession();
+ const identity = () => ({ ...props.request, kind: 'permission' as const });
+ const tool = () =>
+ session
+ ?.messages()
+ .find(
+ (message) =>
+ message.author.kind === 'agent' && message.turn === props.request.turn
+ )
+ ?.parts.find(
+ (part) => part.kind === 'tool_use' && part.id === props.request.toolCall
+ );
+ const detail = () => {
+ const part = tool();
+ return part?.kind === 'tool_use' ? toolCallDetail(part) : undefined;
+ };
+ const action = () => {
+ const part = tool();
+ if (part?.kind !== 'tool_use') return undefined;
+ return part.detail.kind === 'terminal'
+ ? 'Run command'
+ : toolLabel(part.name);
+ };
+ return (
+ <PermissionCard
+ action={action()}
+ detail={detail()}
+ options={props.request.options}
+ canAnswer={session?.interactions.canAnswer() === true}
+ disabled={session?.interactions.answering(identity())}
+ onSelect={(optionId) =>
+ void session?.interactions.respond({
+ ...identity(),
+ answer: { kind: 'selected', optionId },
+ })
+ }
+ />
+ );
+}
diff --git a/apps/web/src/features/block-agent/component/parts/ElicitationPart.test.tsx b/apps/web/src/features/block-agent/component/parts/ElicitationPart.test.tsx
index 94c821b4b6..b9d7edaf06 100644
--- a/apps/web/src/features/block-agent/component/parts/ElicitationPart.test.tsx
+++ b/apps/web/src/features/block-agent/component/parts/ElicitationPart.test.tsx
@@ -14,6 +14,7 @@ import type { ElicitationAnswer } from '@service-agent-harness/generated/schemas
import { fireEvent, render } from '@solidjs/testing-library';
import type { JSX } from 'solid-js';
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import type { InteractionResponse } from '../../context/interaction';
const respond = vi.fn<(answer: ElicitationAnswer) => Promise<boolean>>();
let pending: PendingElicitation | undefined;
@@ -22,10 +23,14 @@ let canAnswer = true;
vi.mock('../../context/AgentSessionContext', () => ({
useAgentSession: () => ({
bot: () => ({ name: 'Macro Coder' }),
- elicitation: {
- pending: () => pending,
+ interactions: {
+ pending: () => (pending ? [{ kind: 'elicitation', ...pending }] : []),
canAnswer: () => canAnswer,
- respond,
+ answering: () => false,
+ respond: (response: InteractionResponse) =>
+ response.kind === 'elicitation'
+ ? respond(response.answer)
+ : Promise.resolve(false),
},
}),
}));
@@ -196,7 +201,7 @@ describe('ElicitationPart', () => {
it('offers the form only while the metadata names this question', () => {
pending = live();
const { queryByTestId, getByTestId } = render(() => (
- <ElicitationPart part={part()} />
+ <ElicitationPart turn={0} part={part()} />
));
expect(queryByTestId('form')).not.toBeNull();
expect(getByTestId('title').textContent).toContain('Macro Coder is asking');
@@ -207,7 +212,7 @@ describe('ElicitationPart', () => {
pending = live();
canAnswer = false;
const { getByTestId, getByText } = render(() => (
- <ElicitationPart part={part()} />
+ <ElicitationPart turn={0} part={part()} />
));
expect(getByTestId('trailing').textContent).toBe('Waiting for an editor');
expect(getByTestId('body').textContent).toContain(
@@ -224,22 +229,33 @@ describe('ElicitationPart', () => {
it('reads as not answered once the agent has moved on', () => {
pending = undefined;
const { queryByTestId, getByTestId } = render(() => (
- <ElicitationPart part={part()} />
+ <ElicitationPart turn={0} part={part()} />
));
expect(queryByTestId('form')).toBeNull();
expect(getByTestId('trailing').textContent).toBe('Not answered');
});
+ it('a request id reused in a later turn does not reactivate this card', () => {
+ pending = { ...live(), turn: 1 };
+ const { queryByTestId } = render(() => (
+ <ElicitationPart turn={0} part={part()} />
+ ));
+ expect(queryByTestId('elicitation-form')).toBeNull();
+ expect(respond).not.toHaveBeenCalled();
+ });
+
it('a different pending question does not make this one live', () => {
pending = { ...live(), requestId: 7 };
- const { queryByTestId } = render(() => <ElicitationPart part={part()} />);
+ const { queryByTestId } = render(() => (
+ <ElicitationPart turn={0} part={part()} />
+ ));
expect(queryByTestId('form')).toBeNull();
});
it('submits the chosen option under the property name', () => {
pending = live();
const { getByTestId, getByText } = render(() => (
- <ElicitationPart part={part()} />
+ <ElicitationPart turn={0} part={part()} />
));
fireEvent.click(getByTestId('pick-red'));
fireEvent.click(getByText('Submit'));
@@ -252,7 +268,7 @@ describe('ElicitationPart', () => {
it('submits custom text under the custom key, and never both', () => {
pending = live();
const { getByTestId, getByText } = render(() => (
- <ElicitationPart part={part()} />
+ <ElicitationPart turn={0} part={part()} />
));
fireEvent.click(getByTestId('type-other'));
fireEvent.click(getByText('Submit'));
@@ -264,14 +280,18 @@ describe('ElicitationPart', () => {
it('refuses to submit an empty required form', () => {
pending = live();
- const { getByText } = render(() => <ElicitationPart part={part()} />);
+ const { getByText } = render(() => (
+ <ElicitationPart turn={0} part={part()} />
+ ));
fireEvent.click(getByText('Submit'));
expect(respond).not.toHaveBeenCalled();
});
it('decline and cancel send their actions', () => {
pending = live();
- const { getByText } = render(() => <ElicitationPart part={part()} />);
+ const { getByText } = render(() => (
+ <ElicitationPart turn={0} part={part()} />
+ ));
fireEvent.click(getByText('Decline'));
expect(respond).toHaveBeenCalledWith({ action: 'decline' });
fireEvent.click(getByText('Cancel'));
@@ -281,6 +301,7 @@ describe('ElicitationPart', () => {
it('shows the harness-reported answer over what was sent', () => {
const { getByTestId } = render(() => (
<ElicitationPart
+ turn={0}
part={part({
outcome: {
kind: 'accepted',
@@ -322,6 +343,7 @@ describe('ElicitationPart', () => {
};
const { getByText } = render(() => (
<ElicitationPart
+ turn={0}
part={part({
request: {
kind: 'url',
@@ -380,6 +402,7 @@ describe('ElicitationPart', () => {
pending = { ...live(), request };
const { getByTestId, queryByTestId } = render(() => (
<ElicitationPart
+ turn={0}
part={part({ request, message: 'Create calendar event?' })}
/>
));
@@ -406,7 +429,7 @@ describe('ElicitationPart', () => {
});
pending = { ...live(), request };
const { queryByTestId } = render(() => (
- <ElicitationPart part={part({ request })} />
+ <ElicitationPart turn={0} part={part({ request })} />
));
expect(queryByTestId('email-composer')).not.toBeNull();
});
@@ -423,7 +446,7 @@ describe('ElicitationPart', () => {
});
pending = { ...live(), request };
const { getByText } = render(() => (
- <ElicitationPart part={part({ request })} />
+ <ElicitationPart turn={0} part={part({ request })} />
));
fireEvent.click(getByText('Cancel'));
expect(respond).toHaveBeenCalledWith({ action: 'decline' });
@@ -434,7 +457,7 @@ describe('ElicitationPart', () => {
const request = review('CreateCalendarEvent', eventDraft);
pending = { ...live(), request };
const { getByTestId } = render(() => (
- <ElicitationPart part={part({ request })} />
+ <ElicitationPart turn={0} part={part({ request })} />
));
expect(getByTestId('calendar-composer').dataset.canAct).toBe('false');
expect(getByTestId('locked-notice').textContent).toBe(
@@ -451,7 +474,7 @@ describe('ElicitationPart', () => {
};
pending = { ...live(), request };
const { queryByTestId } = render(() => (
- <ElicitationPart part={part({ request })} />
+ <ElicitationPart turn={0} part={part({ request })} />
));
expect(queryByTestId('calendar-composer')).toBeNull();
expect(queryByTestId('form')).not.toBeNull();
@@ -461,6 +484,7 @@ describe('ElicitationPart', () => {
const request = review('CreateCalendarEvent', eventDraft);
const { getByTestId } = render(() => (
<ElicitationPart
+ turn={0}
part={part({
request,
outcome: { kind: 'accepted', answers: [] },
@@ -481,6 +505,7 @@ describe('ElicitationPart', () => {
const request = review('CreateCalendarEvent', eventDraft);
const { getByTestId, queryByTestId } = render(() => (
<ElicitationPart
+ turn={0}
part={part({ request, outcome: { kind: 'declined' } })}
/>
));
@@ -502,6 +527,7 @@ describe('ElicitationPart', () => {
};
const { getByText } = render(() => (
<ElicitationPart
+ turn={0}
part={part({
request: {
kind: 'url',
diff --git a/apps/web/src/features/block-agent/component/parts/ElicitationPart.tsx b/apps/web/src/features/block-agent/component/parts/ElicitationPart.tsx
index 60ac52dc08..6f1e511238 100644
--- a/apps/web/src/features/block-agent/component/parts/ElicitationPart.tsx
+++ b/apps/web/src/features/block-agent/component/parts/ElicitationPart.tsx
@@ -6,9 +6,7 @@
* connection, reads as "not answered" rather than offering a form the agent
* is no longer waiting on. Resolved parts read back what was chosen.
*
- * Only the session's owner can answer (the service refuses anyone else), so
- * another viewer sees the same live card with its controls disabled and the
- * owner named as the one it waits on.
+ * Editors can answer; viewers see the same live card with inert controls.
*
* The form, URL consent, and unrecognized-request controls are the
* `LiveElicitation` ones the channel's Magic Chip shares; a Macro user tool
@@ -52,21 +50,36 @@ function outcomeLabel(part: ElicitationPartData): string {
.exhaustive();
}
-export function ElicitationPart(props: { part: ElicitationPartData }) {
- const { elicitation, bot } = useAgentSession();
+export function ElicitationPart(props: {
+ part: ElicitationPartData;
+ turn: number;
+}) {
+ const { interactions, bot } = useAgentSession();
// Live only while the metadata slot names this exact request.
const live = () =>
props.part.outcome.kind === 'pending' &&
- elicitation.pending()?.requestId === props.part.requestId;
+ interactions
+ .pending()
+ .some(
+ (request) =>
+ request.kind === 'elicitation' &&
+ request.requestId === props.part.requestId &&
+ request.turn === props.turn
+ );
const agentName = () => bot()?.name ?? 'The agent';
- // Controls are inert for anyone without edit access. An answer in flight
- // needs no lock of its own: the fold speculates it, so the card has
- // already left its live state by the time the POST lands.
- const locked = () => !elicitation.canAnswer();
+ const identity = () => ({
+ kind: 'elicitation' as const,
+ requestId: props.part.requestId,
+ turn: props.turn,
+ });
+ const locked = () =>
+ !interactions.canAnswer() || interactions.answering(identity());
+ const respond: RespondToElicitation = (answer) =>
+ interactions.respond({ ...identity(), answer });
const waitingFor = () =>
- elicitation.canAnswer() ? 'Waiting for you' : 'Waiting for an editor';
+ interactions.canAnswer() ? 'Waiting for you' : 'Waiting for an editor';
return (
<Show when={live()} fallback={<ResolvedElicitation part={props.part} />}>
@@ -78,7 +91,7 @@ export function ElicitationPart(props: { part: ElicitationPartData }) {
>
<div class="flex flex-col gap-3 py-1">
<div class="text-sm text-ink">{props.part.message}</div>
- <Show when={!elicitation.canAnswer()}>
+ <Show when={!interactions.canAnswer()}>
<div class="text-xs text-ink-extra-muted">
Only people who can edit this session can answer.
</div>
@@ -89,7 +102,7 @@ export function ElicitationPart(props: { part: ElicitationPartData }) {
request={request}
toolCall={props.part.toolCall ?? String(props.part.requestId)}
locked={locked()}
- onRespond={elicitation.respond}
+ onRespond={respond}
/>
))
.with(
@@ -98,7 +111,7 @@ export function ElicitationPart(props: { part: ElicitationPartData }) {
<LiveQuestionCard
request={request}
locked={locked()}
- onRespond={elicitation.respond}
+ onRespond={respond}
/>
)
)
@@ -122,7 +135,7 @@ function LiveUserTool(props: {
locked: boolean;
onRespond: RespondToElicitation;
}) {
- const { elicitation } = useAgentSession();
+ const { interactions } = useAgentSession();
const drafted = createMemo(() =>
parseDraftedTool(props.request, props.toolCall)
);
@@ -142,7 +155,7 @@ function LiveUserTool(props: {
cancel
fallback={fallback}
review={{
- canAnswer: elicitation.canAnswer,
+ canAnswer: () => interactions.canAnswer() && !props.locked,
respond: props.onRespond,
}}
/>
diff --git a/apps/web/src/features/block-agent/component/parts/PermissionPart.tsx b/apps/web/src/features/block-agent/component/parts/PermissionPart.tsx
index 2812a594a4..5545d89808 100644
--- a/apps/web/src/features/block-agent/component/parts/PermissionPart.tsx
+++ b/apps/web/src/features/block-agent/component/parts/PermissionPart.tsx
@@ -1,7 +1,11 @@
-/** A permission request, with the outcome (chosen option) as trailing text. */
+/**
+ * Resolved permission outcomes in the transcript. Pending decisions live
+ * above the composer so there is only one place to answer them.
+ */
import type { MessagePart } from '@service-agent-fold/generated/types';
import { Show } from 'solid-js';
+import { match } from 'ts-pattern';
import { ToolCard } from '../../ui';
export function PermissionPart(props: {
@@ -9,25 +13,31 @@ export function PermissionPart(props: {
}) {
const outcome = () => {
const resolved = props.part.outcome;
- if (!resolved || resolved.kind === 'pending') return undefined;
+ if (resolved.kind === 'pending') {
+ return 'No longer waiting';
+ }
if (resolved.kind === 'cancelled') return 'Cancelled';
if (resolved.kind === 'errored') return 'Failed';
if (resolved.kind === 'unrecognized') return 'Answered';
const chosen = props.part.options.find(
(option) => option.id === resolved.optionId
);
- return chosen?.name ?? 'Answered';
+ if (!chosen) return 'Answered';
+ return match(chosen.kind)
+ .with('allow_once', () => 'Allowed once')
+ .with('allow_always', () => 'Approval remembered')
+ .with('reject_once', () => 'Denied')
+ .with('reject_always', () => 'Denial remembered')
+ .exhaustive();
};
return (
- <ToolCard
- title="Permission requested"
- trailing={
- <Show when={outcome()}>
- {(label) => <span class="text-ink">{label()}</span>}
- </Show>
- }
- status="completed"
- />
+ <Show when={props.part.outcome.kind !== 'pending'}>
+ <ToolCard
+ title="Permission"
+ trailing={<span class="text-ink">{outcome()}</span>}
+ status="completed"
+ />
+ </Show>
);
}
diff --git a/apps/web/src/features/block-agent/context/AgentSessionContext.tsx b/apps/web/src/features/block-agent/context/AgentSessionContext.tsx
index f97e6404ee..1c52a414d9 100644
--- a/apps/web/src/features/block-agent/context/AgentSessionContext.tsx
+++ b/apps/web/src/features/block-agent/context/AgentSessionContext.tsx
@@ -1,22 +1,6 @@
-import { isCodexBotId } from '@core/constant/codexAgent';
-
-/**
- * Block-level state for the agent block, following the chat block's
- * `ChatInputProvider`/`useChatInputContext` convention: the provider owns the
- * session and its controllers, composer/container components consume them
- * from context, and the `ui/` leaves stay dumb — they only ever receive
- * derived props.
- *
- * The session itself is `createAgentSession`, the Solid face of the shared
- * `AgentSession` class: one machine per session, speculation inside it, so
- * everything about "what is the agent doing" is read off the fold's
- * `metadata.turn` and the messages' `pending` marks rather than kept here.
- */
+/** Feature-owned session state and its provider/consumer boundary. */
import type { IssueResult } from '@core/agent-session/AgentSession';
-import { isCursorBotId } from '@core/constant/cursorAgent';
-import { useUserId } from '@core/context/user';
-import { useAgentSessionExternalUrlQuery } from '@queries/agent-session/session';
import type {
FoldedMessage,
SessionMetadata,
@@ -27,27 +11,15 @@ import type {
AgentSessionResponse,
SessionBot,
} from '@service-agent-harness/generated/schemas';
-import {
- type Accessor,
- createContext,
- createEffect,
- type ParentProps,
- Suspense,
- useContext,
-} from 'solid-js';
+import { type Accessor, createContext, useContext } from 'solid-js';
import type { QuoteInsert } from '../ui';
-import { createAgentSession } from './create-agent-session';
-import {
- createElicitationController,
- type ElicitationController,
-} from './create-elicitation-controller';
-import {
- createQueueController,
- type QueueController,
-} from './create-queue-controller';
-import { resolveSessionId } from './resolve-session-id';
+import type { QueueController } from './create-queue-controller';
+import type { InteractionController } from './interaction';
export type AgentSessionState = {
+ /** The viewer and display-name lookup supplied by production composition. */
+ userId: Accessor<string | undefined>;
+ displayName: (userId: string) => string;
/**
* The session this block shows, absent while a just-created one's `POST`
* is still on the wire. See `pending-session.ts`.
@@ -94,8 +66,8 @@ export type AgentSessionState = {
* the speculation in place. No-op with nothing queued.
*/
sendNext: () => void;
- /** The live question, and the action that answers it. */
- elicitation: ElicitationController;
+ /** The live requests, and the action that answers each one. */
+ interactions: InteractionController;
/**
* The session's server-side action queue: prompts sent mid-turn wait
* there and dispatch one per turn end. The server is the only truth —
@@ -111,154 +83,10 @@ export type AgentSessionState = {
registerQuoteInsert: (insert: QuoteInsert | undefined) => void;
};
-const AgentSessionCtx = createContext<AgentSessionState>();
-
-export function AgentSessionProvider(
- props: ParentProps & {
- /** The block's id: a session, or a placeholder for one being created. */
- blockId: string;
- /** The real id, once known — the block adopts it into the URL. */
- onSessionId?: (sessionId: string) => void;
- }
-) {
- const { sessionId, pending, failed, error } = resolveSessionId(
- () => props.blockId
- );
-
- createEffect(() => {
- const id = sessionId();
- if (id && id !== props.blockId) props.onSessionId?.(id);
- });
-
- const userId = useUserId();
- const live = createAgentSession(sessionId, { userId });
- const turn = () => live.metadata()?.turn ?? 'idle';
- const served = createQueueController({
- sessionId,
- messages: live.messages,
- });
- // A row the user removes may be one `sendNext` already showed as sent;
- // the fold has to forget it too, or it stays a bubble the log never fills.
- const queue: QueueController = {
- ...served,
- remove: (actionId) => {
- live.retract(actionId);
- return served.remove(actionId);
- },
- };
- const sendNext = () => {
- const head = queue.entries()[0];
- if (!head) return;
- const action: AgentAction | undefined =
- head.kind === 'prompt' && head.prompt != null
- ? { type: 'prompt', prompt: head.prompt }
- : head.kind === 'compact'
- ? { type: 'compact' }
- : undefined;
- void live.issue({ type: 'stop' })?.then((result) => {
- if (result.isErr()) live.retract(head.actionId);
- });
- if (action) live.expect(head.actionId, action);
- };
- // A question the connection that asked is gone cannot be answered; the
- // fold keeps the part but the slot is dead.
- const pendingElicitation = () =>
- turn() === 'disconnected'
- ? undefined
- : (live.metadata()?.pendingElicitation ?? undefined);
- const elicitation = createElicitationController({
- pending: pendingElicitation,
- canEdit: () => live.session()?.canEdit,
- issue: live.issue,
- });
-
- // The transcript's "Reply to this" chip hands selected text to the
- // composer through here. A plain variable, not a signal: it is only read
- // at call time, never rendered from.
- let quoteInsert: QuoteInsert | undefined;
- const registerQuoteInsert = (insert: QuoteInsert | undefined) => {
- quoteInsert = insert;
- };
- const quoteSelection: QuoteInsert = (text) => quoteInsert?.(text);
-
- return (
- <>
- {/* Nested so a pending poll cannot take the block orchestrator's
- <Suspense fallback={<LoadingBlock />}> and blank the transcript.
- The poll component gates on `isSuccess` so it should not suspend;
- this boundary is the backstop if a read of `query.data` ever does. */}
- <Suspense fallback={null}>
- <CloudExternalUrlPoll
- sessionId={sessionId}
- session={live.session}
- applySnapshot={live.applySnapshot}
- />
- </Suspense>
- <AgentSessionCtx.Provider
- value={{
- sessionId,
- pending,
- startupError: error,
- session: live.session,
- bot: live.bot,
- metadata: live.metadata,
- messages: live.messages,
- // A create that failed leaves the block with nothing to load, which
- // is the same dead end for the reader as a load that failed.
- loadFailed: () => live.loadFailed() || failed(),
- loadRetryable: live.loadFailed,
- retryLoad: live.retry,
- turn,
- issue: live.issue,
- sendNext,
- elicitation,
- queue,
- quoteSelection,
- registerQuoteInsert,
- }}
- >
- {props.children}
- </AgentSessionCtx.Provider>
- </>
- );
-}
-
-/**
- * Compensating read for a cloud session whose provider URL arrived after
- * the feed's snapshot. Lives in its own Suspense so the rest of the block
- * stays mounted while this query's first fetch is in flight.
- */
-function CloudExternalUrlPoll(props: {
- sessionId: Accessor<string | undefined>;
- session: Accessor<AgentSessionResponse | undefined>;
- applySnapshot: (session: AgentSessionResponse) => void;
-}) {
- // Only a loaded cloud session whose provider URL is still missing polls;
- // everything else passes `undefined`, which disables the query.
- const query = useAgentSessionExternalUrlQuery(() => {
- const id = props.sessionId();
- const session = props.session();
- if (!id || !session || session.external?.url) return undefined;
- return isCursorBotId(session.botId) ||
- isCodexBotId(session.botId) ||
- session.harness === 'claude-cloud'
- ? id
- : undefined;
- });
- createEffect(() => {
- // `query.data` suspends while pending and throws once it errors
- // (`useFavoritesData`). Gate on success so neither reaches the
- // orchestrator Suspense / an error boundary.
- if (!query.isSuccess) return;
- const snapshot = query.data;
- if (!snapshot?.external?.url) return;
- props.applySnapshot(snapshot);
- });
- return null;
-}
+export const AgentSessionContext = createContext<AgentSessionState>();
export function useAgentSession(): AgentSessionState {
- const ctx = useContext(AgentSessionCtx);
+ const ctx = useContext(AgentSessionContext);
if (!ctx) {
throw new Error(
'useAgentSession must be used within <AgentSessionProvider />'
@@ -266,3 +94,12 @@ export function useAgentSession(): AgentSessionState {
}
return ctx;
}
+
+/**
+ * The session state when rendered inside a block, `undefined` when a
+ * transcript is shown on its own (the debug gallery, replay fixtures). For
+ * parts that act on the session when they can and read as inert otherwise.
+ */
+export function useOptionalAgentSession(): AgentSessionState | undefined {
+ return useContext(AgentSessionContext);
+}
diff --git a/apps/web/src/features/block-agent/context/create-elicitation-controller.test.ts b/apps/web/src/features/block-agent/context/create-elicitation-controller.test.ts
deleted file mode 100644
index e546cec1fa..0000000000
--- a/apps/web/src/features/block-agent/context/create-elicitation-controller.test.ts
+++ /dev/null
@@ -1,141 +0,0 @@
-/**
- * @vitest-environment jsdom
- *
- * The controller against a stub `issue`: an answer is one action on the
- * session's optimistic path, only a viewer with edit access may send it, and
- * a 409 is said once.
- */
-
-import type { IssueResult } from '@core/agent-session/AgentSession';
-import type { PendingElicitation } from '@service-agent-fold/generated/types';
-import type { AgentAction } from '@service-agent-harness/generated/schemas';
-import { err, ok } from 'neverthrow';
-import { createRoot, createSignal } from 'solid-js';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { createElicitationController } from './create-elicitation-controller';
-
-const issued = vi.hoisted(() => ({
- actions: [] as AgentAction[],
- outcome: 'ok' as 'ok' | 'conflict' | 'err' | 'reject' | 'no-session',
-}));
-
-const toast = vi.hoisted(() => ({ failure: vi.fn(), success: vi.fn() }));
-vi.mock('@core/component/Toast/Toast', () => ({ toast }));
-
-const issue = (action: AgentAction): Promise<IssueResult> | undefined => {
- issued.actions.push(action);
- if (issued.outcome === 'no-session') return undefined;
- if (issued.outcome === 'reject') return Promise.reject(new Error('network'));
- if (issued.outcome === 'ok') {
- return Promise.resolve(
- ok({ actionId: 'accepted', status: 'sent' }) as IssueResult
- );
- }
- return Promise.resolve(
- err([
- { code: issued.outcome === 'conflict' ? 'CONFLICT' : 'INTERNAL' },
- ]) as unknown as IssueResult
- );
-};
-
-const question: PendingElicitation = {
- requestId: 43,
- turn: 0,
- toolCall: null,
- message: 'Which colour?',
- request: {
- kind: 'form',
- schema: { title: null, description: null, properties: [], required: [] },
- },
-};
-
-function setup(options: { canEdit?: boolean } = { canEdit: true }) {
- const [pending, setPending] = createSignal<PendingElicitation | undefined>(
- question
- );
- const [canEdit] = createSignal<boolean | undefined>(options.canEdit);
- const { controller, dispose } = createRoot((dispose) => ({
- controller: createElicitationController({ pending, canEdit, issue }),
- dispose,
- }));
- return { controller, setPending, dispose };
-}
-
-beforeEach(() => {
- issued.actions = [];
- issued.outcome = 'ok';
- toast.failure.mockReset();
-});
-
-describe('createElicitationController', () => {
- it('answers through the session with the agent request id and the answer', async () => {
- const { controller, dispose } = setup();
- expect(controller.canAnswer()).toBe(true);
- const accepted = await controller.respond({
- action: 'accept',
- content: { colour: 'teal' },
- });
- expect(accepted).toBe(true);
- expect(issued.actions).toEqual([
- {
- type: 'respondElicitation',
- requestId: 43,
- action: 'accept',
- content: { colour: 'teal' },
- },
- ]);
- dispose();
- });
-
- it('a viewer without edit access cannot answer', async () => {
- const { controller, dispose } = setup({ canEdit: false });
- expect(controller.canAnswer()).toBe(false);
- const sent = await controller.respond({ action: 'decline' });
- expect(sent).toBe(false);
- expect(issued.actions).toEqual([]);
- dispose();
- });
-
- it('nobody can answer before the session has loaded', () => {
- const { controller, dispose } = setup({ canEdit: undefined });
- expect(controller.canAnswer()).toBe(false);
- dispose();
- });
-
- it('a 409 means the agent moved on: said once, nothing else', async () => {
- issued.outcome = 'conflict';
- const { controller, dispose } = setup();
- expect(await controller.respond({ action: 'cancel' })).toBe(false);
- expect(toast.failure).toHaveBeenCalledWith(
- 'The agent is no longer waiting on that question'
- );
- dispose();
- });
-
- it('other failures and thrown errors read as a failed send', async () => {
- issued.outcome = 'err';
- const { controller, dispose } = setup();
- expect(await controller.respond({ action: 'decline' })).toBe(false);
- issued.outcome = 'reject';
- expect(await controller.respond({ action: 'decline' })).toBe(false);
- expect(toast.failure).toHaveBeenCalledTimes(2);
- expect(toast.failure).toHaveBeenCalledWith("Couldn't send your answer");
- dispose();
- });
-
- it('a block with no session to act on reports nothing sent', async () => {
- issued.outcome = 'no-session';
- const { controller, dispose } = setup();
- expect(await controller.respond({ action: 'decline' })).toBe(false);
- expect(toast.failure).not.toHaveBeenCalled();
- dispose();
- });
-
- it('nothing is sent once the question is gone', async () => {
- const { controller, setPending, dispose } = setup();
- setPending(undefined);
- expect(await controller.respond({ action: 'decline' })).toBe(false);
- expect(issued.actions).toEqual([]);
- dispose();
- });
-});
diff --git a/apps/web/src/features/block-agent/context/create-elicitation-controller.ts b/apps/web/src/features/block-agent/context/create-elicitation-controller.ts
deleted file mode 100644
index 2b8a7df032..0000000000
--- a/apps/web/src/features/block-agent/context/create-elicitation-controller.ts
+++ /dev/null
@@ -1,91 +0,0 @@
-/**
- * The block's half of answering an elicitation: which question is live (the
- * fold's metadata slot), who may answer it, and the action that answers it.
- *
- * Not a queue. An answer is a response to a request the agent is blocked on,
- * so it goes straight out rather than behind queued prompts - and a second
- * answer to the same question is refused by the server (409), not merged.
- *
- * The answer rides the session's one optimistic path: {@link AgentSession}
- * speculates it into the fold before the POST, so the outcome on the part,
- * the turn leaving `blocked`, and the message's pending mark are the only
- * things a surface reads. There is no second "an answer is on the wire"
- * channel; only a refusal is surfaced after the fact.
- *
- * Anyone with edit access may answer - the same `EditAccessLevel` gate every
- * other control action has - so a surface shared with viewers (the session
- * split, a channel thread) reads {@link ElicitationController.canAnswer}
- * before offering a form, and says it is waiting on an editor otherwise.
- */
-
-import type { IssueResult } from '@core/agent-session/AgentSession';
-import { toast } from '@core/component/Toast/Toast';
-import type { PendingElicitation } from '@service-agent-fold/generated/types';
-import type {
- AgentAction,
- ElicitationAnswer,
-} from '@service-agent-harness/generated/schemas';
-import type { Accessor } from 'solid-js';
-
-export type ElicitationController = {
- /** The question awaiting an answer right now, if any. */
- pending: Accessor<PendingElicitation | undefined>;
- /**
- * Whether the viewer may answer: edit access on the session. `false`
- * until the session has loaded.
- */
- canAnswer: Accessor<boolean>;
- /**
- * Answer the pending question. Resolves `true` when the service accepted
- * the answer; the fold has already shown it. A `409` means the agent is no
- * longer waiting (someone else answered, a stop cancelled it, or the
- * connection that asked is gone) - said once, and the retracted
- * speculation puts the form back where the metadata still has it. A viewer
- * without edit access gets `false` without a request.
- */
- respond: (answer: ElicitationAnswer) => Promise<boolean>;
-};
-
-export function createElicitationController(options: {
- pending: Accessor<PendingElicitation | undefined>;
- /** Whether the viewer may drive the session, once it has loaded. */
- canEdit: Accessor<boolean | undefined>;
- /** The session's one optimistic path; absent while there is no session. */
- issue: (action: AgentAction) => Promise<IssueResult> | undefined;
-}): ElicitationController {
- const canAnswer = () => options.canEdit() === true;
-
- const respond = async (answer: ElicitationAnswer): Promise<boolean> => {
- const pending = options.pending();
- if (!pending || !canAnswer()) return false;
- try {
- const result = await options.issue({
- type: 'respondElicitation',
- requestId: pending.requestId,
- ...answer,
- });
- if (!result) return false;
- if (result.isErr()) {
- const conflict = result.error.some(
- (error) => error.code === 'CONFLICT'
- );
- toast.failure(
- conflict
- ? 'The agent is no longer waiting on that question'
- : "Couldn't send your answer"
- );
- return false;
- }
- return true;
- } catch {
- toast.failure("Couldn't send your answer");
- return false;
- }
- };
-
- return {
- pending: options.pending,
- canAnswer,
- respond,
- };
-}
diff --git a/apps/web/src/features/block-agent/context/interaction.ts b/apps/web/src/features/block-agent/context/interaction.ts
new file mode 100644
index 0000000000..65400e83fa
--- /dev/null
+++ b/apps/web/src/features/block-agent/context/interaction.ts
@@ -0,0 +1,34 @@
+import type { IssueResult } from '@core/agent-session/AgentSession';
+import type { PendingInteraction } from '@service-agent-fold/generated/types';
+import type {
+ AgentAction,
+ ElicitationAnswer,
+ PermissionAnswer,
+} from '@service-agent-harness/generated/schemas';
+import type { Accessor } from 'solid-js';
+
+export type InteractionIdentity = Pick<
+ PendingInteraction,
+ 'kind' | 'requestId' | 'turn'
+>;
+
+export type InteractionResponse = InteractionIdentity &
+ (
+ | { kind: 'permission'; answer: PermissionAnswer }
+ | { kind: 'elicitation'; answer: ElicitationAnswer }
+ );
+
+export type InteractionSource = {
+ sessionId: Accessor<string | undefined>;
+ pending: Accessor<readonly PendingInteraction[]>;
+ canEdit: Accessor<boolean | undefined>;
+ issue: (action: AgentAction) => Promise<IssueResult> | undefined;
+ onFailure: (message: string) => void;
+};
+
+export type InteractionController = {
+ pending: Accessor<readonly PendingInteraction[]>;
+ canAnswer: Accessor<boolean>;
+ answering: (request: InteractionIdentity) => boolean;
+ respond: (response: InteractionResponse) => Promise<boolean>;
+};
diff --git a/apps/web/src/features/block-agent/debug/Gallery.tsx b/apps/web/src/features/block-agent/debug/Gallery.tsx
index 63140d7a46..ba7fdbef5d 100644
--- a/apps/web/src/features/block-agent/debug/Gallery.tsx
+++ b/apps/web/src/features/block-agent/debug/Gallery.tsx
@@ -247,6 +247,7 @@ const FIXTURE_MESSAGE: FoldedMessage = {
},
{
kind: 'permission',
+ requestId: 'demo-permission-1',
toolCall: 'demo-terminal',
options: [
{ id: 'allow', name: 'Allow', kind: 'allow_once' },
@@ -646,7 +647,8 @@ function MagicChipAskingDemo(props: {
kind: 'asking',
markdown: 'Happy to. One quick question before I go on.',
asking: {
- question: {
+ request: {
+ kind: 'elicitation',
requestId: 0,
turn: 0,
toolCall: null,
@@ -654,6 +656,7 @@ function MagicChipAskingDemo(props: {
request: props.request,
},
canAnswer: true,
+ answering: false,
},
};
return (
diff --git a/apps/web/src/features/block-agent/debug/replay/Replay.tsx b/apps/web/src/features/block-agent/debug/replay/Replay.tsx
index f8c27653ab..ec6ffe649a 100644
--- a/apps/web/src/features/block-agent/debug/replay/Replay.tsx
+++ b/apps/web/src/features/block-agent/debug/replay/Replay.tsx
@@ -12,12 +12,10 @@
import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';
import type { AgentSessionLogEntryDto } from '@service-agent-harness/generated/schemas';
import { createSignal, onCleanup, Show } from 'solid-js';
+import { AgentSessionProvider } from '../../agent-session-provider';
import { AgentComposer } from '../../component/AgentComposer';
import { Transcript } from '../../component/Transcript';
-import {
- AgentSessionProvider,
- useAgentSession,
-} from '../../context/AgentSessionContext';
+import { useAgentSession } from '../../context/AgentSessionContext';
import { sessionStatus } from '../../state/session-status';
import { SessionStatusPill } from '../../ui';
import { createReplayDriver, type ReplayDriver } from './driver';
diff --git a/apps/web/src/features/block-agent/primitives/create-interaction-controller.test.ts b/apps/web/src/features/block-agent/primitives/create-interaction-controller.test.ts
new file mode 100644
index 0000000000..a9844fe379
--- /dev/null
+++ b/apps/web/src/features/block-agent/primitives/create-interaction-controller.test.ts
@@ -0,0 +1,185 @@
+/** @vitest-environment jsdom */
+import type { IssueResult } from '@core/agent-session/AgentSession';
+import type { PendingInteraction } from '@service-agent-fold/generated/types';
+import type { AgentAction } from '@service-agent-harness/generated/schemas';
+import { err, ok } from 'neverthrow';
+import { createRoot, createSignal } from 'solid-js';
+import { describe, expect, it, vi } from 'vitest';
+import type { InteractionResponse } from '../context/interaction';
+import { createInteractionController } from './create-interaction-controller';
+
+const permission = {
+ kind: 'permission',
+ requestId: 7,
+ turn: 0,
+ toolCall: 'tool',
+ options: [{ id: 'once', name: 'Allow once', kind: 'allow_once' }],
+} satisfies PendingInteraction;
+const question = {
+ kind: 'elicitation',
+ requestId: '7',
+ turn: 0,
+ toolCall: null,
+ message: 'Which colour?',
+ request: {
+ kind: 'form',
+ schema: { title: null, description: null, properties: [], required: [] },
+ },
+} satisfies PendingInteraction;
+const approval = {
+ ...permission,
+ answer: { kind: 'selected', optionId: 'once' },
+} satisfies InteractionResponse;
+const answer = {
+ ...question,
+ answer: { action: 'accept', content: { colour: 'teal' } },
+} satisfies InteractionResponse;
+const accepted: IssueResult = ok({ actionId: 'accepted', status: 'sent' });
+
+function setup() {
+ const [sessionId, setSessionId] = createSignal<string | undefined>(
+ 'session-a'
+ );
+ const [pending, setPending] = createSignal<PendingInteraction[]>([
+ permission,
+ question,
+ ]);
+ const [canEdit, setCanEdit] = createSignal<boolean | undefined>(true);
+ const issue = vi.fn<
+ (action: AgentAction) => Promise<IssueResult> | undefined
+ >(() => Promise.resolve(accepted));
+ const onFailure = vi.fn();
+ const { controller, dispose } = createRoot((dispose) => ({
+ controller: createInteractionController({
+ sessionId,
+ pending,
+ canEdit,
+ issue,
+ onFailure,
+ }),
+ dispose,
+ }));
+ return {
+ controller,
+ dispose,
+ issue,
+ onFailure,
+ setSessionId,
+ setPending,
+ setCanEdit,
+ };
+}
+
+describe('interaction responses', () => {
+ it('preserves each response type and numeric versus string request ids', async () => {
+ const { controller, issue, dispose } = setup();
+ expect(await controller.respond(approval)).toBe(true);
+ expect(await controller.respond(answer)).toBe(true);
+ expect(issue.mock.calls.map(([action]) => action)).toEqual([
+ { type: 'respondToPermission', requestId: 7, answer: approval.answer },
+ { type: 'respondElicitation', requestId: '7', ...answer.answer },
+ ]);
+ dispose();
+ });
+
+ it.each([approval, answer])(
+ 'deduplicates an in-flight $kind response',
+ async (response) => {
+ const { controller, issue, dispose } = setup();
+ const first = controller.respond(response);
+ expect(controller.answering(response)).toBe(true);
+ expect(await controller.respond(response)).toBe(false);
+ expect(issue).toHaveBeenCalledTimes(1);
+ expect(await first).toBe(true);
+ expect(controller.answering(response)).toBe(false);
+ dispose();
+ }
+ );
+
+ it.each([false, undefined])(
+ 'requires loaded edit access (%s)',
+ async (canEdit) => {
+ const { controller, issue, setCanEdit, dispose } = setup();
+ setCanEdit(canEdit);
+ expect(controller.canAnswer()).toBe(false);
+ expect(await controller.respond(approval)).toBe(false);
+ expect(await controller.respond(answer)).toBe(false);
+ expect(issue).not.toHaveBeenCalled();
+ dispose();
+ }
+ );
+
+ it('rejects dead requests and ids reused by a later turn', async () => {
+ const { controller, issue, setPending, dispose } = setup();
+ setPending([
+ { ...permission, turn: 1 },
+ { ...question, turn: 1 },
+ ]);
+ expect(await controller.respond(approval)).toBe(false);
+ expect(await controller.respond(answer)).toBe(false);
+ setPending([]);
+ expect(await controller.respond({ ...approval, turn: 1 })).toBe(false);
+ expect(issue).not.toHaveBeenCalled();
+ dispose();
+ });
+
+ it('does not confuse numeric ids with string ids of the same kind', async () => {
+ const { controller, issue, setPending, dispose } = setup();
+ setPending([{ ...permission, requestId: '7' }]);
+ expect(await controller.respond(approval)).toBe(false);
+ expect(await controller.respond({ ...approval, requestId: '7' })).toBe(
+ true
+ );
+ expect(issue).toHaveBeenCalledTimes(1);
+ dispose();
+ });
+
+ it('reports a stale response once and allows a retry after refusal', async () => {
+ const { controller, issue, onFailure, dispose } = setup();
+ issue.mockResolvedValueOnce(
+ err([{ code: 'CONFLICT', message: 'answered' }])
+ );
+ expect(await controller.respond(approval)).toBe(false);
+ expect(onFailure).toHaveBeenCalledExactlyOnceWith(
+ 'The agent is no longer waiting on that request'
+ );
+ expect(await controller.respond(approval)).toBe(true);
+ dispose();
+ });
+
+ it('releases answers after a network error or a disappearing session', async () => {
+ const { controller, issue, onFailure, setSessionId, dispose } = setup();
+ issue.mockRejectedValueOnce(new Error('network'));
+ expect(await controller.respond(answer)).toBe(false);
+ expect(controller.answering(answer)).toBe(false);
+ expect(onFailure).toHaveBeenCalledExactlyOnceWith(
+ "Couldn't send your answer"
+ );
+ issue.mockReturnValueOnce(undefined);
+ expect(await controller.respond(answer)).toBe(false);
+ expect(onFailure).toHaveBeenCalledTimes(1);
+ setSessionId(undefined);
+ expect(await controller.respond(approval)).toBe(false);
+ expect(issue).toHaveBeenCalledTimes(2);
+ dispose();
+ });
+
+ it('keeps in-flight answers scoped to the session that issued them', async () => {
+ const { controller, issue, setSessionId, dispose } = setup();
+ const releases: ((result: IssueResult) => void)[] = [];
+ issue.mockImplementation(
+ () => new Promise((resolve) => releases.push(resolve))
+ );
+ const first = controller.respond(approval);
+ setSessionId('session-b');
+ expect(controller.answering(approval)).toBe(false);
+ const second = controller.respond(approval);
+ releases[0](accepted);
+ await first;
+ expect(controller.answering(approval)).toBe(true);
+ releases[1](accepted);
+ await second;
+ expect(controller.answering(approval)).toBe(false);
+ dispose();
+ });
+});
diff --git a/apps/web/src/features/block-agent/primitives/create-interaction-controller.ts b/apps/web/src/features/block-agent/primitives/create-interaction-controller.ts
new file mode 100644
index 0000000000..a27e46da05
--- /dev/null
+++ b/apps/web/src/features/block-agent/primitives/create-interaction-controller.ts
@@ -0,0 +1,81 @@
+import { createStore } from 'solid-js/store';
+import { match } from 'ts-pattern';
+import type {
+ InteractionController,
+ InteractionIdentity,
+ InteractionResponse,
+ InteractionSource,
+} from '../context/interaction';
+
+/** Answers live requests through the session's existing optimistic path. */
+export function createInteractionController(
+ source: InteractionSource
+): InteractionController {
+ // The fold runs in a worker. Guard the gap before its optimistic update
+ // reaches every surface, while leaving the request's outcome in the fold.
+ const [answering, setAnswering] = createStore<
+ Record<string, true | undefined>
+ >({});
+ const key = (request: InteractionIdentity) =>
+ JSON.stringify([
+ source.sessionId(),
+ request.turn,
+ request.kind,
+ request.requestId,
+ ]);
+ const canAnswer = () => source.canEdit() === true;
+
+ const respond = async (response: InteractionResponse): Promise<boolean> => {
+ const identity = key(response);
+ const live = source
+ .pending()
+ .some(
+ (request) =>
+ request.kind === response.kind &&
+ request.turn === response.turn &&
+ request.requestId === response.requestId
+ );
+ if (!source.sessionId() || !canAnswer() || !live || answering[identity])
+ return false;
+
+ const action = match(response)
+ .with({ kind: 'permission' }, ({ requestId, answer }) => ({
+ type: 'respondToPermission' as const,
+ requestId,
+ answer,
+ }))
+ .with({ kind: 'elicitation' }, ({ requestId, answer }) => ({
+ type: 'respondElicitation' as const,
+ requestId,
+ ...answer,
+ }))
+ .exhaustive();
+
+ setAnswering(identity, true);
+ try {
+ const result = await source.issue(action);
+ if (!result) return false;
+ if (result.isErr()) {
+ source.onFailure(
+ result.error.some((error) => error.code === 'CONFLICT')
+ ? 'The agent is no longer waiting on that request'
+ : "Couldn't send your answer"
+ );
+ return false;
+ }
+ return true;
+ } catch {
+ source.onFailure("Couldn't send your answer");
+ return false;
+ } finally {
+ setAnswering(identity, undefined);
+ }
+ };
+
+ return {
+ pending: source.pending,
+ canAnswer,
+ answering: (request) => answering[key(request)] === true,
+ respond,
+ };
+}
diff --git a/apps/web/src/features/block-agent/state/tool-groups.test.ts b/apps/web/src/features/block-agent/state/tool-groups.test.ts
index c04ab87626..11ac23df05 100644
--- a/apps/web/src/features/block-agent/state/tool-groups.test.ts
+++ b/apps/web/src/features/block-agent/state/tool-groups.test.ts
@@ -13,6 +13,7 @@ const tool = (): MessagePart => ({
const thought = (): MessagePart => ({ kind: 'thought', text: 'thinking...' });
const permission = (): MessagePart => ({
kind: 'permission',
+ requestId: 'permission-test',
toolCall: 'call',
options: [],
outcome: { kind: 'pending' },
diff --git a/apps/web/src/features/block-agent/ui/PermissionCard.tsx b/apps/web/src/features/block-agent/ui/PermissionCard.tsx
new file mode 100644
index 0000000000..085ee9f50c
--- /dev/null
+++ b/apps/web/src/features/block-agent/ui/PermissionCard.tsx
@@ -0,0 +1,59 @@
+import ShieldCheck from '@phosphor/shield-check.svg';
+import { Show } from 'solid-js';
+import {
+ PermissionOptions,
+ type PermissionOptionsProps,
+} from './PermissionOptions';
+
+/** A pending decision, with the action separated from its approval controls. */
+export function PermissionCard(
+ props: PermissionOptionsProps & {
+ action?: string;
+ detail?: string;
+ canAnswer: boolean;
+ }
+) {
+ return (
+ <section
+ aria-label="Permission request"
+ class="min-w-0 overflow-hidden rounded-xl border border-edge-muted bg-panel text-ink"
+ >
+ <div class="flex items-start gap-3 px-4 pt-4">
+ <div class="flex size-8 shrink-0 items-center justify-center rounded-lg bg-accent-bg text-accent">
+ <ShieldCheck class="size-4" />
+ </div>
+ <div class="min-w-0 flex-1">
+ <div class="text-sm font-medium">Approval needed</div>
+ <p class="mt-0.5 text-xs leading-5 text-ink-muted">
+ {props.canAnswer
+ ? 'Review this action before the agent continues.'
+ : 'Waiting for a session editor to approve this action.'}
+ </p>
+ </div>
+ </div>
+ <Show when={props.action || props.detail}>
+ <div class="mx-4 mt-3 rounded-lg bg-surface px-3 py-2.5">
+ <Show when={props.action}>
+ <div class="text-xs font-medium text-ink-muted [overflow-wrap:anywhere]">
+ {props.action}
+ </div>
+ </Show>
+ <Show when={props.detail}>
+ <pre class="mt-1 max-h-32 overflow-y-auto font-mono text-xs leading-5 whitespace-pre-wrap [overflow-wrap:anywhere]">
+ {props.detail}
+ </pre>
+ </Show>
+ </div>
+ </Show>
+ <div class="p-3">
+ <Show when={props.canAnswer}>
+ <PermissionOptions
+ options={props.options}
+ disabled={props.disabled}
+ onSelect={props.onSelect}
+ />
+ </Show>
+ </div>
+ </section>
+ );
+}
diff --git a/apps/web/src/features/block-agent/ui/PermissionOptions.tsx b/apps/web/src/features/block-agent/ui/PermissionOptions.tsx
new file mode 100644
index 0000000000..618d379f7a
--- /dev/null
+++ b/apps/web/src/features/block-agent/ui/PermissionOptions.tsx
@@ -0,0 +1,119 @@
+/**
+ * One-time decisions stay close at hand. Additional choices retain the
+ * agent's full wording in a menu so remembered rules can be read before use.
+ */
+
+import CaretDown from '@phosphor/caret-down.svg';
+import { Button, Dropdown } from '@ui';
+import { For, Show } from 'solid-js';
+import { match } from 'ts-pattern';
+
+export type PermissionOptionKind =
+ | 'allow_once'
+ | 'allow_always'
+ | 'reject_once'
+ | 'reject_always';
+
+export type PermissionOptionItem = {
+ id: string;
+ name: string;
+ kind: PermissionOptionKind;
+};
+
+export type PermissionOptionsProps = {
+ options: readonly PermissionOptionItem[];
+ /** An answer is on the wire: nothing here can be clicked again. */
+ disabled?: boolean;
+ onSelect: (optionId: string) => void;
+};
+
+export function PermissionOptions(props: PermissionOptionsProps) {
+ // Multiple choices of the same kind can grant different scopes. Keep
+ // those in the menu with their full wording instead of merging them.
+ const unique = (kind: PermissionOptionKind) => {
+ const options = props.options.filter((option) => option.kind === kind);
+ return options.length === 1 ? options[0] : undefined;
+ };
+ const allow = () => unique('allow_once');
+ const deny = () => unique('reject_once');
+ const more = () =>
+ props.options.filter(
+ (option) => option.id !== allow()?.id && option.id !== deny()?.id
+ );
+
+ return (
+ <div class="flex min-w-0 flex-wrap items-center justify-end gap-2">
+ <Show when={deny()}>
+ {(option) => (
+ <Button
+ type="button"
+ size="md"
+ variant="ghost"
+ class="mr-auto"
+ tooltip={option().name}
+ disabled={props.disabled}
+ onClick={() => props.onSelect(option().id)}
+ >
+ Deny
+ </Button>
+ )}
+ </Show>
+ <Show when={more().length > 0}>
+ <Dropdown placement="top-end">
+ <Dropdown.Trigger
+ size="md"
+ variant="outline"
+ disabled={props.disabled}
+ >
+ More options
+ <CaretDown />
+ </Dropdown.Trigger>
+ <Dropdown.Content class="w-80 max-w-[calc(100vw-2rem)]">
+ <Dropdown.Group class="max-h-64 overflow-y-auto">
+ <For each={more()}>
+ {(option) => (
+ <Dropdown.Item
+ class="h-auto min-w-0 flex-col items-start gap-1 whitespace-normal px-3 py-2.5"
+ disabled={props.disabled}
+ onSelect={() => props.onSelect(option.id)}
+ textValue={option.name}
+ >
+ <span class="text-sm font-medium text-ink">
+ {permissionOptionLabel(option.kind)}
+ </span>
+ <span class="w-full text-xs leading-5 whitespace-pre-wrap text-ink-muted [overflow-wrap:anywhere]">
+ {option.name}
+ </span>
+ </Dropdown.Item>
+ )}
+ </For>
+ </Dropdown.Group>
+ </Dropdown.Content>
+ </Dropdown>
+ </Show>
+ <Show when={allow()}>
+ {(option) => (
+ <Button
+ type="button"
+ size="md"
+ variant="strong"
+ tooltip={option().name}
+ disabled={props.disabled}
+ onClick={() => props.onSelect(option().id)}
+ >
+ Allow once
+ </Button>
+ )}
+ </Show>
+ </div>
+ );
+}
+
+function permissionOptionLabel(kind: PermissionOptionKind): string {
+ return match(kind)
+ .with('allow_once', () => 'Allow once')
+ .with('allow_always', () => 'Remember approval')
+ .with('reject_once', () => 'Deny')
+ .with('reject_always', () => 'Remember denial')
+ .exhaustive();
+}
diff --git a/apps/web/src/features/block-agent/ui/index.ts b/apps/web/src/features/block-agent/ui/index.ts
index 6d69a3fa8c..89df49277e 100644
--- a/apps/web/src/features/block-agent/ui/index.ts
+++ b/apps/web/src/features/block-agent/ui/index.ts
@@ -34,6 +34,12 @@ export {
export { FoldedOutput } from './FoldedOutput';
export { FoldedPathList } from './FoldedPathList';
export { FoldedTerminal } from './FoldedTerminal';
+export {
+ type PermissionOptionItem,
+ type PermissionOptionKind,
+ PermissionOptions,
+ type PermissionOptionsProps,
+} from './PermissionOptions';
export { PierreDiff } from './PierreDiff';
export { QuestionAnswers, type QuestionAnswersProps } from './QuestionAnswers';
export {
diff --git a/apps/web/src/features/settings/Agents.test.tsx b/apps/web/src/features/settings/Agents.test.tsx
index f5c762f791..e0f972caf4 100644
--- a/apps/web/src/features/settings/Agents.test.tsx
+++ b/apps/web/src/features/settings/Agents.test.tsx
@@ -300,6 +300,7 @@ beforeEach(() => {
});
const MACROD_HARNESS = {
+ allow_permission_bypass: false,
id: '3f1c9d2e-8a4b-4c5d-9e6f-1a2b3c4d5e6f',
kind: 'macrod',
name: 'Dev box',
@@ -714,6 +715,7 @@ describe('Agents', () => {
await waitFor(() => {
expect(agentMocks.update).toHaveBeenCalledWith({
agentId: 'agent-1',
+ autoAcceptPermissions: true,
avatarUrl: undefined,
channelIds: ['channel-engineering'],
channelScope: 'selected',
@@ -937,6 +939,7 @@ describe('Agents', () => {
await waitFor(() => {
expect(agentMocks.create).toHaveBeenCalledWith({
+ autoAcceptPermissions: true,
avatarUrl: undefined,
channelIds: [],
channelScope: 'all',
@@ -1210,6 +1213,7 @@ describe('Agents', () => {
await waitFor(() => {
expect(agentMocks.create).toHaveBeenCalledWith({
+ autoAcceptPermissions: false,
avatarUrl: undefined,
channelIds: [],
channelScope: 'all',
@@ -1514,3 +1518,85 @@ describe('Agents', () => {
});
});
});
+
+it('requires prompts unless the harness operator permits bypass', async () => {
+ harnessMocks.query.data = [MACROD_HARNESS];
+ modelMocks.queries[`macrod:${MACROD_HARNESS.id}`] = successfulModels([
+ { id: 'claude-code', name: 'Claude Code' },
+ ]);
+ render(() => <Agents />);
+ fireEvent.click(screen.getByRole('button', { name: 'Create agent' }));
+ const dialog = screen.getByRole('dialog');
+ fireEvent.change(within(dialog).getByLabelText('Harness'), {
+ target: { value: MACROD_HARNESS.id },
+ });
+ expect(within(dialog).getByLabelText('Always prompt')).toHaveProperty(
+ 'checked',
+ true
+ );
+ expect(within(dialog).queryByLabelText('Always bypass')).toBeNull();
+});
+
+it('offers bypass only after harness consent and resets the choice on harness change', async () => {
+ harnessMocks.query.data = [
+ { ...MACROD_HARNESS, allow_permission_bypass: true },
+ { ...MACROD_HARNESS, id: 'prompt-only', name: 'Prompt only' },
+ ];
+ modelMocks.queries[`macrod:${MACROD_HARNESS.id}`] = successfulModels([
+ { id: 'claude-code', name: 'Claude Code' },
+ ]);
+ render(() => <Agents />);
+ fireEvent.click(screen.getByRole('button', { name: 'Create agent' }));
+ const dialog = screen.getByRole('dialog');
+ fireEvent.change(within(dialog).getByLabelText('Harness'), {
+ target: { value: MACROD_HARNESS.id },
+ });
+ expect(within(dialog).getByLabelText('Always prompt')).toHaveProperty(
+ 'checked',
+ true
+ );
+ fireEvent.click(within(dialog).getByLabelText('Always bypass'));
+ expect(within(dialog).getByLabelText('Always bypass')).toHaveProperty(
+ 'checked',
+ true
+ );
+ fireEvent.change(within(dialog).getByLabelText('Harness'), {
+ target: { value: 'prompt-only' },
+ });
+ expect(within(dialog).getByLabelText('Always prompt')).toHaveProperty(
+ 'checked',
+ true
+ );
+ expect(within(dialog).queryByLabelText('Always bypass')).toBeNull();
+});
+
+it.each(['in-memory', 'cursor', 'claude-cloud'])(
+ 'hides permission choices and saves bypass for built-in %s',
+ async (harness) => {
+ cursorMocks.status.data.registered = true;
+ modelMocks.queries[`${harness}:`] = successfulModels([
+ { id: 'provider-default', name: 'Provider default' },
+ ]);
+ agentMocks.create.mockClear();
+ render(() => <Agents />);
+ fireEvent.click(screen.getByRole('button', { name: 'Create agent' }));
+ const dialog = screen.getByRole('dialog');
+ fireEvent.input(within(dialog).getByLabelText('Name'), {
+ target: { value: 'Built-in agent' },
+ });
+ fireEvent.change(within(dialog).getByLabelText('Harness'), {
+ target: { value: harness },
+ });
+ expect(within(dialog).queryByText('Permission requests')).toBeNull();
+ expect(within(dialog).queryByLabelText('Always prompt')).toBeNull();
+ expect(within(dialog).queryByLabelText('Always bypass')).toBeNull();
+ fireEvent.click(
+ within(dialog).getByRole('button', { name: 'Create agent' })
+ );
+ await waitFor(() => {
+ expect(agentMocks.create).toHaveBeenCalledWith(
+ expect.objectContaining({ harness, autoAcceptPermissions: true })
+ );
+ });
+ }
+);
diff --git a/apps/web/src/features/settings/Agents.tsx b/apps/web/src/features/settings/Agents.tsx
index 0ad68794e4..aaf182bcd5 100644
--- a/apps/web/src/features/settings/Agents.tsx
+++ b/apps/web/src/features/settings/Agents.tsx
@@ -69,6 +69,7 @@ type ConnectedHarness = {
id: string;
name: string;
kind: 'builtin' | 'macrod';
+ allowPermissionBypass: boolean;
target: AgentModelTarget;
connected?: boolean;
};
@@ -79,6 +80,7 @@ const IN_MEMORY_HARNESS: ConnectedHarness = {
id: 'in-memory',
name: 'In-memory',
kind: 'builtin',
+ allowPermissionBypass: true,
target: { harness: 'in-memory' },
};
@@ -132,6 +134,7 @@ export function Agents() {
id: 'claude-cloud',
name: 'Claude Cloud',
kind: 'builtin',
+ allowPermissionBypass: true,
target,
};
}
@@ -140,6 +143,7 @@ export function Agents() {
id: 'cursor',
name: 'Cursor',
kind: 'builtin',
+ allowPermissionBypass: true,
target,
};
}
@@ -154,6 +158,7 @@ export function Agents() {
? `${harness.name} · Team`
: (harness?.name ?? 'macrod'),
kind: 'macrod',
+ allowPermissionBypass: harness?.allow_permission_bypass ?? false,
target,
connected: harness?.connected,
};
@@ -659,6 +664,14 @@ function AgentDialog(props: {
rememberedMcpServers = servers;
setMcp({ scope: 'selected', servers });
};
+ const [autoAcceptChoice, setAutoAcceptChoice] = createSignal(
+ props.agent?.auto_accept_permissions === true
+ );
+ const allowPermissionBypass = () =>
+ selectedHarness()?.allowPermissionBypass === true;
+ const autoAcceptPermissions = () =>
+ selectedHarness()?.kind === 'builtin' ||
+ (allowPermissionBypass() && autoAcceptChoice());
let avatarInputRef: HTMLInputElement | undefined;
let dialogContentRef: HTMLDivElement | undefined;
@@ -672,6 +685,7 @@ function AgentDialog(props: {
const handleHarnessChange = (id: string) => {
setHarnessId(id);
setDefaultModelId(preferredModelId(id));
+ setAutoAcceptChoice(false);
};
const handleAvatarInput = (file: File | undefined) => {
@@ -721,6 +735,7 @@ function AgentDialog(props: {
// section never wipes a selection somebody else made.
mcp: mcp(),
teamId: selectedTeamId(),
+ autoAcceptPermissions: autoAcceptPermissions(),
});
if (saved) close();
};
@@ -992,6 +1007,38 @@ function AgentDialog(props: {
</Show>
</label>
</div>
+ <Show when={selectedHarness()?.kind === 'macrod'}>
+ <fieldset class="mt-4 grid gap-2 border-t border-ink/[0.06] pt-4">
+ <legend class="text-xs font-medium text-ink">
+ Permission requests
+ </legend>
+ <ChoiceRow
+ name="agent-permission-policy"
+ value="prompt"
+ title="Always prompt"
+ description="Session editors approve or reject each permission request."
+ checked={!autoAcceptPermissions()}
+ onChange={() => setAutoAcceptChoice(false)}
+ />
+ <Show
+ when={allowPermissionBypass()}
+ fallback={
+ <p class="text-xs text-ink-muted">
+ This harness requires permission prompts.
+ </p>
+ }
+ >
+ <ChoiceRow
+ name="agent-permission-policy"
+ value="bypass"
+ title="Always bypass"
+ description="Approve tool calls without asking."
+ checked={autoAcceptPermissions()}
+ onChange={() => setAutoAcceptChoice(true)}
+ />
+ </Show>
+ </fieldset>
+ </Show>
</AgentFormSection>
<Show when={pipedreamMcp()}>
diff --git a/apps/web/src/features/settings/HarnessPairingDialog.test.tsx b/apps/web/src/features/settings/HarnessPairingDialog.test.tsx
index e8912bd8b2..8a27a97308 100644
--- a/apps/web/src/features/settings/HarnessPairingDialog.test.tsx
+++ b/apps/web/src/features/settings/HarnessPairingDialog.test.tsx
@@ -18,6 +18,7 @@ const mocks = vi.hoisted(() => ({
code: 'KX7M-4QHD',
requested_name: 'Dev laptop',
requested_scope: null,
+ requested_allow_permission_bypass: null as boolean | null,
host: 'erics-mbp.local',
created_at: '2026-08-27T12:00:00Z',
expires_at: new Date(Date.now() + 10 * 60_000).toISOString(),
@@ -69,6 +70,7 @@ beforeAll(() => {
beforeEach(() => {
vi.clearAllMocks();
mocks.pairing.isError = false;
+ mocks.pairing.data.requested_allow_permission_bypass = null;
mocks.approve.mockResolvedValue({ id: 'harness-1' });
mocks.currentTeam = { team: { id: 'team-1' } };
});
@@ -112,6 +114,7 @@ describe('HarnessPairingDialog', () => {
expect(mocks.approve).toHaveBeenCalledWith({
code: 'KX7M-4QHD',
name: 'Home desktop',
+ allowPermissionBypass: false,
teamId: undefined,
});
expect(mocks.toastSuccess).toHaveBeenCalledWith('Harness connected');
@@ -131,6 +134,7 @@ describe('HarnessPairingDialog', () => {
expect(mocks.approve).toHaveBeenCalledWith({
code: 'KX7M-4QHD',
name: 'Dev laptop',
+ allowPermissionBypass: false,
teamId: 'team-1',
});
});
@@ -196,3 +200,66 @@ describe('HarnessPairingDialog', () => {
expect(onClose).toHaveBeenCalledOnce();
});
});
+
+it('warns before opting a harness into permission bypass', async () => {
+ render(() => (
+ <HarnessPairingDialog initialCode="KX7M-4QHD" onClose={() => {}} />
+ ));
+ const dialog = screen.getByRole('dialog');
+ const toggle = within(dialog).getByRole('checkbox');
+ expect(toggle).toHaveProperty('checked', false);
+ fireEvent.click(toggle);
+ expect(within(dialog).getByRole('alert').textContent).toContain(
+ 'without approval'
+ );
+ fireEvent.click(within(dialog).getByRole('button', { name: 'Approve' }));
+ await waitFor(() =>
+ expect(mocks.approve).toHaveBeenCalledWith(
+ expect.objectContaining({ allowPermissionBypass: true })
+ )
+ );
+});
+
+it('preselects daemon bypass consent and lets the approving user decline it', async () => {
+ mocks.pairing.data.requested_allow_permission_bypass = true;
+ render(() => (
+ <HarnessPairingDialog initialCode="KX7M-4QHD" onClose={() => {}} />
+ ));
+ const checkbox = screen.getByRole('checkbox', {
+ name: 'Allow bypassing permission requests',
+ });
+ expect(checkbox).toHaveProperty('checked', true);
+ expect(screen.getByRole('alert').textContent).toContain('without approval');
+ fireEvent.click(checkbox);
+ fireEvent.click(screen.getByRole('button', { name: 'Approve' }));
+ await waitFor(() =>
+ expect(mocks.approve).toHaveBeenCalledWith(
+ expect.objectContaining({ allowPermissionBypass: false })
+ )
+ );
+});
+
+it('prevents approval from overriding the daemon prompt-only choice', async () => {
+ mocks.pairing.data.requested_allow_permission_bypass = false;
+ render(() => (
+ <HarnessPairingDialog initialCode="KX7M-4QHD" onClose={() => {}} />
+ ));
+ const checkbox = screen.getByRole('checkbox', {
+ name: 'Allow bypassing permission requests',
+ });
+ expect(checkbox).toHaveProperty('checked', false);
+ expect(
+ checkbox.hasAttribute('disabled') ||
+ checkbox.getAttribute('aria-disabled') === 'true'
+ ).toBe(true);
+ expect(
+ screen.getByText(/This daemon requires permission prompts/)
+ ).toBeTruthy();
+ fireEvent.click(checkbox);
+ fireEvent.click(screen.getByRole('button', { name: 'Approve' }));
+ await waitFor(() =>
+ expect(mocks.approve).toHaveBeenCalledWith(
+ expect.objectContaining({ allowPermissionBypass: false })
+ )
+ );
+});
diff --git a/apps/web/src/features/settings/HarnessPairingDialog.tsx b/apps/web/src/features/settings/HarnessPairingDialog.tsx
index 9b332a7bc8..4484becaac 100644
--- a/apps/web/src/features/settings/HarnessPairingDialog.tsx
+++ b/apps/web/src/features/settings/HarnessPairingDialog.tsx
@@ -5,7 +5,7 @@ import {
useHarnessPairingQuery,
} from '@queries/harnesses/harnesses';
import { useCurrentTeamQuery } from '@queries/team/teams';
-import { Button, Dialog, Panel } from '@ui';
+import { Button, Checkbox, Dialog, Panel } from '@ui';
import { createEffect, createSignal, Match, Show, Switch } from 'solid-js';
import { ChoiceRow } from './primitives';
@@ -38,6 +38,9 @@ export function HarnessPairingDialog(props: {
const [committedCode, setCommittedCode] = createSignal<string | undefined>(
props.initialCode || undefined
);
+ const [allowPermissionBypass, setAllowPermissionBypass] = createSignal(false);
+ const [permissionBypassEdited, setPermissionBypassEdited] =
+ createSignal(false);
const [approved, setApproved] = createSignal(false);
const [approveError, setApproveError] = createSignal<string>();
const [name, setName] = createSignal('');
@@ -57,6 +60,11 @@ export function HarnessPairingDialog(props: {
const pairing = pairingData();
if (!pairing) return;
if (!nameEdited()) setName(pairing.requested_name);
+ if (!permissionBypassEdited()) {
+ setAllowPermissionBypass(
+ pairing.requested_allow_permission_bypass === true
+ );
+ }
// The daemon's config may ask for a scope; preselect it, but the person
// approving keeps the final say.
if (
@@ -88,6 +96,8 @@ export function HarnessPairingDialog(props: {
setName('');
setShare('Private');
setShareEdited(false);
+ setAllowPermissionBypass(false);
+ setPermissionBypassEdited(false);
};
const canApprove = () =>
@@ -103,6 +113,9 @@ export function HarnessPairingDialog(props: {
try {
await approveMutation.mutateAsync({
code: pairing.code,
+ allowPermissionBypass:
+ pairing.requested_allow_permission_bypass !== false &&
+ allowPermissionBypass(),
name: name().trim(),
teamId: share() === 'Team' ? currentTeamId() : undefined,
});
@@ -227,6 +240,36 @@ export function HarnessPairingDialog(props: {
}}
/>
</fieldset>
+ <div class="flex flex-col gap-2">
+ <Checkbox
+ class="flex items-center gap-3 text-sm"
+ checked={allowPermissionBypass()}
+ disabled={
+ pairing().requested_allow_permission_bypass === false
+ }
+ onChange={(allowed) => {
+ setPermissionBypassEdited(true);
+ setAllowPermissionBypass(allowed);
+ }}
+ >
+ <Checkbox.Control />
+ <Checkbox.Label>
+ Allow bypassing permission requests
+ </Checkbox.Label>
+ </Checkbox>
+ <p class="text-xs text-ink-muted">
+ {pairing().requested_allow_permission_bypass === false
+ ? 'This daemon requires permission prompts. Change its setting and pair again to allow bypass.'
+ : 'When off, every agent on this harness must ask for permission.'}
+ </p>
+ <Show when={allowPermissionBypass()}>
+ <p class="text-xs text-negative" role="alert">
+ Agents can run commands and edit files on this machine
+ without approval. Only enable this if you trust everyone
+ who can create agents on this harness.
+ </p>
+ </Show>
+ </div>
</div>
)}
</Match>
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChip.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChip.tsx
index 8484ff2841..61093d5c03 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChip.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChip.tsx
@@ -17,7 +17,7 @@ export const MagicChip: Component<
presentation={model.presentation()}
header={model.header()}
onCollapse={props.onCollapse}
- answer={{ respond: model.elicitation.respond }}
+ answer={{ respond: model.interactions.respond }}
onOpen={() => insertSplit({ type: 'agent', id: props.agentSessionId })}
/>
);
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipView.test.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipView.test.tsx
index 2b0734c167..d1092d0bc8 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipView.test.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipView.test.tsx
@@ -1,4 +1,6 @@
/** @vitest-environment jsdom */
+import type { InteractionResponse } from '@app/features/block-agent/context/interaction';
+import type { PendingElicitation } from '@service-agent-fold/generated/types';
import type { ElicitationAnswer } from '@service-agent-harness/generated/schemas';
import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';
import { createSignal } from 'solid-js';
@@ -99,6 +101,12 @@ vi.mock('@core/component/AI/component/tool/email/DraftComposer', () => ({
}));
const respond = vi.fn<(answer: ElicitationAnswer) => Promise<boolean>>();
+const elicitationAnswer = {
+ respond: (response: InteractionResponse) =>
+ response.kind === 'elicitation'
+ ? respond(response.answer)
+ : Promise.resolve(false),
+};
const onOpen = vi.fn();
beforeEach(() => {
@@ -107,6 +115,74 @@ beforeEach(() => {
onOpen.mockReset();
});
+describe('MagicChipView permission requests', () => {
+ it.each([true, false])(
+ 'replaces loading with an approval card for canAnswer=%s',
+ (canAnswer) => {
+ const answer = vi
+ .fn<(response: InteractionResponse) => Promise<boolean>>()
+ .mockResolvedValue(true);
+ const [presentation, setPresentation] =
+ createSignal<MagicChipPresentation>({
+ kind: 'asking',
+ markdown: '',
+ asking: {
+ request: {
+ kind: 'permission',
+ requestId: 0,
+ turn: 3,
+ toolCall: 'cmd',
+ options: [
+ {
+ id: 'approve-command',
+ kind: 'allow_once',
+ name: 'Yes, proceed',
+ },
+ { id: 'reject-command', kind: 'reject_once', name: 'No' },
+ ],
+ },
+ canAnswer,
+ answering: false,
+ action: 'Run command',
+ detail: 'echo hi',
+ },
+ });
+ const view = render(() => (
+ <MagicChipView
+ agentSessionId="session"
+ presentation={presentation()}
+ answer={{ respond: answer }}
+ />
+ ));
+ expect(view.getByText('Approval needed')).toBeTruthy();
+ expect(view.getByText('echo hi')).toBeTruthy();
+ expect(
+ view.container.querySelector('[data-magic-chip-pending]')
+ ).toBeNull();
+ if (canAnswer) {
+ fireEvent.click(view.getByRole('button', { name: 'Allow once' }));
+ expect(answer).toHaveBeenCalledExactlyOnceWith({
+ kind: 'permission',
+ requestId: 0,
+ turn: 3,
+ answer: { kind: 'selected', optionId: 'approve-command' },
+ });
+ } else {
+ expect(view.queryByRole('button', { name: 'Allow once' })).toBeNull();
+ expect(view.queryByRole('button', { name: 'Deny' })).toBeNull();
+ expect(answer).not.toHaveBeenCalled();
+ }
+ setPresentation({
+ kind: 'answering',
+ markdown: 'Done.',
+ activity: { label: 'Writing response', busy: true },
+ });
+ expect(view.queryByText('Approval needed')).toBeNull();
+ expect(view.getByText('Done.')).toBeTruthy();
+ }
+ );
+});
+
describe('Magic Chip inside an editor', () => {
it('collapses even when the editor stops delegated clicks', () => {
const collapse = vi.fn();
@@ -314,7 +390,8 @@ function asking(canAnswer: boolean, markdown = ''): MagicChipPresentation {
kind: 'asking',
markdown,
asking: {
- question: {
+ request: {
+ kind: 'elicitation',
requestId: 9,
turn: 0,
toolCall: 'toolu_evt',
@@ -332,6 +409,7 @@ function asking(canAnswer: boolean, markdown = ''): MagicChipPresentation {
},
},
canAnswer,
+ answering: false,
},
};
}
@@ -349,7 +427,7 @@ describe('MagicChipView reviewing a tool draft', () => {
<MagicChipView
agentSessionId="session"
presentation={asking(true, 'Setting that up.')}
- answer={{ respond }}
+ answer={elicitationAnswer}
onOpen={onOpen}
/>
));
@@ -393,7 +471,7 @@ describe('MagicChipView reviewing a tool draft', () => {
<MagicChipView
agentSessionId="session"
presentation={asking(true)}
- answer={{ respond }}
+ answer={elicitationAnswer}
onOpen={onOpen}
/>
));
@@ -422,7 +500,7 @@ describe('MagicChipView reviewing a tool draft', () => {
<MagicChipView
agentSessionId="session"
presentation={asking(false)}
- answer={{ respond }}
+ answer={elicitationAnswer}
onOpen={onOpen}
/>
));
@@ -463,7 +541,7 @@ describe('MagicChipView reviewing a tool draft', () => {
<MagicChipView
agentSessionId="session"
presentation={presentation()}
- answer={{ respond }}
+ answer={elicitationAnswer}
onOpen={onOpen}
/>
));
@@ -521,17 +599,15 @@ const colourForm = {
};
function askingQuestion(
- request: Extract<
- MagicChipPresentation,
- { kind: 'asking' }
- >['asking']['question']['request'],
+ request: PendingElicitation['request'],
options: { canAnswer?: boolean; requestId?: number; markdown?: string } = {}
): MagicChipPresentation {
return {
kind: 'asking',
markdown: options.markdown ?? '',
asking: {
- question: {
+ request: {
+ kind: 'elicitation',
requestId: options.requestId ?? 0,
turn: 0,
toolCall: null,
@@ -539,6 +615,7 @@ function askingQuestion(
request,
},
canAnswer: options.canAnswer ?? true,
+ answering: false,
},
};
}
@@ -549,7 +626,7 @@ describe('MagicChipView asking a form', () => {
<MagicChipView
agentSessionId="session"
presentation={askingQuestion(colourForm)}
- answer={{ respond }}
+ answer={elicitationAnswer}
onOpen={onOpen}
/>
));
@@ -593,7 +670,7 @@ describe('MagicChipView asking a form', () => {
<MagicChipView
agentSessionId="session"
presentation={askingQuestion(colourForm)}
- answer={{ respond }}
+ answer={elicitationAnswer}
/>
));
fireEvent.input(view.getByPlaceholderText('Type your own answer'), {
@@ -614,7 +691,7 @@ describe('MagicChipView asking a form', () => {
<MagicChipView
agentSessionId="session"
presentation={presentation()}
- answer={{ respond }}
+ answer={elicitationAnswer}
/>
));
fireEvent.click(view.getByRole('radio', { name: 'Blue' }));
@@ -636,7 +713,7 @@ describe('MagicChipView asking a form', () => {
<MagicChipView
agentSessionId="session"
presentation={askingQuestion(colourForm, { canAnswer: false })}
- answer={{ respond }}
+ answer={elicitationAnswer}
onOpen={onOpen}
/>
));
@@ -660,7 +737,7 @@ describe('MagicChipView asking a form', () => {
elicitationId: 'gh-1',
url: 'https://agent.example.com/connect?e=gh-1',
})}
- answer={{ respond }}
+ answer={elicitationAnswer}
/>
));
expect(view.getByText('agent.example.com')).toBeTruthy();
@@ -686,7 +763,7 @@ describe('MagicChipView asking a form', () => {
mode: 'hologram',
raw: {},
})}
- answer={{ respond }}
+ answer={elicitationAnswer}
/>
));
expect(view.getByText(/cannot display a "hologram" request/)).toBeTruthy();
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipView.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipView.tsx
index 1341aec16a..e88e17018f 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipView.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipView.tsx
@@ -8,6 +8,8 @@ import {
type RespondToElicitation,
UserToolComposer,
} from '@app/features/block-agent/component/parts/LiveElicitation';
+import type { InteractionResponse } from '@app/features/block-agent/context/interaction';
+import { PermissionCard } from '@app/features/block-agent/ui/PermissionCard';
import {
StaticMarkdown,
StaticMarkdownContext,
@@ -16,7 +18,7 @@ import { channelTheme } from '@core/component/LexicalMarkdown/theme';
import { PulsingStar } from '@entity/components/PulsingStar';
import ArrowUpRight from '@phosphor/arrow-up-right.svg';
import ArrowsIn from '@phosphor/arrows-in.svg';
-import type { ElicitationAnswer } from '@service-agent-harness/generated/schemas';
+import type { PendingElicitation } from '@service-agent-fold/generated/types';
import { Button, Layer } from '@ui';
import {
type Component,
@@ -31,8 +33,8 @@ import { MagicChipPullRequest } from './MagicChipPullRequest';
import {
type MagicChipActivity,
type MagicChipHeader,
+ type MagicChipInteraction,
type MagicChipPresentation,
- type MagicChipQuestion,
presentationStatus,
} from './presentation';
@@ -61,7 +63,7 @@ function isTextEntry(target: EventTarget | null) {
/** What the chip's answer to a question does. */
export type MagicChipAnswer = {
- respond: (answer: ElicitationAnswer) => Promise<boolean>;
+ respond: (response: InteractionResponse) => Promise<boolean>;
};
/**
@@ -74,11 +76,14 @@ type ChipQuestion =
| LiveQuestion
| { kind: 'user_tool'; tool: DraftedTool; toolCall: string };
+type MagicChipQuestion = Omit<MagicChipInteraction, 'request'> & {
+ request: PendingElicitation & { kind: 'elicitation' };
+};
+
function createChipQuestion(asking: MagicChipQuestion): ChipQuestion {
- const request = asking.question.request;
+ const request = asking.request.request;
if (request.kind !== 'user_tool') return createLiveQuestion(request);
- const toolCall =
- asking.question.toolCall ?? String(asking.question.requestId);
+ const toolCall = asking.request.toolCall ?? String(asking.request.requestId);
const tool = parseDraftedTool(request, toolCall);
return tool
? { kind: 'user_tool', tool, toolCall }
@@ -300,7 +305,7 @@ const Passage: Component<{ markdown: string }> = (props) => (
const Question: Component<ChipAsking> = (props) => (
<div class="flex min-w-0 flex-col gap-2" data-magic-chip-asking>
<span class="text-sm leading-5 text-ink wrap-break-word">
- {props.asking.question.message}
+ {props.asking.request.message}
</span>
<Switch>
<Match when={reviewedTool(props.question)}>
@@ -352,6 +357,18 @@ export const MagicChipView: Component<{
const asking = createMemo(() =>
props.presentation.kind === 'asking' ? props.presentation.asking : undefined
);
+ const elicitation = (): MagicChipQuestion | undefined => {
+ const current = asking();
+ return current?.request.kind === 'elicitation'
+ ? { ...current, request: current.request }
+ : undefined;
+ };
+ const permission = () => {
+ const current = asking();
+ return current?.request.kind === 'permission'
+ ? { ...current, request: current.request }
+ : undefined;
+ };
const markdown = createMemo(() => answerMarkdown(props.presentation));
const status = createMemo(() => presentationStatus(props.presentation));
const [expanded, setExpanded] = createSignal(false);
@@ -359,27 +376,40 @@ export const MagicChipView: Component<{
// One draft per question: keyed on the request id so metadata refreshes of
// the same question keep what was typed, and a new question starts clean.
const requestKey = createMemo(() => {
- const current = asking();
- return current ? String(current.question.requestId) : undefined;
+ const current = elicitation();
+ return current
+ ? JSON.stringify([
+ current.request.kind,
+ current.request.turn,
+ current.request.requestId,
+ ])
+ : undefined;
});
const question = createMemo(() => {
if (!requestKey()) return undefined;
return untrack(() => {
- const current = asking();
+ const current = elicitation();
return current ? createChipQuestion(current) : undefined;
});
});
const chipAsking = (): ChipAsking | undefined => {
- const current = asking();
+ const current = elicitation();
const state = question();
if (!current || !state) return undefined;
- const locked = !current.canAnswer || !props.answer;
+ const locked = !current.canAnswer || current.answering || !props.answer;
return {
asking: current,
question: state,
locked,
respond: async (answer) =>
- locked ? false : ((await props.answer?.respond(answer)) ?? false),
+ locked
+ ? false
+ : ((await props.answer?.respond({
+ kind: 'elicitation',
+ requestId: current.request.requestId,
+ turn: current.request.turn,
+ answer,
+ })) ?? false),
};
};
// The question's state, kept through its own teardown: once the answer
@@ -399,7 +429,11 @@ export const MagicChipView: Component<{
if (markdown() && !live) return undefined;
const current = status();
const line = `${current.label}${current.detail ? ` ${current.detail}` : ''}`;
- return live ? `${line} · ${live.question.message}` : line;
+ return live?.request.kind === 'elicitation'
+ ? `${line} · ${live.request.message}`
+ : live?.detail
+ ? `${line} · ${live.detail}`
+ : line;
};
// Before there is anything to expand, the whole card leads to the session.
@@ -430,60 +464,87 @@ export const MagicChipView: Component<{
onOpen={props.onOpen}
onCollapse={props.onCollapse}
/>
- <div
- role="button"
- tabIndex={0}
- aria-expanded={expandable() ? expanded() : undefined}
- class="flex min-h-41 min-w-0 flex-col text-left"
- classList={{ 'h-41': !expanded() }}
- data-magic-chip-answer
- onClick={onAreaClick}
- on:keydown={(event) => {
- if (event.target !== event.currentTarget) return;
- if (event.key !== 'Enter' && event.key !== ' ') return;
- event.preventDefault();
- event.stopPropagation();
- if (expandable()) setExpanded((open) => !open);
- else props.onOpen?.();
- }}
- >
- <div
- class="relative mx-3 mt-1 mb-1 min-h-0 flex-1"
- classList={{ 'overflow-hidden': !expanded() }}
- data-magic-chip-clip
- >
- <Show
- when={requestKey()}
- keyed
- fallback={
+ <Show
+ when={permission()}
+ fallback={
+ <div
+ role="button"
+ tabIndex={0}
+ aria-expanded={expandable() ? expanded() : undefined}
+ class="flex min-h-41 min-w-0 flex-col text-left"
+ classList={{ 'h-41': !expanded() }}
+ data-magic-chip-answer
+ onClick={onAreaClick}
+ on:keydown={(event) => {
+ if (event.target !== event.currentTarget) return;
+ if (event.key !== 'Enter' && event.key !== ' ') return;
+ event.preventDefault();
+ event.stopPropagation();
+ if (expandable()) setExpanded((open) => !open);
+ else props.onOpen?.();
+ }}
+ >
+ <div
+ class="relative mx-3 mt-1 mb-1 min-h-0 flex-1"
+ classList={{ 'overflow-hidden': !expanded() }}
+ data-magic-chip-clip
+ >
<Show
- when={markdown()}
- fallback={<AnswerPending busy={status().busy} />}
+ when={requestKey()}
+ keyed
+ fallback={
+ <Show
+ when={markdown()}
+ fallback={<AnswerPending busy={status().busy} />}
+ >
+ {(answer) => <Passage markdown={answer()} />}
+ </Show>
+ }
>
- {(answer) => <Passage markdown={answer()} />}
+ {/* `held` is set whenever a request id is. */}
+ <Question {...held()!} />
</Show>
- }
- >
- {/* `held` is set whenever a request id is. */}
- <Question {...held()!} />
- </Show>
- {/* Cropped content fades out; expanding shows it whole. */}
- <Show when={expandable() && !expanded()}>
- <div
- class="pointer-events-none absolute inset-x-0 bottom-0 h-12 bg-linear-to-t from-surface to-transparent"
- data-magic-chip-fade
+ {/* Cropped content fades out; expanding shows it whole. */}
+ <Show when={expandable() && !expanded()}>
+ <div
+ class="pointer-events-none absolute inset-x-0 bottom-0 h-12 bg-linear-to-t from-surface to-transparent"
+ data-magic-chip-fade
+ />
+ </Show>
+ </div>
+ <Show when={requestKey() && held()?.asking.canAnswer}>
+ <div
+ class="flex shrink-0 items-center justify-end gap-2 px-3 pb-2"
+ data-magic-chip-decisions
+ >
+ <AskingActions {...held()!} onOpen={props.onOpen} />
+ </div>
+ </Show>
+ </div>
+ }
+ >
+ {(pending) => (
+ <div class="p-3" data-magic-chip-permission>
+ <PermissionCard
+ action={pending().action}
+ detail={pending().detail}
+ options={pending().request.options}
+ canAnswer={pending().canAnswer && Boolean(props.answer)}
+ disabled={pending().answering}
+ onSelect={(optionId) => {
+ const current = pending();
+ if (!current.canAnswer || current.answering) return;
+ void props.answer?.respond({
+ kind: 'permission',
+ requestId: current.request.requestId,
+ turn: current.request.turn,
+ answer: { kind: 'selected', optionId },
+ });
+ }}
/>
- </Show>
- </div>
- <Show when={requestKey() && held()?.asking.canAnswer}>
- <div
- class="flex shrink-0 items-center justify-end gap-2 px-3 pb-2"
- data-magic-chip-decisions
- >
- <AskingActions {...held()!} onOpen={props.onOpen} />
</div>
- </Show>
- </div>
+ )}
+ </Show>
</div>
</Layer>
);
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.test.ts
index 5ae4bccb5b..fc6be9f3f4 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.test.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.test.ts
@@ -8,6 +8,7 @@ import type {
FoldedMessage,
FoldedStreamEvent,
PendingElicitation,
+ PendingInteraction,
SessionMetadata,
} from '@service-agent-fold/generated/types';
import { QueryClientProvider } from '@tanstack/solid-query';
@@ -134,7 +135,12 @@ const question: PendingElicitation = {
const metadata = (
pendingElicitation: PendingElicitation | null
-): SessionMetadata => ({ pendingElicitation }) as unknown as SessionMetadata;
+): SessionMetadata =>
+ ({
+ pendingInteractions: pendingElicitation
+ ? [{ kind: 'elicitation', ...pendingElicitation }]
+ : [],
+ }) as unknown as SessionMetadata;
const props = {
agentSessionId: 'session',
@@ -165,6 +171,127 @@ describe('createMagicChipModel', () => {
live.issue.mockResolvedValue({ isErr: () => false });
});
+ it.each([0, '0'])(
+ 'offers a permission from metadata before its tool arrives, preserving request id %s',
+ async (requestId) => {
+ const permission: PendingInteraction = {
+ kind: 'permission',
+ requestId,
+ turn: 4,
+ toolCall: 'command',
+ options: [{ id: 'allow', name: 'Proceed', kind: 'allow_once' }],
+ };
+ live.snapshot = {
+ messages: [],
+ metadata: { ...metadata(null), pendingInteractions: [permission] },
+ };
+ let model!: ReturnType<typeof createMagicChipModel>;
+ const dispose = createRoot((dispose) => {
+ model = createModel({ ...props, promptedMessage: null });
+ return dispose;
+ });
+ await settle();
+ expect(model.presentation()).toMatchObject({
+ kind: 'asking',
+ asking: { request: permission, canAnswer: true, answering: false },
+ });
+ onChange([
+ {
+ ...openResponse,
+ turn: 4,
+ parts: [
+ {
+ kind: 'tool_use',
+ id: 'command',
+ name: { kind: 'native', name: 'Terminal' },
+ status: 'pending',
+ detail: {
+ kind: 'terminal',
+ command: 'echo hi',
+ output: null,
+ exitCode: null,
+ },
+ },
+ ],
+ },
+ ]);
+ expect(model.presentation()).toMatchObject({
+ asking: { action: 'Run command', detail: 'echo hi' },
+ });
+ expect(
+ await model.interactions.respond({
+ ...permission,
+ answer: { kind: 'selected', optionId: 'allow' },
+ })
+ ).toBe(true);
+ expect(live.issue).toHaveBeenCalledWith({
+ type: 'respondToPermission',
+ requestId,
+ answer: { kind: 'selected', optionId: 'allow' },
+ });
+ onMetadata(metadata(null));
+ expect(model.presentation().kind).not.toBe('asking');
+ expect(
+ await model.interactions.respond({
+ ...permission,
+ answer: { kind: 'selected', optionId: 'allow' },
+ })
+ ).toBe(false);
+ dispose();
+ }
+ );
+
+ it('does not answer a permission from another turn or a read-only session', async () => {
+ const permission: PendingInteraction = {
+ kind: 'permission',
+ requestId: 'approval',
+ turn: 1,
+ toolCall: 'command',
+ options: [],
+ };
+ live.snapshot = {
+ messages: [prompt, openResponse],
+ metadata: { ...metadata(null), pendingInteractions: [permission] },
+ };
+ let model!: ReturnType<typeof createMagicChipModel>;
+ const dispose = createRoot((dispose) => {
+ model = createModel(props);
+ return dispose;
+ });
+ await settle();
+ expect(model.presentation().kind).not.toBe('asking');
+ expect(
+ await model.interactions.respond({
+ ...permission,
+ answer: { kind: 'cancelled' },
+ })
+ ).toBe(false);
+ serviceClient.get.mockResolvedValue({
+ isOk: () => true,
+ isErr: () => false,
+ value: { canEdit: false },
+ });
+ await invalidateAgentSessionMetadata();
+ await settle();
+ onMetadata({
+ ...metadata(null),
+ pendingInteractions: [{ ...permission, turn: 0 }],
+ });
+ expect(model.presentation()).toMatchObject({
+ kind: 'asking',
+ asking: { canAnswer: false },
+ });
+ expect(
+ await model.interactions.respond({
+ ...permission,
+ turn: 0,
+ answer: { kind: 'cancelled' },
+ })
+ ).toBe(false);
+ expect(live.issue).not.toHaveBeenCalled();
+ dispose();
+ });
+
it.each(['cursor', 'codex-cloud'])(
'reloads the completed %s session PR on gateway updates and reconnect without folding it',
async (harness) => {
@@ -303,7 +430,12 @@ describe('createMagicChipModel', () => {
onMetadata(metadata({ ...question, turn: 4 }));
expect(model.presentation()).toMatchObject({
kind: 'asking',
- asking: { question: { turn: 4 } },
+ asking: {
+ request: {
+ kind: 'elicitation',
+ turn: 4,
+ },
+ },
});
dispose();
expect(live.release).toHaveBeenCalledOnce();
@@ -396,9 +528,22 @@ describe('createMagicChipModel', () => {
expect(model.presentation()).toEqual({
kind: 'asking',
markdown: 'Setting that up.',
- asking: { question, canAnswer: true },
+ asking: {
+ request: {
+ kind: 'elicitation',
+ ...question,
+ },
+ canAnswer: true,
+ answering: false,
+ },
});
- expect(await model.elicitation.respond({ action: 'decline' })).toBe(true);
+ expect(
+ await model.interactions.respond({
+ ...question,
+ kind: 'elicitation',
+ answer: { action: 'decline' },
+ })
+ ).toBe(true);
// The answer rides the session's optimistic path, not a bare POST.
expect(live.issue).toHaveBeenCalledWith({
type: 'respondElicitation',
@@ -436,7 +581,13 @@ describe('createMagicChipModel', () => {
if (presentation.kind === 'asking') {
expect(presentation.asking.canAnswer).toBe(false);
}
- expect(await model.elicitation.respond({ action: 'decline' })).toBe(false);
+ expect(
+ await model.interactions.respond({
+ ...question,
+ kind: 'elicitation',
+ answer: { action: 'decline' },
+ })
+ ).toBe(false);
expect(live.issue).not.toHaveBeenCalled();
dispose();
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.ts
index 7e4528d253..0b8f64d014 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.ts
@@ -4,10 +4,13 @@ import {
modelDisplayName,
} from '@app/features/block-agent/component/compose-agent-session-options';
import {
- createElicitationController,
- type ElicitationController,
-} from '@app/features/block-agent/context/create-elicitation-controller';
+ toolCallDetail,
+ toolLabel,
+} from '@app/features/block-agent/component/parts/shared';
+import type { InteractionController } from '@app/features/block-agent/context/interaction';
+import { createInteractionController } from '@app/features/block-agent/primitives/create-interaction-controller';
import { AgentSession } from '@core/agent-session/AgentSession';
+import { toast } from '@core/component/Toast/Toast';
import {
MAGIC_CHIP_STATUSES,
type MagicChipData,
@@ -25,8 +28,8 @@ import { type Accessor, createMemo, createSignal, onCleanup } from 'solid-js';
import {
deriveMagicChipPresentation,
type MagicChipHeader,
+ type MagicChipInteraction,
type MagicChipPresentation,
- type MagicChipQuestion,
} from './presentation';
function magicChipStatus(
@@ -87,7 +90,7 @@ function upsert(
*
* Also the chip's half of answering a question the agent stops to ask in
* that turn: the session's metadata names the live question, the session
- * row names its owner, and {@link ElicitationController} sends the answer.
+ * row reports edit access, and the shared interaction controller sends the answer.
* The header names the persona and model from the session row and the fold.
*
* The fold is the shared {@link AgentSession} for the id, so a chip and a
@@ -96,7 +99,7 @@ function upsert(
export function createMagicChipModel(props: MagicChipData): {
presentation: Accessor<MagicChipPresentation>;
header: Accessor<MagicChipHeader | undefined>;
- elicitation: ElicitationController;
+ interactions: InteractionController;
} {
const [messages, setMessages] = createSignal<FoldedMessage[]>([]);
const sessionQuery = useAgentSessionQuery(() => props.agentSessionId);
@@ -109,7 +112,7 @@ export function createMagicChipModel(props: MagicChipData): {
return (status ? magicChipStatus(status) : undefined) ?? props.status;
};
const [metadata, setMetadata] = createSignal<SessionMetadata>();
- const pendingElicitation = () => metadata()?.pendingElicitation ?? undefined;
+ const pending = () => metadata()?.pendingInteractions ?? [];
// The last system event's wire name, which the fold carries as status.
const latestEvent = () => metadata()?.status ?? undefined;
@@ -144,25 +147,43 @@ export function createMagicChipModel(props: MagicChipData): {
props.promptedMessage?.turn ??
messages().reduce(
(latest, message) => Math.max(latest, message.turn),
- pendingElicitation()?.turn ?? 0
+ pending().reduce((latest, request) => Math.max(latest, request.turn), 0)
);
- // A locked chip only offers questions from its anchored turn.
- const questionForTurn = () => {
- const question = pendingElicitation();
- return question?.turn === turn() ? question : undefined;
- };
- const elicitation = createElicitationController({
- pending: questionForTurn,
+ // An anchored chip only offers interactions from its own turn.
+ const pendingForTurn = () =>
+ pending().filter((request) => request.turn === turn());
+ const interactions = createInteractionController({
+ sessionId: () => props.agentSessionId,
+ pending: pendingForTurn,
canEdit,
issue: (action) => live.issue(action),
+ onFailure: toast.failure,
});
- const asking = (): MagicChipQuestion | undefined => {
- const question = questionForTurn();
- if (!question) return undefined;
+ const asking = (): MagicChipInteraction | undefined => {
+ const request = pendingForTurn()[0];
+ if (!request) return undefined;
+ const tool = messages()
+ .find(
+ (message) =>
+ message.author.kind === 'agent' && message.turn === request.turn
+ )
+ ?.parts.find(
+ (part) => part.kind === 'tool_use' && part.id === request.toolCall
+ );
return {
- question,
- canAnswer: elicitation.canAnswer(),
+ request,
+ canAnswer: interactions.canAnswer(),
+ answering: interactions.answering(request),
+ ...(request.kind === 'permission' && tool?.kind === 'tool_use'
+ ? {
+ action:
+ tool.detail.kind === 'terminal'
+ ? 'Run command'
+ : toolLabel(tool.name),
+ detail: toolCallDetail(tool),
+ }
+ : {}),
};
};
@@ -193,5 +214,5 @@ export function createMagicChipModel(props: MagicChipData): {
: undefined;
});
- return { presentation, header, elicitation };
+ return { presentation, header, interactions };
}
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.test.ts
index 8e71a1fd49..dc7467f067 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.test.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.test.ts
@@ -202,6 +202,7 @@ describe('deriveMagicChipPresentation', () => {
},
{
kind: 'permission',
+ requestId: 'perm-1',
toolCall: 'tool',
options: [],
outcome: { kind },
@@ -223,7 +224,7 @@ describe('deriveMagicChipPresentation', () => {
response: response({
parts: [
{
- kind: 'elicitation',
+ kind: 'elicitation' as const,
requestId: 0,
toolCall: 'tool',
message: 'Which approach?',
@@ -362,7 +363,8 @@ describe('deriveMagicChipPresentation', () => {
describe('a question the agent is waiting on', () => {
const asking = {
- question: {
+ request: {
+ kind: 'elicitation' as const,
requestId: 9,
turn: 0,
toolCall: 'toolu_evt',
@@ -380,6 +382,7 @@ describe('deriveMagicChipPresentation', () => {
},
},
canAnswer: true,
+ answering: false,
};
it('outranks whatever else the open turn is doing, keeping the answer so far', () => {
@@ -478,7 +481,8 @@ describe('presentationStatus', () => {
busy: true,
};
const question = {
- question: {
+ request: {
+ kind: 'elicitation' as const,
requestId: 1,
turn: 0,
toolCall: null,
@@ -499,14 +503,14 @@ describe('presentationStatus', () => {
presentationStatus({
kind: 'asking',
markdown: '',
- asking: { ...question, canAnswer: true },
+ asking: { ...question, canAnswer: true, answering: false },
})
).toEqual({ label: 'Waiting for you', busy: false });
expect(
presentationStatus({
kind: 'asking',
markdown: '',
- asking: { ...question, canAnswer: false },
+ asking: { ...question, canAnswer: false, answering: false },
})
).toEqual({ label: 'Waiting for an editor', busy: false });
});
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.ts
index 67bf8298f8..58331dc4ef 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.ts
@@ -2,7 +2,7 @@ import type { MagicChipStatus } from '@macro-inc/lexical-core';
import type {
FoldedMessage,
MessagePart,
- PendingElicitation,
+ PendingInteraction,
ToolName,
} from '@service-agent-fold/generated/types';
import { match } from 'ts-pattern';
@@ -29,12 +29,15 @@ export type MagicChipHeader = {
};
/**
- * A question the agent is waiting on, as the chip offers it: the live slot
+ * A permission or question the agent is waiting on: the live interaction
* from the session's metadata, and whether this viewer may answer (edit
* access on the session) or is watching someone else be asked.
*/
-export type MagicChipQuestion = {
- question: PendingElicitation;
+export type MagicChipInteraction = {
+ request: PendingInteraction;
+ answering: boolean;
+ action?: string;
+ detail?: string;
canAnswer: boolean;
};
@@ -50,17 +53,17 @@ export type MagicChipQuestion = {
export type MagicChipPresentation =
| { kind: 'working'; activity: MagicChipActivity }
| { kind: 'answering'; markdown: string; activity: MagicChipActivity }
- | { kind: 'asking'; markdown: string; asking: MagicChipQuestion }
+ | { kind: 'asking'; markdown: string; asking: MagicChipInteraction }
| { kind: 'settled'; markdown: string };
export type MagicChipPresentationInput = {
persistedStatus: MagicChipStatus;
/**
- * The question the session is blocked on, when it belongs to this chip's
- * turn. The chip is a turn's surface, so a question asked in a later turn
+ * The interaction the session is blocked on, when it belongs to this chip's
+ * turn. The chip is a turn's surface, so a request made in a later turn
* is that turn's chip's to show.
*/
- asking?: MagicChipQuestion;
+ asking?: MagicChipInteraction;
/**
* Freshest lifecycle event seen on the live log stream, as its wire string.
* A stopgap for {@link persistedStatus} being a snapshot from when the chip
@@ -365,7 +368,11 @@ export function presentationStatus(
return match(presentation)
.with({ kind: 'working' }, { kind: 'answering' }, (p) => p.activity)
.with({ kind: 'asking' }, ({ asking }) => ({
- label: asking.canAnswer ? 'Waiting for you' : 'Waiting for an editor',
+ label: asking.answering
+ ? 'Sending answer'
+ : asking.canAnswer
+ ? 'Waiting for you'
+ : 'Waiting for an editor',
busy: false,
}))
.with({ kind: 'settled' }, () => ({ label: 'Done', busy: false }))
diff --git a/apps/web/src/lib/queries/agent-session/control.ts b/apps/web/src/lib/queries/agent-session/control.ts
index 0cd92b5a7c..3b11ec7d57 100644
--- a/apps/web/src/lib/queries/agent-session/control.ts
+++ b/apps/web/src/lib/queries/agent-session/control.ts
@@ -46,12 +46,18 @@ export function useAgentSessionControlMutation(
return useMutation(() => ({
gcTime: 0,
mutationFn: async ({ sessionId, action }: AgentSessionControlVars) =>
- await throwOnErr(() =>
- agentHarnessServiceClient.control(sessionId, action)
- ),
+ await throwOnErr(() => controlAgentSession(sessionId, action)),
...withCallbacks<ControlResponse, Error, AgentSessionControlVars, unknown>(
{},
callbacks
),
}));
}
+
+/** Send a session action while preserving the client's typed result. */
+export function controlAgentSession(
+ sessionId: string,
+ request: ControlRequest
+) {
+ return agentHarnessServiceClient.control(sessionId, request);
+}
diff --git a/apps/web/src/lib/queries/agent-session/mutations.ts b/apps/web/src/lib/queries/agent-session/mutations.ts
index c3958203bd..40e31f95ba 100644
--- a/apps/web/src/lib/queries/agent-session/mutations.ts
+++ b/apps/web/src/lib/queries/agent-session/mutations.ts
@@ -6,6 +6,7 @@ import type {
} from '@service-agent-harness/generated/schemas';
import { useMutation } from '@tanstack/solid-query';
import { invalidateAllSoup } from '../soup/cache';
+import { controlAgentSession } from './control';
export function useCreateAgentSessionMutation() {
return useMutation(() => ({
@@ -22,8 +23,6 @@ export function useAgentSessionControlMutation() {
return useMutation(() => ({
retry: false,
mutationFn: (vars: { sessionId: string; request: ControlRequest }) =>
- throwOnErr(() =>
- agentHarnessServiceClient.control(vars.sessionId, vars.request)
- ),
+ throwOnErr(() => controlAgentSession(vars.sessionId, vars.request)),
}));
}
diff --git a/apps/web/src/lib/queries/agents/agents.ts b/apps/web/src/lib/queries/agents/agents.ts
index ff61dc1e8d..246998b58a 100644
--- a/apps/web/src/lib/queries/agents/agents.ts
+++ b/apps/web/src/lib/queries/agents/agents.ts
@@ -30,6 +30,12 @@ export type CreateAgentParams = {
/** Which Pipedream MCP servers the agent's sessions are handed. */
mcp: AgentMcpServers;
teamId?: string;
+ /**
+ * Whether the agent's sessions approve permission requests without asking.
+ * Omit to defer to the runtime's default: built-in runtimes auto-accept,
+ * macrod prompts.
+ */
+ autoAcceptPermissions?: boolean;
};
export type UpdateAgentParams = CreateAgentParams & {
@@ -81,6 +87,7 @@ export function useCreateAgentMutation() {
instructions: vars.instructions,
mcp: vars.mcp,
team_id: vars.teamId,
+ auto_accept_permissions: vars.autoAcceptPermissions ?? null,
})
),
onSuccess: async (agent) => {
@@ -113,6 +120,7 @@ export function useUpdateAgentMutation() {
instructions: vars.instructions,
mcp: vars.mcp,
team_id: vars.teamId,
+ auto_accept_permissions: vars.autoAcceptPermissions ?? null,
})
),
onSuccess: async (updated) => {
diff --git a/apps/web/src/lib/queries/harnesses/harnesses.ts b/apps/web/src/lib/queries/harnesses/harnesses.ts
index 3bda39a246..d10f3b7472 100644
--- a/apps/web/src/lib/queries/harnesses/harnesses.ts
+++ b/apps/web/src/lib/queries/harnesses/harnesses.ts
@@ -10,6 +10,7 @@ import { useMutation, useQuery } from '@tanstack/solid-query';
import { harnessKeys } from './keys';
export type ApproveHarnessPairingParams = {
+ allowPermissionBypass?: boolean;
code: string;
name?: string;
teamId?: string;
@@ -65,6 +66,7 @@ export function useApproveHarnessPairingMutation() {
code: vars.code,
name: vars.name,
team_id: vars.teamId,
+ allow_permission_bypass: vars.allowPermissionBypass ?? false,
})
),
onSuccess: async (_harness, vars) => {
diff --git a/apps/web/src/lib/service-clients/service-agent-fold/generated/types.ts b/apps/web/src/lib/service-clients/service-agent-fold/generated/types.ts
index a617d2cf84..7dacc5deb1 100644
--- a/apps/web/src/lib/service-clients/service-agent-fold/generated/types.ts
+++ b/apps/web/src/lib/service-clients/service-agent-fold/generated/types.ts
@@ -1,4 +1,19 @@
// This file has been generated by Specta. Do not edit this file manually.
+/**
+ * The JSON-RPC id of a request the agent made, as the agent wrote it.
+ *
+ * Kept in the agent's own shape - a number stays a number - because an
+ * answer has to echo it exactly; `"7"` does not answer `7`.
+ */
+export type AgentRequestId =
+ /**
+ * A numeric id. Exported as a plain TypeScript number: agents count
+ * requests from zero, nowhere near where an `i64` stops round-tripping.
+ */
+ | number
+ /** A string id. */
+ | string;
+
/**
* Terminal output with ANSI escape sequences left in place.
*
@@ -551,6 +566,8 @@ export type MessagePart =
/** The agent asking to proceed. */
| {
kind: 'permission';
+ /** The agent request id an approval must echo. */
+ requestId: AgentRequestId;
/** The tool call permission was requested for. */
toolCall: ToolUseId;
/** The choices offered, in the order ACP listed them. */
@@ -651,6 +668,29 @@ export type PendingElicitation = {
request: ElicitationRequest;
};
+/** An answerable request. Each variant retains its own response semantics. */
+export type PendingInteraction =
+ /** A choice among the permission options offered by the agent. */
+ | ({
+ kind: 'permission';
+ } & PendingPermission)
+ /** A form, URL consent, or user tool review. */
+ | ({
+ kind: 'elicitation';
+ } & PendingElicitation);
+
+/** A permission request the current connection can still answer. */
+export type PendingPermission = {
+ /** The agent's request id, preserving numeric and string identities. */
+ requestId: AgentRequestId;
+ /** The turn that asked. */
+ turn: number;
+ /** The tool whose execution needs permission. */
+ toolCall: ToolUseId;
+ /** The options the agent offered. */
+ options: PermissionOption[];
+};
+
/** One choice offered for a permission request. */
export type PermissionOption = {
/** The id to report back when this option is chosen. */
@@ -776,11 +816,11 @@ export type SessionMetadata = {
*/
status: string | null;
/**
- * The one elicitation the user can answer right now. `None` when
- * nothing is pending, when the turn that asked has ended, or when the
- * connection that asked is gone - the request id dies with it.
+ * Requests the user can answer on the current turn and connection.
+ * Multiple permissions may coexist with the one allowed elicitation.
+ * History remains in the transcript after these live requests clear.
*/
- pendingElicitation: PendingElicitation | null;
+ pendingInteractions: PendingInteraction[];
/**
* Where the newest turn stands, as one value. Readers used to derive it
* from the transcript's tail, the status, and their own record of what
@@ -1148,7 +1188,7 @@ export type TurnState =
| 'running'
/** A stop was issued against the open turn and no stop reason has arrived. */
| 'stopping'
- /** The open turn is waiting on the user to answer an elicitation. */
+ /** The open turn is waiting on a permission or elicitation response. */
| 'blocked'
/** The runtime reported `disconnected`; whatever was open is not moving. */
| 'disconnected';
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentAction.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentAction.ts
index 04ac108cb0..94432bdc9c 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentAction.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentAction.ts
@@ -7,6 +7,7 @@
import type { AgentActionOneOf } from './agentActionOneOf';
import type { AgentActionOneOfFour } from './agentActionOneOfFour';
import type { AgentActionOneOfNine } from './agentActionOneOfNine';
+import type { AgentActionOneOfOnefour } from './agentActionOneOfOnefour';
import type { AgentActionOneOfOneone } from './agentActionOneOfOneone';
import type { AgentActionOneOfSeven } from './agentActionOneOfSeven';
@@ -18,4 +19,5 @@ export type AgentAction =
| AgentActionOneOfFour
| AgentActionOneOfSeven
| AgentActionOneOfNine
- | AgentActionOneOfOneone;
+ | AgentActionOneOfOneone
+ | AgentActionOneOfOnefour;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentActionOneOfOnefour.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentActionOneOfOnefour.ts
new file mode 100644
index 0000000000..a53f964063
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentActionOneOfOnefour.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 { AgentActionOneOfOnefourAllOf } from './agentActionOneOfOnefourAllOf';
+import type { AgentPermissionAction } from './agentPermissionAction';
+
+/**
+ * Answer a permission request the agent is waiting on.
+ */
+export type AgentActionOneOfOnefour = AgentPermissionAction &
+ AgentActionOneOfOnefourAllOf;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentActionOneOfOnefourAllOf.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentActionOneOfOnefourAllOf.ts
new file mode 100644
index 0000000000..509044a209
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentActionOneOfOnefourAllOf.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 { AgentActionOneOfOnefourAllOfType } from './agentActionOneOfOnefourAllOfType';
+
+export type AgentActionOneOfOnefourAllOf = {
+ type: AgentActionOneOfOnefourAllOfType;
+};
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentActionOneOfOnefourAllOfType.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentActionOneOfOnefourAllOfType.ts
new file mode 100644
index 0000000000..0c7cb3c06e
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentActionOneOfOnefourAllOfType.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 AgentActionOneOfOnefourAllOfType =
+ (typeof AgentActionOneOfOnefourAllOfType)[keyof typeof AgentActionOneOfOnefourAllOfType];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const AgentActionOneOfOnefourAllOfType = {
+ respondToPermission: 'respondToPermission',
+} as const;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentPermissionAction.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentPermissionAction.ts
new file mode 100644
index 0000000000..eca492c24a
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentPermissionAction.ts
@@ -0,0 +1,23 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { PermissionAnswer } from './permissionAnswer';
+
+/**
+ * A user's answer to the agent's `session/request_permission`.
+
+Unlike every other action this is not a new request but the reply to one
+the agent made, so it carries the agent's own request id rather than
+receiving a server-minted one.
+ */
+export interface AgentPermissionAction {
+ /** What the user decided. */
+ answer: PermissionAnswer;
+ /** The agent's JSON-RPC request id, echoed verbatim from the folded
+permission part. A string or a number on the wire; agents mint both,
+and `7` does not answer `"7"`. */
+ requestId: unknown;
+}
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.ts
index ed99e4909f..3ab37bc318 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
@@ -15,6 +15,9 @@ export * from './agentActionOneOfFourAllOf';
export * from './agentActionOneOfFourAllOfType';
export * from './agentActionOneOfNine';
export * from './agentActionOneOfNineType';
+export * from './agentActionOneOfOnefour';
+export * from './agentActionOneOfOnefourAllOf';
+export * from './agentActionOneOfOnefourAllOfType';
export * from './agentActionOneOfOneone';
export * from './agentActionOneOfOneoneAllOf';
export * from './agentActionOneOfOneoneAllOfType';
@@ -24,6 +27,7 @@ export * from './agentModelDto';
export * from './agentModelDtoDescription';
export * from './agentModelDtoGroup';
export * from './agentModelsStatusDto';
+export * from './agentPermissionAction';
export * from './agentPromptAction';
export * from './agentRepositoriesResponse';
export * from './agentRepositoryDto';
@@ -127,6 +131,11 @@ export * from './messageParentOneOfThree';
export * from './messageParentOneOfThreeType';
export * from './messageParentOneOfType';
export * from './modelHarnessDto';
+export * from './permissionAnswer';
+export * from './permissionAnswerOneOf';
+export * from './permissionAnswerOneOfKind';
+export * from './permissionAnswerOneOfThree';
+export * from './permissionAnswerOneOfThreeKind';
export * from './previewAgentSessionsRequest';
export * from './previewAgentSessionsResponse';
export * from './promptAttachment';
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/permissionAnswer.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/permissionAnswer.ts
new file mode 100644
index 0000000000..73fda076c5
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/permissionAnswer.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 { PermissionAnswerOneOf } from './permissionAnswerOneOf';
+import type { PermissionAnswerOneOfThree } from './permissionAnswerOneOfThree';
+
+/**
+ * The decision carried by an [`AgentPermissionAction`].
+ */
+export type PermissionAnswer =
+ | PermissionAnswerOneOf
+ | PermissionAnswerOneOfThree;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/permissionAnswerOneOf.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/permissionAnswerOneOf.ts
new file mode 100644
index 0000000000..78df7f6f91
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/permissionAnswerOneOf.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 { PermissionAnswerOneOfKind } from './permissionAnswerOneOfKind';
+
+/**
+ * One of the options the agent offered was chosen.
+ */
+export type PermissionAnswerOneOf = {
+ kind: PermissionAnswerOneOfKind;
+ /** The chosen option's id, as the agent listed it. */
+ optionId: string;
+};
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/permissionAnswerOneOfKind.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/permissionAnswerOneOfKind.ts
new file mode 100644
index 0000000000..0086cd9766
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/permissionAnswerOneOfKind.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 PermissionAnswerOneOfKind =
+ (typeof PermissionAnswerOneOfKind)[keyof typeof PermissionAnswerOneOfKind];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const PermissionAnswerOneOfKind = {
+ selected: 'selected',
+} as const;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/permissionAnswerOneOfThree.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/permissionAnswerOneOfThree.ts
new file mode 100644
index 0000000000..de43741a45
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/permissionAnswerOneOfThree.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 { PermissionAnswerOneOfThreeKind } from './permissionAnswerOneOfThreeKind';
+
+/**
+ * The request was dismissed without choosing.
+ */
+export type PermissionAnswerOneOfThree = {
+ kind: PermissionAnswerOneOfThreeKind;
+};
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/permissionAnswerOneOfThreeKind.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/permissionAnswerOneOfThreeKind.ts
new file mode 100644
index 0000000000..e58a873fa0
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/permissionAnswerOneOfThreeKind.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 PermissionAnswerOneOfThreeKind =
+ (typeof PermissionAnswerOneOfThreeKind)[keyof typeof PermissionAnswerOneOfThreeKind];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const PermissionAnswerOneOfThreeKind = {
+ cancelled: 'cancelled',
+} 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.json
index 136eda6e54..42d0ef5f75 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
@@ -1354,6 +1354,25 @@
}
],
"description": "Answer an `elicitation/create` the agent sent.\n\nThe one action whose wire form is a JSON-RPC *response* rather than a\nrequest or notification: the agent asked, we answer on its id. The\nminted [`AgentActionId`] therefore never reaches the wire for this\naction; the fold correlates on the agent's id instead."
+ },
+ {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/AgentPermissionAction",
+ "description": "Answer a permission request the agent is waiting on."
+ },
+ {
+ "type": "object",
+ "required": ["type"],
+ "properties": {
+ "type": {
+ "type": "string",
+ "enum": ["respondToPermission"]
+ }
+ }
+ }
+ ],
+ "description": "Answer a permission request the agent is waiting on."
}
],
"description": "One thing a caller wants an agent to do."
@@ -1391,6 +1410,20 @@
"description": "Model-selection availability returned over HTTP.",
"enum": ["available", "unsupported"]
},
+ "AgentPermissionAction": {
+ "type": "object",
+ "description": "A user's answer to the agent's `session/request_permission`.\n\nUnlike every other action this is not a new request but the reply to one\nthe agent made, so it carries the agent's own request id rather than\nreceiving a server-minted one.",
+ "required": ["requestId", "answer"],
+ "properties": {
+ "answer": {
+ "$ref": "#/components/schemas/PermissionAnswer",
+ "description": "What the user decided."
+ },
+ "requestId": {
+ "description": "The agent's JSON-RPC request id, echoed verbatim from the folded\npermission part. A string or a number on the wire; agents mint both,\nand `7` does not answer `\"7\"`."
+ }
+ }
+ },
"AgentPromptAction": {
"type": "object",
"description": "Ask the agent to work on something.",
@@ -2387,6 +2420,37 @@
"description": "Harness names accepted by the model discovery endpoint.",
"enum": ["in-memory", "cursor", "claude-cloud", "macrod"]
},
+ "PermissionAnswer": {
+ "oneOf": [
+ {
+ "type": "object",
+ "description": "One of the options the agent offered was chosen.",
+ "required": ["optionId", "kind"],
+ "properties": {
+ "kind": {
+ "type": "string",
+ "enum": ["selected"]
+ },
+ "optionId": {
+ "type": "string",
+ "description": "The chosen option's id, as the agent listed it."
+ }
+ }
+ },
+ {
+ "type": "object",
+ "description": "The request was dismissed without choosing.",
+ "required": ["kind"],
+ "properties": {
+ "kind": {
+ "type": "string",
+ "enum": ["cancelled"]
+ }
+ }
+ }
+ ],
+ "description": "The decision carried by an [`AgentPermissionAction`]."
+ },
"PreviewAgentSessionsRequest": {
"type": "object",
"description": "Request body for `POST /agent-sessions/preview`.\n\nClients serialize this, so both derives are used.",
diff --git a/apps/web/src/lib/service-clients/service-storage/client.ts b/apps/web/src/lib/service-clients/service-storage/client.ts
index a41fb6af80..1672c9b329 100644
--- a/apps/web/src/lib/service-clients/service-storage/client.ts
+++ b/apps/web/src/lib/service-clients/service-storage/client.ts
@@ -285,6 +285,7 @@ export type HarnessOwner =
/** A macrod harness registered with the workspace. */
export type Harness = {
+ allow_permission_bypass: boolean;
id: string;
kind: 'macrod';
name: string;
@@ -300,6 +301,7 @@ export type Harness = {
export type HarnessPairing = PairingDetails;
type ApproveHarnessPairingRequest = {
+ allow_permission_bypass?: boolean;
name?: string;
team_id?: string;
};
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agent.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agent.ts
index 0ccdc5e7c3..936f9088e9 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agent.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agent.ts
@@ -4,7 +4,7 @@
* document_storage_service
* OpenAPI spec version: 0.1.0
*/
-
+import type { AgentAutoAcceptPermissions } from './agentAutoAcceptPermissions';
import type { AgentChannelScope } from './agentChannelScope';
import type { AgentHarnessId } from './agentHarnessId';
import type { AgentMcpServers } from './agentMcpServers';
@@ -14,6 +14,9 @@ import type { Bot } from './bot';
* A persisted user- or team-owned AI agent.
*/
export interface Agent {
+ /** Whether the agent's sessions approve ACP permission requests without
+asking. `None` means always prompt. Bypass also requires the harness's opt-in. */
+ auto_accept_permissions?: AgentAutoAcceptPermissions;
/** The bot identity used for mentions and channel participation. */
bot: Bot;
/** Selected channel ids. Empty for a global agent. */
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentAutoAcceptPermissions.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentAutoAcceptPermissions.ts
new file mode 100644
index 0000000000..3b7ee8ba9e
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentAutoAcceptPermissions.ts
@@ -0,0 +1,12 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Whether the agent's sessions approve ACP permission requests without
+asking. `None` means always prompt. Bypass also requires the harness's opt-in.
+ */
+export type AgentAutoAcceptPermissions = boolean | null;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/approvePairingRequest.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/approvePairingRequest.ts
index 396b1bfcd8..ab2773a59f 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/approvePairingRequest.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/approvePairingRequest.ts
@@ -11,6 +11,8 @@ import type { ApprovePairingRequestTeamId } from './approvePairingRequestTeamId'
* Request to approve a pairing and register the harness.
*/
export interface ApprovePairingRequest {
+ /** Whether agents may bypass ACP permission requests on this harness. */
+ allow_permission_bypass?: boolean;
/** Display name override. Defaults to the daemon's requested name. */
name?: ApprovePairingRequestName;
/** Owning team. Omit for a private, user-owned harness. */
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createAgentRequest.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createAgentRequest.ts
index 829304925f..f95a92c88b 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createAgentRequest.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createAgentRequest.ts
@@ -7,6 +7,7 @@
import type { AgentChannelScope } from './agentChannelScope';
import type { AgentMcpServers } from './agentMcpServers';
+import type { CreateAgentRequestAutoAcceptPermissions } from './createAgentRequestAutoAcceptPermissions';
import type { CreateAgentRequestAvatarUrl } from './createAgentRequestAvatarUrl';
import type { CreateAgentRequestDescription } from './createAgentRequestDescription';
import type { CreateAgentRequestHarnessId } from './createAgentRequestHarnessId';
@@ -16,6 +17,9 @@ import type { CreateAgentRequestTeamId } from './createAgentRequestTeamId';
* Request to create a persisted AI agent.
*/
export interface CreateAgentRequest {
+ /** Whether the agent's sessions approve ACP permission requests without
+asking. Omit to always prompt. */
+ auto_accept_permissions?: CreateAgentRequestAutoAcceptPermissions;
/** Optional avatar URL or data URL. */
avatar_url?: CreateAgentRequestAvatarUrl;
/** Selected channels. Must be non-empty only for `selected` scope. */
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createAgentRequestAutoAcceptPermissions.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createAgentRequestAutoAcceptPermissions.ts
new file mode 100644
index 0000000000..a974b240d7
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createAgentRequestAutoAcceptPermissions.ts
@@ -0,0 +1,12 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Whether the agent's sessions approve ACP permission requests without
+asking. Omit to always prompt.
+ */
+export type CreateAgentRequestAutoAcceptPermissions = boolean | null;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createPairingRequest.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createPairingRequest.ts
index 3d6b2269e2..558432c241 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createPairingRequest.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createPairingRequest.ts
@@ -4,6 +4,7 @@
* document_storage_service
* OpenAPI spec version: 0.1.0
*/
+import type { CreatePairingRequestAllowPermissionBypass } from './createPairingRequestAllowPermissionBypass';
import type { CreatePairingRequestHost } from './createPairingRequestHost';
import type { CreatePairingRequestScope } from './createPairingRequestScope';
@@ -13,6 +14,8 @@ import type { CreatePairingRequestScope } from './createPairingRequestScope';
The daemon serializes this, so both derives are used.
*/
export interface CreatePairingRequest {
+ /** Daemon operator consent ceiling. Omitted by older clients; web approval decides. */
+ allow_permission_bypass?: CreatePairingRequestAllowPermissionBypass;
/** Display-only description of the machine, e.g. `eric@macbook / darwin`. */
host?: CreatePairingRequestHost;
/** Requested harness display name (typically the machine's hostname). */
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createPairingRequestAllowPermissionBypass.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createPairingRequestAllowPermissionBypass.ts
new file mode 100644
index 0000000000..ba7a7562d7
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createPairingRequestAllowPermissionBypass.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Daemon operator consent ceiling. Omitted by older clients; web approval decides.
+ */
+export type CreatePairingRequestAllowPermissionBypass = boolean | null;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/harness.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/harness.ts
index fe41a2d2bc..97ca486ce4 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/harness.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/harness.ts
@@ -14,6 +14,8 @@ import type { HarnessOwner } from './harnessOwner';
Clients deserialize this, so both derives are used.
*/
export interface Harness {
+ /** Whether agents may bypass ACP permission requests on this harness. */
+ allow_permission_bypass?: boolean;
/** Whether the daemon currently holds a runtime connection. */
connected: boolean;
/** Creation timestamp. */
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
index e6a2048236..aff5f960ff 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
@@ -15,6 +15,7 @@ export * from './addParticipantsRequest';
export * from './addPinRequest';
export * from './agent';
export * from './agentActionId';
+export * from './agentAutoAcceptPermissions';
export * from './agentChannelScope';
export * from './agentHarnessId';
export * from './agentMcpServer';
@@ -360,6 +361,7 @@ export * from './copyDocumentRequestVersionId';
export * from './copyDocumentResponse';
export * from './countedReaction';
export * from './createAgentRequest';
+export * from './createAgentRequestAutoAcceptPermissions';
export * from './createAgentRequestAvatarUrl';
export * from './createAgentRequestDescription';
export * from './createAgentRequestHarnessId';
@@ -431,6 +433,7 @@ export * from './createMarkdownDocumentRequestProjectId';
export * from './createMarkdownDocumentResponse';
export * from './createMarkdownHandler200';
export * from './createPairingRequest';
+export * from './createPairingRequestAllowPermissionBypass';
export * from './createPairingRequestHost';
export * from './createPairingRequestScope';
export * from './createProjectRequest';
@@ -956,6 +959,7 @@ export * from './notificationFilters';
export * from './notificationState';
export * from './pairingDetails';
export * from './pairingDetailsHost';
+export * from './pairingDetailsRequestedAllowPermissionBypass';
export * from './pairingDetailsRequestedScope';
export * from './params';
export * from './paramsExpand';
@@ -1434,6 +1438,7 @@ export * from './unthreadedPdfUuidRequest';
export * from './unthreadedPdfUuidRequestOneOf';
export * from './unthreadedPdfUuidRequestOneOfAttachmentType';
export * from './updateAgentRequest';
+export * from './updateAgentRequestAutoAcceptPermissions';
export * from './updateAgentRequestAvatarUrl';
export * from './updateAgentRequestDescription';
export * from './updateAgentRequestHarnessId';
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/pairingDetails.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/pairingDetails.ts
index e86243b231..bb8276589d 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/pairingDetails.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/pairingDetails.ts
@@ -5,6 +5,7 @@
* OpenAPI spec version: 0.1.0
*/
import type { PairingDetailsHost } from './pairingDetailsHost';
+import type { PairingDetailsRequestedAllowPermissionBypass } from './pairingDetailsRequestedAllowPermissionBypass';
import type { PairingDetailsRequestedScope } from './pairingDetailsRequestedScope';
/**
@@ -19,6 +20,8 @@ export interface PairingDetails {
expires_at: string;
/** Display-only description of the machine. */
host?: PairingDetailsHost;
+ /** Daemon operator consent ceiling; false forbids bypass at approval. */
+ requested_allow_permission_bypass?: PairingDetailsRequestedAllowPermissionBypass;
/** Harness display name the daemon asked for. */
requested_name: string;
requested_scope?: PairingDetailsRequestedScope;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/pairingDetailsRequestedAllowPermissionBypass.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/pairingDetailsRequestedAllowPermissionBypass.ts
new file mode 100644
index 0000000000..3d61aeb7fb
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/pairingDetailsRequestedAllowPermissionBypass.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Daemon operator consent ceiling; false forbids bypass at approval.
+ */
+export type PairingDetailsRequestedAllowPermissionBypass = boolean | null;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/updateAgentRequest.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/updateAgentRequest.ts
index 51b96ba30f..02c4098b17 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/updateAgentRequest.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/updateAgentRequest.ts
@@ -7,6 +7,7 @@
import type { AgentChannelScope } from './agentChannelScope';
import type { AgentMcpServers } from './agentMcpServers';
+import type { UpdateAgentRequestAutoAcceptPermissions } from './updateAgentRequestAutoAcceptPermissions';
import type { UpdateAgentRequestAvatarUrl } from './updateAgentRequestAvatarUrl';
import type { UpdateAgentRequestDescription } from './updateAgentRequestDescription';
import type { UpdateAgentRequestHarnessId } from './updateAgentRequestHarnessId';
@@ -16,6 +17,9 @@ import type { UpdateAgentRequestTeamId } from './updateAgentRequestTeamId';
* Request to replace the editable configuration of a persisted AI agent.
*/
export interface UpdateAgentRequest {
+ /** Whether the agent's sessions approve ACP permission requests without
+asking. Omit to always prompt. */
+ auto_accept_permissions?: UpdateAgentRequestAutoAcceptPermissions;
/** Optional avatar URL or data URL. */
avatar_url?: UpdateAgentRequestAvatarUrl;
/** Selected channels. Must be non-empty only for `selected` scope. */
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/updateAgentRequestAutoAcceptPermissions.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/updateAgentRequestAutoAcceptPermissions.ts
new file mode 100644
index 0000000000..55d0b4f51b
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/updateAgentRequestAutoAcceptPermissions.ts
@@ -0,0 +1,12 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Whether the agent's sessions approve ACP permission requests without
+asking. Omit to always prompt.
+ */
+export type UpdateAgentRequestAutoAcceptPermissions = boolean | null;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
index b76cab9fd3..e92d3e462c 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
@@ -11,6 +11,12 @@ import * as zod from 'zod';
*/
export const listAgentsResponseItem = zod
.object({
+ auto_accept_permissions: zod
+ .boolean()
+ .nullish()
+ .describe(
+ "Whether the agent's sessions approve ACP permission requests without\nasking. `None` means always prompt. Bypass also requires the harness's opt-in."
+ ),
bot: zod
.object({
avatar_url: zod.string().nullish().describe('Optional avatar URL.'),
@@ -122,6 +128,12 @@ export const listAgentsResponse = zod.array(listAgentsResponseItem);
*/
export const createAgentBody = zod
.object({
+ auto_accept_permissions: zod
+ .boolean()
+ .nullish()
+ .describe(
+ "Whether the agent's sessions approve ACP permission requests without\nasking. Omit to always prompt."
+ ),
avatar_url: zod
.string()
.nullish()
@@ -203,6 +215,12 @@ export const updateAgentParams = zod.object({
export const updateAgentBody = zod
.object({
+ auto_accept_permissions: zod
+ .boolean()
+ .nullish()
+ .describe(
+ "Whether the agent's sessions approve ACP permission requests without\nasking. Omit to always prompt."
+ ),
avatar_url: zod
.string()
.nullish()
@@ -279,6 +297,12 @@ export const updateAgentBody = zod
export const updateAgentResponse = zod
.object({
+ auto_accept_permissions: zod
+ .boolean()
+ .nullish()
+ .describe(
+ "Whether the agent's sessions approve ACP permission requests without\nasking. `None` means always prompt. Bypass also requires the harness's opt-in."
+ ),
bot: zod
.object({
avatar_url: zod.string().nullish().describe('Optional avatar URL.'),
@@ -8981,6 +9005,12 @@ it, and creation is throttled in the domain service.
*/
export const createHarnessPairingBody = zod
.object({
+ allow_permission_bypass: zod
+ .boolean()
+ .nullish()
+ .describe(
+ 'Daemon operator consent ceiling. Omitted by older clients; web approval decides.'
+ ),
host: zod
.string()
.nullish()
@@ -9023,6 +9053,12 @@ export const getHarnessPairingResponse = zod
.string()
.nullish()
.describe('Display-only description of the machine.'),
+ requested_allow_permission_bypass: zod
+ .boolean()
+ .nullish()
+ .describe(
+ 'Daemon operator consent ceiling; false forbids bypass at approval.'
+ ),
requested_name: zod
.string()
.describe('Harness display name the daemon asked for.'),
@@ -9048,6 +9084,12 @@ export const approveHarnessPairingParams = zod.object({
export const approveHarnessPairingBody = zod
.object({
+ allow_permission_bypass: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'Whether agents may bypass ACP permission requests on this harness.'
+ ),
name: zod
.string()
.nullish()
@@ -9063,6 +9105,12 @@ export const approveHarnessPairingBody = zod
export const approveHarnessPairingResponse = zod
.object({
+ allow_permission_bypass: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'Whether agents may bypass ACP permission requests on this harness.'
+ ),
connected: zod
.boolean()
.describe('Whether the daemon currently holds a runtime connection.'),
@@ -9123,6 +9171,12 @@ export const claimHarnessPairingResponse = zod
.object({
harness: zod
.object({
+ allow_permission_bypass: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'Whether agents may bypass ACP permission requests on this harness.'
+ ),
connected: zod
.boolean()
.describe('Whether the daemon currently holds a runtime connection.'),
@@ -9171,6 +9225,12 @@ export const claimHarnessPairingResponse = zod
*/
export const listHarnessesResponseItem = zod
.object({
+ allow_permission_bypass: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'Whether agents may bypass ACP permission requests on this harness.'
+ ),
connected: zod
.boolean()
.describe('Whether the daemon currently holds a runtime connection.'),
@@ -9213,6 +9273,12 @@ export const listHarnessesResponse = zod.array(listHarnessesResponseItem);
*/
export const getSelfHarnessResponse = zod
.object({
+ allow_permission_bypass: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'Whether agents may bypass ACP permission requests on this harness.'
+ ),
connected: zod
.boolean()
.describe('Whether the daemon currently holds a runtime connection.'),
diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.json
index 240858172b..b68126c5dc 100644
--- a/apps/web/src/lib/service-clients/service-storage/openapi.json
+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json
@@ -14287,6 +14287,10 @@
"mcp"
],
"properties": {
+ "auto_accept_permissions": {
+ "type": ["boolean", "null"],
+ "description": "Whether the agent's sessions approve ACP permission requests without\nasking. `None` means always prompt. Bypass also requires the harness's opt-in."
+ },
"bot": {
"$ref": "#/components/schemas/Bot",
"description": "The bot identity used for mentions and channel participation."
@@ -15861,6 +15865,10 @@
"type": "object",
"description": "Request to approve a pairing and register the harness.",
"properties": {
+ "allow_permission_bypass": {
+ "type": "boolean",
+ "description": "Whether agents may bypass ACP permission requests on this harness."
+ },
"name": {
"type": ["string", "null"],
"description": "Display name override. Defaults to the daemon's requested name."
@@ -18628,6 +18636,10 @@
"channel_scope"
],
"properties": {
+ "auto_accept_permissions": {
+ "type": ["boolean", "null"],
+ "description": "Whether the agent's sessions approve ACP permission requests without\nasking. Omit to always prompt."
+ },
"avatar_url": {
"type": ["string", "null"],
"description": "Optional avatar URL or data URL."
@@ -19235,6 +19247,10 @@
"description": "Request to open a pairing: the daemon asks for a code the user approves.\n\nThe daemon serializes this, so both derives are used.",
"required": ["name"],
"properties": {
+ "allow_permission_bypass": {
+ "type": ["boolean", "null"],
+ "description": "Daemon operator consent ceiling. Omitted by older clients; web approval decides."
+ },
"host": {
"type": ["string", "null"],
"description": "Display-only description of the machine, e.g. `eric@macbook / darwin`."
@@ -23829,6 +23845,10 @@
"connected"
],
"properties": {
+ "allow_permission_bypass": {
+ "type": "boolean",
+ "description": "Whether agents may bypass ACP permission requests on this harness."
+ },
"connected": {
"type": "boolean",
"description": "Whether the daemon currently holds a runtime connection."
@@ -25150,6 +25170,10 @@
"type": ["string", "null"],
"description": "Display-only description of the machine."
},
+ "requested_allow_permission_bypass": {
+ "type": ["boolean", "null"],
+ "description": "Daemon operator consent ceiling; false forbids bypass at approval."
+ },
"requested_name": {
"type": "string",
"description": "Harness display name the daemon asked for."
@@ -30037,6 +30061,10 @@
"channel_scope"
],
"properties": {
+ "auto_accept_permissions": {
+ "type": ["boolean", "null"],
+ "description": "Whether the agent's sessions approve ACP permission requests without\nasking. Omit to always prompt."
+ },
"avatar_url": {
"type": ["string", "null"],
"description": "Optional avatar URL or data URL."
diff --git a/crates/agent_fold/src/bin/fold_jsonl.rs b/crates/agent_fold/src/bin/fold_jsonl.rs
index d5da41fcd3..91184be277 100644
--- a/crates/agent_fold/src/bin/fold_jsonl.rs
+++ b/crates/agent_fold/src/bin/fold_jsonl.rs
@@ -261,6 +261,7 @@ fn render_part(part: &MessagePart) -> String {
tool_call,
options,
outcome,
+ ..
} => out.push_str(&render_permission(tool_call, options, outcome)),
MessagePart::Control { control, outcome } => {
let label = match control {
diff --git a/crates/agent_fold/src/domain/fold/control.rs b/crates/agent_fold/src/domain/fold/control.rs
index 79343aca05..704b1ba62c 100644
--- a/crates/agent_fold/src/domain/fold/control.rs
+++ b/crates/agent_fold/src/domain/fold/control.rs
@@ -1,7 +1,5 @@
//! Control operations the user issues on the session.
-use std::collections::HashMap;
-
use crate::domain::model::{Author, Control, ControlOutcome, FoldedMessage, MessagePart, TurnId};
use agent_client_protocol::schema::v1::RequestId;
use agent_runtime_protocol::domain::action::AgentActionId;
@@ -41,7 +39,6 @@ impl FoldState {
stop_requested: false,
prompt_id: Some(prompt_id.clone()),
agent: None,
- permission_positions: HashMap::new(),
plan_position: None,
expects_reply: false,
});
diff --git a/crates/agent_fold/src/domain/fold/elicitation.rs b/crates/agent_fold/src/domain/fold/elicitation.rs
index 06ee208b03..30eade7be8 100644
--- a/crates/agent_fold/src/domain/fold/elicitation.rs
+++ b/crates/agent_fold/src/domain/fold/elicitation.rs
@@ -29,7 +29,7 @@ use crate::domain::harness::{HarnessReader, ToolFrame};
use crate::domain::model::{
AnsweredChoice, AnsweredField, AnsweredValue, ElicitationOption, ElicitationOutcome,
ElicitationProperty, ElicitationPropertySchema, ElicitationRequest, ElicitationRequestId,
- ElicitationSchema, MessagePart, PendingElicitation, ToolUseId,
+ ElicitationSchema, MessagePart, PendingElicitation, PendingInteraction, ToolUseId,
};
impl FoldState {
@@ -120,14 +120,16 @@ impl FoldState {
// by refusing a second create; the fold mirrors it by never letting a
// second one take the slot, so a refused request still gets its part
// (and its `Errored` outcome) without ever being offered to the user.
- let metadata_changed = if self.metadata.pending_elicitation.is_none() {
- self.metadata.pending_elicitation = Some(PendingElicitation {
- request_id: id,
- turn: self.messages[at.message].id.0,
- tool_call,
- message: message_text,
- request: elicitation_request,
- });
+ let metadata_changed = if self.metadata.pending_elicitation().is_none() {
+ self.metadata
+ .pending_interactions
+ .push(PendingInteraction::Elicitation(PendingElicitation {
+ request_id: id,
+ turn: self.messages[at.message].id.0,
+ tool_call,
+ message: message_text,
+ request: elicitation_request,
+ }));
true
} else {
false
@@ -315,25 +317,13 @@ impl FoldState {
/// Returns whether the metadata moved.
pub(super) fn clear_pending_elicitation_if(
&mut self,
- matches: impl FnOnce(&PendingElicitation) -> bool,
+ matches: impl Fn(&PendingElicitation) -> bool,
) -> bool {
- match &self.metadata.pending_elicitation {
- Some(pending) if matches(pending) => {
- self.metadata.pending_elicitation = None;
- true
- }
- _ => false,
- }
- }
-
- /// After a prompt response: if no turn is open any more, the agent has
- /// moved past whatever it asked, and nothing should still offer the form.
- /// The part keeps its `Pending` outcome; only the live pointer clears.
- pub(super) fn turn_ended_clears_elicitation(&mut self) -> bool {
- if self.turn.is_some() {
- return false;
- }
- self.clear_pending_elicitation_if(|_| true)
+ let before = self.metadata.pending_interactions.len();
+ self.metadata.pending_interactions.retain(|pending| {
+ !matches!(pending, PendingInteraction::Elicitation(question) if matches(question))
+ });
+ before != self.metadata.pending_interactions.len()
}
/// Whether the question asked under `request_id` has an outcome. See
@@ -344,14 +334,6 @@ impl FoldState {
.flat_map(|message| message.parts.iter())
.any(|part| answered(part, request_id))
}
-
- /// Forget everything about outstanding elicitations: the connection that
- /// asked is gone and its request ids with it.
- pub(super) fn forget_elicitations(&mut self) -> bool {
- self.pending_elicitations.clear();
- self.completable_elicitations.clear();
- self.clear_pending_elicitation_if(|_| true)
- }
}
/// Whether `part`, or anything nested under it, is the question asked under
diff --git a/crates/agent_fold/src/domain/fold/permission.rs b/crates/agent_fold/src/domain/fold/permission.rs
index 99e1f1da42..7830f61d03 100644
--- a/crates/agent_fold/src/domain/fold/permission.rs
+++ b/crates/agent_fold/src/domain/fold/permission.rs
@@ -1,7 +1,8 @@
//! Permission requests and their answers.
use crate::domain::model::{
- MessagePart, PermissionOption, PermissionOptionKind, PermissionOutcome, ToolUseId,
+ MessagePart, PendingInteraction, PendingPermission, PermissionOption, PermissionOptionKind,
+ PermissionOutcome, ToolUseId,
};
use agent_client_protocol::RawJsonRpcParams;
use agent_client_protocol::schema::v1::{
@@ -9,7 +10,7 @@ use agent_client_protocol::schema::v1::{
};
use super::convert::deserialize_params;
-use super::state::{Changed, FoldState};
+use super::state::{Changed, FoldState, ToolPath};
impl FoldState {
/// Handle a `session/request_permission`: add a permission part and record
@@ -18,10 +19,10 @@ impl FoldState {
&mut self,
request_id: &RequestId,
params: Option<&RawJsonRpcParams>,
- ) -> Option<Changed> {
+ ) -> Option<(Changed, bool)> {
let request = deserialize_params::<RequestPermissionRequest>(params)?;
let tool_call = ToolUseId(request.tool_call.tool_call_id.0.to_string());
- let options = request
+ let options: Vec<PermissionOption> = request
.options
.into_iter()
.map(|option| PermissionOption {
@@ -31,20 +32,28 @@ impl FoldState {
})
.collect();
- // Recorded even with no turn open, so a late response is still
- // recognized as an answer rather than an uncorrelated frame.
- self.pending_permissions
- .insert(request_id.clone(), tool_call.clone());
-
let (changed, position) = self.push_agent_part(MessagePart::Permission {
+ request_id: request_id.into(),
tool_call: tool_call.clone(),
- options,
+ options: options.clone(),
outcome: PermissionOutcome::Pending,
})?;
- self.open_turn()
- .permission_positions
- .insert(tool_call, position);
- Some(changed)
+ self.pending_permissions.insert(
+ request_id.clone(),
+ ToolPath {
+ message: changed.message,
+ path: vec![position],
+ },
+ );
+ self.metadata
+ .pending_interactions
+ .push(PendingInteraction::Permission(PendingPermission {
+ request_id: request_id.into(),
+ turn: self.messages[changed.message].id.0,
+ tool_call,
+ options,
+ }));
+ Some((changed, true))
}
/// Handle the response to a permission request.
@@ -52,8 +61,8 @@ impl FoldState {
&mut self,
response_id: &RequestId,
value: Option<&serde_json::Value>,
- ) -> Option<Changed> {
- let tool_call = self.pending_permissions.remove(response_id)?;
+ ) -> Option<(Changed, bool)> {
+ let at = self.pending_permissions.remove(response_id)?;
let outcome = match value {
// A JSON-RPC error, not a result: the harness failed to answer
@@ -78,15 +87,20 @@ impl FoldState {
}
};
- let position = *self.turn.as_ref()?.permission_positions.get(&tool_call)?;
- let (message, parts) = self.agent_parts_mut()?;
if let Some(MessagePart::Permission {
outcome: existing, ..
- }) = parts.get_mut(position)
+ }) = self.part_at_mut(&at)
{
*existing = outcome;
}
- Some(Changed::updated(message))
+ let before = self.metadata.pending_interactions.len();
+ self.metadata.pending_interactions.retain(|pending| {
+ !matches!(pending, PendingInteraction::Permission(permission) if permission.request_id == response_id.into())
+ });
+ Some((
+ Changed::updated(at.message),
+ before != self.metadata.pending_interactions.len(),
+ ))
}
}
diff --git a/crates/agent_fold/src/domain/fold/state.rs b/crates/agent_fold/src/domain/fold/state.rs
index 1d48c6cf94..fc08d2a565 100644
--- a/crates/agent_fold/src/domain/fold/state.rs
+++ b/crates/agent_fold/src/domain/fold/state.rs
@@ -116,7 +116,7 @@ pub(super) struct FoldState {
/// How many turns have been opened, which is also the next [`TurnId`].
pub(super) turns_opened: u32,
/// Outstanding permission requests, by the id of the request that asked.
- pub(super) pending_permissions: HashMap<RequestId, ToolUseId>,
+ pub(super) pending_permissions: HashMap<RequestId, ToolPath>,
/// Outstanding `elicitation/create`s, by the id of the request that
/// asked: where the question's part sits, so its answer can find it.
/// Session-wide like [`Self::tool_positions`], since the part may have
@@ -177,9 +177,6 @@ pub(super) struct Turn {
/// [`FoldedMessage`] cannot hold an empty part list - which is also what
/// makes a turn the agent never answered derive no agent message at all.
pub(super) agent: Option<usize>,
- /// Where each permission sits in the agent message's parts, so outcomes
- /// can find it.
- pub(super) permission_positions: HashMap<ToolUseId, usize>,
/// Where this turn's plan sits in the agent message's parts, so later
/// plan updates can replace it.
pub(super) plan_position: Option<usize>,
@@ -198,7 +195,7 @@ impl FoldState {
pub(super) fn clear_pending(&mut self) {
self.pending_initialize = None;
self.pending_config_requests.clear();
- self.pending_permissions.clear();
+ self.forget_interactions();
self.pending_controls.clear();
self.close_turn(None);
}
@@ -251,7 +248,9 @@ impl FoldState {
// `control_from_runtime` never yields these: a prompt
// is folded below, and an elicitation answer is a
// response frame, correlated by the agent's id.
- AgentAction::Prompt(_) | AgentAction::RespondElicitation(_) => None,
+ AgentAction::Prompt(_)
+ | AgentAction::RespondElicitation(_)
+ | AgentAction::RespondToPermission(_) => None,
});
}
// A user's prompt opens a turn - and may close the one
@@ -265,32 +264,19 @@ impl FoldState {
.map(StepChange::Message)
.collect();
}
- StepChange::message(match &acp.0 {
- // The user's answer to a question or a permission
- // request. Each map holds only the ids of its own
- // requests, so trying the elicitations first is order,
- // not precedence.
- RawJsonRpcMessage::Response(Response::Result { id, result }) => {
- if let Some((changed, metadata)) =
- self.resolve_elicitation(id, Some(result), None)
- {
- return Self::message_and_metadata(changed, metadata);
- }
- self.resolve_permission(id, Some(result))
- }
- // An error response is this client refusing a request it
- // could not hold - a second question, an unknown mode -
- // or failing to answer a permission.
- RawJsonRpcMessage::Response(Response::Error { id, error }) => {
- if let Some((changed, metadata)) =
- self.resolve_elicitation(id, None, Some(&error.message))
- {
- return Self::message_and_metadata(changed, metadata);
- }
- self.resolve_permission(id, None)
- }
- // Handshake and configuration traffic: nothing to render.
+ let changed = match &acp.0 {
+ // Both responses correlate by the agent's request id;
+ // each decoder retains its own answer semantics.
+ RawJsonRpcMessage::Response(Response::Result { id, result }) => self
+ .resolve_elicitation(id, Some(result), None)
+ .or_else(|| self.resolve_permission(id, Some(result))),
+ RawJsonRpcMessage::Response(Response::Error { id, error }) => self
+ .resolve_elicitation(id, None, Some(&error.message))
+ .or_else(|| self.resolve_permission(id, None)),
RawJsonRpcMessage::Request(_) | RawJsonRpcMessage::Notification(_) => None,
+ };
+ changed.map_or_else(Vec::new, |(message, metadata)| {
+ Self::message_and_metadata(message, metadata)
})
}
@@ -334,9 +320,10 @@ impl FoldState {
RawJsonRpcMessage::Request(request)
if RequestPermissionRequest::matches_method(&request.method) =>
{
- StepChange::message(
- self.request_permission(&request.id, request.params.as_ref()),
- )
+ match self.request_permission(&request.id, request.params.as_ref()) {
+ Some((changed, metadata)) => Self::message_and_metadata(changed, metadata),
+ None => Vec::new(),
+ }
}
// The agent asking the user a question.
RawJsonRpcMessage::Request(request)
@@ -370,9 +357,7 @@ impl FoldState {
} else if control.is_some() {
StepChange::message(control)
} else {
- let mut changes = StepChange::message(self.end_turn(id, Some(result)));
- changes.extend(StepChange::metadata(self.turn_ended_clears_elicitation()));
- changes
+ StepChange::message(self.end_turn(id, Some(result)))
}
}
RawJsonRpcMessage::Response(Response::Error { id, error }) => {
@@ -382,9 +367,7 @@ impl FoldState {
if self.pending_config_requests.remove(id) || control.is_some() {
StepChange::message(control)
} else {
- let mut changes = StepChange::message(self.fail_turn(id, &error.message));
- changes.extend(StepChange::metadata(self.turn_ended_clears_elicitation()));
- changes
+ StepChange::message(self.fail_turn(id, &error.message))
}
}
RawJsonRpcMessage::Request(_) | RawJsonRpcMessage::Notification(_) => Vec::new(),
@@ -400,9 +383,8 @@ impl FoldState {
if matches!(event, SystemEvent::AcpReady) {
self.pending_initialize = None;
self.pending_config_requests.clear();
- self.pending_permissions.clear();
self.pending_controls.clear();
- changed |= self.forget_elicitations();
+ changed |= self.forget_interactions();
}
let status = Some(event.as_str().to_owned());
if self.metadata.status != status {
@@ -504,11 +486,35 @@ impl FoldState {
}
}
+ /// Forget live requests at a connection boundary, preserving the transcript.
+ fn forget_interactions(&mut self) -> bool {
+ self.pending_permissions.clear();
+ self.pending_elicitations.clear();
+ self.completable_elicitations.clear();
+ let changed = !self.metadata.pending_interactions.is_empty();
+ self.metadata.pending_interactions.clear();
+ changed
+ }
+
/// Recompute [`SessionMetadata::turn`] from the state, reporting whether
/// it moved. Called once per push, after the step, because it is a
/// projection of several things a step may touch at once.
pub(super) fn refresh_turn_state(&mut self) -> bool {
- let turn = if self.metadata.status.as_deref() == Some(SystemEvent::Disconnected.as_str()) {
+ // A live request belongs to one turn and connection. Its transcript
+ // part survives cancellation, but no surface may answer it afterwards.
+ let before = self.metadata.pending_interactions.len();
+ let live_turn = self
+ .turn
+ .as_ref()
+ .filter(|turn| !turn.stop_requested)
+ .map(|turn| turn.id.0);
+ let disconnected =
+ self.metadata.status.as_deref() == Some(SystemEvent::Disconnected.as_str());
+ self.metadata
+ .pending_interactions
+ .retain(|pending| !disconnected && Some(pending.turn()) == live_turn);
+ let interactions_changed = before != self.metadata.pending_interactions.len();
+ let turn = if disconnected {
TurnState::Disconnected
} else {
match &self.turn {
@@ -517,13 +523,13 @@ impl FoldState {
// was waiting on their answer is owed the stop, not the
// question they just walked away from.
Some(turn) if turn.stop_requested => TurnState::Stopping,
- Some(_) if self.metadata.pending_elicitation.is_some() => TurnState::Blocked,
+ Some(_) if !self.metadata.pending_interactions.is_empty() => TurnState::Blocked,
Some(turn) if turn.prompt_pending && turn.agent.is_none() => TurnState::Starting,
Some(_) => TurnState::Running,
}
};
if self.metadata.turn == turn {
- return false;
+ return interactions_changed;
}
self.metadata.turn = turn;
true
diff --git a/crates/agent_fold/src/domain/fold/turn.rs b/crates/agent_fold/src/domain/fold/turn.rs
index b034ef6c68..128a2c7055 100644
--- a/crates/agent_fold/src/domain/fold/turn.rs
+++ b/crates/agent_fold/src/domain/fold/turn.rs
@@ -1,7 +1,5 @@
//! Opening, closing, and failing turns.
-use std::collections::HashMap;
-
use crate::domain::error::FoldError;
use crate::domain::model::{Author, FoldedMessage, MessagePart, StopReason, TurnId};
use agent_client_protocol::RawJsonRpcParams;
@@ -136,7 +134,6 @@ impl FoldState {
stop_requested: false,
prompt_id: Some(prompt_id.clone()),
agent: None,
- permission_positions: HashMap::new(),
plan_position: None,
expects_reply: true,
});
@@ -279,7 +276,6 @@ impl FoldState {
stop_requested: false,
prompt_id: None,
agent: None,
- permission_positions: HashMap::new(),
plan_position: None,
expects_reply: true,
});
diff --git a/crates/agent_fold/src/domain/lifecycle.rs b/crates/agent_fold/src/domain/lifecycle.rs
index e7d59c320f..c11b0f273c 100644
--- a/crates/agent_fold/src/domain/lifecycle.rs
+++ b/crates/agent_fold/src/domain/lifecycle.rs
@@ -112,8 +112,7 @@ impl LifecycleFold {
fn observe_metadata(&mut self, metadata: &SessionMetadata, signals: &mut Vec<TurnSignal>) {
let now = metadata
- .pending_elicitation
- .as_ref()
+ .pending_elicitation()
.map(|pending| (pending.request_id.clone(), TurnId(pending.turn)));
if now == self.pending {
return;
@@ -122,7 +121,7 @@ impl LifecycleFold {
if let Some((request_id, turn)) = before {
signals.push(TurnSignal::ElicitationCleared { turn, request_id });
}
- if let (Some((request_id, turn)), Some(pending)) = (now, &metadata.pending_elicitation) {
+ if let (Some((request_id, turn)), Some(pending)) = (now, metadata.pending_elicitation()) {
signals.push(TurnSignal::ElicitationRaised {
turn,
request_id,
diff --git a/crates/agent_fold/src/domain/model.rs b/crates/agent_fold/src/domain/model.rs
index 060c70ba76..20d462e941 100644
--- a/crates/agent_fold/src/domain/model.rs
+++ b/crates/agent_fold/src/domain/model.rs
@@ -22,6 +22,8 @@ use specta::Type;
mod elicitation;
/// Per-push change reports.
mod event;
+/// Requests currently awaiting a user response.
+mod interaction;
/// Session-level metadata.
mod metadata;
/// The parts a message is made of.
@@ -47,6 +49,7 @@ pub use elicitation::{
ElicitationSchema, PendingElicitation,
};
pub use event::{FoldEvent, OwnedFoldEvent};
+pub use interaction::{PendingInteraction, PendingPermission};
pub use metadata::{AvailableCommand, Harness, ModelOption, SessionMetadata, TurnState};
pub use part::{Control, ControlOutcome, MessagePart, StopReason};
pub use permission::{PermissionOption, PermissionOptionKind, PermissionOutcome};
@@ -75,6 +78,33 @@ pub struct TurnId(pub u32);
#[specta(transparent)]
pub struct ToolUseId(pub String);
+/// The JSON-RPC id of a request the agent made, as the agent wrote it.
+///
+/// Kept in the agent's own shape - a number stays a number - because an
+/// answer has to echo it exactly; `"7"` does not answer `7`.
+#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Type)]
+#[serde(untagged)]
+pub enum AgentRequestId {
+ /// A numeric id. Exported as a plain TypeScript number: agents count
+ /// requests from zero, nowhere near where an `i64` stops round-tripping.
+ Number(#[specta(type = i32)] i64),
+ /// A string id.
+ Str(String),
+}
+
+impl From<&agent_client_protocol::schema::v1::RequestId> for AgentRequestId {
+ fn from(id: &agent_client_protocol::schema::v1::RequestId) -> Self {
+ use agent_client_protocol::schema::v1::RequestId;
+ match id {
+ RequestId::Number(number) => Self::Number(*number),
+ RequestId::Str(text) => Self::Str(text.clone()),
+ // Requests carry an id by definition; a null one is a protocol
+ // violation the fold renders rather than rejects.
+ RequestId::Null => Self::Str(id.to_string()),
+ }
+ }
+}
+
/// The natural key of a [`FoldedMessage`] within its session.
///
/// Nothing here is stored, so there is no surrogate row id to hand out.
diff --git a/crates/agent_fold/src/domain/model/interaction.rs b/crates/agent_fold/src/domain/model/interaction.rs
new file mode 100644
index 0000000000..baef7f5cf2
--- /dev/null
+++ b/crates/agent_fold/src/domain/model/interaction.rs
@@ -0,0 +1,41 @@
+//! Live requests awaiting a user's response, separate from transcript history.
+
+use serde::Serialize;
+use specta::Type;
+
+use super::{AgentRequestId, PendingElicitation, PermissionOption, ToolUseId};
+
+/// An answerable request. Each variant retains its own response semantics.
+#[derive(Debug, Clone, PartialEq, Serialize, Type)]
+#[serde(tag = "kind", rename_all = "snake_case")]
+pub enum PendingInteraction {
+ /// A choice among the permission options offered by the agent.
+ Permission(PendingPermission),
+ /// A form, URL consent, or user tool review.
+ Elicitation(PendingElicitation),
+}
+
+impl PendingInteraction {
+ /// The turn that asked for this response.
+ #[must_use]
+ pub fn turn(&self) -> u32 {
+ match self {
+ Self::Permission(pending) => pending.turn,
+ Self::Elicitation(pending) => pending.turn,
+ }
+ }
+}
+
+/// A permission request the current connection can still answer.
+#[derive(Debug, Clone, PartialEq, Serialize, Type)]
+#[serde(rename_all = "camelCase")]
+pub struct PendingPermission {
+ /// The agent's request id, preserving numeric and string identities.
+ pub request_id: AgentRequestId,
+ /// The turn that asked.
+ pub turn: u32,
+ /// The tool whose execution needs permission.
+ pub tool_call: ToolUseId,
+ /// The options the agent offered.
+ pub options: Vec<PermissionOption>,
+}
diff --git a/crates/agent_fold/src/domain/model/metadata.rs b/crates/agent_fold/src/domain/model/metadata.rs
index ed83c2b3b4..8f7a1b4067 100644
--- a/crates/agent_fold/src/domain/model/metadata.rs
+++ b/crates/agent_fold/src/domain/model/metadata.rs
@@ -3,6 +3,7 @@
use serde::Serialize;
use specta::Type;
+use super::PendingInteraction;
use super::elicitation::PendingElicitation;
/// Which ACP agent produced a session's log.
@@ -63,16 +64,29 @@ pub struct SessionMetadata {
/// The last system event's wire name (`"acp_ready"`, `"disconnected"`),
/// `None` until the runtime reports one.
pub status: Option<String>,
- /// The one elicitation the user can answer right now. `None` when
- /// nothing is pending, when the turn that asked has ended, or when the
- /// connection that asked is gone - the request id dies with it.
- pub pending_elicitation: Option<PendingElicitation>,
+ /// Requests the user can answer on the current turn and connection.
+ /// Multiple permissions may coexist with the one allowed elicitation.
+ /// History remains in the transcript after these live requests clear.
+ pub pending_interactions: Vec<PendingInteraction>,
/// Where the newest turn stands, as one value. Readers used to derive it
/// from the transcript's tail, the status, and their own record of what
/// they had posted; this is that derivation done once, in the fold.
pub turn: TurnState,
}
+impl SessionMetadata {
+ /// The one elicitation the session can currently answer, if any.
+ #[must_use]
+ pub fn pending_elicitation(&self) -> Option<&PendingElicitation> {
+ self.pending_interactions
+ .iter()
+ .find_map(|pending| match pending {
+ PendingInteraction::Elicitation(question) => Some(question),
+ PendingInteraction::Permission(_) => None,
+ })
+ }
+}
+
/// Where the newest turn stands.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Type)]
#[serde(rename_all = "snake_case")]
@@ -87,7 +101,7 @@ pub enum TurnState {
Running,
/// A stop was issued against the open turn and no stop reason has arrived.
Stopping,
- /// The open turn is waiting on the user to answer an elicitation.
+ /// The open turn is waiting on a permission or elicitation response.
Blocked,
/// The runtime reported `disconnected`; whatever was open is not moving.
Disconnected,
diff --git a/crates/agent_fold/src/domain/model/part.rs b/crates/agent_fold/src/domain/model/part.rs
index 4cf95da500..05223f651e 100644
--- a/crates/agent_fold/src/domain/model/part.rs
+++ b/crates/agent_fold/src/domain/model/part.rs
@@ -60,6 +60,9 @@ pub enum MessagePart {
},
/// The agent asking to proceed.
Permission {
+ /// The agent request id an approval must echo.
+ #[serde(rename = "requestId")]
+ request_id: super::AgentRequestId,
/// The tool call permission was requested for.
#[serde(rename = "toolCall")]
tool_call: ToolUseId,
diff --git a/crates/agent_fold/src/domain/model/search/test.rs b/crates/agent_fold/src/domain/model/search/test.rs
index 4ff1dd38d0..c73d39f6fc 100644
--- a/crates/agent_fold/src/domain/model/search/test.rs
+++ b/crates/agent_fold/src/domain/model/search/test.rs
@@ -116,6 +116,7 @@ fn searchable_text_includes_folded_json_and_visible_failure() {
#[test]
fn searchable_text_omits_non_semantic_permission_boilerplate() {
let message = message(vec![MessagePart::Permission {
+ request_id: crate::domain::model::AgentRequestId::Number(7),
tool_call: ToolUseId("tool-1".to_owned()),
options: Vec::new(),
outcome: PermissionOutcome::Pending,
diff --git a/crates/agent_fold/src/domain/speculation.rs b/crates/agent_fold/src/domain/speculation.rs
index 04c4dd0a7c..bcd10f29ae 100644
--- a/crates/agent_fold/src/domain/speculation.rs
+++ b/crates/agent_fold/src/domain/speculation.rs
@@ -354,8 +354,24 @@ impl SpeculativeFold {
match &speculation.action {
AgentAction::Stop => self.tier().stop_requested(),
AgentAction::RespondElicitation(answer) => {
- self.tier().elicitation_answered(&answer.request_id)
+ !self.tier().metadata().pending_elicitation().is_some_and(|pending| pending.request_id == answer.request_id)
+ && self.tier().elicitation_answered(&answer.request_id)
}
+ AgentAction::RespondToPermission(answer) => !self.tier().metadata().pending_interactions.iter().any(|pending| {
+ matches!(pending, super::model::PendingInteraction::Permission(permission)
+ if permission.request_id == super::model::AgentRequestId::from(&answer.request_id))
+ }) && self
+ .tier()
+ .messages()
+ .iter()
+ .flat_map(|message| message.parts.iter())
+ .any(|part| {
+ matches!(part,
+ super::model::MessagePart::Permission { request_id, outcome, .. }
+ if *request_id == super::model::AgentRequestId::from(&answer.request_id)
+ && !matches!(outcome, super::model::PermissionOutcome::Pending)
+ )
+ }),
AgentAction::Prompt(_) | AgentAction::Compact | AgentAction::SetModel(_) => self
.committed
.machine
diff --git a/crates/agent_fold/src/domain/speculation/test.rs b/crates/agent_fold/src/domain/speculation/test.rs
index cc15a4221f..e17ccd27c1 100644
--- a/crates/agent_fold/src/domain/speculation/test.rs
+++ b/crates/agent_fold/src/domain/speculation/test.rs
@@ -196,7 +196,7 @@ fn a_speculated_answer_resolves_the_question_and_unblocks_the_turn() {
}
);
assert!(pending, "the message holding the question is unconfirmed");
- assert!(fold.metadata().pending_elicitation.is_none());
+ assert!(fold.metadata().pending_elicitation().is_none());
assert_eq!(fold.metadata().turn, TurnState::Running);
// The answer resolves a part; it mints no message of its own.
assert_eq!(fold.messages().len(), before);
@@ -237,7 +237,7 @@ fn retracting_an_answer_restores_the_question() {
assert!(is_replace(&events));
assert_eq!(question(&fold), (ElicitationOutcome::Pending, false));
- assert!(fold.metadata().pending_elicitation.is_some());
+ assert!(fold.metadata().pending_elicitation().is_some());
assert_eq!(fold.metadata().turn, TurnState::Blocked);
}
@@ -805,3 +805,59 @@ fn a_confirmed_prompt_behind_a_stop_predicts_nothing() {
.expect("agent message");
assert_eq!(first_agent.stop, None);
}
+
+#[test]
+fn permission_answers_speculate_once_and_promote_on_the_agents_request_id() {
+ use crate::domain::model::PermissionOutcome;
+ use agent_client_protocol::schema::v1::RequestId;
+ use agent_runtime_protocol::domain::action::PermissionAnswer;
+
+ let mut log: Vec<&str> = TURN.lines().take(5).collect();
+ log.push(r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","id":7,"method":"session/request_permission","params":{"sessionId":"s1","toolCall":{"toolCallId":"t1"},"options":[{"optionId":"once","name":"Allow once","kind":"allow_once"}]}}}"#);
+ let mut fold = SpeculativeFold::new(test_session());
+ fold.push(FoldInput::Snapshot(rows(parse_log(&log.join("\n")))))
+ .unwrap();
+ assert_eq!(fold.metadata().turn, TurnState::Blocked);
+ assert_eq!(fold.metadata().pending_interactions.len(), 1);
+ let answer = AgentAction::RespondToPermission(
+ agent_runtime_protocol::domain::action::AgentPermissionAction {
+ request_id: RequestId::Number(7),
+ answer: PermissionAnswer::Selected {
+ option_id: "once".into(),
+ },
+ },
+ );
+ let id = AgentActionId::mint();
+ fold.push(speculation(answer.clone(), id)).unwrap();
+ assert!(fold.metadata().pending_interactions.is_empty());
+ assert_eq!(fold.metadata().turn, TurnState::Running);
+ fold.push(FoldInput::Retracted(id)).unwrap();
+ assert_eq!(fold.metadata().pending_interactions.len(), 1);
+ assert_eq!(fold.metadata().turn, TurnState::Blocked);
+ fold.push(speculation(answer.clone(), id)).unwrap();
+ fold.push(speculation(answer.clone(), AgentActionId::mint()))
+ .unwrap();
+ assert_eq!(fold.pending().collect::<Vec<_>>(), vec![id]);
+ assert!(fold.messages().iter().flat_map(|message| message.parts.iter()).any(|part|
+ matches!(part, MessagePart::Permission { outcome: PermissionOutcome::Selected { option_id }, .. } if option_id == "once")
+ ));
+ fold.push(FoldInput::Confirmed(
+ cursor(99),
+ logged(&answer, AgentActionId::mint()),
+ ))
+ .unwrap();
+ assert_eq!(fold.pending().count(), 0);
+
+ // A later request can reuse an answered id. Its live identity takes
+ // precedence over an older outcome when deduplicating speculation.
+ fold.push(FoldInput::Confirmed(
+ cursor(100),
+ parse_log(log.last().unwrap()).remove(0),
+ ))
+ .unwrap();
+ assert_eq!(fold.metadata().turn, TurnState::Blocked);
+ fold.push(speculation(answer, AgentActionId::mint()))
+ .unwrap();
+ assert!(fold.metadata().pending_interactions.is_empty());
+ assert_eq!(fold.metadata().turn, TurnState::Running);
+}
diff --git a/crates/agent_fold/src/domain/test.rs b/crates/agent_fold/src/domain/test.rs
index 980cd7bd45..94336513dc 100644
--- a/crates/agent_fold/src/domain/test.rs
+++ b/crates/agent_fold/src/domain/test.rs
@@ -5,6 +5,7 @@ mod elicitation;
mod fold;
mod harness;
mod harness_readers;
+mod interactions;
mod lifecycle;
mod machine;
mod macro_tools;
diff --git a/crates/agent_fold/src/domain/test/elicitation.rs b/crates/agent_fold/src/domain/test/elicitation.rs
index a6a8a06268..30a09097f7 100644
--- a/crates/agent_fold/src/domain/test/elicitation.rs
+++ b/crates/agent_fold/src/domain/test/elicitation.rs
@@ -121,8 +121,7 @@ fn a_form_request_becomes_a_pending_part_and_the_live_slot() {
let pending = machine
.metadata()
- .pending_elicitation
- .as_ref()
+ .pending_elicitation()
.expect("the slot is filled");
assert_eq!(pending.request_id, ElicitationRequestId::Number(7));
assert_eq!(pending.turn, 0);
@@ -282,7 +281,7 @@ fn accept_resolves_the_part_with_its_content_and_frees_the_slot() {
],
}
);
- assert_eq!(machine.metadata().pending_elicitation, None);
+ assert_eq!(machine.metadata().pending_elicitation(), None);
}
/// Multi-select answers resolve to the titles they were offered under, and a
@@ -361,7 +360,7 @@ fn decline_cancel_and_error_each_resolve_and_free_the_slot() {
unreachable!()
};
assert_eq!(*outcome, expected);
- assert_eq!(machine.metadata().pending_elicitation, None);
+ assert_eq!(machine.metadata().pending_elicitation(), None);
}
}
@@ -379,8 +378,7 @@ fn a_second_request_gets_a_part_but_never_the_slot() {
assert_eq!(
machine
.metadata()
- .pending_elicitation
- .as_ref()
+ .pending_elicitation()
.map(|pending| pending.request_id.clone()),
Some(ElicitationRequestId::Number(7)),
"the first question still owns the slot"
@@ -394,7 +392,7 @@ fn the_turn_ending_clears_the_slot_but_leaves_the_part_pending() {
// Turn opened, slot filled, then the turn ending clears the slot and
// closes the turn in one step.
assert_eq!(metadata_events, 3);
- assert_eq!(machine.metadata().pending_elicitation, None);
+ assert_eq!(machine.metadata().pending_elicitation(), None);
let parts = elicitations(&machine);
let MessagePart::Elicitation { outcome, .. } = parts[0] else {
unreachable!()
@@ -416,7 +414,7 @@ fn a_late_answer_after_the_turn_ended_still_resolves_the_part() {
fn a_reconnect_forgets_the_question_because_its_id_died_with_the_connection() {
let (machine, _) = drive(&lines(&[PROMPT, FORM, ACP_READY, &answer(7, "decline")]));
- assert_eq!(machine.metadata().pending_elicitation, None);
+ assert_eq!(machine.metadata().pending_elicitation(), None);
let parts = elicitations(&machine);
let MessagePart::Elicitation { outcome, .. } = parts[0] else {
unreachable!()
@@ -594,7 +592,7 @@ fn claude_code_recording_streams_the_slot_open_then_closed() {
metadata_events >= 2,
"the slot filled and cleared: {metadata_events}"
);
- assert_eq!(machine.metadata().pending_elicitation, None);
+ assert_eq!(machine.metadata().pending_elicitation(), None);
}
/// Hand-shaped from `claude-agent-acp` 0.64's `askUserQuestionsToCreateRequest`:
@@ -768,8 +766,7 @@ fn a_question_asked_under_a_subagent_takes_the_nested_calls_place() {
assert_eq!(
machine
.metadata()
- .pending_elicitation
- .as_ref()
+ .pending_elicitation()
.map(|pending| pending.turn),
Some(0)
);
@@ -880,8 +877,7 @@ fn a_form_scoped_to_a_user_tool_call_is_that_tools_review() {
let pending = machine
.metadata()
- .pending_elicitation
- .as_ref()
+ .pending_elicitation()
.expect("the review is the live question");
assert_eq!(
pending.request, *request,
@@ -927,7 +923,7 @@ fn a_reviewed_tools_own_result_lands_on_the_question() {
"the created event, read as the tool's user-tool response"
);
assert!(
- machine.metadata().pending_elicitation.is_none(),
+ machine.metadata().pending_elicitation().is_none(),
"answered and the turn over: nothing to offer"
);
}
diff --git a/crates/agent_fold/src/domain/test/fold.rs b/crates/agent_fold/src/domain/test/fold.rs
index 57b12b8634..c09e6ffdbc 100644
--- a/crates/agent_fold/src/domain/test/fold.rs
+++ b/crates/agent_fold/src/domain/test/fold.rs
@@ -2,8 +2,8 @@ use super::util::{CapturedFields, TURN, capturing_warnings, parse_log};
use crate::domain::fold::fold;
use crate::domain::log::{AgentSessionLog, Message};
use crate::domain::model::{
- Author, Control, ControlOutcome, FoldedMessage, MessagePart, PermissionOutcome, StopReason,
- ToolDetail, ToolName, ToolStatus, ToolUseId, TurnId,
+ AgentRequestId, Author, Control, ControlOutcome, FoldedMessage, MessagePart, PermissionOutcome,
+ StopReason, ToolDetail, ToolName, ToolStatus, ToolUseId, TurnId,
};
use agent_client_protocol::RawJsonRpcMessage;
use agent_runtime_protocol::domain::schema::v0::ToServerMessage;
@@ -94,6 +94,7 @@ fn folds_a_complete_turn() {
);
let MessagePart::Permission {
+ request_id,
tool_call,
options,
outcome,
@@ -101,6 +102,11 @@ fn folds_a_complete_turn() {
else {
panic!("third part is the permission prompt: {:?}", parts[2]);
};
+ assert_eq!(
+ *request_id,
+ AgentRequestId::Str("perm-1".to_owned()),
+ "the agent's id is exposed for an answer to echo"
+ );
assert_eq!(tool_call, run_id);
assert_eq!(options.len(), 2);
assert_eq!(
diff --git a/crates/agent_fold/src/domain/test/interactions.rs b/crates/agent_fold/src/domain/test/interactions.rs
new file mode 100644
index 0000000000..b2868105a8
--- /dev/null
+++ b/crates/agent_fold/src/domain/test/interactions.rs
@@ -0,0 +1,173 @@
+//! Shared live-request lifecycle, preserving each protocol's answer shape.
+
+use serde_json::{Value, json};
+
+use super::util::parse_log;
+use crate::domain::fold::FoldMachineImpl;
+use crate::domain::model::{
+ AgentRequestId, FoldEvent, MessagePart, PendingInteraction, PermissionOutcome, TurnState,
+};
+use crate::domain::ports::FoldMachine;
+
+fn push(machine: &mut FoldMachineImpl, direction: &str, frame: Value) -> bool {
+ let mut content = frame;
+ content["type"] = json!("acp");
+ content["jsonrpc"] = json!("2.0");
+ let line = json!({"direction": direction, "content": content}).to_string();
+ machine
+ .push(parse_log(&line).remove(0))
+ .iter()
+ .any(|event| matches!(event, FoldEvent::MetadataUpdated(_)))
+}
+
+fn permission(id: Value) -> Value {
+ json!({"id": id, "method": "session/request_permission", "params": {
+ "sessionId": "s", "toolCall": {"toolCallId": "tool"},
+ "options": [{"optionId": "once", "name": "Allow once", "kind": "allow_once"}]
+ }})
+}
+
+fn question(id: Value) -> Value {
+ json!({"id": id, "method": "elicitation/create", "params": {
+ "sessionId": "s", "mode": "form", "message": "Which colour?",
+ "requestedSchema": {"type": "object", "properties": {}}
+ }})
+}
+
+fn prompt(machine: &mut FoldMachineImpl, id: &str) {
+ push(
+ machine,
+ "to_runtime",
+ json!({"id": id, "method": "session/prompt", "params": {
+ "sessionId": "s", "prompt": [{"type": "text", "text": "go"}]
+ }}),
+ );
+}
+
+#[test]
+fn concurrent_requests_share_blocked_state_and_resolve_independently() {
+ let mut machine = FoldMachineImpl::new();
+ prompt(&mut machine, "p");
+ assert!(push(&mut machine, "to_server", permission(json!(7))));
+ assert!(push(&mut machine, "to_server", permission(json!("7"))));
+ assert!(push(&mut machine, "to_server", question(json!(8))));
+ assert_eq!(machine.metadata().pending_interactions.len(), 3);
+ assert_eq!(machine.metadata().turn, TurnState::Blocked);
+
+ assert!(push(
+ &mut machine,
+ "to_runtime",
+ json!({"id": 7, "result": {"outcome": {"outcome": "selected", "optionId": "once"}}})
+ ));
+ assert_eq!(machine.metadata().pending_interactions.len(), 2);
+ assert!(
+ matches!(&machine.metadata().pending_interactions[0], PendingInteraction::Permission(pending) if pending.request_id == AgentRequestId::Str("7".into()))
+ );
+ assert_eq!(machine.metadata().turn, TurnState::Blocked);
+ // Two requests for the same tool still resolve the correct transcript row.
+ let permissions: Vec<_> = machine
+ .messages()
+ .iter()
+ .flat_map(|message| message.parts.iter())
+ .filter_map(|part| match part {
+ MessagePart::Permission { outcome, .. } => Some(outcome),
+ _ => None,
+ })
+ .collect();
+ assert!(matches!(permissions[0], PermissionOutcome::Selected { .. }));
+ assert_eq!(*permissions[1], PermissionOutcome::Pending);
+
+ push(
+ &mut machine,
+ "to_runtime",
+ json!({"id": 8, "result": {"action": "decline"}}),
+ );
+ assert_eq!(machine.metadata().turn, TurnState::Blocked);
+ push(
+ &mut machine,
+ "to_runtime",
+ json!({"id": "7", "result": {"outcome": {"outcome": "cancelled"}}}),
+ );
+ assert!(machine.metadata().pending_interactions.is_empty());
+ assert_eq!(machine.metadata().turn, TurnState::Running);
+}
+
+#[test]
+fn a_second_elicitation_does_not_replace_the_live_question_or_permissions() {
+ let mut machine = FoldMachineImpl::new();
+ prompt(&mut machine, "p");
+ push(&mut machine, "to_server", permission(json!(1)));
+ push(&mut machine, "to_server", question(json!(2)));
+ push(&mut machine, "to_server", question(json!(3)));
+ push(
+ &mut machine,
+ "to_runtime",
+ json!({"id": 3, "error": {"code": -32602, "message": "one elicitation at a time"}}),
+ );
+ assert_eq!(machine.metadata().pending_interactions.len(), 2);
+ assert_eq!(
+ machine
+ .metadata()
+ .pending_elicitation()
+ .unwrap()
+ .request_id
+ .to_request_id(),
+ agent_client_protocol::schema::v1::RequestId::Number(2)
+ );
+}
+
+#[test]
+fn ending_stopping_and_disconnecting_clear_both_live_requests() {
+ for ending in ["end", "stop", "disconnect", "reconnect", "next_turn"] {
+ let mut machine = FoldMachineImpl::new();
+ prompt(&mut machine, "p");
+ push(&mut machine, "to_server", permission(json!(1)));
+ push(&mut machine, "to_server", question(json!(2)));
+ match ending {
+ "end" => {
+ push(
+ &mut machine,
+ "to_server",
+ json!({"id": "p", "result": {"stopReason": "end_turn"}}),
+ );
+ }
+ "stop" => {
+ push(
+ &mut machine,
+ "to_runtime",
+ json!({"method": "session/cancel", "params": {"sessionId": "s"}}),
+ );
+ }
+ "next_turn" => prompt(&mut machine, "next"),
+ _ => {
+ let event = if ending == "disconnect" {
+ "disconnected"
+ } else {
+ "acp_ready"
+ };
+ let line =
+ json!({"direction": "to_server", "content": {"type": "event", "event": event}})
+ .to_string();
+ let _ = machine.push(parse_log(&line).remove(0));
+ }
+ }
+ assert!(
+ machine.metadata().pending_interactions.is_empty(),
+ "{ending}"
+ );
+ assert!(
+ machine
+ .messages()
+ .iter()
+ .flat_map(|message| message.parts.iter())
+ .any(|part| matches!(
+ part,
+ MessagePart::Permission {
+ outcome: PermissionOutcome::Pending,
+ ..
+ }
+ )),
+ "history survives {ending}"
+ );
+ }
+}
diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@command_invocation.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@command_invocation.jsonl.snap
index 912f7e5d25..6fc2041cc7 100644
--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@command_invocation.jsonl.snap
+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@command_invocation.jsonl.snap
@@ -395,6 +395,6 @@ SessionMetadata {
status: Some(
"acp_ready",
),
- pending_elicitation: None,
+ pending_interactions: [],
turn: Idle,
}
diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@elicitation_claude_single_select.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@elicitation_claude_single_select.jsonl.snap
index 189d00bdb7..e204f444a4 100644
--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@elicitation_claude_single_select.jsonl.snap
+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@elicitation_claude_single_select.jsonl.snap
@@ -73,6 +73,6 @@ SessionMetadata {
status: Some(
"acp_ready",
),
- pending_elicitation: None,
+ pending_interactions: [],
turn: Idle,
}
diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@long_multi_resume.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@long_multi_resume.jsonl.snap
index a1b012ab62..0e2457e426 100644
--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@long_multi_resume.jsonl.snap
+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@long_multi_resume.jsonl.snap
@@ -390,6 +390,6 @@ SessionMetadata {
status: Some(
"acp_ready",
),
- pending_elicitation: None,
+ pending_interactions: [],
turn: Idle,
}
diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@plan_todo.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@plan_todo.jsonl.snap
index 15cddab387..702a633110 100644
--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@plan_todo.jsonl.snap
+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@plan_todo.jsonl.snap
@@ -395,6 +395,6 @@ SessionMetadata {
status: Some(
"acp_ready",
),
- pending_elicitation: None,
+ pending_interactions: [],
turn: Idle,
}
diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@real_multi_turn.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@real_multi_turn.jsonl.snap
index c22569c7d6..27e50ec4fa 100644
--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@real_multi_turn.jsonl.snap
+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@real_multi_turn.jsonl.snap
@@ -430,6 +430,6 @@ SessionMetadata {
status: Some(
"acp_ready",
),
- pending_elicitation: None,
+ pending_interactions: [],
turn: Running,
}
diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@real_single_turn.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@real_single_turn.jsonl.snap
index 34989ad533..4223a29fd3 100644
--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@real_single_turn.jsonl.snap
+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@real_single_turn.jsonl.snap
@@ -430,6 +430,6 @@ SessionMetadata {
status: Some(
"acp_ready",
),
- pending_elicitation: None,
+ pending_interactions: [],
turn: Idle,
}
diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@resumed_and_continued.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@resumed_and_continued.jsonl.snap
index 1d9723e03b..2ad701b57e 100644
--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@resumed_and_continued.jsonl.snap
+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@resumed_and_continued.jsonl.snap
@@ -430,6 +430,6 @@ SessionMetadata {
status: Some(
"acp_ready",
),
- pending_elicitation: None,
+ pending_interactions: [],
turn: Idle,
}
diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@resumed_no_prompt.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@resumed_no_prompt.jsonl.snap
index 7adca192f3..0d0edf6140 100644
--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@resumed_no_prompt.jsonl.snap
+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@resumed_no_prompt.jsonl.snap
@@ -428,6 +428,6 @@ SessionMetadata {
status: Some(
"acp_ready",
),
- pending_elicitation: None,
+ pending_interactions: [],
turn: Running,
}
diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@subagent_claude_code.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@subagent_claude_code.jsonl.snap
index 86a7d36780..5b4b89449c 100644
--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@subagent_claude_code.jsonl.snap
+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@subagent_claude_code.jsonl.snap
@@ -57,6 +57,6 @@ SessionMetadata {
status: Some(
"acp_ready",
),
- pending_elicitation: None,
+ pending_interactions: [],
turn: Idle,
}
diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@subagent_cursor.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@subagent_cursor.jsonl.snap
index ed66a374d5..1958af2ba3 100644
--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@subagent_cursor.jsonl.snap
+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@subagent_cursor.jsonl.snap
@@ -243,6 +243,6 @@ SessionMetadata {
status: Some(
"acp_ready",
),
- pending_elicitation: None,
+ pending_interactions: [],
turn: Idle,
}
diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@subagent_macro_inmem.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@subagent_macro_inmem.jsonl.snap
index 40e2921754..246beb3f64 100644
--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@subagent_macro_inmem.jsonl.snap
+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@subagent_macro_inmem.jsonl.snap
@@ -12,6 +12,6 @@ SessionMetadata {
status: Some(
"acp_ready",
),
- pending_elicitation: None,
+ pending_interactions: [],
turn: Idle,
}
diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@subagent_opencode.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@subagent_opencode.jsonl.snap
index ea74c69692..2a85acffcb 100644
--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@subagent_opencode.jsonl.snap
+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@subagent_opencode.jsonl.snap
@@ -60,6 +60,6 @@ SessionMetadata {
status: Some(
"acp_ready",
),
- pending_elicitation: None,
+ pending_interactions: [],
turn: Idle,
}
diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@real_multi_turn.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@real_multi_turn.jsonl.snap
index 42006bd5f0..4ba26eca42 100644
--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@real_multi_turn.jsonl.snap
+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@real_multi_turn.jsonl.snap
@@ -62,6 +62,9 @@ input_file: crates/agent_fold/fixtures/real/real_multi_turn.jsonl
},
},
Permission {
+ request_id: Number(
+ 5,
+ ),
tool_call: ToolUseId(
"toolu_01F5V288iQ8iArGM4B3ayCFm",
),
diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@resumed_and_continued.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@resumed_and_continued.jsonl.snap
index 9bf950467a..edf992a350 100644
--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@resumed_and_continued.jsonl.snap
+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@resumed_and_continued.jsonl.snap
@@ -403,6 +403,9 @@ input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonl
},
},
Permission {
+ request_id: Number(
+ 0,
+ ),
tool_call: ToolUseId(
"toolu_015c1NGtLCDbzzN6gLsNek6c",
),
@@ -495,6 +498,9 @@ input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonl
},
},
Permission {
+ request_id: Number(
+ 1,
+ ),
tool_call: ToolUseId(
"toolu_01SfjW3NaG4UD6znQMU23cyf",
),
@@ -542,6 +548,9 @@ input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonl
},
},
Permission {
+ request_id: Number(
+ 2,
+ ),
tool_call: ToolUseId(
"toolu_01CtXAUSJxvsbs2FD7QmMqDu",
),
@@ -592,6 +601,9 @@ input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonl
},
},
Permission {
+ request_id: Number(
+ 3,
+ ),
tool_call: ToolUseId(
"toolu_01C3WXuHqyYExW1fkiSdhQBm",
),
@@ -639,6 +651,9 @@ input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonl
},
},
Permission {
+ request_id: Number(
+ 4,
+ ),
tool_call: ToolUseId(
"toolu_011EjWXxbBUL3LeeWdhwZzVE",
),
diff --git a/crates/agent_fold/src/inbound/wire/test.rs b/crates/agent_fold/src/inbound/wire/test.rs
index e8ff6c9d85..28ac812518 100644
--- a/crates/agent_fold/src/inbound/wire/test.rs
+++ b/crates/agent_fold/src/inbound/wire/test.rs
@@ -1,6 +1,7 @@
use super::*;
use crate::domain::model::{
- Author, PermissionOutcome, ToolDetail, ToolName, ToolStatus, ToolUseId, TurnId, UserToolOutcome,
+ AgentRequestId, Author, PermissionOutcome, ToolDetail, ToolName, ToolStatus, ToolUseId, TurnId,
+ UserToolOutcome,
};
use non_empty::NonEmpty;
use serde_json::json;
@@ -82,6 +83,7 @@ fn domain_parts_serialize_directly_into_the_browser_contract() {
assert_eq!(
serde_json::to_value(MessagePart::Permission {
+ request_id: AgentRequestId::Number(7),
tool_call: ToolUseId("tool-1".to_owned()),
options: Vec::new(),
outcome: PermissionOutcome::Pending,
@@ -89,11 +91,16 @@ fn domain_parts_serialize_directly_into_the_browser_contract() {
.unwrap(),
json!({
"kind": "permission",
+ "requestId": 7,
"toolCall": "tool-1",
"options": [],
"outcome": { "kind": "pending" }
})
);
+ assert_eq!(
+ serde_json::to_value(AgentRequestId::Str("req-1".to_owned())).unwrap(),
+ json!("req-1")
+ );
}
#[test]
diff --git a/crates/agent_harness/src/domain/model.rs b/crates/agent_harness/src/domain/model.rs
index 8f6b6262a7..589c6ae363 100644
--- a/crates/agent_harness/src/domain/model.rs
+++ b/crates/agent_harness/src/domain/model.rs
@@ -6,6 +6,10 @@ use agent_fold::domain::model::TurnSignal;
use agent_runtime_protocol::domain::action::{AgentAction, AgentActionId, PromptAttachment};
use agent_session::domain::model::{AgentMcpServers, AgentSessionId, MessageId, SandboxSize};
use agent_session::domain::ports::ControlEvent;
+use agent_session::domain::session::PermissionPolicy;
+
+#[cfg(test)]
+mod test;
use bot_id::BotId;
use macro_user_id::user_id::MacroUserIdStr;
use macro_uuid::Uuid;
@@ -191,6 +195,71 @@ impl AgentKind {
pub fn is_managed(self) -> bool {
!matches!(self, Self::External)
}
+
+ /// How this kind's sessions answer permission requests without a registered
+ /// local harness.
+ ///
+ /// Managed runtimes act inside sandboxes this deployment owns (or, for
+ /// Cursor, never ask), so approving on arrival costs nothing. An external
+ /// runtime is somebody's own machine, where a bot approving its own tool
+ /// calls is exactly what a person should be asked about.
+ #[must_use]
+ pub fn default_permission_policy(self) -> PermissionPolicy {
+ match self {
+ Self::SandboxedCoder
+ | Self::Cursor
+ | Self::CodexCloud
+ | Self::ClaudeCloud
+ | Self::InMemory => PermissionPolicy::AutoAccept,
+ Self::External => PermissionPolicy::Prompt,
+ }
+ }
+}
+
+/// Stored facts used by the domain to choose a session permission policy.
+pub enum PermissionPolicyConfig {
+ /// A fixed system bot with no editable persona configuration.
+ Fixed(AgentKind),
+ /// An editable persona and its harness operator's limit.
+ Persona {
+ /// The runtime serving this persona.
+ kind: AgentKind,
+ /// A registered harness's opt-in. `None` denotes a built-in runtime.
+ harness_allows_bypass: Option<bool>,
+ /// The agent owner's choice for a local harness; absent means prompt.
+ auto_accept_permissions: Option<bool>,
+ },
+}
+
+impl PermissionPolicyConfig {
+ /// Apply local harness consent and agent choice, or the built-in policy.
+ #[must_use]
+ pub fn resolve(self) -> PermissionPolicy {
+ match self {
+ Self::Fixed(kind) => kind.default_permission_policy(),
+ Self::Persona {
+ kind,
+ harness_allows_bypass,
+ auto_accept_permissions,
+ } => match harness_allows_bypass {
+ Some(allowed) => resolve_permission_policy(allowed, auto_accept_permissions),
+ None => kind.default_permission_policy(),
+ },
+ }
+ }
+}
+
+/// Resolve a persona's choice within the harness operator's permission limit.
+#[must_use]
+pub fn resolve_permission_policy(
+ allow_bypass: bool,
+ auto_accept: Option<bool>,
+) -> PermissionPolicy {
+ if allow_bypass && auto_accept == Some(true) {
+ PermissionPolicy::AutoAccept
+ } else {
+ PermissionPolicy::Prompt
+ }
}
/// Runtime settings used to open one database-backed or fixed agent.
@@ -737,26 +806,3 @@ impl From<SessionDefaults> for HarnessDefaults {
Self::new(default)
}
}
-
-#[cfg(test)]
-mod test {
- use super::SessionRepository;
-
- /// The URL survives verbatim - it is what a session's row carries, and
- /// what the egress proxy re-reads - and one that names no repository is
- /// refused rather than repaired. The shapes themselves are the parser's
- /// own tests, in `agent_egress`.
- #[test]
- fn a_session_repository_keeps_the_url_it_was_read_from() {
- let repository =
- SessionRepository::parse("https://github.com/macro-inc/macro.git").expect("a repo");
- assert_eq!(
- repository.as_str(),
- "https://github.com/macro-inc/macro.git"
- );
-
- for url in ["", "https://github.com/macro-inc", "not a url"] {
- assert_eq!(SessionRepository::parse(url), None, "accepted {url}");
- }
- }
-}
diff --git a/crates/agent_harness/src/domain/model/test.rs b/crates/agent_harness/src/domain/model/test.rs
new file mode 100644
index 0000000000..60a1dab0e0
--- /dev/null
+++ b/crates/agent_harness/src/domain/model/test.rs
@@ -0,0 +1,120 @@
+use super::*;
+
+#[test]
+fn only_external_runtimes_prompt_by_default() {
+ assert_eq!(
+ AgentKind::External.default_permission_policy(),
+ PermissionPolicy::Prompt
+ );
+ for managed in [
+ AgentKind::SandboxedCoder,
+ AgentKind::Cursor,
+ AgentKind::CodexCloud,
+ AgentKind::ClaudeCloud,
+ AgentKind::InMemory,
+ ] {
+ assert_eq!(
+ managed.default_permission_policy(),
+ PermissionPolicy::AutoAccept,
+ "{managed:?} runs where approving on arrival is safe"
+ );
+ }
+}
+
+#[test]
+fn bypass_requires_both_operator_opt_in_and_persona_choice() {
+ for allowed in [false, true] {
+ for choice in [None, Some(false), Some(true)] {
+ let expected = if allowed && choice == Some(true) {
+ PermissionPolicy::AutoAccept
+ } else {
+ PermissionPolicy::Prompt
+ };
+ assert_eq!(resolve_permission_policy(allowed, choice), expected);
+ }
+ }
+}
+
+#[test]
+fn builtin_runtimes_always_bypass_regardless_of_saved_agent_choice() {
+ for kind in [
+ AgentKind::InMemory,
+ AgentKind::Cursor,
+ AgentKind::CodexCloud,
+ AgentKind::ClaudeCloud,
+ AgentKind::SandboxedCoder,
+ ] {
+ for auto_accept_permissions in [None, Some(false), Some(true)] {
+ assert_eq!(
+ PermissionPolicyConfig::Persona {
+ kind,
+ harness_allows_bypass: None,
+ auto_accept_permissions,
+ }
+ .resolve(),
+ PermissionPolicy::AutoAccept
+ );
+ }
+ }
+}
+
+#[test]
+fn external_runtimes_require_registered_harness_consent_and_agent_choice() {
+ for harness_allows_bypass in [None, Some(false), Some(true)] {
+ for auto_accept_permissions in [None, Some(false), Some(true)] {
+ assert_eq!(
+ PermissionPolicyConfig::Persona {
+ kind: AgentKind::External,
+ harness_allows_bypass,
+ auto_accept_permissions,
+ }
+ .resolve(),
+ if harness_allows_bypass == Some(true) && auto_accept_permissions == Some(true) {
+ PermissionPolicy::AutoAccept
+ } else {
+ PermissionPolicy::Prompt
+ }
+ );
+ }
+ }
+}
+
+#[test]
+fn registered_harness_limit_wins_over_runtime_kind_and_persona_choice() {
+ for kind in [
+ AgentKind::InMemory,
+ AgentKind::Cursor,
+ AgentKind::CodexCloud,
+ AgentKind::ClaudeCloud,
+ AgentKind::SandboxedCoder,
+ AgentKind::External,
+ ] {
+ assert_eq!(
+ PermissionPolicyConfig::Persona {
+ kind,
+ harness_allows_bypass: Some(false),
+ auto_accept_permissions: Some(true),
+ }
+ .resolve(),
+ PermissionPolicy::Prompt
+ );
+ }
+}
+
+/// The URL survives verbatim - it is what a session's row carries, and
+/// what the egress proxy re-reads - and one that names no repository is
+/// refused rather than repaired. The shapes themselves are the parser's
+/// own tests, in `agent_egress`.
+#[test]
+fn a_session_repository_keeps_the_url_it_was_read_from() {
+ let repository =
+ SessionRepository::parse("https://github.com/macro-inc/macro.git").expect("a repo");
+ assert_eq!(
+ repository.as_str(),
+ "https://github.com/macro-inc/macro.git"
+ );
+
+ for url in ["", "https://github.com/macro-inc", "not a url"] {
+ assert_eq!(SessionRepository::parse(url), None, "accepted {url}");
+ }
+}
diff --git a/crates/agent_harness/src/domain/ports.rs b/crates/agent_harness/src/domain/ports.rs
index 7c0e2739a4..ac3ae17d34 100644
--- a/crates/agent_harness/src/domain/ports.rs
+++ b/crates/agent_harness/src/domain/ports.rs
@@ -4,6 +4,7 @@ use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
+use crate::domain::model::PermissionPolicyConfig;
use agent_session::domain::connection::RuntimeAttachment;
use agent_session::domain::model::{AgentMcpServers, AgentSessionId, SandboxSize};
use agent_session::domain::ports::AgentConnector;
@@ -85,6 +86,18 @@ pub trait HarnessBindings: Send + Sync + 'static {
) -> impl Future<Output = anyhow::Result<Option<HarnessId>>> + Send;
}
+/// Loads facts for the domain to resolve a bot's permission policy.
+///
+/// Resolved at attach time like [`HarnessBindings`], so changing the agent's
+/// setting takes effect on its existing sessions the next time they attach.
+pub trait PermissionPolicySource: Send + Sync + 'static {
+ /// The persona choice and harness limit for `bot` right now.
+ fn permission_policy(
+ &self,
+ bot: BotId,
+ ) -> impl Future<Output = anyhow::Result<PermissionPolicyConfig>> + Send;
+}
+
/// Durable attach/detach bookkeeping for harness runtime connections.
///
/// The registry itself is in-process liveness; this is what lets the rest of
diff --git a/crates/agent_harness/src/domain/queue.rs b/crates/agent_harness/src/domain/queue.rs
index f2ae6bb5c3..04e40d698f 100644
--- a/crates/agent_harness/src/domain/queue.rs
+++ b/crates/agent_harness/src/domain/queue.rs
@@ -253,7 +253,8 @@ impl SessionQueues {
AgentAction::SetModel(_)
| AgentAction::Compact
| AgentAction::Stop
- | AgentAction::RespondElicitation(_) => Err(QueueError::NotEditable),
+ | AgentAction::RespondElicitation(_)
+ | AgentAction::RespondToPermission(_) => Err(QueueError::NotEditable),
}
}
diff --git a/crates/agent_harness/src/domain/service.rs b/crates/agent_harness/src/domain/service.rs
index 3393305979..7ba54424f9 100644
--- a/crates/agent_harness/src/domain/service.rs
+++ b/crates/agent_harness/src/domain/service.rs
@@ -36,6 +36,7 @@ use agent_session::domain::ports::{
AgentSessionQueueChanged, ControlDisposition, ControlEvent, QueuedControl,
};
use agent_session::domain::service::AgentSessionService;
+use agent_session::domain::session::PermissionPolicy;
use bot_id::BotId;
use dashmap::DashMap;
use dashmap::mapref::entry::Entry;
@@ -53,14 +54,44 @@ use crate::domain::model::{
use crate::domain::pending::PendingCommands;
use crate::domain::ports::{
AgentPromptComposer, AgentSessionNotifier, CommandForwarder, ContainerManager,
- MessagePromptContext, PromptMentions, RuntimeConnections, SandboxEgressProvisioner,
- SessionAnnouncer,
+ MessagePromptContext, PermissionPolicySource, PromptMentions, RuntimeConnections,
+ SandboxEgressProvisioner, SessionAnnouncer,
};
use crate::domain::queue::{InFlightTurn, QueueError, QueuedEntry, SessionQueues};
use crate::domain::sandbox::SandboxResizeEffect;
use self::queue::{ErasedForwarder, SessionWorkers};
+/// [`PermissionPolicySource`], object-safe, erased for the same reason as
+/// [`ErasedForwarder`].
+trait ErasedPermissionPolicySource: Send + Sync + 'static {
+ fn permission_policy<'a>(
+ &'a self,
+ bot: BotId,
+ ) -> std::pin::Pin<
+ Box<
+ dyn Future<Output = anyhow::Result<crate::domain::model::PermissionPolicyConfig>>
+ + Send
+ + 'a,
+ >,
+ >;
+}
+
+impl<S: PermissionPolicySource> ErasedPermissionPolicySource for S {
+ fn permission_policy<'a>(
+ &'a self,
+ bot: BotId,
+ ) -> std::pin::Pin<
+ Box<
+ dyn Future<Output = anyhow::Result<crate::domain::model::PermissionPolicyConfig>>
+ + Send
+ + 'a,
+ >,
+ > {
+ Box::pin(PermissionPolicySource::permission_policy(self, bot))
+ }
+}
+
struct AgentHarnessInner<
Sessions,
Containers,
@@ -81,6 +112,7 @@ struct AgentHarnessInner<
prompt_composer: PromptComposer,
egress: Egress,
forwarder: Box<dyn ErasedForwarder>,
+ permission_policies: Box<dyn ErasedPermissionPolicySource>,
defaults: HarnessDefaults,
/// Turn-occupying actions waiting for their session's running turn to
/// end. In-memory beside the live actors this replica manages.
@@ -251,6 +283,7 @@ where
prompt_composer: PromptComposer,
egress: Egress,
forwarder: impl CommandForwarder,
+ permission_policies: impl PermissionPolicySource,
defaults: impl Into<HarnessDefaults>,
lifecycle_publisher: Lifecycle,
pending: PendingCommands,
@@ -267,6 +300,7 @@ where
prompt_composer,
egress,
forwarder: Box::new(forwarder),
+ permission_policies: Box::new(permission_policies),
defaults: defaults.into(),
queues: SessionQueues::new(),
busy: pending,
diff --git a/crates/agent_harness/src/domain/service/deliver.rs b/crates/agent_harness/src/domain/service/deliver.rs
index 9a269ed59b..9ba71a56b9 100644
--- a/crates/agent_harness/src/domain/service/deliver.rs
+++ b/crates/agent_harness/src/domain/service/deliver.rs
@@ -67,15 +67,26 @@ where
// Nothing is attached, so get this session onto a transport and
// retry against it. Same id: the first attempt never reached the
// wire.
+ Err(error @ AgentSessionError::Disconnected(_))
+ if matches!(action, AgentAction::RespondToPermission(_)) =>
+ {
+ return Err(error.into());
+ }
Err(AgentSessionError::Disconnected(_)) => {
let session = self.sessions.get_session(session_id).await?;
+ let permission_policy = self.permission_policy_for(session.bot_id).await;
if AgentKind::for_session(session.bot_id, &session.harness).is_managed() {
let container = self.containers.resume(session_id).await?;
let mcp_servers = self
.resumed_mcp_servers(session_id, &session.owner_id, &session.mcp_servers)
.await?;
self.sessions
- .attach_session(session_id, container.mcp_servers(mcp_servers))
+ .attach_session(
+ session_id,
+ container
+ .mcp_servers(mcp_servers)
+ .permission_policy(permission_policy),
+ )
.await?;
} else {
// An external runtime is not ours to start - only its
@@ -84,7 +95,7 @@ where
// yet. That is the ordinary case: sessions bind when they
// are prompted, not when the runtime dials, so the first
// prompt after a reconnect is what restores the session.
- let Some(attachment) = self.runtimes.bind(session.bot_id, session_id).await
+ let Some(mut attachment) = self.runtimes.bind(session.bot_id, session_id).await
else {
// Kept in the session vocabulary so transports report
// it as a disconnect, not an internal error.
@@ -92,6 +103,9 @@ where
session_id,
)));
};
+ if session.harness == harness_id::MACROD_HARNESS_SLUG {
+ attachment = attachment.initial_model(session.model.clone());
+ }
let egress = self
.egress
.provision(
@@ -108,7 +122,9 @@ where
self.sessions
.attach_session(
session_id,
- attachment.mcp_servers(vec![egress.sandbox.internal_mcp_server()]),
+ attachment
+ .permission_policy(permission_policy)
+ .mcp_servers(vec![egress.sandbox.internal_mcp_server()]),
)
.await?;
}
diff --git a/crates/agent_harness/src/domain/service/lifecycle.rs b/crates/agent_harness/src/domain/service/lifecycle.rs
index f82d0429c1..2bea123967 100644
--- a/crates/agent_harness/src/domain/service/lifecycle.rs
+++ b/crates/agent_harness/src/domain/service/lifecycle.rs
@@ -235,6 +235,14 @@ where
Mentions: PromptMentions,
Notifier: AgentSessionNotifier,
{
+ /// Resolve current permission policy, failing closed if lookup fails.
+ pub(super) async fn permission_policy_for(&self, bot: BotId) -> PermissionPolicy {
+ self.permission_policies.permission_policy(bot).await.inspect_err(|error| {
+ tracing::warn!(error = ?error, %bot, "could not resolve permission policy; prompting");
+ }).map(crate::domain::model::PermissionPolicyConfig::resolve)
+ .unwrap_or(PermissionPolicy::Prompt)
+ }
+
/// The MCP servers to advertise when reattaching to an existing container.
///
/// The raw session token exists in exactly one place after spawn - the
@@ -303,8 +311,14 @@ where
let mcp_servers = self
.resumed_mcp_servers(session_id, &session.owner_id, &session.mcp_servers)
.await?;
+ let permission_policy = self.permission_policy_for(session.bot_id).await;
self.sessions
- .attach_session(session_id, container.mcp_servers(mcp_servers))
+ .attach_session(
+ session_id,
+ container
+ .mcp_servers(mcp_servers)
+ .permission_policy(permission_policy),
+ )
.await?;
}
}
diff --git a/crates/agent_harness/src/domain/service/open.rs b/crates/agent_harness/src/domain/service/open.rs
index 8397e6b7cd..925443cb72 100644
--- a/crates/agent_harness/src/domain/service/open.rs
+++ b/crates/agent_harness/src/domain/service/open.rs
@@ -79,6 +79,10 @@ where
})?;
}
let defaults = self.inner.defaults.for_bot(request.bot_id);
+ let (model, harness) = match request.profile {
+ Some(profile) => (profile.model, profile.harness),
+ None => (defaults.model.clone(), defaults.harness.clone()),
+ };
let session = self
.inner
.sessions
@@ -89,8 +93,8 @@ where
bot_id: request.bot_id,
thread_id: request.thread.as_ref().map(|thread| thread.thread_id),
originating_message_id: request.thread.as_ref().map(|thread| thread.message_id),
- model: defaults.model.clone(),
- harness: defaults.harness.clone(),
+ model,
+ harness,
repo_url: request.repo_url,
workspace: request.workspace,
sandbox_size: SandboxSize::Default,
@@ -306,9 +310,15 @@ where
return Err(into_session_error(error));
}
};
+ let permission_policy = self.inner.permission_policy_for(session.bot_id).await;
self.inner
.sessions
- .attach_session(session.id, container.mcp_servers(mcp_servers))
+ .attach_session(
+ session.id,
+ container
+ .mcp_servers(mcp_servers)
+ .permission_policy(permission_policy),
+ )
.await?;
// Raw, through the session's own command worker: dispatch is where a
@@ -524,8 +534,14 @@ where
return Err(error);
}
};
+ let permission_policy = self.permission_policy_for(bot_id).await;
self.sessions
- .attach_session(session_id, container.mcp_servers(mcp_servers))
+ .attach_session(
+ session_id,
+ container
+ .mcp_servers(mcp_servers)
+ .permission_policy(permission_policy),
+ )
.await?;
// The first prompt goes through the same door as every later one:
// queued raw, then dispatched - which is where it is composed with
diff --git a/crates/agent_harness/src/domain/service/queue.rs b/crates/agent_harness/src/domain/service/queue.rs
index 93e671229e..bf55ed9169 100644
--- a/crates/agent_harness/src/domain/service/queue.rs
+++ b/crates/agent_harness/src/domain/service/queue.rs
@@ -289,6 +289,15 @@ where
// an edited entry is delivered later under its original identity,
// so rewriting (or dropping) what a Daytona session is about to
// run is the same privilege as prompting it.
+ HarnessCommand::Deliver(DeliverAction {
+ actor,
+ action: AgentAction::RespondToPermission(_),
+ ..
+ }) => {
+ if actor.is_none() {
+ return Err(AgentSessionError::Forbidden.into());
+ }
+ }
HarnessCommand::Deliver(DeliverAction { actor, .. })
| HarnessCommand::EditQueued { actor, .. }
| HarnessCommand::RemoveQueued { actor, .. } => {
diff --git a/crates/agent_harness/src/domain/service/test.rs b/crates/agent_harness/src/domain/service/test.rs
index 2280800a50..6cc34a6bed 100644
--- a/crates/agent_harness/src/domain/service/test.rs
+++ b/crates/agent_harness/src/domain/service/test.rs
@@ -5,17 +5,19 @@
use messages::domain::models::MessageParent;
use std::sync::{Arc, Mutex};
-use agent_client_protocol::RawJsonRpcMessage;
use agent_client_protocol::schema::v1::{
AgentCapabilities, ClientNotification, ClientRequest, ContentBlock, InitializeResponse,
- NewSessionResponse, ResumeSessionResponse, SessionCapabilities, SessionId,
- SessionResumeCapabilities,
+ NewSessionResponse, PermissionOption, PermissionOptionKind, RequestId,
+ RequestPermissionOutcome, RequestPermissionRequest, RequestPermissionResponse, Response,
+ ResumeSessionResponse, SelectedPermissionOutcome, SessionCapabilities, SessionId,
+ SessionResumeCapabilities, ToolCallUpdate, ToolCallUpdateFields,
};
+use agent_client_protocol::{JsonRpcMessage, RawJsonRpcMessage};
use agent_fold::domain::model::TurnSignal;
use agent_fold::domain::model::{AuthorKind, MessageId};
use agent_fold::domain::service::FoldedMessageService;
use agent_runtime_protocol::domain::{
- action::{AgentAction, AgentActionId},
+ action::{AgentAction, AgentActionId, AgentPermissionAction, PermissionAnswer},
schema::v0::{AcpMessage, SystemEvent, ToRuntimeMessage, ToServerMessage},
};
use agent_session::PROTOCOL_VERSION;
@@ -253,6 +255,21 @@ impl crate::domain::ports::HarnessBindings for MirrorBindings {
}
}
+/// No agent has said anything about permissions: every bot runs under its
+/// kind's default.
+struct KindDefaultPolicies;
+
+impl crate::domain::ports::PermissionPolicySource for KindDefaultPolicies {
+ async fn permission_policy(
+ &self,
+ bot: BotId,
+ ) -> anyhow::Result<crate::domain::model::PermissionPolicyConfig> {
+ Ok(crate::domain::model::PermissionPolicyConfig::Fixed(
+ AgentKind::of(bot),
+ ))
+ }
+}
+
fn harness_for_bot(bot: BotId) -> harness_id::HarnessId {
harness_id::HarnessId::new_from_uuid(bot.as_uuid())
}
@@ -348,6 +365,33 @@ fn harness_with_mentions(
prompt_context: PromptContextMock,
prompt_composer: PromptComposerMock,
mentions: PromptMentionsMock,
+) -> (TestBench, TurnSignals) {
+ harness_with_policies_and_mentions(
+ prompt_context,
+ prompt_composer,
+ KindDefaultPolicies,
+ mentions,
+ )
+}
+
+fn harness_with_policy(
+ prompt_context: PromptContextMock,
+ prompt_composer: PromptComposerMock,
+ permission_policies: impl crate::domain::ports::PermissionPolicySource,
+) -> (TestBench, TurnSignals) {
+ harness_with_policies_and_mentions(
+ prompt_context,
+ prompt_composer,
+ permission_policies,
+ PromptMentionsMock::new(),
+ )
+}
+
+fn harness_with_policies_and_mentions(
+ prompt_context: PromptContextMock,
+ prompt_composer: PromptComposerMock,
+ permission_policies: impl crate::domain::ports::PermissionPolicySource,
+ mentions: PromptMentionsMock,
) -> (TestBench, TurnSignals) {
let repo = InMemoryAgentSessionRepo::new();
let containers = MockContainerManager::new();
@@ -377,6 +421,7 @@ fn harness_with_mentions(
prompt_composer,
EgressProvisionerMock::new(),
NoPeers,
+ permission_policies,
HarnessDefaults::new(SessionDefaults {
bot_id: BotId::TEST_A,
model: "claude".to_owned(),
@@ -1516,6 +1561,154 @@ async fn a_non_staff_control_event_cannot_drive_a_sandboxed_coder_session() {
assert_eq!(prompts(&container.agent()).len(), 1);
}
+/// The agent asking whether it may run a tool, as an ACP request frame.
+fn permission_request(id: &str) -> RawJsonRpcMessage {
+ let (method, params) = RequestPermissionRequest::new(
+ "acp-test",
+ ToolCallUpdate::new("call-1", ToolCallUpdateFields::new()),
+ vec![
+ PermissionOption::new("once", "Allow once", PermissionOptionKind::AllowOnce),
+ PermissionOption::new("always", "Always allow", PermissionOptionKind::AllowAlways),
+ PermissionOption::new("reject", "Reject", PermissionOptionKind::RejectOnce),
+ ],
+ )
+ .to_untyped_message()
+ .expect("a permission request serializes")
+ .into_parts();
+ RawJsonRpcMessage::request(method, params, RequestId::Str(id.to_owned()))
+ .expect("a permission request is a valid frame")
+}
+
+fn permission_answer(id: &str, option_id: &str) -> AgentAction {
+ AgentAction::RespondToPermission(AgentPermissionAction {
+ request_id: RequestId::Str(id.to_owned()),
+ answer: PermissionAnswer::Selected {
+ option_id: option_id.to_owned(),
+ },
+ })
+}
+
+/// The outcome the harness answered `id` with, from what the agent received.
+fn permission_outcome(agent: &FakeAgent, id: &str) -> Option<RequestPermissionOutcome> {
+ agent
+ .received_responses()
+ .into_iter()
+ .find_map(|frame| match frame {
+ RawJsonRpcMessage::Response(Response::Result { id: got, result })
+ if got == RequestId::Str(id.to_owned()) =>
+ {
+ serde_json::from_value::<RequestPermissionResponse>(result)
+ .ok()
+ .map(|response| response.outcome)
+ }
+ _ => None,
+ })
+}
+
+#[tokio::test]
+async fn an_external_bots_permission_request_waits_for_a_users_answer() {
+ // The test bot is nobody's fixed system bot, so its kind is `External`
+ // and the policy source's default for it is to prompt.
+ let (service, _repo, containers, _announcer, _runtimes) = harness();
+ let id = AgentSessionId::new();
+ let container = live_session(&service, &containers, id).await;
+ let agent = container.agent();
+
+ agent.sends_raw(permission_request("perm-1"));
+ service
+ .control_event(
+ id,
+ ControlEvent {
+ action_id: None,
+ action: permission_answer("perm-1", "once"),
+ actor: Some(sender()),
+ },
+ )
+ .await
+ .expect("a user's answer reaches the agent");
+
+ let responses = agent.received_responses();
+ assert_eq!(
+ responses.len(),
+ 1,
+ "one answer, the user's; got {responses:?}"
+ );
+ assert_eq!(
+ permission_outcome(&agent, "perm-1"),
+ Some(RequestPermissionOutcome::Selected(
+ SelectedPermissionOutcome::new("once")
+ )),
+ "the user's choice is what goes out, not auto-accept's broadest allow"
+ );
+}
+
+#[tokio::test]
+async fn a_harness_principal_cannot_answer_a_permission_request() {
+ let (service, _repo, containers, _announcer, _runtimes) = harness();
+ let id = AgentSessionId::new();
+ let container = live_session(&service, &containers, id).await;
+ container.agent().sends_raw(permission_request("perm-1"));
+
+ let error = service
+ .control_event(
+ id,
+ ControlEvent {
+ action_id: None,
+ action: permission_answer("perm-1", "always"),
+ actor: None,
+ },
+ )
+ .await
+ .expect_err("a runtime must not approve its own tool call");
+
+ assert!(matches!(error, AgentSessionError::Forbidden));
+ assert!(container.agent().received_responses().is_empty());
+}
+
+#[tokio::test]
+async fn a_managed_bots_permission_request_is_accepted_on_arrival() {
+ let (service, _repo, containers, _announcer, _runtimes) = harness();
+ let id = AgentSessionId::new();
+ let container = live_sandboxed_coder_session(&service, &containers, id).await;
+ let agent = container.agent();
+
+ agent.sends_raw(permission_request("perm-1"));
+ agent.wait_for_responses(1).await;
+
+ assert_eq!(
+ permission_outcome(&agent, "perm-1"),
+ Some(RequestPermissionOutcome::Selected(
+ SelectedPermissionOutcome::new("always")
+ )),
+ "a sandboxed runtime keeps today's auto-accept"
+ );
+}
+
+#[tokio::test]
+async fn answering_a_disconnected_session_does_not_wake_its_sandbox() {
+ let (service, repo, containers, _announcer, _runtimes) = harness();
+ let id = disconnected_session(&repo, &containers).await;
+
+ let error = service
+ .control_event(
+ id,
+ ControlEvent {
+ action_id: None,
+ action: permission_answer("perm-1", "once"),
+ actor: Some(staff_sender()),
+ },
+ )
+ .await
+ .expect_err("nothing on a fresh connection could be waiting for this");
+
+ assert!(matches!(error, AgentSessionError::Disconnected(_)));
+ assert_eq!(
+ containers.resumed(),
+ 0,
+ "a prompt would resume the sandbox; an answer has nothing to deliver to"
+ );
+}
+
#[tokio::test]
async fn a_staff_control_event_can_drive_a_sandboxed_coder_session() {
let ((service, _repo, containers, _announcer, _runtimes), mut turns) =
@@ -2081,6 +2274,7 @@ async fn a_prompt_through_control_resumes_a_disconnected_session() {
fn open_external_request(workspace: &str) -> OpenExternalAgentSession {
OpenExternalAgentSession {
+ profile: None,
instructions: None,
bot_id: BotId::new_from_uuid(macro_uuid::generate_uuid_v7()),
workspace: workspace.to_owned(),
@@ -2244,6 +2438,92 @@ async fn an_external_open_provisions_nothing_and_prompts_nobody() {
assert_eq!(row.acp_session_id, Some(SessionId::new("acp-test")));
}
+#[tokio::test]
+async fn a_macrod_session_selects_its_saved_model_before_the_first_prompt() {
+ for accepted in [true, false] {
+ let (service, repo, _, _, runtimes) = harness();
+ let mut request = open_external_request("/home/operator/code");
+ request.profile = Some(agent_session::domain::ports::ManagedAgentProfile {
+ model: "gpt-5.6-luna".into(),
+ harness: harness_id::MACROD_HARNESS_SLUG.into(),
+ instructions: String::new(),
+ mcp_servers: AgentMcpServers::OwnerConnections,
+ });
+ let session = service.open_external_session(request).await.unwrap();
+ assert_eq!(session.model, "gpt-5.6-luna");
+ assert_eq!(session.harness, harness_id::MACROD_HARNESS_SLUG);
+ let runtime = ContainerMock::default();
+ runtimes.attach(harness_for_bot(session.bot_id), runtime.clone());
+
+ let drive = async {
+ let agent = runtime.agent();
+ while agent.received_requests().is_empty() {
+ runtime.sends_ready();
+ tokio::task::yield_now().await;
+ }
+ agent.completes_initialize(InitializeResponse::new(PROTOCOL_VERSION));
+ agent.wait_for_requests(2).await;
+ let config = |model| {
+ serde_json::json!([{
+ "id": "model", "name": "Model", "type": "select",
+ "currentValue": model, "options": []
+ }])
+ };
+ agent.opens_session(
+ serde_json::from_value(serde_json::json!({
+ "sessionId": "acp-test", "configOptions": config("gpt-6-astra")
+ }))
+ .unwrap(),
+ );
+ agent.wait_for_requests(3).await;
+ assert!(prompts(&agent).is_empty());
+ let row = repo.get(session.id).await.unwrap();
+ assert_eq!(
+ row.model, "gpt-5.6-luna",
+ "session/new must not overwrite the saved selection"
+ );
+ assert!(row.acp_session_id.is_none());
+ let frames = agent.received_frames();
+ let RawJsonRpcMessage::Request(change) = frames.last().unwrap() else {
+ panic!("expected model selection");
+ };
+ assert_eq!(change.method.as_ref(), "session/set_config_option");
+ assert_eq!(
+ serde_json::to_value(&change.params).unwrap()["value"],
+ "gpt-5.6-luna"
+ );
+ if accepted {
+ agent.sends_raw(RawJsonRpcMessage::response(
+ change.id.clone(),
+ Ok(serde_json::json!({
+ "configOptions": config("gpt-5.6-luna")
+ })),
+ ));
+ agent.completes_prompt().await;
+ } else {
+ agent.sends_error(
+ change.id.clone(),
+ agent_client_protocol::Error::invalid_params(),
+ );
+ }
+ };
+ let (result, ()) = tokio::join!(prompt(&service, session.id, "hello"), drive);
+ if accepted {
+ result.unwrap();
+ assert_eq!(prompts(&runtime.agent()).len(), 1);
+ } else {
+ assert!(result.is_err());
+ assert!(prompts(&runtime.agent()).is_empty());
+ }
+ let row = repo.get(session.id).await.unwrap();
+ assert_eq!(
+ row.model, "gpt-5.6-luna",
+ "a retry must retain the requested model"
+ );
+ assert_eq!(row.acp_session_id.is_some(), accepted);
+ }
+}
+
#[tokio::test]
async fn a_bound_session_stays_on_its_connection_until_it_drops() {
let (service, _repo, _containers, _announcer, runtimes) = harness();
@@ -2338,6 +2618,7 @@ async fn a_managed_session_opens_as_the_managed_default_bot() {
PromptComposerMock::default(),
EgressProvisionerMock::new(),
NoPeers,
+ KindDefaultPolicies,
HarnessDefaults::new(SessionDefaults {
bot_id: BotId::TEST_A,
model: "claude".to_owned(),
@@ -2803,6 +3084,7 @@ async fn commands_for_a_peer_managed_session_forward_through_redis() {
PromptComposerMock::default(),
EgressProvisionerMock::new(),
forwarder.clone(),
+ KindDefaultPolicies,
SessionDefaults {
bot_id: BotId::TEST_A,
model: "claude".to_owned(),
@@ -2854,6 +3136,7 @@ async fn unmanaged_external_session_forwards_to_its_remote_harness() {
PromptComposerMock::default(),
EgressProvisionerMock::new(),
forwarder.clone(),
+ KindDefaultPolicies,
SessionDefaults {
bot_id: BotId::TEST_A,
model: "claude".to_owned(),
@@ -2894,7 +3177,6 @@ async fn unmanaged_external_session_forwards_to_its_remote_harness() {
mod lifecycle_events {
use super::*;
- use agent_client_protocol::JsonRpcMessage as _;
use agent_client_protocol::schema::v1::{
CreateElicitationRequest, ElicitationFormMode, ElicitationSchema, ElicitationSessionScope,
RequestId,
@@ -3589,3 +3871,45 @@ async fn branch_without_repository_is_rejected_before_provisioning() {
assert!(service.inner.egress.provisioned().is_empty());
assert_eq!(containers.spawned(), 0);
}
+
+struct PromptPolicies;
+impl crate::domain::ports::PermissionPolicySource for PromptPolicies {
+ async fn permission_policy(
+ &self,
+ _: BotId,
+ ) -> anyhow::Result<crate::domain::model::PermissionPolicyConfig> {
+ Ok(crate::domain::model::PermissionPolicyConfig::Fixed(
+ AgentKind::External,
+ ))
+ }
+}
+
+#[tokio::test]
+async fn a_non_staff_session_editor_can_approve_a_managed_session_request() {
+ let ((service, _repo, containers, _announcer, _runtimes), _signals) = harness_with_policy(
+ PromptContextMock::default(),
+ PromptComposerMock::default(),
+ PromptPolicies,
+ );
+ let id = AgentSessionId::new();
+ let container = live_sandboxed_coder_session(&service, &containers, id).await;
+ let agent = container.agent();
+ agent.sends_raw(permission_request("editor-approval"));
+ service
+ .control_event(
+ id,
+ ControlEvent {
+ action_id: None,
+ action: permission_answer("editor-approval", "once"),
+ actor: Some(sender()),
+ },
+ )
+ .await
+ .expect("a human editor can approve even though only staff may prompt the coder");
+ assert_eq!(
+ permission_outcome(&agent, "editor-approval"),
+ Some(RequestPermissionOutcome::Selected(
+ SelectedPermissionOutcome::new("once")
+ ))
+ );
+}
diff --git a/crates/agent_harness/src/testing/helpers/agent.rs b/crates/agent_harness/src/testing/helpers/agent.rs
index c9518d0afa..29c9cbe2b7 100644
--- a/crates/agent_harness/src/testing/helpers/agent.rs
+++ b/crates/agent_harness/src/testing/helpers/agent.rs
@@ -219,6 +219,33 @@ impl FakeAgent {
.expect("fake agent frame history should remain open");
}
+ /// Wait until the harness has answered at least `count` of this agent's
+ /// own requests.
+ pub async fn wait_for_responses(&self, count: usize) {
+ let mut received = self.received.subscribe();
+ received
+ .wait_for(|frames| {
+ frames
+ .iter()
+ .filter(|frame| matches!(frame, RawJsonRpcMessage::Response(_)))
+ .count()
+ >= count
+ })
+ .await
+ .expect("fake agent frame history should remain open");
+ }
+
+ /// The response frames the harness sent to this agent's requests, in order.
+ #[must_use]
+ pub fn received_responses(&self) -> Vec<RawJsonRpcMessage> {
+ self.received
+ .borrow()
+ .iter()
+ .filter(|frame| matches!(frame, RawJsonRpcMessage::Response(_)))
+ .cloned()
+ .collect()
+ }
+
/// The notifications the harness sent, in order.
#[must_use]
pub fn received_notifications(&self) -> Vec<ClientNotification> {
diff --git a/crates/agent_runtime_protocol/src/domain/action.rs b/crates/agent_runtime_protocol/src/domain/action.rs
index 46bc4dc7f4..6cabc9e0f7 100644
--- a/crates/agent_runtime_protocol/src/domain/action.rs
+++ b/crates/agent_runtime_protocol/src/domain/action.rs
@@ -8,7 +8,8 @@ use std::collections::BTreeMap;
use agent_client_protocol::schema::v1::{
CancelNotification, ClientRequest, ContentBlock, CreateElicitationResponse,
ElicitationAcceptAction, ElicitationAction, ElicitationContentValue as AcpContentValue,
- PromptRequest, RequestId, ResourceLink, SessionId, SetSessionConfigOptionRequest,
+ PromptRequest, RequestId, RequestPermissionOutcome, RequestPermissionResponse, ResourceLink,
+ SelectedPermissionOutcome, SessionId, SetSessionConfigOptionRequest,
};
use agent_client_protocol::{JsonRpcMessage, RawJsonRpcMessage};
use macro_uuid::Uuid;
@@ -343,6 +344,52 @@ pub struct AgentRespondElicitationAction {
pub answer: ElicitationAnswer,
}
+/// A user's answer to the agent's `session/request_permission`.
+///
+/// Unlike every other action this is not a new request but the reply to one
+/// the agent made, so it carries the agent's own request id rather than
+/// receiving a server-minted one.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
+#[serde(rename_all = "camelCase")]
+pub struct AgentPermissionAction {
+ /// The agent's JSON-RPC request id, echoed verbatim from the folded
+ /// permission part. A string or a number on the wire; agents mint both,
+ /// and `7` does not answer `"7"`.
+ #[cfg_attr(feature = "utoipa", schema(value_type = serde_json::Value))]
+ pub request_id: RequestId,
+ /// What the user decided.
+ pub answer: PermissionAnswer,
+}
+
+/// The decision carried by an [`AgentPermissionAction`].
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
+#[serde(tag = "kind", rename_all = "camelCase")]
+pub enum PermissionAnswer {
+ /// One of the options the agent offered was chosen.
+ Selected {
+ /// The chosen option's id, as the agent listed it.
+ #[serde(rename = "optionId")]
+ option_id: String,
+ },
+ /// The request was dismissed without choosing.
+ Cancelled,
+}
+
+impl PermissionAnswer {
+ /// The ACP outcome this answer resolves the request with.
+ #[must_use]
+ pub fn to_acp(&self) -> RequestPermissionOutcome {
+ match self {
+ Self::Selected { option_id } => RequestPermissionOutcome::Selected(
+ SelectedPermissionOutcome::new(option_id.clone()),
+ ),
+ Self::Cancelled => RequestPermissionOutcome::Cancelled,
+ }
+ }
+}
+
/// One thing a caller wants an agent to do.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, strum::AsRefStr)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
@@ -364,6 +411,8 @@ pub enum AgentAction {
/// minted [`AgentActionId`] therefore never reaches the wire for this
/// action; the fold correlates on the agent's id instead.
RespondElicitation(AgentRespondElicitationAction),
+ /// Answer a permission request the agent is waiting on.
+ RespondToPermission(AgentPermissionAction),
}
impl AgentAction {
@@ -447,7 +496,10 @@ impl AgentAction {
Self::Prompt(_) | Self::Compact => true,
// An elicitation answer is the running turn's own business: the
// agent is blocked on it mid-turn, so it must ride alongside.
- Self::SetModel(_) | Self::Stop | Self::RespondElicitation(_) => false,
+ Self::SetModel(_)
+ | Self::Stop
+ | Self::RespondElicitation(_)
+ | Self::RespondToPermission(_) => false,
}
}
@@ -530,6 +582,14 @@ impl AgentAction {
RawJsonRpcMessage::response(action.request_id.to_request_id(), Ok(result));
Ok(ToRuntimeMessage::Acp(AcpMessage(frame)))
}
+ // A response to the agent's own request, so both `session_id` and
+ // the minted `request_id` are unused: the frame carries the id the
+ // agent chose. The session machine validates the answer against
+ // the request it is holding open before translating it.
+ Self::RespondToPermission(action) => Ok(permission_response(
+ action.request_id.clone(),
+ action.answer.to_acp(),
+ )?),
}
}
}
@@ -559,3 +619,15 @@ impl AgentRespondElicitationAction {
CreateElicitationResponse::new(action)
}
}
+
+/// The ACP frame answering permission request `request_id` with `outcome`.
+pub fn permission_response(
+ request_id: RequestId,
+ outcome: RequestPermissionOutcome,
+) -> Result<ToRuntimeMessage, ActionError> {
+ let result = serde_json::to_value(RequestPermissionResponse::new(outcome))
+ .map_err(|error| ActionError::Acp(error.to_string()))?;
+ Ok(ToRuntimeMessage::Acp(AcpMessage(
+ RawJsonRpcMessage::response(request_id, Ok(result)),
+ )))
+}
diff --git a/crates/agent_runtime_protocol/src/domain/action/test.rs b/crates/agent_runtime_protocol/src/domain/action/test.rs
index f19ebdb6b9..604e8f235b 100644
--- a/crates/agent_runtime_protocol/src/domain/action/test.rs
+++ b/crates/agent_runtime_protocol/src/domain/action/test.rs
@@ -1,5 +1,5 @@
use super::ElicitationContentValue as ContentValue;
-use agent_client_protocol::schema::v1::{ClientRequest, ContentBlock, SessionId};
+use agent_client_protocol::schema::v1::{ClientRequest, ContentBlock, Response, SessionId};
use super::*;
@@ -325,6 +325,74 @@ fn elicitation_ids_round_trip_and_null_is_unanswerable() {
);
}
+#[test]
+fn a_permission_answer_becomes_a_response_carrying_the_agents_request_id() {
+ let session_id = SessionId::new("acp-abc");
+ let translated = permission_answer(RequestId::Number(7))
+ .to_runtime(&session_id, RequestId::Str("minted-and-ignored".to_owned()))
+ .unwrap();
+
+ let ToRuntimeMessage::Acp(AcpMessage(RawJsonRpcMessage::Response(Response::Result {
+ id,
+ result,
+ }))) = translated
+ else {
+ panic!("a permission answer translates to a successful ACP response");
+ };
+ assert_eq!(id, RequestId::Number(7));
+ let response: RequestPermissionResponse = serde_json::from_value(result).unwrap();
+ assert_eq!(
+ response.outcome,
+ RequestPermissionOutcome::Selected(SelectedPermissionOutcome::new("allow"))
+ );
+
+ let message =
+ ToRuntimeMessage::Acp(AcpMessage(RawJsonRpcMessage::Response(Response::Result {
+ id: RequestId::Number(7),
+ result: serde_json::json!({}),
+ })));
+ assert_eq!(AgentAction::control_from_runtime(&message), None);
+}
+
+#[test]
+fn a_permission_answer_round_trips_through_json_keeping_the_ids_shape() {
+ let numeric = permission_answer(RequestId::Number(7));
+ let json = serde_json::to_value(&numeric).unwrap();
+ assert_eq!(
+ json,
+ serde_json::json!({
+ "type": "respondToPermission",
+ "requestId": 7,
+ "answer": { "kind": "selected", "optionId": "allow" },
+ })
+ );
+ assert_eq!(
+ serde_json::from_value::<AgentAction>(json).unwrap(),
+ numeric
+ );
+
+ let cancelled = AgentAction::RespondToPermission(AgentPermissionAction {
+ request_id: RequestId::Str("req-1".to_owned()),
+ answer: PermissionAnswer::Cancelled,
+ });
+ let json = serde_json::to_value(&cancelled).unwrap();
+ assert_eq!(json["requestId"], serde_json::json!("req-1"));
+ assert_eq!(json["answer"], serde_json::json!({ "kind": "cancelled" }));
+ assert_eq!(
+ serde_json::from_value::<AgentAction>(json).unwrap(),
+ cancelled
+ );
+}
+
+fn permission_answer(request_id: RequestId) -> AgentAction {
+ AgentAction::RespondToPermission(AgentPermissionAction {
+ request_id,
+ answer: PermissionAnswer::Selected {
+ option_id: "allow".to_owned(),
+ },
+ })
+}
+
#[test]
fn a_prompt_with_attachments_sends_text_then_one_resource_link_each() {
let session_id = SessionId::new("acp-abc");
diff --git a/crates/agent_session/src/domain/connection.rs b/crates/agent_session/src/domain/connection.rs
index f9321825bf..afdee7be7e 100644
--- a/crates/agent_session/src/domain/connection.rs
+++ b/crates/agent_session/src/domain/connection.rs
@@ -35,7 +35,7 @@ use tokio::sync::{Mutex, mpsc, watch};
use tokio_util::sync::CancellationToken;
use crate::domain::model::{AgentSessionId, SessionClaim};
-use crate::domain::session::HandshakeStatus;
+use crate::domain::session::{HandshakeStatus, PermissionPolicy};
#[cfg(test)]
mod test;
@@ -156,6 +156,12 @@ pub struct RuntimeAttachment<Connector> {
/// callers waiting on a reply then fall back to their own timeout alone,
/// exactly as before this existed.
pub(crate) closed: Option<CancellationToken>,
+ /// How this attachment's session answers permission requests. Per
+ /// attachment for the same reason as `mcp_servers`: it follows what the
+ /// agent's owner has configured *now*.
+ pub(crate) permission_policy: PermissionPolicy,
+ /// Model to select after creating a fresh ACP session, before any prompt.
+ pub(crate) initial_model: Option<String>,
}
/// Activate attachment-owned resources with the exact acquired ownership claim.
@@ -175,6 +181,8 @@ impl<Connector> RuntimeAttachment<Connector> {
handshake,
mcp_servers: Vec::new(),
closed: None,
+ permission_policy: PermissionPolicy::default(),
+ initial_model: None,
}
}
@@ -204,6 +212,8 @@ impl<Connector> RuntimeAttachment<Connector> {
mcp_servers: self.mcp_servers,
activation: self.activation,
closed: self.closed,
+ permission_policy: self.permission_policy,
+ initial_model: self.initial_model,
}
}
@@ -214,6 +224,21 @@ impl<Connector> RuntimeAttachment<Connector> {
self.mcp_servers = mcp_servers;
self
}
+
+ /// Select this model before the first prompt of a newly created ACP session.
+ /// Empty values and the provider-default sentinel keep the runtime's default.
+ #[must_use]
+ pub fn initial_model(mut self, model: String) -> Self {
+ self.initial_model = (!model.trim().is_empty() && model != "default").then_some(model);
+ self
+ }
+
+ /// How this attachment's session answers the agent's permission requests.
+ #[must_use]
+ pub fn permission_policy(mut self, permission_policy: PermissionPolicy) -> Self {
+ self.permission_policy = permission_policy;
+ self
+ }
}
/// Every session this connection carries, and where to reach it.
@@ -383,6 +408,9 @@ where
// This connection already tracks its own end (`evict`, or the
// router task finishing) - the same signal `closed()` awaits.
closed: Some(self.closed.clone()),
+ // The caller knows whose agent this is; the connection does not.
+ permission_policy: PermissionPolicy::default(),
+ initial_model: None,
}
}
diff --git a/crates/agent_session/src/domain/control.rs b/crates/agent_session/src/domain/control.rs
new file mode 100644
index 0000000000..dc1786cd9e
--- /dev/null
+++ b/crates/agent_session/src/domain/control.rs
@@ -0,0 +1,54 @@
+//! Human approval remains distinct from a runtime forwarding a user's prompt.
+
+use agent_runtime_protocol::domain::action::{AgentAction, AgentActionId};
+use entity_access::domain::models::{EditAccessLevel, EntityAccessReceipt};
+use macro_user_id::user_id::MacroUserIdStr;
+
+use super::error::{AgentSessionError, Result};
+use super::ports::ControlEvent;
+
+/// The authenticated principal, before an acting-user claim erases its origin.
+pub enum ControlPrincipal {
+ /// A user authenticated directly, including a user API key.
+ User,
+ /// A bot, daemon, or internal service, possibly forwarding a user's request.
+ Runtime(Option<MacroUserIdStr<'static>>),
+}
+
+impl ControlEvent {
+ /// Only an authenticated user with edit access may answer an interaction.
+ /// Runtime principals may forward ordinary controls, but cannot use their
+ /// acting-user identity to approve their own permission or elicitation.
+ pub fn authorized(
+ action: AgentAction,
+ action_id: Option<AgentActionId>,
+ principal: ControlPrincipal,
+ access: EntityAccessReceipt<EditAccessLevel>,
+ ) -> Result<Self> {
+ let actor = match principal {
+ ControlPrincipal::User => Some(
+ access
+ .get_authenticated_user()
+ .map_err(|_| AgentSessionError::Forbidden)?
+ .clone(),
+ ),
+ ControlPrincipal::Runtime(actor) => {
+ if matches!(
+ action,
+ AgentAction::RespondToPermission(_) | AgentAction::RespondElicitation(_)
+ ) {
+ return Err(AgentSessionError::Forbidden);
+ }
+ actor
+ }
+ };
+ Ok(Self {
+ action,
+ action_id,
+ actor,
+ })
+ }
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/agent_session/src/domain/control/test.rs b/crates/agent_session/src/domain/control/test.rs
new file mode 100644
index 0000000000..55316de3ed
--- /dev/null
+++ b/crates/agent_session/src/domain/control/test.rs
@@ -0,0 +1,73 @@
+use super::*;
+use entity_access::domain::models::{AccessLevel, Entity, EntityPermission, EntityType};
+
+fn user() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from_email("[email protected]").unwrap()
+}
+
+fn access(level: AccessLevel) -> EntityAccessReceipt<EditAccessLevel> {
+ EntityAccessReceipt::try_new_authenticated_user(
+ user(),
+ Entity {
+ entity_id: "session".into(),
+ entity_type: EntityType::AgentSession,
+ },
+ EntityPermission::AccessLevel {
+ access_level: level,
+ },
+ )
+ .unwrap()
+}
+
+fn answers() -> [AgentAction; 2] {
+ [
+ serde_json::from_value(serde_json::json!({
+ "type": "respondToPermission", "requestId": "permission",
+ "answer": { "kind": "selected", "optionId": "allow" }
+ }))
+ .unwrap(),
+ serde_json::from_value(serde_json::json!({
+ "type": "respondElicitation", "requestId": 0, "action": "accept"
+ }))
+ .unwrap(),
+ ]
+}
+
+#[test]
+fn editors_and_owners_can_answer_both_interaction_kinds() {
+ for level in [AccessLevel::Edit, AccessLevel::Owner] {
+ for action in answers() {
+ let event =
+ ControlEvent::authorized(action, None, ControlPrincipal::User, access(level))
+ .unwrap();
+ assert_eq!(event.actor, Some(user()));
+ }
+ }
+}
+
+#[test]
+fn runtimes_cannot_answer_even_when_forwarding_an_owner_or_editor() {
+ for level in [AccessLevel::Edit, AccessLevel::Owner] {
+ for actor in [None, Some(user())] {
+ for action in answers() {
+ assert!(matches!(
+ ControlEvent::authorized(
+ action,
+ None,
+ ControlPrincipal::Runtime(actor.clone()),
+ access(level)
+ ),
+ Err(AgentSessionError::Forbidden)
+ ));
+ }
+ let event = ControlEvent::authorized(
+ AgentAction::prompt("hello"),
+ None,
+ ControlPrincipal::Runtime(actor.clone()),
+ access(level),
+ )
+ .expect("runtimes still forward ordinary prompts");
+ assert_eq!(event.actor, actor);
+ }
+ }
+}
diff --git a/crates/agent_session/src/domain/error.rs b/crates/agent_session/src/domain/error.rs
index 51c9174c3c..8f2dda4bdb 100644
--- a/crates/agent_session/src/domain/error.rs
+++ b/crates/agent_session/src/domain/error.rs
@@ -39,6 +39,12 @@ pub enum AgentSessionError {
EmptyQueuedPrompt,
#[error("agent session {0} has too many queued actions")]
ControlQueueFull(AgentSessionId),
+ #[error(
+ "agent session {0} has no open permission request with this id; it may already have been answered or cancelled"
+ )]
+ PermissionRequestNotFound(AgentSessionId),
+ #[error("agent session {0} was not offered that permission option")]
+ PermissionOptionUnknown(AgentSessionId),
#[error(
"agent session {0} cannot be restored because the agent supports neither session/resume nor session/load"
)]
diff --git a/crates/agent_session/src/domain/mod.rs b/crates/agent_session/src/domain/mod.rs
index 9bed6ea05f..cfdcedc7b3 100644
--- a/crates/agent_session/src/domain/mod.rs
+++ b/crates/agent_session/src/domain/mod.rs
@@ -1,6 +1,8 @@
/// Current authorization for agent session streams.
pub mod audience;
pub mod connection;
+/// Authorization of user and runtime session controls.
+pub mod control;
pub mod error;
pub mod events;
pub mod lifecycle;
diff --git a/crates/agent_session/src/domain/ports.rs b/crates/agent_session/src/domain/ports.rs
index ecc5d2616e..476ff257e9 100644
--- a/crates/agent_session/src/domain/ports.rs
+++ b/crates/agent_session/src/domain/ports.rs
@@ -51,7 +51,7 @@ pub struct BotFacts {
pub selected_channels: bool,
}
-/// Runtime settings snapshotted when a managed persona opens a session.
+/// Runtime settings snapshotted when a persisted agent opens a session.
#[derive(Debug, Clone)]
pub struct ManagedAgentProfile {
/// Model configured as this persona's default.
@@ -194,6 +194,8 @@ pub struct SessionThread {
pub struct OpenExternalAgentSession {
/// The bot the session runs for.
pub bot_id: BotId,
+ /// Persisted agent settings resolved by the authenticated entry point.
+ pub profile: Option<ManagedAgentProfile>,
/// Absolute directory the bot's harness runs in on its runtime.
pub workspace: String,
/// Repository nominally checked out at `workspace`, when stated.
diff --git a/crates/agent_session/src/domain/service.rs b/crates/agent_session/src/domain/service.rs
index 71a495bd25..6ef880cee9 100644
--- a/crates/agent_session/src/domain/service.rs
+++ b/crates/agent_session/src/domain/service.rs
@@ -27,12 +27,18 @@ mod test;
use std::sync::Arc;
-use agent_client_protocol::schema::v1::SessionId;
+use agent_client_protocol::RawJsonRpcMessage;
+use agent_client_protocol::schema::v1::{
+ RequestId, Response, SessionId, SetSessionConfigOptionResponse,
+};
use agent_fold::domain::lifecycle::LifecycleFold;
use agent_fold::domain::model::TurnSignal;
+use agent_fold::domain::model_selection::model_selection;
use agent_fold::domain::ports::FoldedMessageRepo;
-use agent_runtime_protocol::domain::action::{AgentAction, AgentActionId};
-use agent_runtime_protocol::domain::schema::v0::{SystemEvent, ToServerMessage};
+use agent_runtime_protocol::domain::action::{AgentAction, AgentActionId, AgentSetModelAction};
+use agent_runtime_protocol::domain::schema::v0::{
+ AcpMessage, SystemEvent, ToRuntimeMessage, ToServerMessage,
+};
use dashmap::DashMap;
use dashmap::mapref::entry::Entry;
use entity_access::domain::models::{EntityAccessReceipt, EntityType, OwnerAccessLevel};
@@ -464,19 +470,25 @@ impl<R, Folds, Rt, Namer> AgentSessionServiceImpl<R, Folds, Rt, Namer> {
// something. Fenced under the claim taken above: if another replica
// supersedes this one, the store rejects the next append and the
// actor tears down through its ordinary log-failure path.
- let logs = LiveSessionLogWriter::fenced(self.repo.clone(), self.realtime.clone(), claim);
+ let initial_model = attachment
+ .initial_model
+ .filter(|_| session.acp_session_id.is_none());
+ let logs = LiveSessionLogWriter::fenced(self.repo.clone(), self.realtime.clone(), claim)
+ .with_initial_model(initial_model.clone());
let actor = SessionActor::new(
id,
session.acp_session_id,
session.workspace,
attachment.mcp_servers,
+ attachment.permission_policy,
attachment.connector,
logs,
command_rx,
attachment.handshake,
Arc::clone(&self.turn_observer),
Arc::clone(&self.tool_catalog),
- );
+ )
+ .with_initial_model(initial_model);
self.tasks.spawn(
run_session(
actor,
@@ -1100,6 +1112,10 @@ pub struct LiveSessionLogWriter<R, Rt> {
/// replaying a recording, and `mark_disconnected` recording that a
/// runtime dropped before anything attached.
claim: Option<SessionClaim>,
+ /// Keep the saved selection until the runtime confirms it. Otherwise the
+ /// default reported by session/new replaces it even when selection fails.
+ initial_model: Option<String>,
+ initial_model_request: Option<RequestId>,
}
impl<R, Rt> LiveSessionLogWriter<R, Rt> {
@@ -1115,6 +1131,8 @@ impl<R, Rt> LiveSessionLogWriter<R, Rt> {
realtime,
fold: None,
claim: None,
+ initial_model: None,
+ initial_model_request: None,
}
}
@@ -1126,8 +1144,15 @@ impl<R, Rt> LiveSessionLogWriter<R, Rt> {
realtime,
fold: None,
claim: Some(claim),
+ initial_model: None,
+ initial_model_request: None,
}
}
+
+ fn with_initial_model(mut self, model: Option<String>) -> Self {
+ self.initial_model = model;
+ self
+ }
}
impl<R, Rt> AgentSessionLogWriter for LiveSessionLogWriter<R, Rt>
@@ -1191,10 +1216,38 @@ where
// Projected on every frame - idempotent, rebuildable from the log,
// and best-effort like the stream below, so a failed write must not
// fail the append. Batch if the write rate ever matters.
- if let Some(model) = self
+ let model = self
.fold
.as_ref()
- .and_then(|fold| fold.inner().metadata().model.clone())
+ .and_then(|fold| fold.inner().metadata().model.clone());
+ // Track this connection's selection request. A session/new reply or an
+ // unrelated config response must not release the saved-model guard.
+ if let Some(expected) = &self.initial_model
+ && self.initial_model_request.is_none()
+ && let Message::ToRuntime(message) = &log.content
+ && let Some((_, selection)) = AgentSetModelAction::from_runtime(message)
+ && selection.model == *expected
+ && let ToRuntimeMessage::Acp(AcpMessage(RawJsonRpcMessage::Request(request))) = message
+ {
+ self.initial_model_request = Some(request.id.clone());
+ }
+ // Catching up the fold may report a previous connection's model, so
+ // only the matching fresh response can confirm startup.
+ if let Some(expected) = &self.initial_model
+ && let Message::ToServer(ToServerMessage::Acp(AcpMessage(RawJsonRpcMessage::Response(
+ Response::Result { id, result, .. },
+ )))) = &log.content
+ && self.initial_model_request.as_ref() == Some(id)
+ && let Ok(response) =
+ serde_json::from_value::<SetSessionConfigOptionResponse>(result.clone())
+ && model_selection(&response.config_options)
+ .is_some_and(|selection| selection.current == *expected)
+ {
+ self.initial_model = None;
+ self.initial_model_request = None;
+ }
+ if self.initial_model.is_none()
+ && let Some(model) = model
&& let Err(error) = self.repo.set_model(session, &model).await
{
tracing::error!(
diff --git a/crates/agent_session/src/domain/service/test.rs b/crates/agent_session/src/domain/service/test.rs
index df688ab8e6..8767899547 100644
--- a/crates/agent_session/src/domain/service/test.rs
+++ b/crates/agent_session/src/domain/service/test.rs
@@ -5,7 +5,7 @@ use crate::domain::model::{
};
use crate::domain::ports::NoOpRealtime;
use crate::domain::ports::{NoOpTurnObserver, NoopLifecyclePublisher};
-use crate::domain::session::HandshakeStatus;
+use crate::domain::session::{HandshakeStatus, PermissionPolicy};
use crate::testing::{
InMemoryAgentSessionRepo, RecordingLifecyclePublisher, RecordingRealtime, test_agent_session,
};
@@ -920,6 +920,7 @@ async fn cancellation_does_not_drop_an_effect_batch_after_machine_mutation() {
None,
"/workspace".to_owned(),
Vec::new(),
+ PermissionPolicy::AutoAccept,
RecordingTransport {
outbound: outbound_tx,
inbound: inbound_rx,
@@ -1001,6 +1002,7 @@ async fn live_inbound_logs_do_not_reuse_the_expired_handshake_deadline() {
None,
"/workspace".to_owned(),
Vec::new(),
+ PermissionPolicy::AutoAccept,
RecordingTransport {
outbound: outbound_tx,
inbound: inbound_rx,
@@ -1464,6 +1466,7 @@ async fn shared_transport_copies_durable_initialization_before_load() {
Some("first-acp".into()),
"/workspace".into(),
vec![],
+ PermissionPolicy::Prompt,
RecordingTransport {
outbound: send,
inbound,
@@ -1517,6 +1520,7 @@ async fn shared_transport_copies_durable_initialization_before_load() {
Some("second-acp".into()),
"/workspace".into(),
vec![],
+ PermissionPolicy::Prompt,
RecordingTransport {
outbound: send,
inbound,
@@ -1622,6 +1626,7 @@ async fn assert_restore_persistence_failure_does_not_send_prompt(failure: Restor
Some("restored-acp".into()),
"/workspace".into(),
vec![],
+ PermissionPolicy::Prompt,
RecordingTransport {
outbound: send,
inbound,
@@ -1777,6 +1782,7 @@ async fn a_prompt_turn_is_traced_as_an_agent_span_under_its_command() {
None,
"/workspace".to_owned(),
Vec::new(),
+ crate::domain::session::PermissionPolicy::AutoAccept,
RecordingTransport {
outbound: outbound_tx,
inbound: inbound_rx,
@@ -1888,6 +1894,7 @@ async fn a_prompt_turn_is_traced_as_an_agent_span_under_its_command() {
assert!(input.contains("what time is it?"), "{input}");
}
+mod initial_model;
mod owner_binding;
/// The live writer's fold says what each appended frame meant for the turn;
diff --git a/crates/agent_session/src/domain/service/test/initial_model.rs b/crates/agent_session/src/domain/service/test/initial_model.rs
new file mode 100644
index 0000000000..88ffcd89c5
--- /dev/null
+++ b/crates/agent_session/src/domain/service/test/initial_model.rs
@@ -0,0 +1,78 @@
+use super::*;
+use serde_json::json;
+
+fn selection(id: i64, model: &str) -> Message {
+ Message::ToRuntime(
+ AgentAction::set_model(model)
+ .to_runtime(&"runtime-session".into(), RequestId::Number(id))
+ .unwrap(),
+ )
+}
+
+fn response(id: i64, model: &str) -> Message {
+ Message::ToServer(ToServerMessage::Acp(AcpMessage(
+ RawJsonRpcMessage::response(
+ RequestId::Number(id),
+ Ok(json!({
+ "sessionId": "runtime-session",
+ "configOptions": [{
+ "id": "model", "name": "Model", "type": "select",
+ "currentValue": model, "options": []
+ }]
+ })),
+ ),
+ )))
+}
+
+#[tokio::test]
+async fn only_the_startup_selection_reply_releases_model_projection() {
+ let fx = fixture();
+ fx.repo.set_model(fx.session, "saved-model").await.unwrap();
+ let mut logs = connection(fx.repo.clone()).with_initial_model(Some("saved-model".into()));
+ let open = Message::ToRuntime(ToRuntimeMessage::Acp(AcpMessage(
+ RawJsonRpcMessage::request(
+ "session/new".into(),
+ json!({"cwd": "/workspace", "mcpServers": []}),
+ RequestId::Number(1),
+ )
+ .unwrap(),
+ )));
+
+ // Even if the runtime's default already matches, the opening reply and
+ // other config replies cannot confirm the pending startup selection.
+ for content in [
+ open,
+ response(1, "saved-model"),
+ selection(2, "saved-model"),
+ selection(99, "saved-model"),
+ response(99, "saved-model"),
+ response(2, "wrong-model"),
+ ] {
+ logs.append(AgentSessionLog {
+ agent_session_id: fx.session,
+ user_id: None,
+ content,
+ })
+ .await
+ .unwrap();
+ assert_eq!(fx.repo.get(fx.session).await.unwrap().model, "saved-model");
+ }
+
+ // Reattaching must not trust the previous connection's logged responses.
+ let mut logs = connection(fx.repo.clone()).with_initial_model(Some("saved-model".into()));
+ for (content, expected) in [
+ (selection(3, "saved-model"), "saved-model"),
+ (response(3, "saved-model"), "saved-model"),
+ (selection(4, "next-model"), "saved-model"),
+ (response(4, "next-model"), "next-model"),
+ ] {
+ logs.append(AgentSessionLog {
+ agent_session_id: fx.session,
+ user_id: None,
+ content,
+ })
+ .await
+ .unwrap();
+ assert_eq!(fx.repo.get(fx.session).await.unwrap().model, expected);
+ }
+}
diff --git a/crates/agent_session/src/domain/session/actors.rs b/crates/agent_session/src/domain/session/actors.rs
index 272b14f4a1..8cf5a1ea9b 100644
--- a/crates/agent_session/src/domain/session/actors.rs
+++ b/crates/agent_session/src/domain/session/actors.rs
@@ -37,7 +37,8 @@ use agent_fold::domain::model::TurnSignal;
use super::telemetry::GenAiProjector;
use super::{
- CloseReason, Effect, HandshakeStatus, Input, RuntimeStatus, SessionMachine, StopReason,
+ CloseReason, Effect, HandshakeStatus, Input, PermissionPolicy, RuntimeStatus, SessionMachine,
+ StopReason,
};
/// How long the ACP handshake has to finish before the session is declared dead.
@@ -121,6 +122,7 @@ where
acp_session_id: Option<SessionId>,
workspace: String,
mcp_servers: Vec<McpServer>,
+ permission_policy: PermissionPolicy,
connector: Connector,
logs: Logs,
commands: mpsc::Receiver<SessionCommand>,
@@ -150,10 +152,14 @@ where
handshake_seen,
handshake,
machine: match acp_session_id {
- None => SessionMachine::new(id, workspace, mcp_servers.clone()),
- Some(session_id) => {
- SessionMachine::resume(id, session_id, workspace, mcp_servers.clone())
- }
+ None => SessionMachine::new(id, workspace, mcp_servers.clone(), permission_policy),
+ Some(session_id) => SessionMachine::resume(
+ id,
+ session_id,
+ workspace,
+ mcp_servers.clone(),
+ permission_policy,
+ ),
}
.with_connection_context(macro_uuid::generate_uuid_v7()),
logs,
@@ -172,6 +178,12 @@ where
}
}
+ /// Apply an explicit starting model before a new session becomes live.
+ pub(crate) fn with_initial_model(mut self, model: Option<String>) -> Self {
+ self.machine = self.machine.with_initial_model(model);
+ self
+ }
+
/// The session this actor's connection belongs to.
pub(crate) fn id(&self) -> AgentSessionId {
self.machine.id()
diff --git a/crates/agent_session/src/domain/session/mod.rs b/crates/agent_session/src/domain/session/mod.rs
index 4418597fee..cfdb035343 100644
--- a/crates/agent_session/src/domain/session/mod.rs
+++ b/crates/agent_session/src/domain/session/mod.rs
@@ -13,6 +13,6 @@ mod tests;
pub use session::SessionMachine;
pub use types::{
- CloseReason, Effect, HandshakeStatus, InitializationContext, Input, RuntimeStatus,
- SessionRestoreSupport, StopReason,
+ CloseReason, Effect, HandshakeStatus, InitializationContext, Input, PermissionPolicy,
+ RuntimeStatus, SessionRestoreSupport, StopReason,
};
diff --git a/crates/agent_session/src/domain/session/session.rs b/crates/agent_session/src/domain/session/session.rs
index c8391dd5f1..7049e84440 100644
--- a/crates/agent_session/src/domain/session/session.rs
+++ b/crates/agent_session/src/domain/session/session.rs
@@ -1,17 +1,21 @@
//! The machine itself: one input in, ordered effects out.
-use std::collections::VecDeque;
+use std::collections::{HashMap, VecDeque};
use agent_client_protocol::schema::v1::{
ClientCapabilities, CreateElicitationRequest, CreateElicitationResponse, ElicitationAction,
ElicitationCapabilities, ElicitationFormCapabilities, ElicitationMode, ElicitationScope,
ElicitationUrlCapabilities, InitializeRequest, InitializeResponse, LoadSessionRequest,
- LoadSessionResponse, McpServer, NewSessionRequest, NewSessionResponse, PermissionOptionKind,
- RequestId, RequestPermissionOutcome, RequestPermissionRequest, RequestPermissionResponse,
- Response, ResumeSessionRequest, ResumeSessionResponse, SelectedPermissionOutcome, SessionId,
+ LoadSessionResponse, McpServer, NewSessionRequest, NewSessionResponse, PermissionOptionId,
+ PermissionOptionKind, RequestId, RequestPermissionOutcome, RequestPermissionRequest, Response,
+ ResumeSessionRequest, ResumeSessionResponse, SelectedPermissionOutcome, SessionConfigKind,
+ SessionId, SetSessionConfigOptionResponse,
};
use agent_client_protocol::{JsonRpcMessage, RawJsonRpcMessage};
-use agent_runtime_protocol::domain::action::{AgentAction, AgentActionId};
+use agent_runtime_protocol::domain::action::{
+ AgentAction, AgentActionId, AgentPermissionAction, MODEL_CONFIG_ID, PermissionAnswer,
+ permission_response,
+};
use agent_runtime_protocol::domain::schema::v0::{
AcpMessage, SystemEvent, ToRuntimeMessage, ToServerMessage,
};
@@ -22,8 +26,9 @@ use crate::domain::error::AgentSessionError;
use crate::domain::model::AgentSessionId;
use super::types::{
- CloseReason, Effect, Input, PendingAction, PendingElicitation, RuntimeStatus, SessionOpening,
- SessionPhase, SessionRestoreSupport, StopReason,
+ CloseReason, Effect, Input, OutstandingPermission, PendingAction, PendingElicitation,
+ PermissionPolicy, RuntimeStatus, SessionOpening, SessionPhase, SessionRestoreSupport,
+ StopReason,
};
const INITIAL_REQUEST_NUM: u64 = 0;
@@ -57,11 +62,23 @@ pub struct SessionMachine<Token> {
/// `session/resume`, and `session/load` alike, because the agent process
/// behind a reconnect is fresh and holds no server from before.
mcp_servers: Vec<McpServer>,
+ permission_policy: PermissionPolicy,
+ /// Only for a newly created ACP session; restored sessions retain their model.
+ initial_model: Option<String>,
+ /// Permission requests the agent is waiting on, keyed by the agent's own
+ /// request id - the id an answer has to echo. Only ever populated under
+ /// [`PermissionPolicy::Prompt`]; auto-accept answers on arrival.
+ outstanding_permissions: HashMap<RequestId, OutstandingPermission>,
}
impl<Token> SessionMachine<Token> {
/// A fresh connection for `id`: booting, nothing queued.
- pub fn new(id: AgentSessionId, workspace: String, mcp_servers: Vec<McpServer>) -> Self {
+ pub fn new(
+ id: AgentSessionId,
+ workspace: String,
+ mcp_servers: Vec<McpServer>,
+ permission_policy: PermissionPolicy,
+ ) -> Self {
Self {
id,
initialization: None,
@@ -74,6 +91,9 @@ impl<Token> SessionMachine<Token> {
reload_required: false,
workspace,
mcp_servers,
+ permission_policy,
+ initial_model: None,
+ outstanding_permissions: HashMap::new(),
}
}
@@ -83,6 +103,7 @@ impl<Token> SessionMachine<Token> {
session_id: SessionId,
workspace: String,
mcp_servers: Vec<McpServer>,
+ permission_policy: PermissionPolicy,
) -> Self {
Self {
id,
@@ -96,9 +117,19 @@ impl<Token> SessionMachine<Token> {
reload_required: false,
workspace,
mcp_servers,
+ permission_policy,
+ initial_model: None,
+ outstanding_permissions: HashMap::new(),
}
}
+ /// Select this model before releasing prompts on a newly created ACP session.
+ #[must_use]
+ pub fn with_initial_model(mut self, model: Option<String>) -> Self {
+ self.initial_model = model;
+ self
+ }
+
/// The session this connection belongs to.
pub fn id(&self) -> AgentSessionId {
self.id
@@ -121,9 +152,9 @@ impl<Token> SessionMachine<Token> {
pub fn status(&self) -> RuntimeStatus {
match &self.phase {
SessionPhase::Booting => RuntimeStatus::Booting,
- SessionPhase::Initializing { .. } | SessionPhase::Opening { .. } => {
- RuntimeStatus::Handshaking
- }
+ SessionPhase::Initializing { .. }
+ | SessionPhase::Opening { .. }
+ | SessionPhase::ConfiguringModel { .. } => RuntimeStatus::Handshaking,
SessionPhase::Live { session_id, .. } => RuntimeStatus::Live {
session_id: session_id.clone(),
},
@@ -193,6 +224,13 @@ impl<Token> SessionMachine<Token> {
) -> Vec<Effect<Token>> {
let mut effects = Vec::new();
+ // An answer is not a request of ours to queue and mint an id for: it
+ // resolves one the agent made, and it is only ever valid while that
+ // request is open, which cannot be before the session is live.
+ if let AgentAction::RespondToPermission(answer) = &action {
+ self.on_permission_answer(from, answer, token, &mut effects);
+ return effects;
+ }
// A stop cancels the question the agent is waiting on, and does so
// before the cancel notification goes out, so the agent hears the
// answer to its request before it hears that the turn is over.
@@ -203,7 +241,8 @@ impl<Token> SessionMachine<Token> {
let session_id = match &self.phase {
SessionPhase::Booting
| SessionPhase::Initializing { .. }
- | SessionPhase::Opening { .. } => {
+ | SessionPhase::Opening { .. }
+ | SessionPhase::ConfiguringModel { .. } => {
// An answer cannot be queued: it names a request id that only
// a live connection could have received, and any connection
// that opens from here is a fresh one.
@@ -325,6 +364,9 @@ impl<Token> SessionMachine<Token> {
if !matches!(self.phase, SessionPhase::Booting) {
return;
}
+ // Request ids restart with the connection, so nothing recorded before
+ // it could be answered now. Empty in practice; cleared on principle.
+ self.outstanding_permissions.clear();
match self.build_initialize_request() {
Ok((initialize, request_id)) => {
@@ -351,12 +393,13 @@ impl<Token> SessionMachine<Token> {
&& frame.response_id() == Some(request_id)
{
self.in_flight_turn = None;
+ self.cancel_outstanding_permissions(effects);
if self.reload_required {
self.begin_reload(effects);
}
return;
}
- self.respond_to_permission_request(&frame, effects);
+ self.on_permission_request(&frame, effects);
self.hold_or_refuse_elicitation(&frame, effects);
return;
}
@@ -370,6 +413,11 @@ impl<Token> SessionMachine<Token> {
SessionPhase::Opening { request_id, .. } if frame.response_id() == Some(request_id) => {
self.on_session_opened(&frame, effects);
}
+ SessionPhase::ConfiguringModel { request_id, .. }
+ if frame.response_id() == Some(request_id) =>
+ {
+ self.on_model_selected(&frame, effects);
+ }
_ => {}
}
}
@@ -492,15 +540,72 @@ impl<Token> SessionMachine<Token> {
}
};
- self.phase = SessionPhase::Live {
- session_id: session_id.clone(),
- elicitation: None,
- };
if persist {
+ if let Some(model) = self.initial_model.take() {
+ let request_id = self.next_id();
+ match AgentAction::set_model(&model).to_runtime(&session_id, request_id.clone()) {
+ Ok(message) => {
+ self.phase = SessionPhase::ConfiguringModel {
+ request_id,
+ session_id,
+ model,
+ };
+ effects.push(Effect::Send {
+ from: None,
+ message,
+ });
+ }
+ Err(error) => self.die(
+ StopReason::HandshakeNotBuildable(error.to_string()),
+ effects,
+ ),
+ }
+ return;
+ }
effects.push(Effect::PersistAcpSession {
session_id: session_id.clone(),
});
}
+ self.finish_opening(session_id, effects);
+ }
+
+ fn on_model_selected(&mut self, frame: &RawJsonRpcMessage, effects: &mut Vec<Effect<Token>>) {
+ let SessionPhase::ConfiguringModel {
+ session_id, model, ..
+ } = &self.phase
+ else {
+ return;
+ };
+ let selected = match frame {
+ RawJsonRpcMessage::Response(Response::Result { result, .. }) => {
+ serde_json::from_value::<SetSessionConfigOptionResponse>(result.clone())
+ .ok()
+ .is_some_and(|response| {
+ response.config_options.iter().any(|option| {
+ option.id.to_string() == MODEL_CONFIG_ID
+ && matches!(&option.kind, SessionConfigKind::Select(select)
+ if select.current_value.to_string() == *model)
+ })
+ })
+ }
+ _ => false,
+ };
+ if !selected {
+ self.die(StopReason::ModelNotSelected(model.clone()), effects);
+ return;
+ }
+ let session_id = session_id.clone();
+ effects.push(Effect::PersistAcpSession {
+ session_id: session_id.clone(),
+ });
+ self.finish_opening(session_id, effects);
+ }
+
+ fn finish_opening(&mut self, session_id: SessionId, effects: &mut Vec<Effect<Token>>) {
+ self.phase = SessionPhase::Live {
+ session_id: session_id.clone(),
+ elicitation: None,
+ };
if self.reload_required {
self.begin_reload(effects);
return;
@@ -584,11 +689,11 @@ impl<Token> SessionMachine<Token> {
)
}
- /// Permission prompts require a client response. This autonomous agent has
- /// no approval UI, so approve the broadest offered allow option instead of
- /// leaving the turn blocked forever.
- fn respond_to_permission_request(
- &self,
+ /// A `session/request_permission` from the agent. The agent blocks until
+ /// it is answered, so every path out of here either answers now or records
+ /// the request so a user's answer can find it.
+ fn on_permission_request(
+ &mut self,
frame: &RawJsonRpcMessage,
effects: &mut Vec<Effect<Token>>,
) {
@@ -599,39 +704,101 @@ impl<Token> SessionMachine<Token> {
return;
}
- let outcome = request
- .params
- .clone()
- .and_then(|params| {
- serde_json::from_value::<RequestPermissionRequest>(params.into_value()).ok()
- })
- .and_then(|request| {
- request
+ let parsed = request.params.clone().and_then(|params| {
+ serde_json::from_value::<RequestPermissionRequest>(params.into_value()).ok()
+ });
+ let Some(parsed) = parsed else {
+ // Nothing to show a user and nothing to choose from, under either
+ // policy; cancelling is the only answer that does not invent one.
+ self.send_permission_response(
+ None,
+ request.id.clone(),
+ RequestPermissionOutcome::Cancelled,
+ effects,
+ );
+ return;
+ };
+
+ match self.permission_policy {
+ PermissionPolicy::AutoAccept => {
+ let outcome = parsed
.options
.iter()
.find(|option| matches!(option.kind, PermissionOptionKind::AllowAlways))
.or_else(|| {
- request
+ parsed
.options
.iter()
.find(|option| matches!(option.kind, PermissionOptionKind::AllowOnce))
})
- .map(|option| option.option_id.clone())
- })
- .map(|option_id| {
- RequestPermissionOutcome::Selected(SelectedPermissionOutcome::new(option_id))
- })
- .unwrap_or(RequestPermissionOutcome::Cancelled);
- let response = RequestPermissionResponse::new(outcome);
- let Ok(result) = serde_json::to_value(response) else {
+ .map(|option| {
+ RequestPermissionOutcome::Selected(SelectedPermissionOutcome::new(
+ option.option_id.clone(),
+ ))
+ })
+ .unwrap_or(RequestPermissionOutcome::Cancelled);
+ self.send_permission_response(None, request.id.clone(), outcome, effects);
+ }
+ // Nothing goes out: the logged request is what the fold renders
+ // as a pending prompt, and the answer arrives as a command.
+ PermissionPolicy::Prompt => {
+ let options = parsed
+ .options
+ .into_iter()
+ .map(|option| option.option_id)
+ .collect();
+ self.outstanding_permissions
+ .insert(request.id.clone(), OutstandingPermission { options });
+ }
+ }
+ }
+
+ /// A user's answer to a request held open under
+ /// [`PermissionPolicy::Prompt`].
+ fn on_permission_answer(
+ &mut self,
+ from: Option<MacroUserIdStr<'static>>,
+ answer: &AgentPermissionAction,
+ token: Token,
+ effects: &mut Vec<Effect<Token>>,
+ ) {
+ if matches!(self.phase, SessionPhase::Dead) {
+ effects.push(Effect::Complete {
+ token,
+ result: Err(AgentSessionError::Disconnected(self.id)),
+ });
+ return;
+ }
+ let Some(outstanding) = self.outstanding_permissions.get(&answer.request_id) else {
+ effects.push(Effect::Complete {
+ token,
+ result: Err(AgentSessionError::PermissionRequestNotFound(self.id)),
+ });
return;
};
- effects.push(Effect::Send {
- from: None,
- message: ToRuntimeMessage::Acp(AcpMessage(RawJsonRpcMessage::response(
- request.id.clone(),
- Ok(result),
- ))),
+ if let PermissionAnswer::Selected { option_id } = &answer.answer
+ && !outstanding
+ .options
+ .iter()
+ .any(|offered| offered == &PermissionOptionId::new(option_id.clone()))
+ {
+ effects.push(Effect::Complete {
+ token,
+ result: Err(AgentSessionError::PermissionOptionUnknown(self.id)),
+ });
+ return;
+ }
+
+ self.outstanding_permissions.remove(&answer.request_id);
+ self.send_permission_response(
+ from,
+ answer.request_id.clone(),
+ answer.answer.to_acp(),
+ effects,
+ );
+ effects.push(Effect::Complete {
+ token,
+ result: Ok(()),
});
}
@@ -743,6 +910,35 @@ impl<Token> SessionMachine<Token> {
});
}
+ /// Resolve every request the agent is still waiting on with `Cancelled`.
+ /// ACP requires each request to be answered, and once the turn is over -
+ /// cancelled, ended, or the connection gone - there is no answer to give.
+ fn cancel_outstanding_permissions(&mut self, effects: &mut Vec<Effect<Token>>) {
+ let ids: Vec<RequestId> = self
+ .outstanding_permissions
+ .drain()
+ .map(|(id, _)| id)
+ .collect();
+ for id in ids {
+ self.send_permission_response(None, id, RequestPermissionOutcome::Cancelled, effects);
+ }
+ }
+
+ fn send_permission_response(
+ &self,
+ from: Option<MacroUserIdStr<'static>>,
+ request_id: RequestId,
+ outcome: RequestPermissionOutcome,
+ effects: &mut Vec<Effect<Token>>,
+ ) {
+ match permission_response(request_id, outcome) {
+ Ok(message) => effects.push(Effect::Send { from, message }),
+ Err(error) => {
+ tracing::error!(error = ?error, id = %self.id, "could not build a permission response")
+ }
+ }
+ }
+
/// Send everything queued, oldest first. Each action's [`Effect::Complete`]
/// directly follows its [`Effect::Send`], so the shell aborting a batch
/// mid-way strands no false completions - and an action that cannot be
@@ -772,6 +968,11 @@ impl<Token> SessionMachine<Token> {
from: queued.from,
message,
});
+ // ACP: after `session/cancel`, the client answers every
+ // permission request still open with `Cancelled`.
+ if matches!(queued.action, AgentAction::Stop) {
+ self.cancel_outstanding_permissions(effects);
+ }
effects.push(Effect::Complete {
token: queued.token,
result: Ok(()),
@@ -794,6 +995,14 @@ impl<Token> SessionMachine<Token> {
fn die(&mut self, reason: StopReason, effects: &mut Vec<Effect<Token>>) {
self.phase = SessionPhase::Dead;
self.in_flight_turn = None;
+ // Open permission requests are answered `Cancelled` while the agent
+ // can still hear it. When the transport itself is what died, the
+ // sends could only fail; the agent is gone either way.
+ if reason.transport_is_up() {
+ self.cancel_outstanding_permissions(effects);
+ } else {
+ self.outstanding_permissions.clear();
+ }
while let Some(queued) = self.pending.pop_front() {
effects.push(Effect::Complete {
token: queued.token,
diff --git a/crates/agent_session/src/domain/session/tests.rs b/crates/agent_session/src/domain/session/tests.rs
index edb81e648f..4fe558eaa9 100644
--- a/crates/agent_session/src/domain/session/tests.rs
+++ b/crates/agent_session/src/domain/session/tests.rs
@@ -8,7 +8,9 @@ use agent_client_protocol::schema::v1::{
SessionCapabilities, SessionResumeCapabilities, ToolCallUpdate, ToolCallUpdateFields,
};
use agent_client_protocol::{JsonRpcMessage, RawJsonRpcMessage};
-use agent_runtime_protocol::domain::action::{AgentAction, AgentActionId};
+use agent_runtime_protocol::domain::action::{
+ AgentAction, AgentActionId, AgentPermissionAction, PermissionAnswer,
+};
use agent_runtime_protocol::domain::schema::v0::{
AcpMessage, SystemEvent, ToRuntimeMessage, ToServerMessage,
};
@@ -19,11 +21,29 @@ use crate::domain::error::AgentSessionError;
use crate::domain::model::AgentSessionId;
use super::{
- CloseReason, Effect, Input, RuntimeStatus, SessionMachine, SessionRestoreSupport, StopReason,
+ CloseReason, Effect, Input, PermissionPolicy, RuntimeStatus, SessionMachine,
+ SessionRestoreSupport, StopReason,
};
fn machine() -> SessionMachine<u32> {
- SessionMachine::new(AgentSessionId::TEST_A, "/workspace".to_owned(), Vec::new())
+ machine_under(PermissionPolicy::AutoAccept)
+}
+
+fn machine_under(policy: PermissionPolicy) -> SessionMachine<u32> {
+ SessionMachine::new(
+ AgentSessionId::TEST_A,
+ "/workspace".to_owned(),
+ Vec::new(),
+ policy,
+ )
+}
+
+/// A live machine under `policy`, past the whole handshake.
+fn live_machine_under(policy: PermissionPolicy) -> SessionMachine<u32> {
+ let mut machine = machine_under(policy);
+ begin_opening(&mut machine);
+ machine.handle(session_opened("acp-42"));
+ machine
}
fn command(text: &str, token: u32) -> Input<u32> {
@@ -336,6 +356,79 @@ fn session_new_success_flushes_the_queue() {
);
}
+#[test]
+fn initial_model_selection_holds_prompts_until_the_runtime_confirms_it() {
+ let mut machine = machine().with_initial_model(Some("gpt-5.6-luna".into()));
+ machine.handle(command("hello", 1));
+ begin_opening(&mut machine);
+ let effects = machine.handle(session_opened("acp-42"));
+ assert_eq!(sent_methods(&effects), ["session/set_config_option"]);
+ let Effect::Send { message, .. } = &effects[1] else {
+ panic!("expected the initial model change");
+ };
+ let request = serde_json::to_value(message).unwrap();
+ assert_eq!(request["params"]["configId"], "model");
+ assert_eq!(request["params"]["value"], "gpt-5.6-luna");
+ assert_eq!(machine.status(), RuntimeStatus::Handshaking);
+ assert_eq!(machine.pending_count(), 1);
+
+ // An unrelated reply cannot release the prompt.
+ let response = serde_json::json!({"configOptions": [{
+ "id": "model", "name": "Model", "type": "select",
+ "currentValue": "gpt-5.6-luna", "options": []
+ }]});
+ assert!(
+ sent_methods(&machine.handle(frame(RawJsonRpcMessage::response(
+ request_id(99),
+ Ok(response.clone()),
+ ))))
+ .is_empty()
+ );
+ let effects = machine.handle(frame(RawJsonRpcMessage::response(
+ request_id(2),
+ Ok(response),
+ )));
+ assert_eq!(sent_methods(&effects), ["session/prompt"]);
+ assert!(matches!(machine.status(), RuntimeStatus::Live { .. }));
+ assert!(
+ effects
+ .iter()
+ .any(|effect| matches!(effect, Effect::PersistAcpSession { .. }))
+ );
+}
+
+#[test]
+fn an_unconfirmed_initial_model_never_prompts_the_runtime_default() {
+ for response in [
+ Err(agent_client_protocol::Error::invalid_params()),
+ Ok(serde_json::json!({})),
+ Ok(serde_json::json!({"configOptions": [{
+ "id": "model", "name": "Model", "type": "select",
+ "currentValue": "gpt-6-astra", "options": []
+ }]})),
+ ] {
+ let mut machine = machine().with_initial_model(Some("gpt-5.6-luna".into()));
+ machine.handle(command("hello", 1));
+ begin_opening(&mut machine);
+ machine.handle(session_opened("acp-42"));
+ let effects = machine.handle(frame(RawJsonRpcMessage::response(request_id(2), response)));
+ assert_eq!(machine.status(), RuntimeStatus::Dead);
+ assert!(sent_methods(&effects).is_empty());
+ assert!(
+ !effects
+ .iter()
+ .any(|effect| matches!(effect, Effect::PersistAcpSession { .. }))
+ );
+ assert!(effects.iter().any(|effect| matches!(
+ effect,
+ Effect::Complete {
+ token: 1,
+ result: Err(_)
+ }
+ )));
+ }
+}
+
#[test]
fn reconnect_uses_session_resume_when_the_agent_supports_it() {
let mut machine = SessionMachine::resume(
@@ -343,7 +436,9 @@ fn reconnect_uses_session_resume_when_the_agent_supports_it() {
"acp-42".into(),
"/workspace".to_owned(),
Vec::new(),
- );
+ PermissionPolicy::AutoAccept,
+ )
+ .with_initial_model(Some("a-different-default".into()));
machine.handle(command("continue", 1));
machine.handle(acp_ready());
let initialized = InitializeResponse::new(PROTOCOL_VERSION).agent_capabilities(
@@ -380,6 +475,7 @@ fn reconnect_falls_back_to_session_load() {
"acp-42".into(),
"/workspace".to_owned(),
Vec::new(),
+ PermissionPolicy::AutoAccept,
);
machine.handle(acp_ready());
let initialized = InitializeResponse::new(PROTOCOL_VERSION)
@@ -397,6 +493,7 @@ fn reconnect_stops_when_the_agent_cannot_restore_sessions() {
"acp-42".into(),
"/workspace".to_owned(),
Vec::new(),
+ PermissionPolicy::AutoAccept,
);
machine.handle(command("cannot continue", 1));
machine.handle(acp_ready());
@@ -532,44 +629,276 @@ fn a_live_frame_only_logs() {
}
#[test]
-fn a_permission_request_prefers_allow_always_so_the_agent_does_not_block() {
- let outcome = permission_response(vec![
- PermissionOption::new("once", "Allow once", PermissionOptionKind::AllowOnce),
- PermissionOption::new("always", "Always allow", PermissionOptionKind::AllowAlways),
- PermissionOption::new("reject", "Reject", PermissionOptionKind::RejectOnce),
- ]);
+fn auto_accept_prefers_allow_always_so_the_agent_does_not_block() {
+ let mut machine = live_machine_under(PermissionPolicy::AutoAccept);
+ let effects = machine.handle(permission_request(
+ permission_id(0),
+ vec![
+ PermissionOption::new("once", "Allow once", PermissionOptionKind::AllowOnce),
+ PermissionOption::new("always", "Always allow", PermissionOptionKind::AllowAlways),
+ PermissionOption::new("reject", "Reject", PermissionOptionKind::RejectOnce),
+ ],
+ ));
+ assert!(matches!(effects.first(), Some(Effect::Log { .. })));
assert_eq!(
- outcome,
+ permission_outcome(&effects[1], &permission_id(0)),
RequestPermissionOutcome::Selected(SelectedPermissionOutcome::new("always"))
);
}
#[test]
-fn a_permission_request_falls_back_to_allow_once() {
- let outcome = permission_response(vec![
- PermissionOption::new("once", "Allow once", PermissionOptionKind::AllowOnce),
- PermissionOption::new("reject", "Reject", PermissionOptionKind::RejectOnce),
- ]);
+fn auto_accept_falls_back_to_allow_once() {
+ let mut machine = live_machine_under(PermissionPolicy::AutoAccept);
+ let effects = machine.handle(permission_request(
+ permission_id(0),
+ vec![
+ PermissionOption::new("once", "Allow once", PermissionOptionKind::AllowOnce),
+ PermissionOption::new("reject", "Reject", PermissionOptionKind::RejectOnce),
+ ],
+ ));
assert_eq!(
- outcome,
+ permission_outcome(&effects[1], &permission_id(0)),
RequestPermissionOutcome::Selected(SelectedPermissionOutcome::new("once"))
);
}
#[test]
-fn a_permission_request_without_an_allow_option_is_cancelled() {
- let outcome = permission_response(Vec::new());
+fn auto_accept_cancels_a_request_without_an_allow_option() {
+ let mut machine = live_machine_under(PermissionPolicy::AutoAccept);
+ let effects = machine.handle(permission_request(permission_id(0), Vec::new()));
- assert_eq!(outcome, RequestPermissionOutcome::Cancelled);
+ assert_eq!(
+ permission_outcome(&effects[1], &permission_id(0)),
+ RequestPermissionOutcome::Cancelled
+ );
}
-fn permission_response(options: Vec<PermissionOption>) -> RequestPermissionOutcome {
- let mut machine = machine();
- begin_opening(&mut machine);
- machine.handle(session_opened("acp-42"));
- let permission_id = RequestId::Str("agent:permission:0".to_owned());
+#[test]
+fn prompting_holds_the_request_open_and_only_logs_it() {
+ let mut machine = live_machine_under(PermissionPolicy::Prompt);
+ let effects = machine.handle(permission_request(permission_id(0), allow_or_reject()));
+
+ assert!(matches!(effects[..], [Effect::Log { .. }]));
+}
+
+#[test]
+fn a_users_answer_is_sent_as_the_agents_response_and_attributed_to_them() {
+ let mut machine = live_machine_under(PermissionPolicy::Prompt);
+ machine.handle(permission_request(permission_id(0), allow_or_reject()));
+
+ let effects = machine.handle(permission_answer(permission_id(0), "allow", 7));
+
+ let [
+ Effect::Send { from, .. },
+ Effect::Complete {
+ token: 7,
+ result: Ok(()),
+ },
+ ] = &effects[..]
+ else {
+ panic!("expected the response then the caller's completion, got {effects:?}");
+ };
+ assert_eq!(
+ from.as_ref().map(ToString::to_string).as_deref(),
+ Some("macro|[email protected]")
+ );
+ assert_eq!(
+ permission_outcome(&effects[0], &permission_id(0)),
+ RequestPermissionOutcome::Selected(SelectedPermissionOutcome::new("allow"))
+ );
+ // Answered: a second answer has nothing to resolve.
+ let effects = machine.handle(permission_answer(permission_id(0), "allow", 8));
+ assert!(matches!(
+ effects[..],
+ [Effect::Complete {
+ token: 8,
+ result: Err(AgentSessionError::PermissionRequestNotFound(_))
+ }]
+ ));
+}
+
+#[test]
+fn numeric_request_ids_are_answered_by_the_same_number() {
+ let mut machine = live_machine_under(PermissionPolicy::Prompt);
+ machine.handle(permission_request(RequestId::Number(7), allow_or_reject()));
+
+ let effects = machine.handle(permission_answer(RequestId::Number(7), "reject", 1));
+
+ assert_eq!(
+ permission_outcome(&effects[0], &RequestId::Number(7)),
+ RequestPermissionOutcome::Selected(SelectedPermissionOutcome::new("reject"))
+ );
+}
+
+#[test]
+fn an_answer_naming_an_unoffered_option_is_refused_and_the_request_stays_open() {
+ let mut machine = live_machine_under(PermissionPolicy::Prompt);
+ machine.handle(permission_request(permission_id(0), allow_or_reject()));
+
+ let effects = machine.handle(permission_answer(permission_id(0), "sudo", 1));
+ assert!(matches!(
+ effects[..],
+ [Effect::Complete {
+ token: 1,
+ result: Err(AgentSessionError::PermissionOptionUnknown(_))
+ }]
+ ));
+
+ let effects = machine.handle(permission_answer(permission_id(0), "allow", 2));
+ assert!(matches!(
+ effects[..],
+ [
+ Effect::Send { .. },
+ Effect::Complete {
+ token: 2,
+ result: Ok(())
+ }
+ ]
+ ));
+}
+
+#[test]
+fn a_cancelled_answer_needs_no_option() {
+ let mut machine = live_machine_under(PermissionPolicy::Prompt);
+ machine.handle(permission_request(permission_id(0), allow_or_reject()));
+
+ let effects = machine.handle(Input::Command {
+ from: None,
+ action: AgentAction::RespondToPermission(AgentPermissionAction {
+ request_id: permission_id(0),
+ answer: PermissionAnswer::Cancelled,
+ }),
+ action_id: AgentActionId::mint(),
+ token: 1,
+ });
+
+ assert_eq!(
+ permission_outcome(&effects[0], &permission_id(0)),
+ RequestPermissionOutcome::Cancelled
+ );
+}
+
+#[test]
+fn an_answer_before_the_session_is_live_is_never_queued() {
+ let mut machine = machine_under(PermissionPolicy::Prompt);
+
+ let effects = machine.handle(permission_answer(permission_id(0), "allow", 1));
+
+ assert!(matches!(
+ effects[..],
+ [Effect::Complete {
+ token: 1,
+ result: Err(AgentSessionError::PermissionRequestNotFound(_))
+ }]
+ ));
+ assert_eq!(machine.pending_count(), 0);
+}
+
+#[test]
+fn an_answer_to_a_dead_session_is_a_disconnect() {
+ let mut machine = live_machine_under(PermissionPolicy::Prompt);
+ machine.handle(permission_request(permission_id(0), allow_or_reject()));
+ machine.handle(Input::Closed(CloseReason::TransportClosed));
+
+ let effects = machine.handle(permission_answer(permission_id(0), "allow", 1));
+
+ assert!(matches!(
+ effects[..],
+ [Effect::Complete {
+ token: 1,
+ result: Err(AgentSessionError::Disconnected(_))
+ }]
+ ));
+}
+
+#[test]
+fn stop_cancels_open_permission_requests_after_the_cancel_notification() {
+ let mut machine = live_machine_under(PermissionPolicy::Prompt);
+ machine.handle(permission_request(permission_id(0), allow_or_reject()));
+
+ let effects = machine.handle(Input::Command {
+ from: None,
+ action: AgentAction::Stop,
+ action_id: AgentActionId::mint(),
+ token: 1,
+ });
+
+ assert_eq!(sent_methods(&effects), vec!["session/cancel"]);
+ let [
+ Effect::Send { .. },
+ cancelled @ Effect::Send { .. },
+ Effect::Complete { token: 1, .. },
+ ] = &effects[..]
+ else {
+ panic!("expected cancel, then the cancelled response, then completion; got {effects:?}");
+ };
+ assert_eq!(
+ permission_outcome(cancelled, &permission_id(0)),
+ RequestPermissionOutcome::Cancelled
+ );
+}
+
+#[test]
+fn a_turn_ending_cancels_whatever_the_agent_left_open() {
+ let mut machine = live_machine_under(PermissionPolicy::Prompt);
+ let action_id = AgentActionId::mint();
+ machine.handle(command_with_id("run it", action_id, 1));
+ machine.handle(permission_request(permission_id(0), allow_or_reject()));
+
+ let effects = machine.handle(frame(RawJsonRpcMessage::response(
+ action_id.to_request_id(),
+ Ok(serde_json::json!({ "stopReason": "end_turn" })),
+ )));
+
+ let [Effect::Log { .. }, cancelled @ Effect::Send { .. }] = &effects[..] else {
+ panic!("expected log and cancelled response; got {effects:?}");
+ };
+ assert_eq!(
+ permission_outcome(cancelled, &permission_id(0)),
+ RequestPermissionOutcome::Cancelled
+ );
+}
+
+#[test]
+fn an_abandoned_session_cancels_open_requests_before_stopping() {
+ let mut machine = live_machine_under(PermissionPolicy::Prompt);
+ machine.handle(permission_request(permission_id(0), allow_or_reject()));
+
+ let effects = machine.handle(Input::Closed(CloseReason::Abandoned));
+
+ let [cancelled @ Effect::Send { .. }, Effect::Stop { .. }] = &effects[..] else {
+ panic!("expected the cancelled response then stop; got {effects:?}");
+ };
+ assert_eq!(
+ permission_outcome(cancelled, &permission_id(0)),
+ RequestPermissionOutcome::Cancelled
+ );
+}
+
+#[test]
+fn a_dead_transport_gets_no_cancellations_it_cannot_carry() {
+ let mut machine = live_machine_under(PermissionPolicy::Prompt);
+ machine.handle(permission_request(permission_id(0), allow_or_reject()));
+
+ let effects = machine.handle(Input::Closed(CloseReason::TransportClosed));
+
+ assert!(matches!(effects[..], [Effect::Stop { .. }]));
+}
+
+fn allow_or_reject() -> Vec<PermissionOption> {
+ vec![
+ PermissionOption::new("allow", "Allow once", PermissionOptionKind::AllowOnce),
+ PermissionOption::new("reject", "Reject", PermissionOptionKind::RejectOnce),
+ ]
+}
+
+fn permission_id(n: u64) -> RequestId {
+ RequestId::Str(format!("agent:permission:{n}"))
+}
+
+fn permission_request(id: RequestId, options: Vec<PermissionOption>) -> Input<u32> {
let (method, params) = RequestPermissionRequest::new(
"acp-42",
ToolCallUpdate::new("call-1", ToolCallUpdateFields::new()),
@@ -578,12 +907,25 @@ fn permission_response(options: Vec<PermissionOption>) -> RequestPermissionOutco
.to_untyped_message()
.unwrap()
.into_parts();
+ frame(RawJsonRpcMessage::request(method, params, id).unwrap())
+}
- let effects = machine.handle(frame(
- RawJsonRpcMessage::request(method, params, permission_id.clone()).unwrap(),
- ));
+fn permission_answer(request_id: RequestId, option_id: &str, token: u32) -> Input<u32> {
+ Input::Command {
+ from: Some(MacroUserIdStr::try_from_email("[email protected]").expect("a valid user id")),
+ action: AgentAction::RespondToPermission(AgentPermissionAction {
+ request_id,
+ answer: PermissionAnswer::Selected {
+ option_id: option_id.to_owned(),
+ },
+ }),
+ action_id: AgentActionId::mint(),
+ token,
+ }
+}
- assert!(matches!(effects.first(), Some(Effect::Log { .. })));
+/// The outcome carried by a sent permission response to `expected_id`.
+fn permission_outcome(effect: &Effect<u32>, expected_id: &RequestId) -> RequestPermissionOutcome {
let Effect::Send {
message:
ToRuntimeMessage::Acp(AcpMessage(RawJsonRpcMessage::Response(Response::Result {
@@ -591,11 +933,11 @@ fn permission_response(options: Vec<PermissionOption>) -> RequestPermissionOutco
result,
}))),
..
- } = &effects[1]
+ } = effect
else {
- panic!("expected a successful ACP permission response");
+ panic!("expected a successful ACP permission response, got {effect:?}");
};
- assert_eq!(id, &permission_id);
+ assert_eq!(id, expected_id);
serde_json::from_value::<RequestPermissionResponse>(result.clone())
.unwrap()
.outcome
@@ -884,6 +1226,7 @@ fn session_new_carries_the_sessions_workspace() {
AgentSessionId::TEST_A,
"/home/operator/code".to_owned(),
Vec::new(),
+ PermissionPolicy::AutoAccept,
);
machine.handle(acp_ready());
let effects = machine.handle(initialized());
@@ -899,6 +1242,7 @@ fn resume_carries_the_sessions_workspace() {
"acp-42".into(),
"/home/operator/code".to_owned(),
Vec::new(),
+ PermissionPolicy::AutoAccept,
);
machine.handle(acp_ready());
let effects = machine.handle(initialized_with(
@@ -944,6 +1288,7 @@ fn a_ready_connection_still_picks_resume_for_a_session_that_has_one() {
"acp-42".into(),
"/workspace".to_owned(),
Vec::new(),
+ PermissionPolicy::AutoAccept,
);
let opening = machine.handle(Input::Ready {
@@ -963,6 +1308,7 @@ fn a_ready_connection_that_cannot_restore_stops_the_session() {
"acp-42".into(),
"/workspace".to_owned(),
Vec::new(),
+ PermissionPolicy::AutoAccept,
);
let effects = machine.handle(Input::Ready {
@@ -1029,6 +1375,7 @@ fn only_matching_successful_load_selects_its_connection_initialization() {
"acp-42".into(),
"/workspace".into(),
vec![],
+ PermissionPolicy::Prompt,
);
machine.handle(acp_ready());
let initialization_log_id = macro_uuid::generate_uuid_v7();
@@ -1083,6 +1430,7 @@ fn failed_or_interrupted_load_never_selects_history() {
"acp-42".into(),
"/workspace".into(),
vec![],
+ PermissionPolicy::Prompt,
);
machine.handle(acp_ready());
machine.initialization_persisted(macro_uuid::generate_uuid_v7());
@@ -1099,6 +1447,7 @@ fn failed_or_interrupted_load_never_selects_history() {
"acp-42".into(),
"/workspace".into(),
vec![],
+ PermissionPolicy::Prompt,
);
machine.handle(acp_ready());
machine.initialization_persisted(macro_uuid::generate_uuid_v7());
@@ -1121,6 +1470,7 @@ fn load_without_durable_initialization_cannot_become_live() {
"acp-42".into(),
"/workspace".into(),
vec![],
+ PermissionPolicy::Prompt,
);
machine.handle(acp_ready());
machine.handle(initialized_with(
@@ -1151,6 +1501,7 @@ fn late_load_response_from_a_previous_actor_cannot_select_history() {
"acp-42".into(),
"/workspace".into(),
vec![],
+ PermissionPolicy::Prompt,
)
.with_connection_context(macro_uuid::generate_uuid_v7());
let initialization = macro_uuid::generate_uuid_v7();
diff --git a/crates/agent_session/src/domain/session/types.rs b/crates/agent_session/src/domain/session/types.rs
index f1768bfbfa..bea1135a99 100644
--- a/crates/agent_session/src/domain/session/types.rs
+++ b/crates/agent_session/src/domain/session/types.rs
@@ -1,6 +1,6 @@
//! The machine's vocabulary: phases, inputs, and effects.
-use agent_client_protocol::schema::v1::{RequestId, SessionId};
+use agent_client_protocol::schema::v1::{PermissionOptionId, RequestId, SessionId};
use agent_runtime_protocol::domain::action::{AgentAction, AgentActionId};
use agent_runtime_protocol::domain::schema::v0::{ToRuntimeMessage, ToServerMessage};
use macro_user_id::user_id::MacroUserIdStr;
@@ -17,6 +17,28 @@ pub(super) struct PendingAction<Token> {
pub(super) token: Token,
}
+/// How a connection answers the agent's `session/request_permission`.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
+pub enum PermissionPolicy {
+ /// Approve the broadest allow option the moment the request arrives.
+ /// Right for runtimes in sandboxes this deployment owns, where nothing
+ /// the agent can touch is anyone's real machine.
+ AutoAccept,
+ /// Hold the request open until a user answers it through the control
+ /// endpoint. The turn blocks meanwhile, which is the point.
+ #[default]
+ Prompt,
+}
+
+/// A permission request the agent is waiting on, under
+/// [`PermissionPolicy::Prompt`].
+#[derive(Debug)]
+pub(super) struct OutstandingPermission {
+ /// The choices the agent offered; an answer naming anything else is
+ /// refused rather than forwarded.
+ pub(super) options: Vec<PermissionOptionId>,
+}
+
pub(super) enum SessionPhase {
/// The runtime has not reported its agent ready. Nothing may go out.
Booting,
@@ -32,6 +54,12 @@ pub(super) enum SessionPhase {
/// How this connection is establishing its ACP session.
kind: SessionOpening,
},
+ /// The ACP session exists, but its configured model must be acknowledged first.
+ ConfiguringModel {
+ request_id: RequestId,
+ session_id: SessionId,
+ model: String,
+ },
Live {
session_id: SessionId,
/// The one `elicitation/create` this connection is holding for the
@@ -268,6 +296,23 @@ pub enum StopReason {
/// The agent answered `session/new` with something unintelligible; the
/// detail is the parser's.
SessionUnintelligible(String),
+ /// The runtime refused or did not confirm the configured starting model.
+ ModelNotSelected(String),
+}
+
+impl StopReason {
+ /// Whether the runtime can still be reached when the machine stops for
+ /// this reason - true for every death except the transport's own.
+ pub(super) fn transport_is_up(&self) -> bool {
+ !matches!(
+ self,
+ Self::Closed(
+ CloseReason::TransportClosed
+ | CloseReason::TransportFailed
+ | CloseReason::SendFailed
+ )
+ )
+ }
}
impl std::fmt::Display for StopReason {
@@ -297,6 +342,12 @@ impl std::fmt::Display for StopReason {
"the agent answered session/new unintelligibly: {detail}"
)
}
+ Self::ModelNotSelected(model) => {
+ write!(
+ formatter,
+ "the agent did not select the configured model {model}"
+ )
+ }
}
}
}
diff --git a/crates/agent_session/src/inbound/axum_router.rs b/crates/agent_session/src/inbound/axum_router.rs
index 9680ff731a..6427567e7a 100644
--- a/crates/agent_session/src/inbound/axum_router.rs
+++ b/crates/agent_session/src/inbound/axum_router.rs
@@ -309,6 +309,14 @@ impl IntoResponse for AgentSessionApiError {
Self::Domain(error @ AgentSessionError::TooManyPreviewIds(_)) => {
(StatusCode::BAD_REQUEST, error.to_string()).into_response()
}
+ // Somebody else answered first, or the agent moved on: nothing to
+ // answer anymore, and the transcript already shows how it went.
+ Self::Domain(error @ AgentSessionError::PermissionRequestNotFound(_)) => {
+ (StatusCode::CONFLICT, error.to_string()).into_response()
+ }
+ Self::Domain(error @ AgentSessionError::PermissionOptionUnknown(_)) => {
+ (StatusCode::UNPROCESSABLE_ENTITY, error.to_string()).into_response()
+ }
Self::Domain(error) => {
if let AgentSessionError::InvalidName(message) = error {
return (StatusCode::BAD_REQUEST, Json(message)).into_response();
@@ -847,7 +855,7 @@ pub async fn control_agent_session_handler<
Access: EntityAccessService,
Auth: MacroAuthorizationService,
>(
- _access: AgentSessionAccessLevelExtractor<EditAccessLevel, Access, Auth>,
+ access: AgentSessionAccessLevelExtractor<EditAccessLevel, Access, Auth>,
State(state): State<AgentSessionControlState<R, Access, Auth>>,
caller: MacroAuthorizationExtractor<Auth, UserBotOrHarness>,
Path(session_id): Path<Uuid>,
@@ -860,20 +868,25 @@ pub async fn control_agent_session_handler<
)
.await?;
- let actor = caller
- .authorization
- .acting_user()
- .map(|user| user.macro_user_id.clone());
+ let principal = match &caller.authorization {
+ UserBotOrHarnessAuthorization::User(_) => crate::domain::control::ControlPrincipal::User,
+ authorization => crate::domain::control::ControlPrincipal::Runtime(
+ authorization
+ .acting_user()
+ .map(|user| user.macro_user_id.clone()),
+ ),
+ };
let accepted = state
.recipient
.control_event(
AgentSessionId::new_from_uuid(session_id),
- ControlEvent {
- action: req.action,
- action_id: req.action_id,
- actor,
- },
+ ControlEvent::authorized(
+ req.action,
+ req.action_id,
+ principal,
+ access.entity_access_receipt,
+ )?,
)
.await?;
@@ -1774,6 +1787,7 @@ pub async fn create_agent_session_handler<
is_managed,
owner_user_id,
harness_id,
+ managed_profile,
..
} = state
.bots
@@ -1825,6 +1839,7 @@ pub async fn create_agent_session_handler<
.opener
.open_external_session(OpenExternalAgentSession {
bot_id,
+ profile: managed_profile,
workspace,
repo_url: request.repo_url,
owner,
diff --git a/crates/agent_session/src/inbound/axum_router/test.rs b/crates/agent_session/src/inbound/axum_router/test.rs
index 79a1e5ad2e..6e141ff7e3 100644
--- a/crates/agent_session/src/inbound/axum_router/test.rs
+++ b/crates/agent_session/src/inbound/axum_router/test.rs
@@ -424,6 +424,34 @@ async fn the_owner_opens_a_session_for_their_bot() {
assert_eq!(opened[0].owner.as_ref(), OWNER);
}
+#[tokio::test]
+async fn an_external_session_receives_the_saved_agent_profile() {
+ let opener = Arc::new(RecordingOpener::default());
+ let mut bots = OneBotDirectory::external_agent();
+ bots.facts.managed_profile = Some(crate::domain::ports::ManagedAgentProfile {
+ model: "gpt-5.6-luna".into(),
+ harness: harness_id::MACROD_HARNESS_SLUG.into(),
+ instructions: String::new(),
+ mcp_servers: crate::domain::model::AgentMcpServers::OwnerConnections,
+ });
+ let request = as_harness_for(
+ OWNER,
+ body(Some(BotId::TEST_A.as_uuid()), "/srv/agent", None),
+ );
+ let response = router_for(opener.clone(), bots)
+ .oneshot(request)
+ .await
+ .unwrap();
+ assert_eq!(response.status(), StatusCode::CREATED);
+ let opened = opener.opened.lock().unwrap();
+ let profile = opened[0]
+ .profile
+ .as_ref()
+ .expect("saved profile is forwarded");
+ assert_eq!(profile.model, "gpt-5.6-luna");
+ assert_eq!(profile.harness, harness_id::MACROD_HARNESS_SLUG);
+}
+
#[tokio::test]
async fn a_stranger_may_not_open_sessions_for_someone_elses_bot() {
let opener = Arc::new(RecordingOpener::default());
diff --git a/crates/agent_trigger/src/domain/service/test.rs b/crates/agent_trigger/src/domain/service/test.rs
index d841b7fb53..8627e112d4 100644
--- a/crates/agent_trigger/src/domain/service/test.rs
+++ b/crates/agent_trigger/src/domain/service/test.rs
@@ -63,6 +63,7 @@ fn agent_with(bot_id: BotId, owner: BotOwner, channel_scope: AgentChannelScope)
channel_scope,
channel_ids: vec![],
mcp: AgentMcpServers::OwnerConnections,
+ auto_accept_permissions: None,
}
}
diff --git a/crates/bots/Cargo.toml b/crates/bots/Cargo.toml
index 4a5a3a0f87..19a5f4c236 100644
--- a/crates/bots/Cargo.toml
+++ b/crates/bots/Cargo.toml
@@ -65,6 +65,7 @@ uuid = { workspace = true }
workspace-hack = { version = "0.1", path = "../workspace-hack" }
[dev-dependencies]
+async-trait = { workspace = true }
entity_access = { path = "../entity_access", default-features = false, features = [
"outbound",
"ports",
diff --git a/crates/bots/src/domain/models.rs b/crates/bots/src/domain/models.rs
index e32f960689..36bfb7962a 100644
--- a/crates/bots/src/domain/models.rs
+++ b/crates/bots/src/domain/models.rs
@@ -296,6 +296,9 @@ pub struct Agent {
pub channel_ids: Vec<Uuid>,
/// Which MCP servers sessions of this agent are handed.
pub mcp: AgentMcpServers,
+ /// Whether the agent's sessions approve ACP permission requests without
+ /// asking. `None` means always prompt. Bypass also requires the harness's opt-in.
+ pub auto_accept_permissions: Option<bool>,
}
/// Request to create a persisted AI agent.
@@ -330,6 +333,10 @@ pub struct CreateAgentRequest {
/// Which MCP servers sessions of this agent are handed.
#[serde(default)]
pub mcp: AgentMcpServers,
+ /// Whether the agent's sessions approve ACP permission requests without
+ /// asking. Omit to always prompt.
+ #[serde(default)]
+ pub auto_accept_permissions: Option<bool>,
}
/// Request to replace the editable configuration of a persisted AI agent.
@@ -364,6 +371,10 @@ pub struct UpdateAgentRequest {
/// Which MCP servers sessions of this agent are handed.
#[serde(default)]
pub mcp: AgentMcpServers,
+ /// Whether the agent's sessions approve ACP permission requests without
+ /// asking. Omit to always prompt.
+ #[serde(default)]
+ pub auto_accept_permissions: Option<bool>,
}
/// Channel containing a bot.
@@ -542,3 +553,11 @@ pub struct ChannelWebhookResponse {
/// Created message id.
pub message_id: String,
}
+
+/// Facts about a registered harness used to validate a persona.
+pub struct HarnessFacts {
+ /// Who may use the harness.
+ pub owner: HarnessOwner,
+ /// Whether the harness operator permits unattended tool approvals.
+ pub allow_permission_bypass: bool,
+}
diff --git a/crates/bots/src/domain/ports.rs b/crates/bots/src/domain/ports.rs
index 7d38e89be3..7a9d42282a 100644
--- a/crates/bots/src/domain/ports.rs
+++ b/crates/bots/src/domain/ports.rs
@@ -4,7 +4,7 @@ use super::models::{
Agent, AuthenticatedBot, Bot, BotChannel, BotChannelListCaller, BotId, BotOwner, BotProfile,
BotToken, BotTokenCandidate, CreateAgentRequest, CreateBotRequest, CreateBotTokenRequest,
CreateBotTokenResponse, CreateChannelScopedBotRequest, CreateChannelScopedBotResponse,
- HarnessId, HarnessOwner, PatchBotRequest, UpdateAgentRequest,
+ HarnessFacts, HarnessId, PatchBotRequest, UpdateAgentRequest,
};
use bot_token::HashedBotToken;
use entity_access::domain::models::{EntityAccessReceipt, MemberParticipantRole};
@@ -100,11 +100,11 @@ pub trait BotRepo: Send + Sync + 'static {
team_id: Uuid,
) -> impl Future<Output = Result<bool, Self::Err>> + Send;
- /// Get the owner of an active registered harness.
- fn get_harness_owner(
+ /// Get ownership and permission capabilities of an active registered harness.
+ fn get_harness_facts(
&self,
harness_id: HarnessId,
- ) -> impl Future<Output = Result<Option<HarnessOwner>, Self::Err>> + Send;
+ ) -> impl Future<Output = Result<Option<HarnessFacts>, Self::Err>> + Send;
/// Check whether a bot is an active channel participant.
fn bot_active_in_channel(
diff --git a/crates/bots/src/domain/service.rs b/crates/bots/src/domain/service.rs
index 74291ab1dc..73b91393d6 100644
--- a/crates/bots/src/domain/service.rs
+++ b/crates/bots/src/domain/service.rs
@@ -284,18 +284,23 @@ where
caller: MacroUserIdStr<'static>,
owner: &BotOwner,
harness_id: Option<HarnessId>,
+ auto_accept_permissions: Option<bool>,
) -> Result<(), BotError> {
let Some(harness_id) = harness_id else {
return Ok(());
};
let harness_owner = self
.repo
- .get_harness_owner(harness_id)
+ .get_harness_facts(harness_id)
.await
.map_err(|err| BotError::Repo(err.into()))?
.ok_or_else(|| BotError::BadRequest("unknown harness".to_string()))?;
- let usable = match (owner, harness_owner) {
+ validate_permission_bypass(
+ harness_owner.allow_permission_bypass,
+ auto_accept_permissions,
+ )?;
+ let usable = match (owner, harness_owner.owner) {
(
BotOwner::Team { team_id },
HarnessOwner::Team {
@@ -439,8 +444,13 @@ where
let owner = self
.agent_owner_for_request(caller.clone(), req.team_id)
.await?;
- self.ensure_harness_usable(caller.clone(), &owner, req.harness_id)
- .await?;
+ self.ensure_harness_usable(
+ caller.clone(),
+ &owner,
+ req.harness_id,
+ req.auto_accept_permissions,
+ )
+ .await?;
let created_by_user_id = caller.clone();
let agent = self
.repo
@@ -490,8 +500,13 @@ where
let owner = self
.owner_for_agent_update(caller.clone(), &current, req.team_id)
.await?;
- self.ensure_harness_usable(caller.clone(), &owner, req.harness_id)
- .await?;
+ self.ensure_harness_usable(
+ caller.clone(),
+ &owner,
+ req.harness_id,
+ req.auto_accept_permissions,
+ )
+ .await?;
let requested_name = req.name.clone();
let requested_handle = req.handle.clone();
let requested_description = req.description.clone();
@@ -871,3 +886,16 @@ where
Ok(self.authenticate_candidate(candidate).await?.bot)
}
}
+
+/// A persona cannot override its harness operator's permission policy.
+fn validate_permission_bypass(allowed: bool, requested: Option<bool>) -> Result<(), BotError> {
+ if requested == Some(true) && !allowed {
+ return Err(BotError::BadRequest(
+ "this harness requires permission prompts".to_owned(),
+ ));
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/bots/src/domain/service/test.rs b/crates/bots/src/domain/service/test.rs
new file mode 100644
index 0000000000..5b746e9a39
--- /dev/null
+++ b/crates/bots/src/domain/service/test.rs
@@ -0,0 +1,12 @@
+use super::*;
+
+#[test]
+fn persona_cannot_bypass_a_harness_that_requires_prompts() {
+ assert!(validate_permission_bypass(false, Some(true)).is_err());
+ for choice in [None, Some(false)] {
+ assert!(validate_permission_bypass(false, choice).is_ok());
+ }
+ for choice in [None, Some(false), Some(true)] {
+ assert!(validate_permission_bypass(true, choice).is_ok());
+ }
+}
diff --git a/crates/bots/src/outbound/pg_bots_repo.rs b/crates/bots/src/outbound/pg_bots_repo.rs
index b6ec9cdd20..40ee16412a 100644
--- a/crates/bots/src/outbound/pg_bots_repo.rs
+++ b/crates/bots/src/outbound/pg_bots_repo.rs
@@ -8,7 +8,7 @@ use crate::domain::{
Agent, AgentChannelScope, AgentMcpServer, AgentMcpServers, AuthenticatedBot, Bot,
BotChannel, BotChannelType, BotId, BotKind, BotOwner, BotProfile, BotToken,
BotTokenCandidate, CreateAgentRequest, CreateBotRequest, CreateBotTokenRequest,
- CreateChannelScopedBotRequest, HarnessId, HarnessOwner, PatchBotRequest,
+ CreateChannelScopedBotRequest, HarnessFacts, HarnessId, HarnessOwner, PatchBotRequest,
UpdateAgentRequest,
},
ports::BotRepo,
@@ -117,6 +117,7 @@ struct AgentRow {
mcp_scope: String,
mcp_app_slugs: Vec<String>,
mcp_server_names: Vec<String>,
+ auto_accept_permissions: Option<bool>,
}
impl TryFrom<AgentRow> for Agent {
@@ -166,6 +167,7 @@ impl TryFrom<AgentRow> for Agent {
channel_scope,
channel_ids: row.channel_ids,
mcp,
+ auto_accept_permissions: row.auto_accept_permissions,
})
}
}
@@ -356,9 +358,9 @@ impl BotRepo for PgBotsRepo {
sqlx::query!(
r#"
INSERT INTO agent_configs (
- bot_id, instructions, harness, harness_id, default_model, channel_scope, mcp_scope
+ bot_id, instructions, harness, harness_id, default_model, channel_scope, mcp_scope, auto_accept_permissions
)
- VALUES ($1, $2, $3, $4, $5, $6, $7)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
"#,
bot_id.as_uuid(),
&req.instructions,
@@ -367,6 +369,7 @@ impl BotRepo for PgBotsRepo {
&req.default_model,
req.channel_scope.as_str(),
req.mcp.scope_str(),
+ req.auto_accept_permissions,
)
.execute(&mut *tx)
.await
@@ -401,6 +404,7 @@ impl BotRepo for PgBotsRepo {
harness_id: req.harness_id,
default_model: req.default_model,
channel_scope: req.channel_scope,
+ auto_accept_permissions: req.auto_accept_permissions,
channel_ids: req.channel_ids,
mcp: req.mcp,
})
@@ -473,6 +477,7 @@ impl BotRepo for PgBotsRepo {
default_model = $5,
channel_scope = $6,
mcp_scope = $7,
+ auto_accept_permissions = $8,
updated_at = now()
WHERE bot_id = $1
"#,
@@ -483,6 +488,7 @@ impl BotRepo for PgBotsRepo {
&req.default_model,
req.channel_scope.as_str(),
req.mcp.scope_str(),
+ req.auto_accept_permissions,
)
.execute(&mut *tx)
.await
@@ -545,6 +551,7 @@ impl BotRepo for PgBotsRepo {
channel_scope: req.channel_scope,
channel_ids: req.channel_ids,
mcp: req.mcp,
+ auto_accept_permissions: req.auto_accept_permissions,
}))
}
@@ -574,6 +581,7 @@ impl BotRepo for PgBotsRepo {
a.harness_id,
a.default_model,
a.channel_scope,
+ a.auto_accept_permissions,
ARRAY(
SELECT p.channel_id
FROM comms_channel_participants p
@@ -950,6 +958,7 @@ impl BotRepo for PgBotsRepo {
a.harness_id,
a.default_model,
a.channel_scope,
+ a.auto_accept_permissions,
ARRAY(
SELECT p.channel_id
FROM comms_channel_participants p
@@ -985,13 +994,13 @@ impl BotRepo for PgBotsRepo {
row.map(Agent::try_from).transpose()
}
- async fn get_harness_owner(
+ async fn get_harness_facts(
&self,
harness_id: HarnessId,
- ) -> Result<Option<HarnessOwner>, Self::Err> {
+ ) -> Result<Option<HarnessFacts>, Self::Err> {
let row = sqlx::query!(
r#"
- SELECT owner_user_id, team_id
+ SELECT owner_user_id, team_id, allow_permission_bypass
FROM harnesses
WHERE id = $1 AND deleted_at IS NULL
"#,
@@ -1002,8 +1011,14 @@ impl BotRepo for PgBotsRepo {
.context("failed to fetch harness owner")?;
row.map(|row| match (row.owner_user_id, row.team_id) {
- (Some(user_id), None) => Ok(HarnessOwner::User { user_id }),
- (None, Some(team_id)) => Ok(HarnessOwner::Team { team_id }),
+ (Some(user_id), None) => Ok(HarnessFacts {
+ owner: HarnessOwner::User { user_id },
+ allow_permission_bypass: row.allow_permission_bypass,
+ }),
+ (None, Some(team_id)) => Ok(HarnessFacts {
+ owner: HarnessOwner::Team { team_id },
+ allow_permission_bypass: row.allow_permission_bypass,
+ }),
// Unreachable: harnesses_owner_check enforces exactly one owner.
_ => Err(anyhow::anyhow!("harness {harness_id} violates owner xor")),
})
diff --git a/crates/bots/src/outbound/pg_bots_repo/tests.rs b/crates/bots/src/outbound/pg_bots_repo/tests.rs
index 0a4023ea83..608b9dd308 100644
--- a/crates/bots/src/outbound/pg_bots_repo/tests.rs
+++ b/crates/bots/src/outbound/pg_bots_repo/tests.rs
@@ -83,6 +83,7 @@ fn create_agent_req(handle: &str, channel_scope: AgentChannelScope) -> CreateAge
channel_scope,
channel_ids: Vec::new(),
mcp: AgentMcpServers::OwnerConnections,
+ auto_accept_permissions: None,
}
}
@@ -100,6 +101,7 @@ fn update_agent_req(handle: &str, channel_scope: AgentChannelScope) -> UpdateAge
channel_scope,
channel_ids: Vec::new(),
mcp: AgentMcpServers::OwnerConnections,
+ auto_accept_permissions: Some(false),
}
}
@@ -464,6 +466,7 @@ async fn created_agent_round_trips_every_agent_field(pool: PgPool) -> anyhow::Re
assert_eq!(created.default_model, "cursor-small");
assert_eq!(created.channel_scope, AgentChannelScope::All);
assert!(created.channel_ids.is_empty());
+ assert_eq!(created.auto_accept_permissions, None);
let listed = service.list_agents(user_id(USER_OWNER)).await?;
assert_eq!(listed.len(), 1);
@@ -471,6 +474,7 @@ async fn created_agent_round_trips_every_agent_field(pool: PgPool) -> anyhow::Re
assert_eq!(listed[0].instructions, created.instructions);
assert_eq!(listed[0].harness, created.harness);
assert_eq!(listed[0].default_model, created.default_model);
+ assert_eq!(listed[0].auto_accept_permissions, None);
let fetched = PgBotsRepo::new(pool.clone())
.get_agent(created.bot.id)
@@ -480,6 +484,7 @@ async fn created_agent_round_trips_every_agent_field(pool: PgPool) -> anyhow::Re
assert_eq!(fetched.instructions, created.instructions);
assert_eq!(fetched.harness, created.harness);
assert_eq!(fetched.default_model, created.default_model);
+ assert_eq!(fetched.auto_accept_permissions, None);
assert!(service.list_agents(user_id(USER_OTHER)).await?.is_empty());
Ok(())
@@ -623,6 +628,7 @@ async fn updated_agent_replaces_every_field_and_selected_channel(
assert_eq!(updated.harness, "in-memory");
assert_eq!(updated.default_model, "claude-sonnet-4-5");
assert_eq!(updated.channel_ids, vec![second]);
+ assert_eq!(updated.auto_accept_permissions, Some(false));
assert_eq!(
active_channel_participant_count(&pool, first, created.bot.id).await?,
0
@@ -636,6 +642,47 @@ async fn updated_agent_replaces_every_field_and_selected_channel(
assert_eq!(listed.len(), 1);
assert_eq!(listed[0].bot.handle, "updated-fixer");
assert_eq!(listed[0].channel_ids, vec![second]);
+ assert_eq!(listed[0].auto_accept_permissions, Some(false));
+
+ let fetched = PgBotsRepo::new(pool.clone())
+ .get_agent(created.bot.id)
+ .await?
+ .expect("updated agent should still be addressable by bot id");
+ assert_eq!(fetched.auto_accept_permissions, Some(false));
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn auto_accept_permissions_persists_each_of_its_three_states(
+ pool: PgPool,
+) -> anyhow::Result<()> {
+ let service = service(&pool);
+ let repo = PgBotsRepo::new(pool.clone());
+ let mut create = create_agent_req("permissive", AgentChannelScope::All);
+ create.auto_accept_permissions = Some(true);
+ let created = service.create_agent(user_id(USER_OWNER), create).await?;
+ assert_eq!(created.auto_accept_permissions, Some(true));
+ assert_eq!(
+ repo.get_agent(created.bot.id)
+ .await?
+ .unwrap()
+ .auto_accept_permissions,
+ Some(true)
+ );
+
+ // An update that says nothing clears the choice back to the kind default.
+ let mut update = update_agent_req("permissive", AgentChannelScope::All);
+ update.auto_accept_permissions = None;
+ service
+ .update_agent(user_id(USER_OWNER), created.bot.id, update)
+ .await?;
+ assert_eq!(
+ repo.get_agent(created.bot.id)
+ .await?
+ .unwrap()
+ .auto_accept_permissions,
+ None
+ );
Ok(())
}
@@ -1888,3 +1935,41 @@ async fn team_harnesses_back_member_agents_but_not_team_agents_on_private_harnes
Ok(())
}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn persona_create_and_update_cannot_bypass_a_prompt_only_harness(
+ pool: PgPool,
+) -> anyhow::Result<()> {
+ insert_user(&pool, USER_OWNER).await?;
+ let harness = insert_harness(&pool, Some(USER_OWNER), None).await?;
+ let service = service(&pool);
+ let mut request = macrod_agent_req("permission-policy", Some(harness));
+ request.auto_accept_permissions = Some(true);
+ assert!(matches!(
+ service
+ .create_agent(user_id(USER_OWNER), request.clone())
+ .await,
+ Err(BotError::BadRequest(_))
+ ));
+ request.auto_accept_permissions = Some(false);
+ let agent = service.create_agent(user_id(USER_OWNER), request).await?;
+ let mut update = update_agent_req("permission-policy", AgentChannelScope::All);
+ update.harness = "macrod".to_owned();
+ update.harness_id = Some(harness);
+ update.auto_accept_permissions = Some(true);
+ assert!(matches!(
+ service
+ .update_agent(user_id(USER_OWNER), agent.bot.id, update)
+ .await,
+ Err(BotError::BadRequest(_))
+ ));
+ assert_eq!(
+ PgBotsRepo::new(pool)
+ .get_agent(agent.bot.id)
+ .await?
+ .unwrap()
+ .auto_accept_permissions,
+ Some(false)
+ );
+ Ok(())
+}
diff --git a/crates/coding_agent_worker/config.example.toml b/crates/coding_agent_worker/config.example.toml
index 76f2b3a5db..971f195abd 100644
--- a/crates/coding_agent_worker/config.example.toml
+++ b/crates/coding_agent_worker/config.example.toml
@@ -21,6 +21,10 @@ name = "erics-macbook"
# Optional: "private" (default) or "team". Team harnesses can run agents any
# of your teammates create. The approval dialog arrives preselected to this.
scope = "private"
+# Allow agents to bypass tool permissions, subject to web confirmation.
+# When enabled, agents can run commands and edit files without approval.
+# Changes apply at the next pairing.
+allow_permission_bypass = false
[harness]
command = "hermes"
diff --git a/crates/coding_agent_worker/default.macrod.toml b/crates/coding_agent_worker/default.macrod.toml
index 0ac449bc72..575022c58b 100644
--- a/crates/coding_agent_worker/default.macrod.toml
+++ b/crates/coding_agent_worker/default.macrod.toml
@@ -7,6 +7,10 @@ web_url = "https://macro.com/app"
[identity]
scope = "private"
+# Allow agents to bypass tool permissions, subject to web confirmation.
+# When enabled, agents can run commands and edit files without approval.
+# Changes apply at the next pairing.
+allow_permission_bypass = false
[harness]
command = "hermes"
diff --git a/crates/coding_agent_worker/src/config.rs b/crates/coding_agent_worker/src/config.rs
index 1bf4a4444b..d9458c1daa 100644
--- a/crates/coding_agent_worker/src/config.rs
+++ b/crates/coding_agent_worker/src/config.rs
@@ -108,6 +108,9 @@ impl MacroApi {
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Identity {
+ /// Whether the next pairing may enable permission bypass. Requires web approval.
+ #[serde(default)]
+ pub allow_permission_bypass: bool,
/// Requested harness display name; the approving user may rename it.
/// Defaults to this machine's hostname.
#[serde(default)]
diff --git a/crates/coding_agent_worker/src/config/test.rs b/crates/coding_agent_worker/src/config/test.rs
index c3b04b6083..8b71b347e2 100644
--- a/crates/coding_agent_worker/src/config/test.rs
+++ b/crates/coding_agent_worker/src/config/test.rs
@@ -9,6 +9,7 @@ fn the_example_config_parses() {
assert_eq!(config.harness.args, vec!["acp"]);
assert_eq!(config.identity.name.as_deref(), Some("erics-macbook"));
assert_eq!(config.identity.scope, IdentityScope::Private);
+ assert!(!config.identity.allow_permission_bypass);
assert_eq!(config.credentials, None);
}
@@ -25,6 +26,7 @@ fn embedded_credentials_parse_with_their_approved_scope() {
assert_eq!(credentials.scope, HarnessScope::Team);
assert!(credentials.is_valid());
assert_eq!(config.identity.scope, IdentityScope::Private);
+ assert!(!config.identity.allow_permission_bypass);
}
#[test]
@@ -68,6 +70,7 @@ fn identity_args_and_web_url_default() {
let trimmed = EXAMPLE
.replace("args = [\"acp\"]\n", "")
.replace("[identity]\n", "")
+ .replace("allow_permission_bypass = false\n", "")
.replace("name = \"erics-macbook\"\n", "")
.replace("scope = \"private\"\n", "")
.replace("web_url = \"http://localhost:3000/app\"\n", "");
@@ -75,6 +78,7 @@ fn identity_args_and_web_url_default() {
assert!(config.harness.args.is_empty());
assert_eq!(config.identity.name, None);
assert_eq!(config.identity.scope, IdentityScope::Private);
+ assert!(!config.identity.allow_permission_bypass);
assert_eq!(config.macro_api.web_url, "https://macro.com/app");
}
diff --git a/crates/coding_agent_worker/src/outbound/pairing.rs b/crates/coding_agent_worker/src/outbound/pairing.rs
index bb47461024..27042ebea2 100644
--- a/crates/coding_agent_worker/src/outbound/pairing.rs
+++ b/crates/coding_agent_worker/src/outbound/pairing.rs
@@ -61,6 +61,7 @@ impl PairingClient {
.http
.post(format!("{}/harness-pairings", self.base))
.json(&CreatePairingRequest {
+ allow_permission_bypass: Some(config.identity.allow_permission_bypass),
name,
host: Some(host_info()),
scope: Some(scope),
diff --git a/crates/coding_agent_worker/src/tui/app.rs b/crates/coding_agent_worker/src/tui/app.rs
index 2a06ed8941..4daf622c55 100644
--- a/crates/coding_agent_worker/src/tui/app.rs
+++ b/crates/coding_agent_worker/src/tui/app.rs
@@ -423,7 +423,9 @@ impl App {
let apply = match setting {
Setting::Workspace => ApplyConfig::Now,
Setting::Name => ApplyConfig::NextPairing,
- Setting::Agent | Setting::Scope => unreachable!("not edited as text"),
+ Setting::Agent | Setting::Scope | Setting::PermissionBypass => {
+ unreachable!("not edited as text")
+ }
};
self.save_config(apply).await;
}
@@ -551,6 +553,11 @@ impl App {
self.form.toggle_scope(&self.config);
self.save_config(ApplyConfig::NextPairing).await;
}
+ Setting::PermissionBypass => {
+ self.form
+ .set_permission_bypass(!self.config.identity.allow_permission_bypass);
+ self.save_config(ApplyConfig::NextPairing).await;
+ }
setting @ (Setting::Workspace | Setting::Name) => {
self.mode = Mode::EditSetting {
index: self.selected_setting,
diff --git a/crates/coding_agent_worker/src/tui/config_form.rs b/crates/coding_agent_worker/src/tui/config_form.rs
index 11054dbd79..157b6fcba3 100644
--- a/crates/coding_agent_worker/src/tui/config_form.rs
+++ b/crates/coding_agent_worker/src/tui/config_form.rs
@@ -39,6 +39,8 @@ pub enum Setting {
Name,
/// Private or team ownership requested during pairing.
Scope,
+ /// Whether the next pairing may enable permission bypass.
+ PermissionBypass,
}
impl Setting {
@@ -49,6 +51,7 @@ impl Setting {
Self::Workspace => "Workspace",
Self::Name => "Name",
Self::Scope => "Access",
+ Self::PermissionBypass => "Full Access",
}
}
}
@@ -59,6 +62,7 @@ pub const SETTINGS: &[Setting] = &[
Setting::Workspace,
Setting::Name,
Setting::Scope,
+ Setting::PermissionBypass,
];
/// The config document being viewed and edited.
@@ -129,6 +133,13 @@ impl ConfigForm {
.name
.clone()
.unwrap_or_else(|| "Hostname default".to_owned()),
+ Setting::PermissionBypass => {
+ if config.identity.allow_permission_bypass {
+ "Allowed at next pairing".to_owned()
+ } else {
+ "Always prompt at next pairing".to_owned()
+ }
+ }
Setting::Scope => match config.identity.scope {
crate::config::IdentityScope::Private => "Private".to_owned(),
crate::config::IdentityScope::Team => "Team".to_owned(),
@@ -141,7 +152,7 @@ impl ConfigForm {
match setting {
Setting::Workspace => self.string("workspace", "path").unwrap_or_default(),
Setting::Name => self.string("identity", "name").unwrap_or_default(),
- Setting::Agent | Setting::Scope => String::new(),
+ Setting::Agent | Setting::Scope | Setting::PermissionBypass => String::new(),
}
}
@@ -168,7 +179,7 @@ impl ConfigForm {
self.set_string("identity", "name", input);
}
}
- Setting::Agent | Setting::Scope => {
+ Setting::Agent | Setting::Scope | Setting::PermissionBypass => {
return Err(format!("{} is selected rather than typed", setting.label()));
}
}
@@ -216,6 +227,12 @@ impl ConfigForm {
self.set_string("identity", "scope", scope);
}
+ /// Set the permission bypass ceiling for the next pairing.
+ pub fn set_permission_bypass(&mut self, allowed: bool) {
+ let identity = self.doc["identity"].or_insert(toml_edit::table());
+ identity["allow_permission_bypass"] = value(allowed);
+ }
+
/// Persist the credential minted by pairing in this config document.
pub fn persist_credentials(
&mut self,
diff --git a/crates/coding_agent_worker/src/tui/config_form/test.rs b/crates/coding_agent_worker/src/tui/config_form/test.rs
index 795fbbe1e5..ce93813fc0 100644
--- a/crates/coding_agent_worker/src/tui/config_form/test.rs
+++ b/crates/coding_agent_worker/src/tui/config_form/test.rs
@@ -200,3 +200,37 @@ fn assert_private_mode(path: &Path) {
#[cfg(not(unix))]
fn assert_private_mode(_path: &Path) {}
+
+#[test]
+fn permission_bypass_edits_preserve_credentials_and_comments() {
+ let directory = tempfile::tempdir().unwrap();
+ let path = directory.path().join("macrod.toml");
+ let agent = discover(&HermesOnly).remove(0);
+ ConfigForm::create_for_deployment(&path, &agent, directory.path(), Deployment::Production)
+ .unwrap();
+ let credentials = HarnessCredentials {
+ harness_id: HarnessId::TEST_A,
+ token: "mhns_secret".to_owned(),
+ scope: HarnessScope::User,
+ };
+ let mut form = ConfigForm::load(&path).unwrap();
+ form.persist_credentials(&credentials).unwrap();
+ assert!(
+ !Config::load(&path)
+ .unwrap()
+ .identity
+ .allow_permission_bypass
+ );
+ for allowed in [true, false] {
+ form.set_permission_bypass(allowed);
+ form.save().unwrap();
+ let config = Config::load(&path).unwrap();
+ assert_eq!(config.identity.allow_permission_bypass, allowed);
+ assert_eq!(config.credentials.as_ref(), Some(&credentials));
+ assert!(
+ fs::read_to_string(&path)
+ .unwrap()
+ .contains("# macrod configuration")
+ );
+ }
+}
diff --git a/crates/coding_agent_worker/src/tui/quickstart.rs b/crates/coding_agent_worker/src/tui/quickstart.rs
index e02b8dd0f1..4c9beece26 100644
--- a/crates/coding_agent_worker/src/tui/quickstart.rs
+++ b/crates/coding_agent_worker/src/tui/quickstart.rs
@@ -17,6 +17,7 @@ pub(crate) struct Quickstart {
pub(crate) focus: QuickstartFocus,
pub(crate) workspace: String,
pub(crate) scope: IdentityScope,
+ pub(crate) allow_permission_bypass: bool,
pub(crate) mode: QuickstartMode,
pub(crate) status: Option<(String, bool)>,
}
@@ -34,6 +35,7 @@ pub(crate) enum QuickstartFocus {
Agent(usize),
Workspace,
Scope,
+ PermissionBypass,
Submit,
}
@@ -55,6 +57,7 @@ impl Quickstart {
focus: QuickstartFocus::Agent(0),
workspace,
scope: IdentityScope::Private,
+ allow_permission_bypass: false,
mode: QuickstartMode::Normal,
status: None,
})
@@ -93,6 +96,7 @@ impl Quickstart {
focus,
workspace: config.workspace.path.display().to_string(),
scope: config.identity.scope,
+ allow_permission_bypass: config.identity.allow_permission_bypass,
mode: QuickstartMode::Normal,
status: None,
}
@@ -115,7 +119,8 @@ impl Quickstart {
}
QuickstartFocus::Workspace => QuickstartFocus::Agent(self.agents.len()),
QuickstartFocus::Scope => QuickstartFocus::Workspace,
- QuickstartFocus::Submit => QuickstartFocus::Scope,
+ QuickstartFocus::PermissionBypass => QuickstartFocus::Scope,
+ QuickstartFocus::Submit => QuickstartFocus::PermissionBypass,
};
QuickstartAction::Continue
}
@@ -126,7 +131,10 @@ impl Quickstart {
}
QuickstartFocus::Agent(_) => QuickstartFocus::Workspace,
QuickstartFocus::Workspace => QuickstartFocus::Scope,
- QuickstartFocus::Scope | QuickstartFocus::Submit => QuickstartFocus::Submit,
+ QuickstartFocus::Scope => QuickstartFocus::PermissionBypass,
+ QuickstartFocus::PermissionBypass | QuickstartFocus::Submit => {
+ QuickstartFocus::Submit
+ }
};
QuickstartAction::Continue
}
@@ -170,6 +178,10 @@ impl Quickstart {
};
QuickstartAction::Continue
}
+ QuickstartFocus::PermissionBypass => {
+ self.allow_permission_bypass = !self.allow_permission_bypass;
+ QuickstartAction::Continue
+ }
QuickstartFocus::Submit if self.selected_agent.is_none() => {
self.status =
Some(("Choose an agent harness before continuing".to_owned(), true));
diff --git a/crates/coding_agent_worker/src/tui/quickstart/test.rs b/crates/coding_agent_worker/src/tui/quickstart/test.rs
index 9406ea25e4..0f2f271181 100644
--- a/crates/coding_agent_worker/src/tui/quickstart/test.rs
+++ b/crates/coding_agent_worker/src/tui/quickstart/test.rs
@@ -15,6 +15,7 @@ fn quickstart_uses_one_flat_focus_order_without_preselecting_an_agent() {
focus: QuickstartFocus::Agent(0),
workspace: "/tmp".to_owned(),
scope: IdentityScope::Private,
+ allow_permission_bypass: false,
mode: QuickstartMode::Normal,
status: None,
};
@@ -24,9 +25,11 @@ fn quickstart_uses_one_flat_focus_order_without_preselecting_an_agent() {
quickstart.on_key(key(KeyCode::Down));
assert_eq!(quickstart.focus, QuickstartFocus::Scope);
quickstart.on_key(key(KeyCode::Down));
+ assert_eq!(quickstart.focus, QuickstartFocus::PermissionBypass);
+ quickstart.on_key(key(KeyCode::Down));
assert_eq!(quickstart.focus, QuickstartFocus::Submit);
quickstart.on_key(key(KeyCode::Up));
- assert_eq!(quickstart.focus, QuickstartFocus::Scope);
+ assert_eq!(quickstart.focus, QuickstartFocus::PermissionBypass);
assert!(quickstart.selected_agent.is_none());
}
@@ -38,6 +41,7 @@ fn tab_and_shift_tab_reach_and_leave_the_submit_button() {
focus: QuickstartFocus::Agent(0),
workspace: "/tmp".to_owned(),
scope: IdentityScope::Private,
+ allow_permission_bypass: false,
mode: QuickstartMode::Normal,
status: None,
};
@@ -45,10 +49,12 @@ fn tab_and_shift_tab_reach_and_leave_the_submit_button() {
quickstart.on_key(key(KeyCode::Tab));
quickstart.on_key(key(KeyCode::Tab));
quickstart.on_key(key(KeyCode::Tab));
+ assert_eq!(quickstart.focus, QuickstartFocus::PermissionBypass);
+ quickstart.on_key(key(KeyCode::Tab));
assert_eq!(quickstart.focus, QuickstartFocus::Submit);
quickstart.on_key(key(KeyCode::BackTab));
- assert_eq!(quickstart.focus, QuickstartFocus::Scope);
+ assert_eq!(quickstart.focus, QuickstartFocus::PermissionBypass);
}
#[test]
@@ -59,6 +65,7 @@ fn custom_agent_reedit_preserves_arguments() {
focus: QuickstartFocus::Agent(0),
workspace: "/tmp".to_owned(),
scope: IdentityScope::Private,
+ allow_permission_bypass: false,
mode: QuickstartMode::Normal,
status: None,
};
@@ -127,3 +134,86 @@ fn config(harness: Harness) -> Config {
};
config
}
+
+#[test]
+fn permission_bypass_defaults_off_and_can_be_toggled() {
+ let mut setup = Quickstart::from_config_with_agents(
+ &config(Harness {
+ command: "hermes".to_owned(),
+ args: vec!["acp".to_owned()],
+ }),
+ Vec::new(),
+ );
+ assert!(!setup.allow_permission_bypass);
+ setup.focus = QuickstartFocus::PermissionBypass;
+ setup.on_key(key(KeyCode::Enter));
+ assert!(setup.allow_permission_bypass);
+ setup.on_key(key(KeyCode::Enter));
+ assert!(!setup.allow_permission_bypass);
+}
+
+#[test]
+fn unpaired_config_prefills_permission_bypass_consent() {
+ let mut config = config(Harness {
+ command: "hermes".to_owned(),
+ args: vec!["acp".to_owned()],
+ });
+ config.identity.allow_permission_bypass = true;
+ let setup = Quickstart::from_config_with_agents(&config, Vec::new());
+ assert!(setup.allow_permission_bypass);
+}
+
+#[test]
+fn quickstart_renders_permission_consent_and_warning() {
+ use ratatui::{Terminal, backend::TestBackend};
+ let mut setup = Quickstart::from_config_with_agents(
+ &config(Harness {
+ command: "hermes".to_owned(),
+ args: vec!["acp".to_owned()],
+ }),
+ Vec::new(),
+ );
+ for allowed in [false, true] {
+ setup.allow_permission_bypass = allowed;
+ let mut terminal = Terminal::new(TestBackend::new(100, 40)).unwrap();
+ terminal
+ .draw(|frame| {
+ crate::tui::ui::render_quickstart(
+ frame,
+ &setup,
+ std::path::Path::new("macrod.toml"),
+ )
+ })
+ .unwrap();
+ let screen = terminal
+ .backend()
+ .buffer()
+ .content()
+ .iter()
+ .map(|cell| cell.symbol())
+ .collect::<String>();
+ assert!(screen.contains("Full Access"));
+ assert!(screen.contains(if allowed {
+ "[x] On"
+ } else {
+ "[ ] Off (always prompt)"
+ }));
+ assert_eq!(screen.contains("without approval"), allowed);
+ assert!(screen.contains("Create and pair"));
+ let rows = terminal
+ .backend()
+ .buffer()
+ .content()
+ .chunks(100)
+ .map(|row| row.iter().map(|cell| cell.symbol()).collect::<String>())
+ .collect::<Vec<_>>();
+ let workspace = rows.iter().find(|row| row.contains("Workspace")).unwrap();
+ let scope = rows
+ .iter()
+ .find(|row| row.contains("Access") && !row.contains("Full Access"))
+ .unwrap();
+ let full_access = rows.iter().find(|row| row.contains("Full Access")).unwrap();
+ assert_eq!(workspace.find("/existing/workspace"), scope.find("Team"));
+ assert_eq!(workspace.find("/existing/workspace"), full_access.find('['));
+ }
+}
diff --git a/crates/coding_agent_worker/src/tui/runner.rs b/crates/coding_agent_worker/src/tui/runner.rs
index 4736f7cb46..640846155c 100644
--- a/crates/coding_agent_worker/src/tui/runner.rs
+++ b/crates/coding_agent_worker/src/tui/runner.rs
@@ -10,7 +10,7 @@ use super::logging::LogBuffer;
use super::platform::open_pending_browser;
use super::quickstart::{Quickstart, QuickstartAction};
use super::ui;
-use crate::config::{Config, IdentityScope};
+use crate::config::Config;
#[cfg(test)]
mod test;
@@ -132,15 +132,14 @@ async fn run_quickstart(
let saved = if existing_config.is_some() {
ConfigForm::load(config_path).and_then(|mut form| {
form.apply_quickstart(agent, &workspace, quickstart.scope);
+ form.set_permission_bypass(quickstart.allow_permission_bypass);
form.save()
})
} else {
ConfigForm::create(config_path, agent, &workspace).and_then(|()| {
- if quickstart.scope == IdentityScope::Private {
- return Ok(());
- }
let mut form = ConfigForm::load(config_path)?;
form.set_scope(quickstart.scope);
+ form.set_permission_bypass(quickstart.allow_permission_bypass);
form.save()
})
};
diff --git a/crates/coding_agent_worker/src/tui/ui/pages/config.rs b/crates/coding_agent_worker/src/tui/ui/pages/config.rs
index 986281a0e4..55e5dc7155 100644
--- a/crates/coding_agent_worker/src/tui/ui/pages/config.rs
+++ b/crates/coding_agent_worker/src/tui/ui/pages/config.rs
@@ -21,13 +21,13 @@ pub(super) fn render(frame: &mut Frame, app: &App, area: Rect) {
..inner
};
frame.render_widget(
- Paragraph::new(format!("{}{:<16}", focus_marker(selected), setting.label()))
+ Paragraph::new(format!("{}{:<14}", focus_marker(selected), setting.label()))
.style(focus_style(selected)),
row,
);
let value_area = Rect {
- x: row.x + 18,
- width: row.width.saturating_sub(18),
+ x: row.x + 16,
+ width: row.width.saturating_sub(16),
..row
};
match &app.mode {
@@ -51,6 +51,13 @@ pub(super) fn render(frame: &mut Frame, app: &App, area: Rect) {
}
}
}
+ if app.config.identity.allow_permission_bypass {
+ frame.render_widget(
+ Paragraph::new("Warning: agents can run commands and edit files without approval.\nApplies at next pairing.")
+ .style(Style::new().fg(WARN)),
+ Rect { y: inner.y + SETTINGS.len() as u16 + 2, height: 2, ..inner },
+ );
+ }
if app.config.identity.scope == IdentityScope::Team {
let warning = Rect {
x: inner.x,
diff --git a/crates/coding_agent_worker/src/tui/ui/quickstart.rs b/crates/coding_agent_worker/src/tui/ui/quickstart.rs
index 47691343de..defa006f02 100644
--- a/crates/coding_agent_worker/src/tui/ui/quickstart.rs
+++ b/crates/coding_agent_worker/src/tui/ui/quickstart.rs
@@ -19,7 +19,7 @@ pub(crate) fn render_quickstart(
let discovered_height = (setup.agents.len() as u16 + 2).clamp(3, 9);
let area = centered(
84,
- frame.area().height.saturating_sub(2).min(27),
+ frame.area().height.saturating_sub(2).min(33),
frame.area(),
);
frame.render_widget(Clear, area);
@@ -33,6 +33,8 @@ pub(crate) fn render_quickstart(
_form_spacer,
workspace_area,
scope_area,
+ permissions_area,
+ permission_warning_area,
_button_spacer,
submit_area,
warning_area,
@@ -45,6 +47,8 @@ pub(crate) fn render_quickstart(
Constraint::Length(1),
Constraint::Length(1),
Constraint::Length(1),
+ Constraint::Length(1),
+ Constraint::Length(2),
Constraint::Min(1),
Constraint::Length(3),
Constraint::Length(1),
@@ -123,6 +127,34 @@ pub(crate) fn render_quickstart(
);
}
+ let permissions_focused = setup.focus == QuickstartFocus::PermissionBypass;
+ frame.render_widget(
+ Paragraph::new(Line::from(vec![
+ Span::styled(
+ format!("{}{:<14}", focus_marker(permissions_focused), "Full Access"),
+ Style::new().fg(DIM),
+ ),
+ Span::styled(
+ if setup.allow_permission_bypass {
+ "[x] On"
+ } else {
+ "[ ] Off (always prompt)"
+ },
+ focus_style(permissions_focused),
+ ),
+ ])),
+ permissions_area,
+ );
+ if setup.allow_permission_bypass {
+ frame.render_widget(
+ Paragraph::new(
+ "Warning: agents can run commands and edit files without approval.\nOnly enable this if you trust everyone who can create agents here.",
+ )
+ .style(Style::new().fg(WARN)),
+ permission_warning_area,
+ );
+ }
+
let submit_focused = setup.focus == QuickstartFocus::Submit;
let button_style = if submit_focused {
Style::new().fg(THEME.accent_text).bg(ACCENT).bold()
diff --git a/crates/entity_access/src/inbound/axum_extractors/agent_session.rs b/crates/entity_access/src/inbound/axum_extractors/agent_session.rs
index bd2ea1a341..f3bab7e8d8 100644
--- a/crates/entity_access/src/inbound/axum_extractors/agent_session.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/agent_session.rs
@@ -151,3 +151,6 @@ where
})
}
}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/entity_access/src/inbound/axum_extractors/agent_session/test.rs b/crates/entity_access/src/inbound/axum_extractors/agent_session/test.rs
new file mode 100644
index 0000000000..bd2202cb61
--- /dev/null
+++ b/crates/entity_access/src/inbound/axum_extractors/agent_session/test.rs
@@ -0,0 +1,51 @@
+use super::*;
+use crate::domain::models::EditAccessLevel;
+use crate::inbound::axum_extractors::test_support::{
+ FakeAuthorizationService, FakeEntityAccessService, TestState, USER_ID,
+};
+use axum::{
+ Router,
+ body::Body,
+ http::{Request, StatusCode},
+ routing::post,
+};
+use tower::ServiceExt;
+
+#[tokio::test]
+async fn permission_approval_access_accepts_editors_and_owners_but_not_viewers() {
+ for (level, expected) in [
+ (Some(AccessLevel::Edit), StatusCode::NO_CONTENT),
+ (Some(AccessLevel::Owner), StatusCode::NO_CONTENT),
+ (Some(AccessLevel::View), StatusCode::UNAUTHORIZED),
+ (Some(AccessLevel::Comment), StatusCode::UNAUTHORIZED),
+ (None, StatusCode::UNAUTHORIZED),
+ ] {
+ let state = TestState::new(level);
+ let app = Router::new()
+ .route(
+ "/sessions/{session_id}/control",
+ post(
+ |_: AgentSessionAccessLevelExtractor<
+ EditAccessLevel,
+ FakeEntityAccessService,
+ FakeAuthorizationService,
+ >| async { StatusCode::NO_CONTENT },
+ ),
+ )
+ .with_state(state.clone());
+ let response = app
+ .oneshot(
+ Request::post("/sessions/shared-session/control")
+ .header("authorization", "Bearer valid")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(response.status(), expected, "{level:?}");
+ let calls = state.entity_access.calls();
+ assert_eq!(calls[0].user_id.as_deref(), Some(USER_ID));
+ assert_eq!(calls[0].entity_id, "shared-session");
+ assert_eq!(calls[0].entity_type, EntityType::AgentSession);
+ }
+}
diff --git a/crates/entity_access/src/inbound/axum_extractors/test_support.rs b/crates/entity_access/src/inbound/axum_extractors/test_support.rs
index f77f2b8307..01f003e32e 100644
--- a/crates/entity_access/src/inbound/axum_extractors/test_support.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/test_support.rs
@@ -169,12 +169,16 @@ impl EntityAccessService for FakeEntityAccessService {
async fn get_entity_permission(
&self,
- _user_id: Option<&MacroUserId<Lowercase<'_>>>,
- _entity_id: &str,
- _entity_type: EntityType,
+ user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ entity_id: &str,
+ entity_type: EntityType,
_user_org_id: Option<i64>,
) -> Result<EntityPermission, AccessError> {
- panic!("unexpected get_entity_permission call")
+ let access_level = self
+ .get_access_level(user_id, entity_id, entity_type)
+ .await?
+ .ok_or(AccessError::Unauthorized)?;
+ Ok(EntityPermission::AccessLevel { access_level })
}
async fn get_crm_entity_permission_with_team(
diff --git a/crates/harnesses/src/domain/models.rs b/crates/harnesses/src/domain/models.rs
index b25daad715..73622aa131 100644
--- a/crates/harnesses/src/domain/models.rs
+++ b/crates/harnesses/src/domain/models.rs
@@ -32,6 +32,9 @@ pub enum HarnessOwner {
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
pub struct Harness {
+ /// Whether agents may bypass ACP permission requests on this harness.
+ #[serde(default)]
+ pub allow_permission_bypass: bool,
/// Harness id.
pub id: HarnessId,
/// Runtime kind. Currently always `macrod`.
@@ -94,6 +97,9 @@ impl std::str::FromStr for RequestedHarnessScope {
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
pub struct CreatePairingRequest {
+ /// Daemon operator consent ceiling. Omitted by older clients; web approval decides.
+ #[serde(default)]
+ pub allow_permission_bypass: Option<bool>,
/// Requested harness display name (typically the machine's hostname).
pub name: String,
/// Display-only description of the machine, e.g. `eric@macbook / darwin`.
@@ -127,6 +133,9 @@ pub struct CreatedPairing {
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
pub struct PairingDetails {
+ /// Daemon operator consent ceiling; false forbids bypass at approval.
+ #[serde(default)]
+ pub requested_allow_permission_bypass: Option<bool>,
/// The pairing code, normalized to `XXXX-XXXX`.
pub code: String,
/// Harness display name the daemon asked for.
@@ -145,6 +154,9 @@ pub struct PairingDetails {
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
pub struct ApprovePairingRequest {
+ /// Whether agents may bypass ACP permission requests on this harness.
+ #[serde(default)]
+ pub allow_permission_bypass: bool,
/// Display name override. Defaults to the daemon's requested name.
pub name: Option<String>,
/// Owning team. Omit for a private, user-owned harness.
diff --git a/crates/harnesses/src/domain/ports.rs b/crates/harnesses/src/domain/ports.rs
index af91ec33c4..ac4aca41f9 100644
--- a/crates/harnesses/src/domain/ports.rs
+++ b/crates/harnesses/src/domain/ports.rs
@@ -17,6 +17,8 @@ use super::models::{
/// A pairing row to persist.
#[derive(Debug, Clone)]
pub struct NewPairing {
+ /// Daemon operator consent ceiling for permission bypass.
+ pub requested_allow_permission_bypass: Option<bool>,
/// Pairing id.
pub id: Uuid,
/// Normalized pairing code, `XXXX-XXXX`.
@@ -36,6 +38,8 @@ pub struct NewPairing {
/// A harness row to create at approval.
#[derive(Debug, Clone)]
pub struct NewHarness {
+ /// Whether personas may bypass ACP permission requests on this harness.
+ pub allow_permission_bypass: bool,
/// Harness id.
pub id: HarnessId,
/// Display name.
diff --git a/crates/harnesses/src/domain/service.rs b/crates/harnesses/src/domain/service.rs
index 281d1e4fdc..99ae39f1ed 100644
--- a/crates/harnesses/src/domain/service.rs
+++ b/crates/harnesses/src/domain/service.rs
@@ -126,6 +126,7 @@ where
requested_name: name.to_owned(),
host: host.clone(),
requested_scope: req.scope,
+ requested_allow_permission_bypass: req.allow_permission_bypass,
expires_at,
})
.await
@@ -182,6 +183,11 @@ where
// Reuses the pending/expired policy so approval failures report the
// same way the lookup does.
let details = self.get_pairing(code).await?;
+ if req.allow_permission_bypass && details.requested_allow_permission_bypass == Some(false) {
+ return Err(HarnessError::BadRequest(
+ "this daemon requires permission prompts".to_owned(),
+ ));
+ }
let code = tokens::normalize_pairing_code(code).expect("get_pairing validated the code");
let name = match &req.name {
@@ -220,6 +226,7 @@ where
.approve_pairing(
&code,
NewHarness {
+ allow_permission_bypass: req.allow_permission_bypass,
id: HarnessId::new_from_uuid(Uuid::new_v4()),
name,
owner,
diff --git a/crates/harnesses/src/domain/service/test.rs b/crates/harnesses/src/domain/service/test.rs
index fe1953557b..c46729b4e3 100644
--- a/crates/harnesses/src/domain/service/test.rs
+++ b/crates/harnesses/src/domain/service/test.rs
@@ -20,6 +20,7 @@ fn caller(id: &str) -> MacroUserIdStr<'static> {
fn harness(owner: HarnessOwner) -> Harness {
Harness {
+ allow_permission_bypass: false,
id: HarnessId::TEST_A,
kind: "macrod".to_owned(),
name: "erics-macbook".to_owned(),
@@ -35,6 +36,7 @@ fn harness(owner: HarnessOwner) -> Harness {
fn pending_pairing() -> PairingRow {
PairingRow {
details: PairingDetails {
+ requested_allow_permission_bypass: None,
code: CODE.to_owned(),
requested_name: "erics-macbook".to_owned(),
host: Some("eric@macbook / darwin".to_owned()),
@@ -191,6 +193,7 @@ async fn creating_a_pairing_returns_code_and_secret_and_persists_only_hashes() {
let repo = FakeRepo::default();
let created = service(repo.clone())
.create_pairing(CreatePairingRequest {
+ allow_permission_bypass: None,
name: " erics-macbook ".to_owned(),
host: Some("eric@macbook".to_owned()),
scope: Some(RequestedHarnessScope::Team),
@@ -221,6 +224,7 @@ async fn pairing_creation_retries_code_collisions() {
};
let created = service(repo.clone())
.create_pairing(CreatePairingRequest {
+ allow_permission_bypass: None,
name: "erics-macbook".to_owned(),
host: None,
scope: None,
@@ -244,6 +248,7 @@ async fn pairing_creation_is_throttled_and_validates_the_name() {
};
let result = service(throttled)
.create_pairing(CreatePairingRequest {
+ allow_permission_bypass: None,
name: "erics-macbook".to_owned(),
host: None,
scope: None,
@@ -253,6 +258,7 @@ async fn pairing_creation_is_throttled_and_validates_the_name() {
let result = service(FakeRepo::default())
.create_pairing(CreatePairingRequest {
+ allow_permission_bypass: None,
name: " ".to_owned(),
host: None,
scope: None,
@@ -315,6 +321,7 @@ async fn approval_registers_a_private_harness_for_the_caller() {
caller(OWNER_ID),
"kx7m4qhd",
ApprovePairingRequest {
+ allow_permission_bypass: false,
name: None,
team_id: None,
},
@@ -334,6 +341,7 @@ async fn approval_registers_a_private_harness_for_the_caller() {
}
);
assert_eq!(new_harness.created_by.as_ref(), OWNER_ID);
+ assert!(!new_harness.allow_permission_bypass);
assert!(calls.team_lookups.is_empty());
}
@@ -350,6 +358,7 @@ async fn team_approval_requires_membership_and_honors_the_name_override() {
caller(MEMBER_ID),
CODE,
ApprovePairingRequest {
+ allow_permission_bypass: false,
name: Some("team box".to_owned()),
team_id: Some(TEAM_ID),
},
@@ -373,6 +382,7 @@ async fn team_approval_requires_membership_and_honors_the_name_override() {
caller(MEMBER_ID),
CODE,
ApprovePairingRequest {
+ allow_permission_bypass: false,
name: None,
team_id: Some(TEAM_ID),
},
@@ -393,6 +403,7 @@ async fn approval_race_reports_gone() {
caller(OWNER_ID),
CODE,
ApprovePairingRequest {
+ allow_permission_bypass: false,
name: None,
team_id: None,
},
@@ -581,3 +592,87 @@ async fn team_harnesses_are_deletable_by_their_registrant_or_the_team_owner() {
.await;
assert!(matches!(result, Err(HarnessError::NotFound(_))));
}
+
+#[tokio::test]
+async fn approval_records_explicit_permission_bypass_consent() {
+ let repo = FakeRepo {
+ pairing: Some(pending_pairing()),
+ approve_result: Some(harness(HarnessOwner::User {
+ user_id: OWNER_ID.to_owned(),
+ })),
+ ..FakeRepo::default()
+ };
+ service(repo.clone())
+ .approve_pairing(
+ caller(OWNER_ID),
+ CODE,
+ ApprovePairingRequest {
+ name: None,
+ team_id: None,
+ allow_permission_bypass: true,
+ },
+ )
+ .await
+ .unwrap();
+ assert!(
+ repo.calls.lock().unwrap().approved[0]
+ .1
+ .allow_permission_bypass
+ );
+}
+
+#[tokio::test]
+async fn pairing_creation_preserves_the_daemons_permission_ceiling() {
+ for allowed in [None, Some(false), Some(true)] {
+ let repo = FakeRepo::default();
+ service(repo.clone())
+ .create_pairing(CreatePairingRequest {
+ allow_permission_bypass: allowed,
+ name: "laptop".to_owned(),
+ host: None,
+ scope: None,
+ })
+ .await
+ .unwrap();
+ assert_eq!(
+ repo.calls.lock().unwrap().inserted_pairings[0].requested_allow_permission_bypass,
+ allowed
+ );
+ }
+}
+
+#[tokio::test]
+async fn approval_requires_daemon_consent_when_the_daemon_names_a_ceiling() {
+ for requested in [None, Some(false), Some(true)] {
+ for approved in [false, true] {
+ let mut pairing = pending_pairing();
+ pairing.details.requested_allow_permission_bypass = requested;
+ let repo = FakeRepo {
+ pairing: Some(pairing),
+ approve_result: Some(harness(HarnessOwner::User {
+ user_id: OWNER_ID.to_owned(),
+ })),
+ ..FakeRepo::default()
+ };
+ let result = service(repo.clone())
+ .approve_pairing(
+ caller(OWNER_ID),
+ CODE,
+ ApprovePairingRequest {
+ allow_permission_bypass: approved,
+ name: None,
+ team_id: None,
+ },
+ )
+ .await;
+ let calls = repo.calls.lock().unwrap();
+ if requested == Some(false) && approved {
+ assert!(matches!(result, Err(HarnessError::BadRequest(_))));
+ assert!(calls.approved.is_empty());
+ } else {
+ result.unwrap();
+ assert_eq!(calls.approved[0].1.allow_permission_bypass, approved);
+ }
+ }
+ }
+}
diff --git a/crates/harnesses/src/outbound/pg_harness_repo.rs b/crates/harnesses/src/outbound/pg_harness_repo.rs
index 32e24e8d1e..04894bd621 100644
--- a/crates/harnesses/src/outbound/pg_harness_repo.rs
+++ b/crates/harnesses/src/outbound/pg_harness_repo.rs
@@ -33,6 +33,7 @@ impl PgHarnessRepo {
}
struct HarnessRow {
+ allow_permission_bypass: bool,
id: Uuid,
kind: String,
name: String,
@@ -62,6 +63,7 @@ impl TryFrom<HarnessRow> for Harness {
Ok(Self {
id: HarnessId::new_from_uuid(row.id),
+ allow_permission_bypass: row.allow_permission_bypass,
kind: row.kind,
name: row.name,
owner,
@@ -91,7 +93,7 @@ async fn fetch_harness(
HarnessRow,
r#"
SELECT
- id, kind, name, owner_user_id, team_id, created_by,
+ id, kind, name, owner_user_id, team_id, created_by, allow_permission_bypass,
created_at, updated_at, last_connected_at, last_disconnected_at
FROM harnesses
WHERE id = $1 AND deleted_at IS NULL
@@ -113,8 +115,8 @@ impl HarnessRepo for PgHarnessRepo {
r#"
INSERT INTO harness_pairing_requests
(id, code, device_secret_hash, requested_name, host_info, requested_scope,
- expires_at)
- VALUES ($1, $2, $3, $4, $5, $6, $7)
+ expires_at, requested_allow_permission_bypass)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
ON CONFLICT (code) DO NOTHING
"#,
pairing.id,
@@ -124,6 +126,7 @@ impl HarnessRepo for PgHarnessRepo {
pairing.host,
pairing.requested_scope.map(RequestedHarnessScope::as_str),
pairing.expires_at,
+ pairing.requested_allow_permission_bypass,
)
.execute(&self.pool)
.await
@@ -172,8 +175,8 @@ impl HarnessRepo for PgHarnessRepo {
async fn get_pairing(&self, code: &str) -> Result<Option<PairingRow>, Self::Err> {
let row = sqlx::query!(
r#"
- SELECT code, requested_name, host_info, requested_scope, status, created_at,
- expires_at
+ SELECT code, requested_name, host_info, requested_scope,
+ requested_allow_permission_bypass, status, created_at, expires_at
FROM harness_pairing_requests
WHERE code = $1
"#,
@@ -196,6 +199,7 @@ impl HarnessRepo for PgHarnessRepo {
requested_name: row.requested_name,
host: row.host_info,
requested_scope,
+ requested_allow_permission_bypass: row.requested_allow_permission_bypass,
created_at: row.created_at,
expires_at: row.expires_at,
},
@@ -218,14 +222,15 @@ impl HarnessRepo for PgHarnessRepo {
};
sqlx::query!(
r#"
- INSERT INTO harnesses (id, kind, name, owner_user_id, team_id, created_by)
- VALUES ($1, 'macrod', $2, $3, $4, $5)
+ INSERT INTO harnesses (id, kind, name, owner_user_id, team_id, created_by, allow_permission_bypass)
+ VALUES ($1, 'macrod', $2, $3, $4, $5, $6)
"#,
harness.id.as_uuid(),
harness.name,
owner_user_id,
team_id,
harness.created_by.as_ref(),
+ harness.allow_permission_bypass,
)
.execute(&mut *tx)
.await
@@ -344,7 +349,7 @@ impl HarnessRepo for PgHarnessRepo {
HarnessRow,
r#"
SELECT
- id, kind, name, owner_user_id, team_id, created_by,
+ id, kind, name, owner_user_id, team_id, created_by, allow_permission_bypass,
created_at, updated_at, last_connected_at, last_disconnected_at
FROM harnesses
WHERE deleted_at IS NULL
diff --git a/crates/harnesses/src/outbound/pg_harness_repo/tests.rs b/crates/harnesses/src/outbound/pg_harness_repo/tests.rs
index aa8e54aaaf..8b0e465c22 100644
--- a/crates/harnesses/src/outbound/pg_harness_repo/tests.rs
+++ b/crates/harnesses/src/outbound/pg_harness_repo/tests.rs
@@ -43,6 +43,7 @@ async fn insert_user(pool: &PgPool, user_id: &str) {
fn new_pairing(code: &str, secret: &str) -> NewPairing {
NewPairing {
+ requested_allow_permission_bypass: None,
id: Uuid::new_v4(),
code: code.to_owned(),
device_secret_hash: harness_token::hash_token(secret),
@@ -55,6 +56,7 @@ fn new_pairing(code: &str, secret: &str) -> NewPairing {
fn new_harness() -> NewHarness {
NewHarness {
+ allow_permission_bypass: false,
id: HarnessId::new_from_uuid(Uuid::new_v4()),
name: "erics-macbook".to_owned(),
owner: HarnessOwner::User {
@@ -501,3 +503,55 @@ async fn sessions_list_only_this_harness_newest_first(pool: PgPool) {
assert_eq!(sessions[0].bot_name, "Bound agent");
assert_eq!(sessions[0].owner_id, OWNER_ID);
}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn permission_bypass_survives_registration_and_listing(pool: PgPool) {
+ let repo = PgHarnessRepo::new(pool.clone());
+ insert_user(&pool, OWNER_ID).await;
+ for (code, allowed) in [("AAAA-BBBB", false), ("CCCC-DDDD", true)] {
+ repo.insert_pairing(new_pairing(code, "secret"))
+ .await
+ .unwrap();
+ let mut registration = new_harness();
+ registration.allow_permission_bypass = allowed;
+ let harness = repo
+ .approve_pairing(code, registration)
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(harness.allow_permission_bypass, allowed);
+ assert_eq!(
+ repo.get_harness(harness.id)
+ .await
+ .unwrap()
+ .unwrap()
+ .allow_permission_bypass,
+ allowed
+ );
+ let listed = repo.list_visible_harnesses(caller()).await.unwrap();
+ assert_eq!(
+ listed
+ .iter()
+ .find(|item| item.id == harness.id)
+ .unwrap()
+ .allow_permission_bypass,
+ allowed
+ );
+ }
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn pairing_permission_ceiling_roundtrips(pool: PgPool) {
+ let repo = PgHarnessRepo::new(pool);
+ for (code, allowed) in [
+ ("AAAA-AAAA", None),
+ ("BBBB-BBBB", Some(false)),
+ ("CCCC-CCCC", Some(true)),
+ ] {
+ let mut pairing = new_pairing(code, "device-secret");
+ pairing.requested_allow_permission_bypass = allowed;
+ assert!(repo.insert_pairing(pairing).await.unwrap());
+ let stored = repo.get_pairing(code).await.unwrap().unwrap();
+ assert_eq!(stored.details.requested_allow_permission_bypass, allowed);
+ }
+}
diff --git a/crates/macro_db_client/migrations/20260903214858_add_agent_configs_auto_accept_permissions.sql b/crates/macro_db_client/migrations/20260903214858_add_agent_configs_auto_accept_permissions.sql
new file mode 100644
index 0000000000..6921d8b895
--- /dev/null
+++ b/crates/macro_db_client/migrations/20260903214858_add_agent_configs_auto_accept_permissions.sql
@@ -0,0 +1,5 @@
+ALTER TABLE agent_configs
+ ADD COLUMN auto_accept_permissions BOOLEAN NULL;
+
+COMMENT ON COLUMN agent_configs.auto_accept_permissions IS
+ 'Whether the agent''s sessions approve ACP permission requests without asking. NULL defers to the runtime kind''s default: managed runtimes (cursor, in-memory, sandboxed coder) auto-accept, macrod prompts.';
diff --git a/crates/macro_db_client/migrations/20260918182715_add_harness_permission_bypass.sql b/crates/macro_db_client/migrations/20260918182715_add_harness_permission_bypass.sql
new file mode 100644
index 0000000000..be9bd99c4b
--- /dev/null
+++ b/crates/macro_db_client/migrations/20260918182715_add_harness_permission_bypass.sql
@@ -0,0 +1,2 @@
+ALTER TABLE harnesses
+ ADD COLUMN allow_permission_bypass boolean NOT NULL DEFAULT false;
diff --git a/crates/macro_db_client/migrations/20260918204158_add_pairing_permission_bypass_consent.sql b/crates/macro_db_client/migrations/20260918204158_add_pairing_permission_bypass_consent.sql
new file mode 100644
index 0000000000..49512a580e
--- /dev/null
+++ b/crates/macro_db_client/migrations/20260918204158_add_pairing_permission_bypass_consent.sql
@@ -0,0 +1,5 @@
+ALTER TABLE harness_pairing_requests
+ ADD COLUMN requested_allow_permission_bypass boolean;
+
+COMMENT ON COLUMN harness_pairing_requests.requested_allow_permission_bypass IS
+ 'Daemon operator consent ceiling: false forbids permission bypass at approval, true permits user confirmation, NULL preserves legacy web-only consent.';
diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.md
index 2295811fa2..8580e1ade8 100644
--- a/docs/AGENT_GUIDE/ai-chat.md
+++ b/docs/AGENT_GUIDE/ai-chat.md
@@ -392,7 +392,7 @@ Other participants can copy a link for people who already have access, but
cannot grant access. Copying a link alone never changes permissions. New,
unsaved session drafts do not offer sharing.
-Agent sessions in the `@` menu use the shared Quick Access feed, loaded when the app opens. Search matches session titles and persona names. The initial feed covers the 500 most recently updated accessible sessions; it does not load transcripts.
+Agent sessions in the `@` menu use the shared Quick Access feed, loaded when the app opens. Search matches session titles and agent names. The initial feed covers the 500 most recently updated accessible sessions; it does not load transcripts.
### Expanded session mentions
@@ -513,6 +513,35 @@ must stay hidden; subsequent live messages must still appear.
- The stop button cancels only the **current** turn. The queue keeps draining: the next
queued prompt starts a new turn. To fully quiesce a session, remove the queued
entries, then stop.
+- **Permission prompts.** Everyone with **Edit** access to a session may approve or
+ reject its ACP permission requests, even when they did not create the session.
+ A pending request shows one `Approval needed` card above the composer, with
+ the command or affected file separate from the actions. The transcript does
+ not repeat the pending request.
+ `Allow once` and `Deny` answer immediately; `More options` contains remembered
+ choices with the agent's full rule text. Channel Magic Chips expose the same
+ approval card in place of their loading state, alongside existing questions.
+ Only authenticated users with **Edit** or **Owner** session access may answer;
+ bot, harness, and internal-service credentials cannot approve on their behalf.
+ Viewers and commenters see a waiting notice without
+ action buttons. Stopping a turn cancels open requests; answered requests show
+ a compact outcome such as `Allowed once` or `Denied` in the transcript.
+ Permission requests and questions both put the agent in a waiting state.
+ Several permissions may be pending alongside one question; answering one leaves
+ the others available. Controls disappear when their turn ends, is stopped, or
+ disconnects, and old transcript requests cannot answer a later turn's request.
+- **Harness bypass consent.** Settings → Harnesses → Connect a harness offers
+ `Allow bypassing permission requests`, off by default. Enabling it warns that
+ agents may run commands and edit files on the machine without approval.
+ Macrod Quickstart and Config also offer `Full Access`, off by
+ default. The choice applies at the next pairing: off disables bypass in the
+ approval dialog; on preselects bypass with a warning, and the approving user
+ can turn it off. Older daemons leave this choice to the approval dialog.
+- **Agent permission policy.** Settings → Agents → Runtime shows `Always prompt`
+ and `Always bypass` only for local macrod harnesses. Macrod defaults to prompts;
+ bypass requires both harness consent and the agent's explicit choice. Built-in
+ Macro, in-memory, Cursor, Codex, and Claude runtimes always bypass and have no
+ permission policy selector. The backend enforces these policies.
Locally sent user messages in both AI implementations enter with a short upward
slide and fade. History and remounted messages stay
diff --git a/docs/AGENT_GUIDE/channels.md b/docs/AGENT_GUIDE/channels.md
index f858dd81c3..caeee2ecfe 100644
--- a/docs/AGENT_GUIDE/channels.md
+++ b/docs/AGENT_GUIDE/channels.md
@@ -164,6 +164,13 @@ PR status in an open Magic Chip updates from connection-gateway events after
webhook sync. Reconnecting refreshes active PR lookups to recover missed updates.
A late webhook does not require reloading the page.
+When the agent requests permission, the Magic Chip replaces its loading state
+with the action and `Allow once`, `Deny`, and `More options` controls. Permission
+requests and questions share the chip's pending-interaction state and apply only
+to its anchored turn. Session editors and owners can answer directly in the chip;
+viewers and commenters see a waiting notice. Answering clears the request in both
+the chip and the open session, and the chip follows the agent's next activity.
+
Coding agents use `macro_internal.set_pull_request` to register an existing or
new GitHub PR with their session. Macro Internal MCP is hosted by the harness
service at `/mcp/internal` on its egress listener, separately from workspace MCP.
diff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.md
index ffa1da5bd1..4cf5573897 100644
--- a/docs/AGENT_GUIDE/surfaces.md
+++ b/docs/AGENT_GUIDE/surfaces.md
@@ -730,6 +730,9 @@ A harness can show `Loading models…`, an unsupported message, or
a retryable error without hiding the other harnesses. Editing preserves a saved model that
is no longer offered and labels it `saved, unavailable`. A macrod with no responding runtime
can remain loading until the 10-second discovery timeout; use Retry after reconnecting it.
+New macrod sessions use the agent's saved model before sending the first prompt.
+Changing that default applies to new sessions; existing sessions keep their selected model.
+If the runtime rejects the saved model, the prompt fails instead of using a different model.
`Harness` shows Cursor, Claude, Codex, and paired macrod runtimes to every user.
Connection chips in agent replies open this page, including before any account is connected. Cursor's default-model picker uses
diff --git a/packages/sdk/generated/agent-harness/index.ts b/packages/sdk/generated/agent-harness/index.ts
index 4f1ca98c21..b5c7934b69 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-ts
export { type Options, Sdk } from './sdk.gen';
-export type { AgentAction, AgentActionId, AgentModelDto, AgentModelsStatusDto, AgentPromptAction, AgentRepositoriesResponse, AgentRepositoryDto, AgentRespondElicitationAction, AgentSessionChangesPatchResponse, AgentSessionChangesResponse, AgentSessionLogEntryDto, AgentSessionLogResponse, AgentSessionPreviewData, AgentSessionPreviewDto, AgentSessionQueueResponse, AgentSessionResponse, AgentSetModelAction, BotId, CaptureAttemptDto, CaptureOutcomeDto, ChangedFileDto, ChangesetDto, ChangesetSourceDto, ClientOptions, CompleteData, CompleteErrors, CompleteRequest, CompleteResponse, CompleteResponses, ControlAgentSessionData, ControlAgentSessionError, ControlAgentSessionErrors, ControlAgentSessionResponse, ControlAgentSessionResponses, ControlRequest, ControlResponse, ControlStatusDto, CreateAgentSessionData, CreateAgentSessionError, CreateAgentSessionErrors, CreateAgentSessionRequest, CreateAgentSessionResponse, CreateAgentSessionResponse2, CreateAgentSessionResponses, CreateSessionThread, DeleteAgentSessionData, DeleteAgentSessionError, DeleteAgentSessionErrors, DeleteAgentSessionResponses, DisconnectData, DisconnectErrors, DisconnectResponse, DisconnectResponses, DocumentId, EditQueuedActionData, EditQueuedActionError, EditQueuedActionErrors, EditQueuedActionRequest, EditQueuedActionResponse, EditQueuedActionResponses, ElicitationAnswer, ElicitationContentValue, ElicitationRequestId, EmptyRequest, ExternalSessionResponse, FileChangeKindDto, GetAgentSandboxSizeData, GetAgentSandboxSizeError, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponse, GetAgentSandboxSizeResponses, GetAgentSessionChangesData, GetAgentSessionChangesError, GetAgentSessionChangesErrors, GetAgentSessionChangesPatchData, GetAgentSessionChangesPatchError, GetAgentSessionChangesPatchErrors, GetAgentSessionChangesPatchResponse, GetAgentSessionChangesPatchResponses, GetAgentSessionChangesResponse, GetAgentSessionChangesResponses, GetAgentSessionData, GetAgentSessionError, GetAgentSessionErrors, GetAgentSessionLogData, GetAgentSessionLogError, GetAgentSessionLogErrors, GetAgentSessionLogResponse, GetAgentSessionLogResponses, GetAgentSessionQueueData, GetAgentSessionQueueError, GetAgentSessionQueueErrors, GetAgentSessionQueueResponse, GetAgentSessionQueueResponses, GetAgentSessionResponse, GetAgentSessionResponses, GitRefDto, ListAgentRepositoriesData, ListAgentRepositoriesErrors, ListAgentRepositoriesResponse, ListAgentRepositoriesResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponse, LoadAgentModelsHandlerResponses, LoadAgentModelsRequest, LoadAgentModelsResponse, LogDirectionDto, LogFrameDto, MessageParent, ModelHarnessDto, PreviewAgentSessionsData, PreviewAgentSessionsError, PreviewAgentSessionsErrors, PreviewAgentSessionsRequest, PreviewAgentSessionsResponse, PreviewAgentSessionsResponse2, PreviewAgentSessionsResponses, PromptAttachment, PutAgentSandboxSizeData, PutAgentSandboxSizeError, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponse, PutAgentSandboxSizeResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeError, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponse, PutAgentSessionSandboxSizeResponses, QueuedActionDto, RefreshAgentSessionChangesData, RefreshAgentSessionChangesError, RefreshAgentSessionChangesErrors, RefreshAgentSessionChangesResponse, RefreshAgentSessionChangesResponses, RemoveQueuedActionData, RemoveQueuedActionError, RemoveQueuedActionErrors, RemoveQueuedActionResponse, RemoveQueuedActionResponses, RenameAgentSessionData, RenameAgentSessionError, RenameAgentSessionErrors, RenameAgentSessionRequest, RenameAgentSessionResponse, RenameAgentSessionResponses, SandboxSize, SandboxSizeBody, SessionBot, SessionStatusDto, StartData, StartErrors, StartResponse, StartResponse2, StartResponses, StatusData, StatusErrors, StatusResponse, StatusResponse2, StatusResponses, WithAgentSessionId } from './types.gen';
+export type { AgentAction, AgentActionId, AgentModelDto, AgentModelsStatusDto, AgentPermissionAction, AgentPromptAction, AgentRepositoriesResponse, AgentRepositoryDto, AgentRespondElicitationAction, AgentSessionChangesPatchResponse, AgentSessionChangesResponse, AgentSessionLogEntryDto, AgentSessionLogResponse, AgentSessionPreviewData, AgentSessionPreviewDto, AgentSessionQueueResponse, AgentSessionResponse, AgentSetModelAction, BotId, CaptureAttemptDto, CaptureOutcomeDto, ChangedFileDto, ChangesetDto, ChangesetSourceDto, ClientOptions, CompleteData, CompleteErrors, CompleteRequest, CompleteResponse, CompleteResponses, ControlAgentSessionData, ControlAgentSessionError, ControlAgentSessionErrors, ControlAgentSessionResponse, ControlAgentSessionResponses, ControlRequest, ControlResponse, ControlStatusDto, CreateAgentSessionData, CreateAgentSessionError, CreateAgentSessionErrors, CreateAgentSessionRequest, CreateAgentSessionResponse, CreateAgentSessionResponse2, CreateAgentSessionResponses, CreateSessionThread, DeleteAgentSessionData, DeleteAgentSessionError, DeleteAgentSessionErrors, DeleteAgentSessionResponses, DisconnectData, DisconnectErrors, DisconnectResponse, DisconnectResponses, DocumentId, EditQueuedActionData, EditQueuedActionError, EditQueuedActionErrors, EditQueuedActionRequest, EditQueuedActionResponse, EditQueuedActionResponses, ElicitationAnswer, ElicitationContentValue, ElicitationRequestId, EmptyRequest, ExternalSessionResponse, FileChangeKindDto, GetAgentSandboxSizeData, GetAgentSandboxSizeError, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponse, GetAgentSandboxSizeResponses, GetAgentSessionChangesData, GetAgentSessionChangesError, GetAgentSessionChangesErrors, GetAgentSessionChangesPatchData, GetAgentSessionChangesPatchError, GetAgentSessionChangesPatchErrors, GetAgentSessionChangesPatchResponse, GetAgentSessionChangesPatchResponses, GetAgentSessionChangesResponse, GetAgentSessionChangesResponses, GetAgentSessionData, GetAgentSessionError, GetAgentSessionErrors, GetAgentSessionLogData, GetAgentSessionLogError, GetAgentSessionLogErrors, GetAgentSessionLogResponse, GetAgentSessionLogResponses, GetAgentSessionQueueData, GetAgentSessionQueueError, GetAgentSessionQueueErrors, GetAgentSessionQueueResponse, GetAgentSessionQueueResponses, GetAgentSessionResponse, GetAgentSessionResponses, GitRefDto, ListAgentRepositoriesData, ListAgentRepositoriesErrors, ListAgentRepositoriesResponse, ListAgentRepositoriesResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponse, LoadAgentModelsHandlerResponses, LoadAgentModelsRequest, LoadAgentModelsResponse, LogDirectionDto, LogFrameDto, MessageParent, ModelHarnessDto, PermissionAnswer, PreviewAgentSessionsData, PreviewAgentSessionsError, PreviewAgentSessionsErrors, PreviewAgentSessionsRequest, PreviewAgentSessionsResponse, PreviewAgentSessionsResponse2, PreviewAgentSessionsResponses, PromptAttachment, PutAgentSandboxSizeData, PutAgentSandboxSizeError, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponse, PutAgentSandboxSizeResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeError, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponse, PutAgentSessionSandboxSizeResponses, QueuedActionDto, RefreshAgentSessionChangesData, RefreshAgentSessionChangesError, RefreshAgentSessionChangesErrors, RefreshAgentSessionChangesResponse, RefreshAgentSessionChangesResponses, RemoveQueuedActionData, RemoveQueuedActionError, RemoveQueuedActionErrors, RemoveQueuedActionResponse, RemoveQueuedActionResponses, RenameAgentSessionData, RenameAgentSessionError, RenameAgentSessionErrors, RenameAgentSessionRequest, RenameAgentSessionResponse, RenameAgentSessionResponses, SandboxSize, SandboxSizeBody, SessionBot, SessionStatusDto, StartData, StartErrors, StartResponse, StartResponse2, StartResponses, StatusData, StatusErrors, StatusResponse, StatusResponse2, StatusResponses, WithAgentSessionId } from './types.gen';
diff --git a/packages/sdk/generated/agent-harness/types.gen.ts b/packages/sdk/generated/agent-harness/types.gen.ts
index fe1f6625dc..a376e602f5 100644
--- a/packages/sdk/generated/agent-harness/types.gen.ts
+++ b/packages/sdk/generated/agent-harness/types.gen.ts
@@ -17,6 +17,8 @@ export type AgentAction = (AgentPromptAction & {
type: 'stop';
} | (AgentRespondElicitationAction & {
type: 'respondElicitation';
+}) | (AgentPermissionAction & {
+ type: 'respondToPermission';
});
/**
@@ -61,6 +63,26 @@ export type AgentModelDto = {
*/
export type AgentModelsStatusDto = 'available' | 'unsupported';
+/**
+ * A user's answer to the agent's `session/request_permission`.
+ *
+ * Unlike every other action this is not a new request but the reply to one
+ * the agent made, so it carries the agent's own request id rather than
+ * receiving a server-minted one.
+ */
+export type AgentPermissionAction = {
+ /**
+ * What the user decided.
+ */
+ answer: PermissionAnswer;
+ /**
+ * The agent's JSON-RPC request id, echoed verbatim from the folded
+ * permission part. A string or a number on the wire; agents mint both,
+ * and `7` does not answer `"7"`.
+ */
+ requestId: unknown;
+};
+
/**
* Ask the agent to work on something.
*/
@@ -838,6 +860,19 @@ export type MessageParent = {
*/
export type ModelHarnessDto = 'in-memory' | 'cursor' | 'claude-cloud' | 'macrod';
+/**
+ * The decision carried by an [`AgentPermissionAction`].
+ */
+export type PermissionAnswer = {
+ kind: 'selected';
+ /**
+ * The chosen option's id, as the agent listed it.
+ */
+ optionId: string;
+} | {
+ kind: 'cancelled';
+};
+
/**
* Request body for `POST /agent-sessions/preview`.
*
diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.ts
index b219646856..d050ef8e7b 100644
--- a/packages/sdk/generated/storage/types.gen.ts
+++ b/packages/sdk/generated/storage/types.gen.ts
@@ -90,6 +90,11 @@ export type AddPinRequest = {
* A persisted user- or team-owned AI agent.
*/
export type Agent = {
+ /**
+ * Whether the agent's sessions approve ACP permission requests without
+ * asking. `None` means always prompt. Bypass also requires the harness's opt-in.
+ */
+ auto_accept_permissions?: boolean | null;
/**
* The bot identity used for mentions and channel participation.
*/
@@ -1122,6 +1127,10 @@ export type ApiThreadReply = {
* Request to approve a pairing and register the harness.
*/
export type ApprovePairingRequest = {
+ /**
+ * Whether agents may bypass ACP permission requests on this harness.
+ */
+ allow_permission_bypass?: boolean;
/**
* Display name override. Defaults to the daemon's requested name.
*/
@@ -3076,6 +3085,11 @@ export type CountedReaction = {
* Request to create a persisted AI agent.
*/
export type CreateAgentRequest = {
+ /**
+ * Whether the agent's sessions approve ACP permission requests without
+ * asking. Omit to always prompt.
+ */
+ auto_accept_permissions?: boolean | null;
/**
* Optional avatar URL or data URL.
*/
@@ -3541,6 +3555,10 @@ export type CreateMarkdownDocumentResponse = {
* The daemon serializes this, so both derives are used.
*/
export type CreatePairingRequest = {
+ /**
+ * Daemon operator consent ceiling. Omitted by older clients; web approval decides.
+ */
+ allow_permission_bypass?: boolean | null;
/**
* Display-only description of the machine, e.g. `eric@macbook / darwin`.
*/
@@ -6270,6 +6288,10 @@ export type GroupedSoupSort = 'viewed_at' | 'created_at' | 'updated_at' | 'viewe
* Clients deserialize this, so both derives are used.
*/
export type Harness = {
+ /**
+ * Whether agents may bypass ACP permission requests on this harness.
+ */
+ allow_permission_bypass?: boolean;
/**
* Whether the daemon currently holds a runtime connection.
*/
@@ -7108,6 +7130,10 @@ export type PairingDetails = {
* Display-only description of the machine.
*/
host?: string | null;
+ /**
+ * Daemon operator consent ceiling; false forbids bypass at approval.
+ */
+ requested_allow_permission_bypass?: boolean | null;
/**
* Harness display name the daemon asked for.
*/
@@ -10091,6 +10117,11 @@ export type UnthreadedPdfUuidRequest = {
* Request to replace the editable configuration of a persisted AI agent.
*/
export type UpdateAgentRequest = {
+ /**
+ * Whether the agent's sessions approve ACP permission requests without
+ * asking. Omit to always prompt.
+ */
+ auto_accept_permissions?: boolean | null;
/**
* Optional avatar URL or data URL.
*/
diff --git a/packages/sdk/specs/agent-harness.json b/packages/sdk/specs/agent-harness.json
index 136eda6e54..42d0ef5f75 100644
--- a/packages/sdk/specs/agent-harness.json
+++ b/packages/sdk/specs/agent-harness.json
@@ -1354,6 +1354,25 @@
}
],
"description": "Answer an `elicitation/create` the agent sent.\n\nThe one action whose wire form is a JSON-RPC *response* rather than a\nrequest or notification: the agent asked, we answer on its id. The\nminted [`AgentActionId`] therefore never reaches the wire for this\naction; the fold correlates on the agent's id instead."
+ },
+ {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/AgentPermissionAction",
+ "description": "Answer a permission request the agent is waiting on."
+ },
+ {
+ "type": "object",
+ "required": ["type"],
+ "properties": {
+ "type": {
+ "type": "string",
+ "enum": ["respondToPermission"]
+ }
+ }
+ }
+ ],
+ "description": "Answer a permission request the agent is waiting on."
}
],
"description": "One thing a caller wants an agent to do."
@@ -1391,6 +1410,20 @@
"description": "Model-selection availability returned over HTTP.",
"enum": ["available", "unsupported"]
},
+ "AgentPermissionAction": {
+ "type": "object",
+ "description": "A user's answer to the agent's `session/request_permission`.\n\nUnlike every other action this is not a new request but the reply to one\nthe agent made, so it carries the agent's own request id rather than\nreceiving a server-minted one.",
+ "required": ["requestId", "answer"],
+ "properties": {
+ "answer": {
+ "$ref": "#/components/schemas/PermissionAnswer",
+ "description": "What the user decided."
+ },
+ "requestId": {
+ "description": "The agent's JSON-RPC request id, echoed verbatim from the folded\npermission part. A string or a number on the wire; agents mint both,\nand `7` does not answer `\"7\"`."
+ }
+ }
+ },
"AgentPromptAction": {
"type": "object",
"description": "Ask the agent to work on something.",
@@ -2387,6 +2420,37 @@
"description": "Harness names accepted by the model discovery endpoint.",
"enum": ["in-memory", "cursor", "claude-cloud", "macrod"]
},
+ "PermissionAnswer": {
+ "oneOf": [
+ {
+ "type": "object",
+ "description": "One of the options the agent offered was chosen.",
+ "required": ["optionId", "kind"],
+ "properties": {
+ "kind": {
+ "type": "string",
+ "enum": ["selected"]
+ },
+ "optionId": {
+ "type": "string",
+ "description": "The chosen option's id, as the agent listed it."
+ }
+ }
+ },
+ {
+ "type": "object",
+ "description": "The request was dismissed without choosing.",
+ "required": ["kind"],
+ "properties": {
+ "kind": {
+ "type": "string",
+ "enum": ["cancelled"]
+ }
+ }
+ }
+ ],
+ "description": "The decision carried by an [`AgentPermissionAction`]."
+ },
"PreviewAgentSessionsRequest": {
"type": "object",
"description": "Request body for `POST /agent-sessions/preview`.\n\nClients serialize this, so both derives are used.",
diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.json
index 240858172b..b68126c5dc 100644
--- a/packages/sdk/specs/storage.json
+++ b/packages/sdk/specs/storage.json
@@ -14287,6 +14287,10 @@
"mcp"
],
"properties": {
+ "auto_accept_permissions": {
+ "type": ["boolean", "null"],
+ "description": "Whether the agent's sessions approve ACP permission requests without\nasking. `None` means always prompt. Bypass also requires the harness's opt-in."
+ },
"bot": {
"$ref": "#/components/schemas/Bot",
"description": "The bot identity used for mentions and channel participation."
@@ -15861,6 +15865,10 @@
"type": "object",
"description": "Request to approve a pairing and register the harness.",
"properties": {
+ "allow_permission_bypass": {
+ "type": "boolean",
+ "description": "Whether agents may bypass ACP permission requests on this harness."
+ },
"name": {
"type": ["string", "null"],
"description": "Display name override. Defaults to the daemon's requested name."
@@ -18628,6 +18636,10 @@
"channel_scope"
],
"properties": {
+ "auto_accept_permissions": {
+ "type": ["boolean", "null"],
+ "description": "Whether the agent's sessions approve ACP permission requests without\nasking. Omit to always prompt."
+ },
"avatar_url": {
"type": ["string", "null"],
"description": "Optional avatar URL or data URL."
@@ -19235,6 +19247,10 @@
"description": "Request to open a pairing: the daemon asks for a code the user approves.\n\nThe daemon serializes this, so both derives are used.",
"required": ["name"],
"properties": {
+ "allow_permission_bypass": {
+ "type": ["boolean", "null"],
+ "description": "Daemon operator consent ceiling. Omitted by older clients; web approval decides."
+ },
"host": {
"type": ["string", "null"],
"description": "Display-only description of the machine, e.g. `eric@macbook / darwin`."
@@ -23829,6 +23845,10 @@
"connected"
],
"properties": {
+ "allow_permission_bypass": {
+ "type": "boolean",
+ "description": "Whether agents may bypass ACP permission requests on this harness."
+ },
"connected": {
"type": "boolean",
"description": "Whether the daemon currently holds a runtime connection."
@@ -25150,6 +25170,10 @@
"type": ["string", "null"],
"description": "Display-only description of the machine."
},
+ "requested_allow_permission_bypass": {
+ "type": ["boolean", "null"],
+ "description": "Daemon operator consent ceiling; false forbids bypass at approval."
+ },
"requested_name": {
"type": "string",
"description": "Harness display name the daemon asked for."
@@ -30037,6 +30061,10 @@
"channel_scope"
],
"properties": {
+ "auto_accept_permissions": {
+ "type": ["boolean", "null"],
+ "description": "Whether the agent's sessions approve ACP permission requests without\nasking. Omit to always prompt."
+ },
"avatar_url": {
"type": ["string", "null"],
"description": "Optional avatar URL or data URL."
diff --git a/rules/ast-grep/ts-feature-components-presentational.yml b/rules/ast-grep/ts-feature-components-presentational.yml
index a2005291f8..731db77708 100644
--- a/rules/ast-grep/ts-feature-components-presentational.yml
+++ b/rules/ast-grep/ts-feature-components-presentational.yml
@@ -10,8 +10,10 @@ note: |-
navigation helpers. It renders what views hand it: domain values from
`core/`, resolved display (typed in `context/`), and event handlers. The
one sanctioned `queries/` import is `property-value`, which parses
- untyped wire JSON for property-changed rows.
+ untyped wire JSON for property-changed rows. In block-agent, `ui/` is
+ the presentation layer and `component/` is the composition layer.
files:
+ - apps/web/src/features/block-agent/ui/**
- apps/web/src/features/block-spreadsheet/components/**
- apps/web/src/features/property/tags/components/**
- apps/web/src/features/claude-connection/components/**
@@ -24,7 +26,7 @@ files:
rule:
any:
- kind: string
- regex: ^['"](@queries/|@urql|urql|@app/lib/urql|@core/util/useSplitNavigationHandler|(\.\./)+(primitives|views)/)
+ regex: ^['"](@queries/|@urql|urql|@app/lib/urql|@core/util/useSplitNavigationHandler|(\.\./)+(primitives|views|component)(/|['"]))
any:
- inside:
kind: import_statement
diff --git a/rules/ast-grep/ts-feature-core-pure.yml b/rules/ast-grep/ts-feature-core-pure.yml
index 2665eaafc7..a2513fbfb1 100644
--- a/rules/ast-grep/ts-feature-core-pure.yml
+++ b/rules/ast-grep/ts-feature-core-pure.yml
@@ -13,7 +13,9 @@ note: |-
`soup/collection/date-buckets` (a pure date-fns module, not the soup barrel)
is the documented exception for feed labels that must match soup views.
The shared @core/util/base64 codec is also pure and may be reused by email.
+ Block-agent names its rendering layers `ui/` and `component/`.
files:
+ - apps/web/src/features/block-agent/core/**
- apps/web/src/features/block-spreadsheet/core/**
- apps/web/src/features/property/tags/core/**
- apps/web/src/features/claude-connection/core/**
@@ -25,7 +27,7 @@ files:
- apps/web/src/features/agent-changes/core/**
rule:
kind: string
- regex: ^['"](solid-js|@urql|urql|@app/lib/urql|@queries/|@service-storage/|@core/|@property/|@components/|@ui|@entity/|(\.\./)+(queries|primitives|components|views)/|(\.\./)+context/)
+ regex: ^['"](solid-js|@urql|urql|@app/lib/urql|@queries/|@service-storage/|@core/|@property/|@components/|@ui|@entity/|(\.\./)+(queries|primitives|components|views|ui|component|context)(/|['"]))
not:
regex: ^['"]@core/util/base64['"]
any:
diff --git a/rules/ast-grep/ts-feature-data-no-ui.yml b/rules/ast-grep/ts-feature-data-no-ui.yml
index c3e055b227..7eb152be55 100644
--- a/rules/ast-grep/ts-feature-data-no-ui.yml
+++ b/rules/ast-grep/ts-feature-data-no-ui.yml
@@ -9,8 +9,10 @@ note: |-
builds query factories; `primitives/` consumes feature-owned capabilities
to produce state and actions with Solid primitives but no JSX. Test adapters
with fake clients and controllers with fake capabilities; neither imports
- rendering code.
+ rendering code, including block-agent’s `ui/` and `component/` layers.
files:
+ - apps/web/src/features/block-agent/queries/**
+ - apps/web/src/features/block-agent/primitives/**
- apps/web/src/features/block-spreadsheet/queries/**
- apps/web/src/features/block-spreadsheet/primitives/**
- apps/web/src/features/property/tags/queries/**
@@ -30,7 +32,7 @@ files:
- apps/web/src/features/agent-changes/primitives/**
rule:
kind: string
- regex: ^['"](solid-js/web|@ui|@components/|(\.\./)+(components|views)/)
+ regex: ^['"](solid-js/web|@ui|@components/|(\.\./)+(components|views|ui|component)(/|['"]))
any:
- inside:
kind: import_statement
diff --git a/rules/ast-grep/ts-feature-layers-use-context.yml b/rules/ast-grep/ts-feature-layers-use-context.yml
index c7c8483a93..a7bd9661b5 100644
--- a/rules/ast-grep/ts-feature-layers-use-context.yml
+++ b/rules/ast-grep/ts-feature-layers-use-context.yml
@@ -12,8 +12,13 @@ note: |-
feature's `Context` record so every layer runs against mocks in tests. Keep `context/` free of production imports. Only production entry points
and adapters at the feature root construct app capabilities. The pure
`@core/user/macroId` identity helpers are a documented exception. Adopting features add their layer paths to
- `files` in each ts-/tsx-feature-* rule.
+ `files` in each ts-/tsx-feature-* rule. Block-agent uses `ui/` for
+ presentation and `component/` for composition.
files:
+ - apps/web/src/features/block-agent/queries/**
+ - apps/web/src/features/block-agent/primitives/**
+ - apps/web/src/features/block-agent/ui/**
+ - apps/web/src/features/block-agent/component/**
- apps/web/src/features/block-spreadsheet/queries/**
- apps/web/src/features/block-spreadsheet/primitives/**
- apps/web/src/features/block-spreadsheet/components/**
diff --git a/rules/ast-grep/tsx-feature-components-presentational.yml b/rules/ast-grep/tsx-feature-components-presentational.yml
index e3e774e94c..672c66d080 100644
--- a/rules/ast-grep/tsx-feature-components-presentational.yml
+++ b/rules/ast-grep/tsx-feature-components-presentational.yml
@@ -10,8 +10,10 @@ note: |-
navigation helpers. It renders what views hand it: domain values from
`core/`, resolved display (typed in `context/`), and event handlers. The
one sanctioned `queries/` import is `property-value`, which parses
- untyped wire JSON for property-changed rows.
+ untyped wire JSON for property-changed rows. In block-agent, `ui/` is
+ the presentation layer and `component/` is the composition layer.
files:
+ - apps/web/src/features/block-agent/ui/**
- apps/web/src/features/block-spreadsheet/components/**
- apps/web/src/features/property/tags/components/**
- apps/web/src/features/claude-connection/components/**
@@ -24,7 +26,7 @@ files:
rule:
any:
- kind: string
- regex: ^['"](@queries/|@urql|urql|@app/lib/urql|@core/util/useSplitNavigationHandler|(\.\./)+(primitives|views)/)
+ regex: ^['"](@queries/|@urql|urql|@app/lib/urql|@core/util/useSplitNavigationHandler|(\.\./)+(primitives|views|component)(/|['"]))
any:
- inside:
kind: import_statement
diff --git a/rules/ast-grep/tsx-feature-core-pure.yml b/rules/ast-grep/tsx-feature-core-pure.yml
index d95046be0c..3211ace6fe 100644
--- a/rules/ast-grep/tsx-feature-core-pure.yml
+++ b/rules/ast-grep/tsx-feature-core-pure.yml
@@ -13,7 +13,9 @@ note: |-
`soup/collection/date-buckets` (a pure date-fns module, not the soup barrel)
is the documented exception for feed labels that must match soup views.
The shared @core/util/base64 codec is also pure and may be reused by email.
+ Block-agent names its rendering layers `ui/` and `component/`.
files:
+ - apps/web/src/features/block-agent/core/**
- apps/web/src/features/block-spreadsheet/core/**
- apps/web/src/features/property/tags/core/**
- apps/web/src/features/claude-connection/core/**
@@ -25,7 +27,7 @@ files:
- apps/web/src/features/agent-changes/core/**
rule:
kind: string
- regex: ^['"](solid-js|@urql|urql|@app/lib/urql|@queries/|@service-storage/|@core/|@property/|@components/|@ui|@entity/|(\.\./)+(queries|primitives|components|views)/|(\.\./)+context/)
+ regex: ^['"](solid-js|@urql|urql|@app/lib/urql|@queries/|@service-storage/|@core/|@property/|@components/|@ui|@entity/|(\.\./)+(queries|primitives|components|views|ui|component|context)(/|['"]))
not:
regex: ^['"]@core/util/base64['"]
any:
diff --git a/rules/ast-grep/tsx-feature-data-no-ui.yml b/rules/ast-grep/tsx-feature-data-no-ui.yml
index e68a80a10a..8f6bc2fa91 100644
--- a/rules/ast-grep/tsx-feature-data-no-ui.yml
+++ b/rules/ast-grep/tsx-feature-data-no-ui.yml
@@ -9,8 +9,10 @@ note: |-
builds query factories; `primitives/` consumes feature-owned capabilities
to produce state and actions with Solid primitives but no JSX. Test adapters
with fake clients and controllers with fake capabilities; neither imports
- rendering code.
+ rendering code, including block-agent’s `ui/` and `component/` layers.
files:
+ - apps/web/src/features/block-agent/queries/**
+ - apps/web/src/features/block-agent/primitives/**
- apps/web/src/features/block-spreadsheet/queries/**
- apps/web/src/features/block-spreadsheet/primitives/**
- apps/web/src/features/property/tags/queries/**
@@ -30,7 +32,7 @@ files:
- apps/web/src/features/agent-changes/primitives/**
rule:
kind: string
- regex: ^['"](solid-js/web|@ui|@components/|(\.\./)+(components|views)/)
+ regex: ^['"](solid-js/web|@ui|@components/|(\.\./)+(components|views|ui|component)(/|['"]))
any:
- inside:
kind: import_statement
diff --git a/rules/ast-grep/tsx-feature-layers-use-context.yml b/rules/ast-grep/tsx-feature-layers-use-context.yml
index b8ba8c6be4..0e40d891f6 100644
--- a/rules/ast-grep/tsx-feature-layers-use-context.yml
+++ b/rules/ast-grep/tsx-feature-layers-use-context.yml
@@ -12,8 +12,13 @@ note: |-
feature's `Context` record so every layer runs against mocks in tests. Keep `context/` free of production imports. Only production entry points
and adapters at the feature root construct app capabilities. The pure
`@core/user/macroId` identity helpers are a documented exception. Adopting features add their layer paths to
- `files` in each ts-/tsx-feature-* rule.
+ `files` in each ts-/tsx-feature-* rule. Block-agent uses `ui/` for
+ presentation and `component/` for composition.
files:
+ - apps/web/src/features/block-agent/queries/**
+ - apps/web/src/features/block-agent/primitives/**
+ - apps/web/src/features/block-agent/ui/**
+ - apps/web/src/features/block-agent/component/**
- apps/web/src/features/block-spreadsheet/queries/**
- apps/web/src/features/block-spreadsheet/primitives/**
- apps/web/src/features/block-spreadsheet/components/**
diff --git a/services/agent_harness_service/src/bots_directory.rs b/services/agent_harness_service/src/bots_directory.rs
index aa7e6f570e..79fd05a722 100644
--- a/services/agent_harness_service/src/bots_directory.rs
+++ b/services/agent_harness_service/src/bots_directory.rs
@@ -65,14 +65,12 @@ impl BotDirectory for PgBotDirectory {
let selected_channels = agent
.as_ref()
.is_some_and(|agent| agent.channel_scope == AgentChannelScope::Selected);
- let managed_profile = agent
- .filter(|_| is_managed)
- .map(|agent| ManagedAgentProfile {
- model: agent.default_model,
- harness: agent.harness,
- instructions: agent.instructions,
- mcp_servers: agent.mcp,
- });
+ let managed_profile = agent.map(|agent| ManagedAgentProfile {
+ model: agent.default_model,
+ harness: agent.harness,
+ instructions: agent.instructions,
+ mcp_servers: agent.mcp,
+ });
(is_managed, harness_id, managed_profile, selected_channels)
} else {
(false, None, None, false)
diff --git a/services/agent_harness_service/src/main.rs b/services/agent_harness_service/src/main.rs
index 54c2453337..d3cef25d94 100644
--- a/services/agent_harness_service/src/main.rs
+++ b/services/agent_harness_service/src/main.rs
@@ -15,6 +15,7 @@ mod containers;
mod harness_bindings;
mod internal_mcp;
mod model_providers;
+mod permission_policy;
mod runtime_commands;
mod trigger;
@@ -125,6 +126,7 @@ use macro_service_urls::{
StaticFileServiceUrl,
};
use model_providers::{CursorModels, InMemoryModels, MacrodModels, VisibleHarnessAccess};
+use permission_policy::PgPermissionPolicySource;
use pipedream_mcp::outbound::api::{PipedreamClient, PipedreamConfig};
use pipedream_mcp::outbound::pg_connection_repo::PgConnectionRepo;
use rdkafka::consumer::CommitMode;
@@ -823,6 +825,7 @@ async fn run() -> anyhow::Result<()> {
prompt_composer,
EgressProvisioner::new(Arc::clone(&mcp_connections), egress_base_url),
RedisCommandForwarder::new(redis.clone()),
+ PgPermissionPolicySource::new(PgBotsRepo::new(pool.clone())),
defaults,
Arc::clone(&lifecycle_publisher),
pending_commands,
diff --git a/services/agent_harness_service/src/permission_policy.rs b/services/agent_harness_service/src/permission_policy.rs
new file mode 100644
index 0000000000..d829cdb3fd
--- /dev/null
+++ b/services/agent_harness_service/src/permission_policy.rs
@@ -0,0 +1,45 @@
+//! Postgres-backed permission policies for fixed and database-backed agents.
+
+use agent_harness::domain::model::{AgentKind, PermissionPolicyConfig};
+use agent_harness::domain::ports::PermissionPolicySource;
+use bot_id::BotId;
+use bots::domain::ports::BotRepo;
+use bots::outbound::pg_bots_repo::PgBotsRepo;
+
+/// Reads the persona choice and the harness operator's bypass opt-in.
+/// Fixed system bots retain
+/// their built-in policy.
+#[derive(Clone)]
+pub struct PgPermissionPolicySource {
+ repo: PgBotsRepo,
+}
+
+impl PgPermissionPolicySource {
+ /// Build the source over the bots repository.
+ pub fn new(repo: PgBotsRepo) -> Self {
+ Self { repo }
+ }
+}
+
+impl PermissionPolicySource for PgPermissionPolicySource {
+ async fn permission_policy(&self, bot: BotId) -> anyhow::Result<PermissionPolicyConfig> {
+ let agent = self.repo.get_agent(bot).await?;
+ let Some(agent) = agent else {
+ return Ok(PermissionPolicyConfig::Fixed(AgentKind::of(bot)));
+ };
+ let harness_allows_bypass = match agent.harness_id {
+ Some(harness) => Some(
+ self.repo
+ .get_harness_facts(harness)
+ .await?
+ .is_some_and(|facts| facts.allow_permission_bypass),
+ ),
+ None => None,
+ };
+ Ok(PermissionPolicyConfig::Persona {
+ kind: AgentKind::for_session(bot, &agent.harness),
+ harness_allows_bypass,
+ auto_accept_permissions: agent.auto_accept_permissions,
+ })
+ }
+}
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main.rs
index ece5a37641..9896ca5330 100644
--- a/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main.rs
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main.rs
@@ -118,6 +118,8 @@ fn cycles() -> Job {
fn build() -> Job {
gated_web_job("Build")
+ // Match preview/deploy capacity for Vite's chunk-rendering memory peak.
+ .runs_on(runners::Runner::Mid.with_cache_tag(vars::WEB_CI_CACHE_TAG))
.add_step(checkout("Checkout Repo", false))
.add_step(steps::mount_web_cache_volume(false))
.add_step(steps::setup_nix())