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-harness): per-session instructions (#6016)

Eric Hayese31d90eeba43
diff --git a/.sqlx/query-f99b8550fdb6c82da89f3b8a66142290daab84ae3b10f784825276a9f2ff6317.json b/.sqlx/query-157e3c11a5b3d87c3a6be9c39ccb6d105b569db6d68f2154b97dbd3c129187ca.json
similarity index 73%
rename from .sqlx/query-f99b8550fdb6c82da89f3b8a66142290daab84ae3b10f784825276a9f2ff6317.json
rename to .sqlx/query-157e3c11a5b3d87c3a6be9c39ccb6d105b569db6d68f2154b97dbd3c129187ca.json
index a7389b6b32..0ccbefde62 100644
--- a/.sqlx/query-f99b8550fdb6c82da89f3b8a66142290daab84ae3b10f784825276a9f2ff6317.json
+++ b/.sqlx/query-157e3c11a5b3d87c3a6be9c39ccb6d105b569db6d68f2154b97dbd3c129187ca.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n id, name, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, workspace, sandbox_size, acp_session_id, status,\n status_event_name, agent_session.created_at, modified_at,\n (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE thread_id = $1\n ORDER BY agent_session.created_at DESC\n ",
+ "query": "\n SELECT\n id, name, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, workspace, sandbox_size, instructions,\n acp_session_id, status,\n status_event_name, agent_session.created_at, modified_at,\n (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE thread_id = $1\n ORDER BY agent_session.created_at DESC\n ",
"describe": {
"columns": [
{
@@ -60,51 +60,56 @@
},
{
"ordinal": 11,
- "name": "acp_session_id",
+ "name": "instructions",
"type_info": "Text"
},
{
"ordinal": 12,
- "name": "status",
+ "name": "acp_session_id",
"type_info": "Text"
},
{
"ordinal": 13,
- "name": "status_event_name",
+ "name": "status",
"type_info": "Text"
},
{
"ordinal": 14,
+ "name": "status_event_name",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 15,
"name": "created_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 15,
+ "ordinal": 16,
"name": "modified_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 16,
+ "ordinal": 17,
"name": "thread_channel_id?",
"type_info": "Uuid"
},
{
- "ordinal": 17,
+ "ordinal": 18,
"name": "external_provider?",
"type_info": "Text"
},
{
- "ordinal": 18,
+ "ordinal": 19,
"name": "external_id?",
"type_info": "Text"
},
{
- "ordinal": 19,
+ "ordinal": 20,
"name": "external_name?",
"type_info": "Text"
},
{
- "ordinal": 20,
+ "ordinal": 21,
"name": "external_url?",
"type_info": "Text"
}
@@ -127,6 +132,7 @@
false,
false,
true,
+ true,
false,
true,
false,
@@ -138,5 +144,5 @@
true
]
},
- "hash": "f99b8550fdb6c82da89f3b8a66142290daab84ae3b10f784825276a9f2ff6317"
+ "hash": "157e3c11a5b3d87c3a6be9c39ccb6d105b569db6d68f2154b97dbd3c129187ca"
}
diff --git a/.sqlx/query-71e4d8840c1d337af853e4b6d6d25ccf7f6126ff9d96105b04868a5367ad8b92.json b/.sqlx/query-4993e942985404ec388cc858815e82d08ad0185cfaa24300545f290e1ba87e49.json
similarity index 72%
rename from .sqlx/query-71e4d8840c1d337af853e4b6d6d25ccf7f6126ff9d96105b04868a5367ad8b92.json
rename to .sqlx/query-4993e942985404ec388cc858815e82d08ad0185cfaa24300545f290e1ba87e49.json
index 368d0560ab..bfed426c57 100644
--- a/.sqlx/query-71e4d8840c1d337af853e4b6d6d25ccf7f6126ff9d96105b04868a5367ad8b92.json
+++ b/.sqlx/query-4993e942985404ec388cc858815e82d08ad0185cfaa24300545f290e1ba87e49.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n INSERT INTO agent_session (\n id, owner_id, thread_id, originating_message_id, bot_id, model,\n harness, repo_url, workspace, sandbox_size, acp_session_id, status,\n status_event_name, egress_token_hash\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)\n RETURNING\n id, name, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, workspace, sandbox_size, acp_session_id, status,\n status_event_name, created_at, modified_at,\n (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\",\n -- A row being created cannot have an external identity yet.\n NULL::TEXT AS \"external_provider?\", NULL::TEXT AS \"external_id?\",\n NULL::TEXT AS \"external_name?\", NULL::TEXT AS \"external_url?\"\n ",
+ "query": "\n INSERT INTO agent_session (\n id, owner_id, thread_id, originating_message_id, bot_id, model,\n harness, repo_url, workspace, sandbox_size, instructions,\n acp_session_id, status, status_event_name, egress_token_hash\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15)\n RETURNING\n id, name, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, workspace, sandbox_size, instructions,\n acp_session_id, status,\n status_event_name, created_at, modified_at,\n (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\",\n -- A row being created cannot have an external identity yet.\n NULL::TEXT AS \"external_provider?\", NULL::TEXT AS \"external_id?\",\n NULL::TEXT AS \"external_name?\", NULL::TEXT AS \"external_url?\"\n ",
"describe": {
"columns": [
{
@@ -60,51 +60,56 @@
},
{
"ordinal": 11,
- "name": "acp_session_id",
+ "name": "instructions",
"type_info": "Text"
},
{
"ordinal": 12,
- "name": "status",
+ "name": "acp_session_id",
"type_info": "Text"
},
{
"ordinal": 13,
- "name": "status_event_name",
+ "name": "status",
"type_info": "Text"
},
{
"ordinal": 14,
+ "name": "status_event_name",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 15,
"name": "created_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 15,
+ "ordinal": 16,
"name": "modified_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 16,
+ "ordinal": 17,
"name": "thread_channel_id?",
"type_info": "Uuid"
},
{
- "ordinal": 17,
+ "ordinal": 18,
"name": "external_provider?",
"type_info": "Text"
},
{
- "ordinal": 18,
+ "ordinal": 19,
"name": "external_id?",
"type_info": "Text"
},
{
- "ordinal": 19,
+ "ordinal": 20,
"name": "external_name?",
"type_info": "Text"
},
{
- "ordinal": 20,
+ "ordinal": 21,
"name": "external_url?",
"type_info": "Text"
}
@@ -124,6 +129,7 @@
"Text",
"Text",
"Text",
+ "Text",
"Text"
]
},
@@ -140,6 +146,7 @@
false,
false,
true,
+ true,
false,
true,
false,
@@ -151,5 +158,5 @@
null
]
},
- "hash": "71e4d8840c1d337af853e4b6d6d25ccf7f6126ff9d96105b04868a5367ad8b92"
+ "hash": "4993e942985404ec388cc858815e82d08ad0185cfaa24300545f290e1ba87e49"
}
diff --git a/.sqlx/query-a90d55253d346aa1afebb966a4c805e8606d9011f0626b2be2bf98344058d4f1.json b/.sqlx/query-5a3dd1831370d60a05f9cda9a1a8608daa8c7fe4f252320f6f3224517dc9019a.json
similarity index 72%
rename from .sqlx/query-a90d55253d346aa1afebb966a4c805e8606d9011f0626b2be2bf98344058d4f1.json
rename to .sqlx/query-5a3dd1831370d60a05f9cda9a1a8608daa8c7fe4f252320f6f3224517dc9019a.json
index 4e2a04c4be..77a1a2927d 100644
--- a/.sqlx/query-a90d55253d346aa1afebb966a4c805e8606d9011f0626b2be2bf98344058d4f1.json
+++ b/.sqlx/query-5a3dd1831370d60a05f9cda9a1a8608daa8c7fe4f252320f6f3224517dc9019a.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n id, name, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, workspace, sandbox_size, acp_session_id, status,\n status_event_name, agent_session.created_at, modified_at,\n (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE id = $1\n ",
+ "query": "\n SELECT\n id, name, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, workspace, sandbox_size, instructions,\n acp_session_id, status,\n status_event_name, agent_session.created_at, modified_at,\n (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE thread_id = $1 AND bot_id = $2\n ORDER BY agent_session.created_at DESC\n LIMIT 1\n ",
"describe": {
"columns": [
{
@@ -60,57 +60,63 @@
},
{
"ordinal": 11,
- "name": "acp_session_id",
+ "name": "instructions",
"type_info": "Text"
},
{
"ordinal": 12,
- "name": "status",
+ "name": "acp_session_id",
"type_info": "Text"
},
{
"ordinal": 13,
- "name": "status_event_name",
+ "name": "status",
"type_info": "Text"
},
{
"ordinal": 14,
+ "name": "status_event_name",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 15,
"name": "created_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 15,
+ "ordinal": 16,
"name": "modified_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 16,
+ "ordinal": 17,
"name": "thread_channel_id?",
"type_info": "Uuid"
},
{
- "ordinal": 17,
+ "ordinal": 18,
"name": "external_provider?",
"type_info": "Text"
},
{
- "ordinal": 18,
+ "ordinal": 19,
"name": "external_id?",
"type_info": "Text"
},
{
- "ordinal": 19,
+ "ordinal": 20,
"name": "external_name?",
"type_info": "Text"
},
{
- "ordinal": 20,
+ "ordinal": 21,
"name": "external_url?",
"type_info": "Text"
}
],
"parameters": {
"Left": [
+ "Uuid",
"Uuid"
]
},
@@ -127,6 +133,7 @@
false,
false,
true,
+ true,
false,
true,
false,
@@ -138,5 +145,5 @@
true
]
},
- "hash": "a90d55253d346aa1afebb966a4c805e8606d9011f0626b2be2bf98344058d4f1"
+ "hash": "5a3dd1831370d60a05f9cda9a1a8608daa8c7fe4f252320f6f3224517dc9019a"
}
diff --git a/.sqlx/query-040b43c242db0706989c48b8eaa72c02b649035b1749e7c8494c1fba5b98100d.json b/.sqlx/query-e110350d84019c5f95862604b525421b8aeffae90f0e6852cc76bb753e9d3e6d.json
similarity index 75%
rename from .sqlx/query-040b43c242db0706989c48b8eaa72c02b649035b1749e7c8494c1fba5b98100d.json
rename to .sqlx/query-e110350d84019c5f95862604b525421b8aeffae90f0e6852cc76bb753e9d3e6d.json
index 8280583a56..d86b878230 100644
--- a/.sqlx/query-040b43c242db0706989c48b8eaa72c02b649035b1749e7c8494c1fba5b98100d.json
+++ b/.sqlx/query-e110350d84019c5f95862604b525421b8aeffae90f0e6852cc76bb753e9d3e6d.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n id, name, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, workspace, sandbox_size, acp_session_id, status,\n status_event_name, agent_session.created_at, modified_at,\n (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE thread_id = $1 AND bot_id = $2\n ORDER BY agent_session.created_at DESC\n LIMIT 1\n ",
+ "query": "\n SELECT\n id, name, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, workspace, sandbox_size, instructions,\n acp_session_id, status,\n status_event_name, agent_session.created_at, modified_at,\n (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE id = $1\n ",
"describe": {
"columns": [
{
@@ -60,58 +60,62 @@
},
{
"ordinal": 11,
- "name": "acp_session_id",
+ "name": "instructions",
"type_info": "Text"
},
{
"ordinal": 12,
- "name": "status",
+ "name": "acp_session_id",
"type_info": "Text"
},
{
"ordinal": 13,
- "name": "status_event_name",
+ "name": "status",
"type_info": "Text"
},
{
"ordinal": 14,
+ "name": "status_event_name",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 15,
"name": "created_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 15,
+ "ordinal": 16,
"name": "modified_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 16,
+ "ordinal": 17,
"name": "thread_channel_id?",
"type_info": "Uuid"
},
{
- "ordinal": 17,
+ "ordinal": 18,
"name": "external_provider?",
"type_info": "Text"
},
{
- "ordinal": 18,
+ "ordinal": 19,
"name": "external_id?",
"type_info": "Text"
},
{
- "ordinal": 19,
+ "ordinal": 20,
"name": "external_name?",
"type_info": "Text"
},
{
- "ordinal": 20,
+ "ordinal": 21,
"name": "external_url?",
"type_info": "Text"
}
],
"parameters": {
"Left": [
- "Uuid",
"Uuid"
]
},
@@ -128,6 +132,7 @@
false,
false,
true,
+ true,
false,
true,
false,
@@ -139,5 +144,5 @@
true
]
},
- "hash": "040b43c242db0706989c48b8eaa72c02b649035b1749e7c8494c1fba5b98100d"
+ "hash": "e110350d84019c5f95862604b525421b8aeffae90f0e6852cc76bb753e9d3e6d"
}
diff --git a/.sqlx/query-0f26267379d1fe3337f14aa30959204ac2d89c9acbe728426c199bde4b41eda7.json b/.sqlx/query-e975e75d2da18b8206df0dc5d4369bea0bc62546e28bcdcecb89ef04fa083f9c.json
similarity index 74%
rename from .sqlx/query-0f26267379d1fe3337f14aa30959204ac2d89c9acbe728426c199bde4b41eda7.json
rename to .sqlx/query-e975e75d2da18b8206df0dc5d4369bea0bc62546e28bcdcecb89ef04fa083f9c.json
index 79b97d7820..d2e517995a 100644
--- a/.sqlx/query-0f26267379d1fe3337f14aa30959204ac2d89c9acbe728426c199bde4b41eda7.json
+++ b/.sqlx/query-e975e75d2da18b8206df0dc5d4369bea0bc62546e28bcdcecb89ef04fa083f9c.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n id, name, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, workspace, sandbox_size, acp_session_id, status,\n status_event_name, agent_session.created_at, modified_at,\n (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE egress_token_hash = $1\n ",
+ "query": "\n SELECT\n id, name, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, workspace, sandbox_size, instructions,\n acp_session_id, status,\n status_event_name, agent_session.created_at, modified_at,\n (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE egress_token_hash = $1\n ",
"describe": {
"columns": [
{
@@ -60,51 +60,56 @@
},
{
"ordinal": 11,
- "name": "acp_session_id",
+ "name": "instructions",
"type_info": "Text"
},
{
"ordinal": 12,
- "name": "status",
+ "name": "acp_session_id",
"type_info": "Text"
},
{
"ordinal": 13,
- "name": "status_event_name",
+ "name": "status",
"type_info": "Text"
},
{
"ordinal": 14,
+ "name": "status_event_name",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 15,
"name": "created_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 15,
+ "ordinal": 16,
"name": "modified_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 16,
+ "ordinal": 17,
"name": "thread_channel_id?",
"type_info": "Uuid"
},
{
- "ordinal": 17,
+ "ordinal": 18,
"name": "external_provider?",
"type_info": "Text"
},
{
- "ordinal": 18,
+ "ordinal": 19,
"name": "external_id?",
"type_info": "Text"
},
{
- "ordinal": 19,
+ "ordinal": 20,
"name": "external_name?",
"type_info": "Text"
},
{
- "ordinal": 20,
+ "ordinal": 21,
"name": "external_url?",
"type_info": "Text"
}
@@ -127,6 +132,7 @@
false,
false,
true,
+ true,
false,
true,
false,
@@ -138,5 +144,5 @@
true
]
},
- "hash": "0f26267379d1fe3337f14aa30959204ac2d89c9acbe728426c199bde4b41eda7"
+ "hash": "e975e75d2da18b8206df0dc5d4369bea0bc62546e28bcdcecb89ef04fa083f9c"
}
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionResponse.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionResponse.ts
index d01c28d3be..8a5436d264 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionResponse.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionResponse.ts
@@ -6,6 +6,7 @@
*/
import type { AgentSessionResponseAcpSessionId } from './agentSessionResponseAcpSessionId';
import type { AgentSessionResponseExternal } from './agentSessionResponseExternal';
+import type { AgentSessionResponseInstructions } from './agentSessionResponseInstructions';
import type { AgentSessionResponseOriginatingMessageId } from './agentSessionResponseOriginatingMessageId';
import type { AgentSessionResponseRepoUrl } from './agentSessionResponseRepoUrl';
import type { AgentSessionResponseThreadChannelId } from './agentSessionResponseThreadChannelId';
@@ -30,6 +31,9 @@ export interface AgentSessionResponse {
harness: string;
/** The session id. */
id: string;
+ /** Instructions the session's runtime works under, when any were stated
+at creation. Absent otherwise, so existing payloads are unchanged. */
+ instructions?: AgentSessionResponseInstructions;
/** Model slug. */
model: string;
/** When the session was last modified. */
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionResponseInstructions.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionResponseInstructions.ts
new file mode 100644
index 0000000000..d72f2db0c4
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionResponseInstructions.ts
@@ -0,0 +1,12 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Instructions the session's runtime works under, when any were stated
+at creation. Absent otherwise, so existing payloads are unchanged.
+ */
+export type AgentSessionResponseInstructions = string | null;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequest.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequest.ts
index 81cc586d98..7ad86766e9 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequest.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequest.ts
@@ -5,6 +5,7 @@
* OpenAPI spec version: 0.1.0
*/
import type { CreateAgentSessionRequestBotId } from './createAgentSessionRequestBotId';
+import type { CreateAgentSessionRequestInstructions } from './createAgentSessionRequestInstructions';
import type { CreateAgentSessionRequestOwner } from './createAgentSessionRequestOwner';
import type { CreateAgentSessionRequestPrompt } from './createAgentSessionRequestPrompt';
import type { CreateAgentSessionRequestRepoUrl } from './createAgentSessionRequestRepoUrl';
@@ -31,6 +32,12 @@ is used) and must not name another bot; user callers must supply a
bot they own. External sessions only: a managed session runs as the
bot its deployment is configured for. */
botId?: CreateAgentSessionRequestBotId;
+ /** Instructions the session's runtime works under, for its whole life.
+
+Recorded on the session whichever runtime serves it. Only the
+in-process one acts on them today; `agent_harness`'s `AgentKind`
+records what each of the others will need to. */
+ instructions?: CreateAgentSessionRequestInstructions;
/** The user who owns the session. Ignored for user callers, who always
own their own sessions; required for bot callers without verified
acting-user claims.
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequestInstructions.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequestInstructions.ts
new file mode 100644
index 0000000000..0df84e3a1f
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequestInstructions.ts
@@ -0,0 +1,15 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Instructions the session's runtime works under, for its whole life.
+
+Recorded on the session whichever runtime serves it. Only the
+in-process one acts on them today; `agent_harness`'s `AgentKind`
+records what each of the others will need to.
+ */
+export type CreateAgentSessionRequestInstructions = string | null;
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 19188b4c04..8727742c87 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
@@ -25,6 +25,7 @@ export * from './agentSessionLogResponse';
export * from './agentSessionResponse';
export * from './agentSessionResponseAcpSessionId';
export * from './agentSessionResponseExternal';
+export * from './agentSessionResponseInstructions';
export * from './agentSessionResponseOriginatingMessageId';
export * from './agentSessionResponseRepoUrl';
export * from './agentSessionResponseThreadChannelId';
@@ -34,6 +35,7 @@ export * from './botId';
export * from './controlRequest';
export * from './createAgentSessionRequest';
export * from './createAgentSessionRequestBotId';
+export * from './createAgentSessionRequestInstructions';
export * from './createAgentSessionRequestOwner';
export * from './createAgentSessionRequestPrompt';
export * from './createAgentSessionRequestRepoUrl';
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 289f51c93b..37eb500ab3 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
@@ -743,6 +743,10 @@
"format": "uuid",
"description": "The session id."
},
+ "instructions": {
+ "type": ["string", "null"],
+ "description": "Instructions the session's runtime works under, when any were stated\nat creation. Absent otherwise, so existing payloads are unchanged."
+ },
"model": {
"type": "string",
"description": "Model slug."
@@ -825,6 +829,10 @@
"format": "uuid",
"description": "Bot the session runs for. Bot callers may omit it (their own identity\nis used) and must not name another bot; user callers must supply a\nbot they own. External sessions only: a managed session runs as the\nbot its deployment is configured for."
},
+ "instructions": {
+ "type": ["string", "null"],
+ "description": "Instructions the session's runtime works under, for its whole life.\n\nRecorded on the session whichever runtime serves it. Only the\nin-process one acts on them today; `agent_harness`'s `AgentKind`\nrecords what each of the others will need to."
+ },
"owner": {
"type": ["string", "null"],
"description": "The user who owns the session. Ignored for user callers, who always\nown their own sessions; required for bot callers without verified\nacting-user claims.\n\nFor bot callers this is a claim, not a verified fact: it is scoped to\nthe bot's own sessions, but the named user owns the session on the\nbot's say-so."
diff --git a/crates/agent_harness/src/domain/model.rs b/crates/agent_harness/src/domain/model.rs
index de909e948b..8d1fd6c2b3 100644
--- a/crates/agent_harness/src/domain/model.rs
+++ b/crates/agent_harness/src/domain/model.rs
@@ -48,6 +48,16 @@ pub struct OpenSession {
/// provider becomes a compile error at every decision site instead of a
/// silently wrong `else`. This becomes a bot attribute the day the set
/// stops being closed.
+///
+/// A session's instructions are stored on its row whichever kind serves it,
+/// but only [`Self::InMemory`] reads them today - it builds its system prompt
+/// in this process, so there is nothing to transport. The rest need one, and
+/// ACP supplies none: `session/new` carries a working directory, MCP servers
+/// and `_meta`, and nothing else. [`Self::SandboxedCoder`] will get a
+/// per-session file listed alongside `SYSTEM.md` in `container/opencode.json`,
+/// [`Self::External`] `_meta` on `session/new` for macrod to translate, and
+/// [`Self::Cursor`] - whose API takes a prompt and nothing more - has to fold
+/// them into the prompt body's hidden agent-context node.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AgentKind {
/// A sandbox this deployment provisions (Daytona, or local Docker when
diff --git a/crates/agent_harness/src/domain/ports/test.rs b/crates/agent_harness/src/domain/ports/test.rs
index 64ed30c510..9a7ec28780 100644
--- a/crates/agent_harness/src/domain/ports/test.rs
+++ b/crates/agent_harness/src/domain/ports/test.rs
@@ -36,6 +36,7 @@ fn params(id: AgentSessionId) -> CreateAgentSessionParams {
repo_url: Some("https://github.com/macro/macro".to_owned()),
workspace: "/workspace".to_owned(),
sandbox_size: agent_session::domain::model::SandboxSize::Default,
+ instructions: None,
egress_token_hash: None,
}
}
diff --git a/crates/agent_harness/src/domain/service.rs b/crates/agent_harness/src/domain/service.rs
index 9478d23df3..77a613b121 100644
--- a/crates/agent_harness/src/domain/service.rs
+++ b/crates/agent_harness/src/domain/service.rs
@@ -343,6 +343,7 @@ where
repo_url: request.repo_url,
workspace: request.workspace,
sandbox_size: SandboxSize::Default,
+ instructions: request.instructions,
// No sandbox: the runtime dials in and reaches the network on
// its operator's own terms, so there is no egress token.
egress_token_hash: None,
@@ -431,6 +432,7 @@ where
// Managed sandboxes run in the path baked into their image.
workspace: agent_session::MANAGED_CONTAINER_WORKSPACE.to_owned(),
sandbox_size,
+ instructions: request.instructions,
egress_token_hash: Some(egress.session_token_hash),
})
.await?;
@@ -696,6 +698,10 @@ where
// Managed sandboxes run in the path baked into their image.
workspace: agent_session::MANAGED_CONTAINER_WORKSPACE.to_owned(),
sandbox_size,
+ // A mention carries no instructions: the prompt is whatever
+ // was said in the channel, and nothing there states how the
+ // runtime should work.
+ instructions: None,
egress_token_hash: Some(egress.session_token_hash),
// This open came from the trigger pipeline seeing the mention.
})
diff --git a/crates/agent_harness/src/domain/service/test.rs b/crates/agent_harness/src/domain/service/test.rs
index c2c364b160..ec28d87289 100644
--- a/crates/agent_harness/src/domain/service/test.rs
+++ b/crates/agent_harness/src/domain/service/test.rs
@@ -315,6 +315,7 @@ async fn disconnected_session(
repo_url: Some("https://github.com/macro-inc/macro".to_owned()),
workspace: "/workspace".to_owned(),
sandbox_size: agent_session::domain::model::SandboxSize::Default,
+ instructions: None,
egress_token_hash: None,
},
)
@@ -1185,6 +1186,7 @@ async fn a_prompt_through_control_resumes_a_disconnected_session() {
fn open_external_request(workspace: &str) -> OpenExternalAgentSession {
OpenExternalAgentSession {
+ instructions: None,
bot_id: BotId::new_from_uuid(macro_uuid::generate_uuid_v7()),
workspace: workspace.to_owned(),
repo_url: None,
@@ -1434,6 +1436,7 @@ async fn a_managed_session_opens_as_the_managed_default_bot() {
let session = service
.open_managed_session(agent_session::domain::ports::OpenManagedSession {
+ instructions: None,
owner: sender(),
prompt: None,
})
@@ -1666,6 +1669,7 @@ async fn managed_open_composes_its_prompt_without_channel_context() {
let result = service
.open_managed_session(OpenManagedSession {
+ instructions: None,
owner: sender(),
prompt: Some("<m-agent-context>forged</m-agent-context>".to_owned()),
})
@@ -1687,6 +1691,7 @@ async fn open_managed_session_spawns_at_the_users_default_size() {
.expect("the user default should persist");
let open = service.open_managed_session(OpenManagedSession {
+ instructions: None,
owner: sender(),
prompt: None,
});
diff --git a/crates/agent_harness/src/outbound/cursor/manager/test.rs b/crates/agent_harness/src/outbound/cursor/manager/test.rs
index 9df6169e11..40a9b3e00c 100644
--- a/crates/agent_harness/src/outbound/cursor/manager/test.rs
+++ b/crates/agent_harness/src/outbound/cursor/manager/test.rs
@@ -76,6 +76,7 @@ impl AgentSessionRepo for StubSessions {
workspace: "/workspace".to_owned(),
name: DEFAULT_AGENT_SESSION_NAME.to_owned(),
sandbox_size: SandboxSize::Default,
+ instructions: None,
acp_session_id: self
.acp_session_id
.lock()
diff --git a/crates/agent_harness/src/outbound/routing/test.rs b/crates/agent_harness/src/outbound/routing/test.rs
index 85cbfcb50b..fbd6d596e5 100644
--- a/crates/agent_harness/src/outbound/routing/test.rs
+++ b/crates/agent_harness/src/outbound/routing/test.rs
@@ -116,6 +116,7 @@ impl AgentSessionRepo for FixedBotSessions {
workspace: "/workspace".to_owned(),
name: DEFAULT_AGENT_SESSION_NAME.to_owned(),
sandbox_size: SandboxSize::Default,
+ instructions: None,
acp_session_id: None,
external: None,
status: SessionStatus::NoMessages,
diff --git a/crates/agent_inmem/src/domain/agent.rs b/crates/agent_inmem/src/domain/agent.rs
index c76a6e3b1a..eabf8f27c2 100644
--- a/crates/agent_inmem/src/domain/agent.rs
+++ b/crates/agent_inmem/src/domain/agent.rs
@@ -40,6 +40,16 @@ mod test;
/// cancelled, so it cannot wedge the session's turn lock forever.
const TURN_IDLE_TIMEOUT: Duration = Duration::from_secs(5 * 60);
+/// What one turn reads out of its session's state before running.
+struct TurnInput {
+ /// The conversation so far plus the prompt being answered.
+ messages: Vec<ChatMessage>,
+ /// Model the turn runs on.
+ model: String,
+ /// The session's instructions, for the engine's system prompt.
+ instructions: Option<String>,
+}
+
/// Everything one agent task serves its session from.
pub struct AgentState {
/// The Macro session this agent runs.
@@ -94,15 +104,19 @@ impl AgentState {
}
}
- /// The messages and model for a turn answering `prompt`.
- fn turn_input(&self, prompt: &str) -> (Vec<ChatMessage>, String) {
+ /// Everything from the session's state that a turn answering `prompt`
+ /// runs from.
+ fn turn_input(&self, prompt: &str) -> TurnInput {
self.store.get(&self.session_id).map_or_else(
- || (messages_for_turn(&[], prompt), String::new()),
- |state| {
- (
- messages_for_turn(&state.history, prompt),
- state.model.clone(),
- )
+ || TurnInput {
+ messages: messages_for_turn(&[], prompt),
+ model: String::new(),
+ instructions: None,
+ },
+ |state| TurnInput {
+ messages: messages_for_turn(&state.history, prompt),
+ model: state.model.clone(),
+ instructions: state.instructions.clone(),
},
)
}
@@ -275,10 +289,15 @@ async fn run_turn(
cancel: CancellationToken,
) -> StopReason {
let _turn = state.turn_lock.lock().await;
- let (messages, model) = state.turn_input(&prompt);
+ let TurnInput {
+ messages,
+ model,
+ instructions,
+ } = state.turn_input(&prompt);
let mut parts = state.engine.run_turn(TurnRequest {
owner: state.owner.clone(),
model,
+ instructions,
messages,
cancel: cancel.clone(),
});
diff --git a/crates/agent_inmem/src/domain/agent/test.rs b/crates/agent_inmem/src/domain/agent/test.rs
index 68e3e03eb5..aa7e18e357 100644
--- a/crates/agent_inmem/src/domain/agent/test.rs
+++ b/crates/agent_inmem/src/domain/agent/test.rs
@@ -169,11 +169,11 @@ async fn turns_accumulate_history_and_send_the_model() {
let requests = engine.requests();
assert_eq!(requests.len(), 2);
- assert_eq!(requests[0].0, "test-model");
- assert_eq!(requests[0].1, vec!["first".to_owned()]);
+ assert_eq!(requests[0].model, "test-model");
+ assert_eq!(requests[0].messages, vec!["first".to_owned()]);
// The second turn carries the first turn's prompt and reply.
assert_eq!(
- requests[1].1,
+ requests[1].messages,
vec!["first".to_owned(), "ok".to_owned(), "second".to_owned()]
);
}
@@ -205,7 +205,7 @@ async fn compact_clears_history_without_running_a_turn() {
let requests = engine.requests();
assert_eq!(requests.len(), 2, "/compact must not reach the engine");
assert_eq!(
- requests[1].1,
+ requests[1].messages,
vec!["after".to_owned()],
"compaction empties the conversation"
);
diff --git a/crates/agent_inmem/src/domain/engine.rs b/crates/agent_inmem/src/domain/engine.rs
index 5311b9aa6e..1e6f7890bb 100644
--- a/crates/agent_inmem/src/domain/engine.rs
+++ b/crates/agent_inmem/src/domain/engine.rs
@@ -14,6 +14,9 @@ pub struct TurnRequest {
/// Model id the turn runs on. Unknown ids fall back to the loop's
/// default model rather than failing the turn.
pub model: String,
+ /// The session's instructions, appended to the engine's own system
+ /// prompt. `None` runs the engine's default prompt unchanged.
+ pub instructions: Option<String>,
/// The full conversation, oldest first, ending with the prompt being
/// answered.
pub messages: Vec<ChatMessage>,
diff --git a/crates/agent_inmem/src/domain/session.rs b/crates/agent_inmem/src/domain/session.rs
index b465b839a1..2f8431bd6e 100644
--- a/crates/agent_inmem/src/domain/session.rs
+++ b/crates/agent_inmem/src/domain/session.rs
@@ -27,6 +27,11 @@ pub struct SessionState {
pub acp_session_id: Option<SessionId>,
/// Model id turns run on; `session/set_config_option` moves it.
pub model: String,
+ /// Instructions every turn runs under, snapshotted from the session row
+ /// at attach. Nothing moves them: they are the session's system prompt,
+ /// and a conversation whose system prompt changed halfway is one the
+ /// agent never agreed to.
+ pub instructions: Option<String>,
/// The conversation so far, oldest first.
pub history: Vec<HistoryEntry>,
}
@@ -38,6 +43,7 @@ impl SessionState {
Self {
acp_session_id: None,
model,
+ instructions: None,
history: Vec::new(),
}
}
diff --git a/crates/agent_inmem/src/outbound/manager.rs b/crates/agent_inmem/src/outbound/manager.rs
index 0e101a032f..42e44bb031 100644
--- a/crates/agent_inmem/src/outbound/manager.rs
+++ b/crates/agent_inmem/src/outbound/manager.rs
@@ -32,6 +32,10 @@ pub struct SessionFacts {
pub owner: MacroUserIdStr<'static>,
/// Model id stamped on the session row.
pub model: String,
+ /// Instructions stamped on the session row, folded into every turn's
+ /// system prompt. Immutable for the session's life, so a reattach that
+ /// finds a live conversation leaves what is stored alone.
+ pub instructions: Option<String>,
/// The ACP session id the row carries, when one was ever negotiated. A
/// cold attach hydrates its rebuilt conversation under this id so the
/// harness's `session/resume` keeps it.
@@ -92,6 +96,7 @@ impl InMemAgentManager {
self.store.entry(facts.id).or_insert_with(|| SessionState {
acp_session_id: facts.acp_session_id.clone(),
model: facts.model.clone(),
+ instructions: facts.instructions.clone(),
history,
});
}
diff --git a/crates/agent_inmem/src/outbound/manager/test.rs b/crates/agent_inmem/src/outbound/manager/test.rs
index 4358ace7d4..09857ae2ab 100644
--- a/crates/agent_inmem/src/outbound/manager/test.rs
+++ b/crates/agent_inmem/src/outbound/manager/test.rs
@@ -13,7 +13,7 @@ use agent_runtime_protocol::domain::action::{AgentAction, AgentActionId};
use agent_session::domain::connection::RuntimeAttachment;
use agent_session::domain::model::{AgentSessionId, CreateAgentSessionParams};
use agent_session::domain::ports::{AgentSessionLogRepo as _, NoOpRealtime};
-use agent_session::domain::service::{AgentSessionService as _, AgentSessionServiceImpl};
+use agent_session::domain::service::{AgentSessionService, AgentSessionServiceImpl};
use agent_session::testing::InMemoryAgentSessionRepo;
use bot_id::BotId;
use macro_user_id::user_id::MacroUserIdStr;
@@ -22,6 +22,65 @@ use super::*;
use crate::outbound::log_frames::LogFrameSource;
use crate::testing::ScriptedEngine;
+/// Instructions long enough to be unmistakable in an assertion, and shaped
+/// like something a real session would carry.
+const INSTRUCTIONS: &str = "Answer in one sentence. Never open a pull request.";
+
+/// Attach `transport`, waiting out the previous one's disconnect.
+///
+/// Replacing a session's agent is two independent events: the manager drops
+/// the old task immediately, and the session service notices the transport
+/// died a moment later. Until it has, the attach is refused as
+/// `AlreadyConnected` - so a reattach retries rather than failing.
+async fn attach_retrying(
+ sessions: &impl AgentSessionService,
+ id: AgentSessionId,
+ manager: &InMemAgentManager,
+ facts: SessionFacts,
+) {
+ let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
+ loop {
+ let transport = manager.attach(facts.clone()).await;
+ match sessions
+ .attach_session(id, RuntimeAttachment::solo(transport))
+ .await
+ {
+ Ok(()) => return,
+ Err(agent_session::domain::error::AgentSessionError::AlreadyConnected(_)) => {
+ assert!(
+ tokio::time::Instant::now() < deadline,
+ "the replaced agent never disconnected"
+ );
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ }
+ Err(error) => panic!("the transport should attach: {error:?}"),
+ }
+ }
+}
+
+/// Block until the engine has been asked to run the turn answering `prompt`.
+///
+/// The prompt returns as soon as the session machine has written the frame,
+/// which is before the agent task has picked it up - so an assertion on the
+/// engine right after `send_action` races it.
+async fn await_turns(engine: &ScriptedEngine, prompt: &str) {
+ let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
+ loop {
+ let seen = engine
+ .requests()
+ .iter()
+ .any(|turn| turn.messages.iter().any(|message| message == prompt));
+ if seen {
+ return;
+ }
+ assert!(
+ tokio::time::Instant::now() < deadline,
+ "the prompt {prompt:?} never reached the engine"
+ );
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ }
+}
+
fn owner() -> MacroUserIdStr<'static> {
MacroUserIdStr::try_from_email("[email protected]").expect("a valid user id")
}
@@ -35,10 +94,19 @@ fn facts(id: AgentSessionId) -> SessionFacts {
id,
owner: owner(),
model: "test-model".to_owned(),
+ instructions: None,
acp_session_id: None,
}
}
+/// The same facts, with the session's row carrying `instructions`.
+fn facts_with_instructions(id: AgentSessionId, instructions: &str) -> SessionFacts {
+ SessionFacts {
+ instructions: Some(instructions.to_owned()),
+ ..facts(id)
+ }
+}
+
/// Frames the log holds, flattened to JSON strings for loose assertions.
async fn logged_frames(repo: &InMemoryAgentSessionRepo, id: AgentSessionId) -> Vec<String> {
repo.list_by_session(id)
@@ -85,6 +153,7 @@ async fn a_prompt_runs_end_to_end_through_the_real_session_machine() {
repo_url: None,
workspace: "/workspace".to_owned(),
sandbox_size: agent_session::domain::model::SandboxSize::Default,
+ instructions: None,
egress_token_hash: None,
})
.await
@@ -218,6 +287,7 @@ async fn a_restarted_manager_rebuilds_the_conversation_from_the_log() {
repo_url: None,
workspace: "/workspace".to_owned(),
sandbox_size: agent_session::domain::model::SandboxSize::Default,
+ instructions: None,
egress_token_hash: None,
})
.await
@@ -316,7 +386,7 @@ async fn a_restarted_manager_rebuilds_the_conversation_from_the_log() {
// The rebuilt context: the first turn's prompt and reply, then the new
// prompt - not just the new prompt.
assert_eq!(
- engine.requests()[0].1,
+ engine.requests()[0].messages,
vec![
"hello agent".to_owned(),
"streamed reply".to_owned(),
@@ -324,3 +394,131 @@ async fn a_restarted_manager_rebuilds_the_conversation_from_the_log() {
]
);
}
+
+/// The session row's instructions reach every turn the engine runs, and keep
+/// reaching it after the agent task is replaced.
+///
+/// Both halves matter and only one is obvious. The first prompt proves the
+/// column is wired to the engine at all; the second proves the value lives on
+/// the conversation state rather than on the agent task, which is what makes
+/// a reattach - the idle reaper's, or a redeploy's - keep the system prompt
+/// the session was opened with.
+#[tokio::test]
+async fn instructions_reach_every_turn_including_after_a_reattach() {
+ let repo = InMemoryAgentSessionRepo::new();
+ let sessions = AgentSessionServiceImpl::new(
+ repo.clone(),
+ FoldedMessageService::new(repo.clone()),
+ NoOpRealtime,
+ );
+
+ let id = AgentSessionId::new();
+ sessions
+ .create_session(CreateAgentSessionParams {
+ id,
+ owner_id: owner(),
+ bot_id: BotId::TEST_A,
+ thread_id: None,
+ originating_message_id: None,
+ model: "test-model".to_owned(),
+ harness: "macro-inmem".to_owned(),
+ repo_url: None,
+ workspace: "/workspace".to_owned(),
+ sandbox_size: agent_session::domain::model::SandboxSize::Default,
+ instructions: Some(INSTRUCTIONS.to_owned()),
+ egress_token_hash: None,
+ })
+ .await
+ .expect("the session row should create");
+
+ let engine = Arc::new(ScriptedEngine::new(vec![StreamPart::Content(
+ "acknowledged".to_owned(),
+ )]));
+ let manager = manager(&repo, Arc::clone(&engine));
+
+ for prompt in ["first", "second"] {
+ // A fresh attach each time, as a reaped-then-resumed session gets:
+ // the agent task is replaced, the conversation store is not.
+ attach_retrying(
+ &sessions,
+ id,
+ &manager,
+ facts_with_instructions(id, INSTRUCTIONS),
+ )
+ .await;
+ sessions
+ .send_action(
+ id,
+ Some(owner()),
+ AgentAction::prompt(prompt),
+ AgentActionId::mint(),
+ )
+ .await
+ .expect("the prompt should send");
+ await_turns(&engine, prompt).await;
+ }
+
+ let instructions: Vec<Option<String>> = engine
+ .requests()
+ .into_iter()
+ .map(|turn| turn.instructions)
+ .collect();
+ assert_eq!(
+ instructions,
+ vec![Some(INSTRUCTIONS.to_owned()), Some(INSTRUCTIONS.to_owned())],
+ "both turns run under the session's instructions"
+ );
+}
+
+/// A session with no instructions hands the engine none, rather than an empty
+/// string it would splice into its system prompt as a blank section.
+#[tokio::test]
+async fn a_session_without_instructions_hands_the_engine_none() {
+ let repo = InMemoryAgentSessionRepo::new();
+ let sessions = AgentSessionServiceImpl::new(
+ repo.clone(),
+ FoldedMessageService::new(repo.clone()),
+ NoOpRealtime,
+ );
+
+ let id = AgentSessionId::new();
+ sessions
+ .create_session(CreateAgentSessionParams {
+ id,
+ owner_id: owner(),
+ bot_id: BotId::TEST_A,
+ thread_id: None,
+ originating_message_id: None,
+ model: "test-model".to_owned(),
+ harness: "macro-inmem".to_owned(),
+ repo_url: None,
+ workspace: "/workspace".to_owned(),
+ sandbox_size: agent_session::domain::model::SandboxSize::Default,
+ instructions: None,
+ egress_token_hash: None,
+ })
+ .await
+ .expect("the session row should create");
+
+ let engine = Arc::new(ScriptedEngine::new(vec![StreamPart::Content(
+ "acknowledged".to_owned(),
+ )]));
+ let manager = manager(&repo, Arc::clone(&engine));
+ let transport = manager.attach(facts(id)).await;
+ sessions
+ .attach_session(id, RuntimeAttachment::solo(transport))
+ .await
+ .expect("the transport should attach");
+ sessions
+ .send_action(
+ id,
+ Some(owner()),
+ AgentAction::prompt("hello"),
+ AgentActionId::mint(),
+ )
+ .await
+ .expect("the prompt should send");
+ await_turns(&engine, "hello").await;
+
+ assert_eq!(engine.requests()[0].instructions, None);
+}
diff --git a/crates/agent_inmem/src/outbound/rig_engine.rs b/crates/agent_inmem/src/outbound/rig_engine.rs
index 13f0a63ba9..53b4fff7a2 100644
--- a/crates/agent_inmem/src/outbound/rig_engine.rs
+++ b/crates/agent_inmem/src/outbound/rig_engine.rs
@@ -6,6 +6,11 @@
//! the full static toolset, the tool-use system prompt plus the agent-session
//! preamble and the owner's memory, and usage recorded per turn against the
//! session owner.
+//!
+//! This is also where a session's own instructions become a system prompt.
+//! Nothing has to be transported for it - the loop runs in this process - which
+//! is why the in-memory runtime is the one provider that needs no wire format
+//! for them. See [`system_prompt`] for how the sections are ordered.
use std::sync::Arc;
@@ -22,6 +27,9 @@ use tokio::sync::mpsc;
use crate::domain::engine::{TurnEngine, TurnRequest};
+#[cfg(test)]
+mod test;
+
/// How many stream parts may sit unread before the engine pauses; keeps a
/// slow consumer from buffering a whole turn.
const PART_BUFFER: usize = 256;
@@ -65,21 +73,18 @@ async fn drive_turn(
let TurnRequest {
owner,
model,
+ instructions,
messages,
cancel,
} = request;
let tools = all_tools();
let user_memory = fetch_user_memory(&db, &base_context, &owner).await;
- let system_prompt = match user_memory {
- Some(memory) => format!(
- "{}\n{}\n<user_memory>\n{}\n</user_memory>",
- tools.prompt,
- prompt::agent_session::PROMPT,
- memory
- ),
- None => format!("{}\n{}", tools.prompt, prompt::agent_session::PROMPT),
- };
+ let system_prompt = system_prompt(
+ &tools.prompt,
+ instructions.as_deref(),
+ user_memory.as_deref(),
+ );
let toolset: Arc<dyn AiToolSet<_> + Send + Sync> = tools.toolset;
let agent_loop = AgentLoop::new(base_context.recorder.clone()).with_model(&model);
@@ -121,6 +126,36 @@ async fn drive_turn(
result
}
+/// The turn's system prompt: the toolset's, the agent-session preamble, then
+/// the session's own instructions and the owner's memory when there are any.
+///
+/// Instructions land after the preamble and before the memory block for the
+/// same reason DCS puts `additional_instructions` there - they are the
+/// caller's word on how this session works, so they qualify the standing
+/// prompt rather than being qualified by it, and memory stays last so a
+/// remembered fact is never read as an instruction.
+fn system_prompt(
+ tools_prompt: &impl std::fmt::Display,
+ instructions: Option<&str>,
+ user_memory: Option<&str>,
+) -> String {
+ let mut prompt = format!("{}\n{}", tools_prompt, prompt::agent_session::PROMPT);
+ // Blank instructions are "none" stated clumsily. A delimited section with
+ // nothing in it is worse than no section: the model has to decide what an
+ // empty instruction means.
+ if let Some(instructions) = instructions.filter(|text| !text.trim().is_empty()) {
+ prompt.push_str("\n<session_instructions>\n");
+ prompt.push_str(instructions);
+ prompt.push_str("\n</session_instructions>");
+ }
+ if let Some(memory) = user_memory {
+ prompt.push_str("\n<user_memory>\n");
+ prompt.push_str(memory);
+ prompt.push_str("\n</user_memory>");
+ }
+ prompt
+}
+
/// The owner's memory block, or `None` when it is missing or failed to load.
async fn fetch_user_memory(
db: &PgPool,
diff --git a/crates/agent_inmem/src/outbound/rig_engine/test.rs b/crates/agent_inmem/src/outbound/rig_engine/test.rs
new file mode 100644
index 0000000000..38f03c07da
--- /dev/null
+++ b/crates/agent_inmem/src/outbound/rig_engine/test.rs
@@ -0,0 +1,50 @@
+use super::*;
+
+/// A stand-in for the toolset prompt, short enough to assert on positionally.
+const TOOLS: &str = "TOOLS";
+
+#[test]
+fn instructions_are_a_delimited_section_after_the_standing_prompt() {
+ let prompt = system_prompt(&TOOLS, Some("be terse"), None);
+
+ assert!(
+ prompt.starts_with(&format!("{TOOLS}\n{}", prompt::agent_session::PROMPT)),
+ "the standing prompt comes first, unchanged"
+ );
+ assert!(prompt.ends_with("\n<session_instructions>\nbe terse\n</session_instructions>"));
+}
+
+/// The order is the contract, not an accident: instructions qualify the
+/// standing prompt, and memory comes last so a remembered fact is never read
+/// as an instruction.
+#[test]
+fn memory_follows_instructions_rather_than_preceding_them() {
+ let prompt = system_prompt(&TOOLS, Some("be terse"), Some("prefers Rust"));
+
+ let instructions = prompt
+ .find("<session_instructions>")
+ .expect("the instructions section should be present");
+ let memory = prompt
+ .find("<user_memory>")
+ .expect("the memory section should be present");
+ assert!(instructions < memory);
+}
+
+/// Absent instructions add no section at all, rather than an empty one the
+/// model would have to interpret.
+#[test]
+fn no_instructions_means_no_section() {
+ let prompt = system_prompt(&TOOLS, None, Some("prefers Rust"));
+
+ assert!(!prompt.contains("session_instructions"));
+ assert!(prompt.contains("<user_memory>\nprefers Rust\n</user_memory>"));
+}
+
+/// An empty string is a caller stating "no instructions" clumsily, and it must
+/// not become a blank delimited section.
+#[test]
+fn empty_instructions_add_no_section() {
+ let prompt = system_prompt(&TOOLS, Some(""), None);
+
+ assert!(!prompt.contains("session_instructions"));
+}
diff --git a/crates/agent_inmem/src/testing.rs b/crates/agent_inmem/src/testing.rs
index e93ffee5f1..fbdb765f23 100644
--- a/crates/agent_inmem/src/testing.rs
+++ b/crates/agent_inmem/src/testing.rs
@@ -8,8 +8,19 @@ use crate::domain::engine::{TurnEngine, TurnRequest};
/// An engine that plays back a script of parts for every turn.
pub(crate) struct ScriptedEngine {
script: Vec<StreamPart>,
- /// `(model, message texts)` per turn the engine has been asked to run.
- requests: std::sync::Mutex<Vec<(String, Vec<String>)>>,
+ /// One entry per turn the engine has been asked to run.
+ requests: std::sync::Mutex<Vec<RecordedTurn>>,
+}
+
+/// What one turn asked of the engine, as far as tests care.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub(crate) struct RecordedTurn {
+ /// Model the turn was to run on.
+ pub(crate) model: String,
+ /// The conversation, flattened to text per message.
+ pub(crate) messages: Vec<String>,
+ /// The session's instructions, as handed to the engine.
+ pub(crate) instructions: Option<String>,
}
impl ScriptedEngine {
@@ -20,21 +31,25 @@ impl ScriptedEngine {
}
}
- pub(crate) fn requests(&self) -> Vec<(String, Vec<String>)> {
+ pub(crate) fn requests(&self) -> Vec<RecordedTurn> {
self.requests.lock().expect("requests lock").clone()
}
}
impl TurnEngine for ScriptedEngine {
fn run_turn(&self, request: TurnRequest) -> mpsc::Receiver<Result<StreamPart, AgentError>> {
- self.requests.lock().expect("requests lock").push((
- request.model.clone(),
- request
- .messages
- .iter()
- .map(|message| message.content.message_text_with_tools())
- .collect(),
- ));
+ self.requests
+ .lock()
+ .expect("requests lock")
+ .push(RecordedTurn {
+ model: request.model.clone(),
+ messages: request
+ .messages
+ .iter()
+ .map(|message| message.content.message_text_with_tools())
+ .collect(),
+ instructions: request.instructions.clone(),
+ });
let (parts, receiver) = mpsc::channel(64);
let script = self.script.clone();
tokio::spawn(async move {
diff --git a/crates/agent_session/src/bin/seed_jsonl.rs b/crates/agent_session/src/bin/seed_jsonl.rs
index f2a835717b..315618f1a9 100644
--- a/crates/agent_session/src/bin/seed_jsonl.rs
+++ b/crates/agent_session/src/bin/seed_jsonl.rs
@@ -249,6 +249,8 @@ async fn seed(args: &Args) -> Result<(), SeedError> {
repo_url: Some(args.repo_url.clone()),
workspace: args.workspace.clone(),
sandbox_size: agent_session::domain::model::SandboxSize::Default,
+ // A recording is replayed, not run; nothing reads instructions.
+ instructions: None,
egress_token_hash: None,
},
)
diff --git a/crates/agent_session/src/domain/model.rs b/crates/agent_session/src/domain/model.rs
index 4750e23a89..28cd843c8e 100644
--- a/crates/agent_session/src/domain/model.rs
+++ b/crates/agent_session/src/domain/model.rs
@@ -56,6 +56,13 @@ pub struct CreateAgentSessionParams {
pub workspace: String,
/// Compute tier the managed sandbox was spawned with.
pub sandbox_size: SandboxSize,
+ /// Instructions the session's runtime works under, when any were stated.
+ ///
+ /// Snapshotted here rather than resolved per turn because they are the
+ /// runtime's system prompt: how a harness is handed them differs by
+ /// provider, but every provider needs the same answer for the session's
+ /// whole life.
+ pub instructions: Option<String>,
/// SHA-256 hex of the opaque token the session's sandbox presents to the
/// egress proxy, or `None` for a session that never gets one.
///
@@ -98,6 +105,10 @@ pub struct AgentSession {
pub workspace: String,
/// Compute tier of the managed sandbox, snapshotted at spawn.
pub sandbox_size: SandboxSize,
+ /// Instructions the session's runtime works under, snapshotted at
+ /// creation. Immutable for the session's life; `None` when none were
+ /// stated.
+ pub instructions: Option<String>,
/// ACP session if we have one
pub acp_session_id: Option<SessionId>,
/// The provider-side identity, when an external provider serves this
diff --git a/crates/agent_session/src/domain/ports.rs b/crates/agent_session/src/domain/ports.rs
index 115d6788d6..73eb13028f 100644
--- a/crates/agent_session/src/domain/ports.rs
+++ b/crates/agent_session/src/domain/ports.rs
@@ -73,6 +73,8 @@ pub struct OpenExternalAgentSession {
pub owner: MacroUserIdStr<'static>,
/// The thread whose mention triggered the session, when one did.
pub thread: Option<SessionThread>,
+ /// Instructions the session's runtime works under, when any were stated.
+ pub instructions: Option<String>,
}
/// Everything needed to open a session the server hosts itself.
@@ -88,6 +90,9 @@ pub struct OpenManagedSession {
/// First prompt to deliver once the sandbox is attached. `None` opens an
/// idle session its owner prompts from the session's own surface.
pub prompt: Option<String>,
+ /// Instructions the session's runtime works under, for its whole life.
+ /// `None` runs the runtime's own default.
+ pub instructions: Option<String>,
}
/// Opens sessions, however they are served. Implemented by the harness, which
diff --git a/crates/agent_session/src/inbound/axum_router.rs b/crates/agent_session/src/inbound/axum_router.rs
index 2d78bcde62..c3c022df5b 100644
--- a/crates/agent_session/src/inbound/axum_router.rs
+++ b/crates/agent_session/src/inbound/axum_router.rs
@@ -367,6 +367,10 @@ pub struct AgentSessionResponse {
pub workspace: String,
/// Compute tier of the managed sandbox.
pub sandbox_size: SandboxSize,
+ /// Instructions the session's runtime works under, when any were stated
+ /// at creation. Absent otherwise, so existing payloads are unchanged.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub instructions: Option<String>,
/// The ACP session id, if one exists.
pub acp_session_id: Option<String>,
/// The session's status.
@@ -420,6 +424,7 @@ impl From<AgentSession> for AgentSessionResponse {
repo_url: session.repo_url,
workspace: session.workspace,
sandbox_size: session.sandbox_size,
+ instructions: session.instructions,
acp_session_id: session.acp_session_id.map(|id| id.to_string()),
external: session.external.map(Into::into),
status: session.status.into(),
@@ -934,6 +939,12 @@ pub struct CreateAgentSessionRequest {
/// Linkage only - the mention's text is delivered by the runtime as the
/// first prompt through the control endpoint, never through here.
pub thread: Option<CreateSessionThread>,
+ /// Instructions the session's runtime works under, for its whole life.
+ ///
+ /// Recorded on the session whichever runtime serves it. Only the
+ /// in-process one acts on them today; `agent_harness`'s `AgentKind`
+ /// records what each of the others will need to.
+ pub instructions: Option<String>,
}
/// The triggering mention on a create request.
@@ -1172,6 +1183,11 @@ pub async fn create_agent_session_handler<
caller: MacroAuthorizationExtractor<Auth, UserOrBot>,
Json(request): Json<CreateAgentSessionRequest>,
) -> Result<(StatusCode, Json<CreateAgentSessionResponse>), CreateSessionApiError> {
+ // Blank instructions are "none" stated clumsily; normalized once here so
+ // the row, the response and every runtime see one representation of
+ // absence, whichever shape the request turns out to be.
+ let instructions = request.instructions.filter(|text| !text.trim().is_empty());
+
// No workspace means the managed shape. It shares this route but not its
// authorization: nothing about which bot runs the session is the caller's
// to say, so the bot-ownership checks below have nothing to check and are
@@ -1191,6 +1207,7 @@ pub async fn create_agent_session_handler<
.open_managed_session(OpenManagedSession {
owner,
prompt: request.prompt,
+ instructions,
})
.await?;
return Ok((
@@ -1249,6 +1266,7 @@ pub async fn create_agent_session_handler<
repo_url: request.repo_url,
owner,
thread: thread.clone(),
+ instructions,
})
.await
{
diff --git a/crates/agent_session/src/inbound/axum_router/test.rs b/crates/agent_session/src/inbound/axum_router/test.rs
index d9a408b2df..b87f8245c9 100644
--- a/crates/agent_session/src/inbound/axum_router/test.rs
+++ b/crates/agent_session/src/inbound/axum_router/test.rs
@@ -79,6 +79,7 @@ impl SessionOpener for RecordingOpener {
repo_url: request.repo_url.clone(),
workspace: request.workspace.clone(),
sandbox_size: crate::domain::model::SandboxSize::Default,
+ instructions: request.instructions.clone(),
acp_session_id: None,
external: None,
status: SessionStatus::NoMessages,
@@ -106,6 +107,7 @@ impl SessionOpener for RecordingOpener {
repo_url: Some("https://github.com/macro-inc/macro".to_owned()),
workspace: crate::MANAGED_CONTAINER_WORKSPACE.to_owned(),
sandbox_size: crate::domain::model::SandboxSize::Default,
+ instructions: request.instructions.clone(),
acp_session_id: None,
external: None,
status: SessionStatus::NoMessages,
@@ -415,3 +417,66 @@ fn other_domain_failures_stay_500() {
assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
}
+
+/// Instructions on a managed open reach the opener verbatim.
+#[tokio::test]
+async fn a_managed_open_carries_its_instructions() {
+ const INSTRUCTIONS: &str = "Answer in one sentence.";
+
+ let opener = Arc::new(RecordingOpener::default());
+ let request = as_user(
+ OWNER,
+ serde_json::json!({ "prompt": "fix it", "instructions": INSTRUCTIONS }).to_string(),
+ );
+
+ let response = router(opener.clone()).oneshot(request).await.unwrap();
+
+ assert_eq!(response.status(), StatusCode::CREATED);
+ let managed = opener.managed.lock().unwrap();
+ assert_eq!(
+ managed
+ .iter()
+ .map(|open| open.instructions.as_deref())
+ .collect::<Vec<_>>(),
+ vec![Some(INSTRUCTIONS)]
+ );
+}
+
+/// Whitespace-only instructions are absence stated clumsily, and are
+/// normalized away rather than stored as a section a runtime would splice in
+/// empty.
+#[tokio::test]
+async fn blank_instructions_are_normalized_to_none() {
+ let opener = Arc::new(RecordingOpener::default());
+ let request = as_user(
+ OWNER,
+ serde_json::json!({ "prompt": "fix it", "instructions": " \n " }).to_string(),
+ );
+
+ let response = router(opener.clone()).oneshot(request).await.unwrap();
+
+ assert_eq!(response.status(), StatusCode::CREATED);
+ assert_eq!(opener.managed.lock().unwrap()[0].instructions, None);
+}
+
+/// An external open records instructions too. Nothing on that side reads them
+/// yet, but the row is the durable statement of what the session was opened
+/// with, so dropping them here would lose the fact rather than defer it.
+#[tokio::test]
+async fn an_external_open_carries_its_instructions() {
+ const INSTRUCTIONS: &str = "Never force-push.";
+
+ let opener = Arc::new(RecordingOpener::default());
+ let mut request_body: serde_json::Value =
+ serde_json::from_str(&body(None, "/home/wolf/code", Some(OWNER))).unwrap();
+ request_body["instructions"] = serde_json::json!(INSTRUCTIONS);
+ let request = as_bot(request_body.to_string());
+
+ let response = router(opener.clone()).oneshot(request).await.unwrap();
+
+ assert_eq!(response.status(), StatusCode::CREATED);
+ assert_eq!(
+ opener.opened.lock().unwrap()[0].instructions.as_deref(),
+ Some(INSTRUCTIONS)
+ );
+}
diff --git a/crates/agent_session/src/outbound/postgres.rs b/crates/agent_session/src/outbound/postgres.rs
index ac667e1df5..d131311651 100644
--- a/crates/agent_session/src/outbound/postgres.rs
+++ b/crates/agent_session/src/outbound/postgres.rs
@@ -106,6 +106,7 @@ struct AgentSessionRow {
repo_url: Option<String>,
workspace: String,
sandbox_size: String,
+ instructions: Option<String>,
acp_session_id: Option<String>,
external_provider: Option<String>,
external_id: Option<String>,
@@ -136,6 +137,7 @@ impl TryFrom<AgentSessionRow> for AgentSession {
repo_url: row.repo_url,
workspace: row.workspace,
sandbox_size: parse_sandbox_size(&row.sandbox_size)?,
+ instructions: row.instructions,
acp_session_id: row.acp_session_id.map(Into::into),
external: row
.external_provider
@@ -166,6 +168,7 @@ impl AgentSessionRepo for PgAgentSessionRepo {
repo_url,
workspace,
sandbox_size,
+ instructions,
egress_token_hash,
} = params;
@@ -184,13 +187,14 @@ impl AgentSessionRepo for PgAgentSessionRepo {
r#"
INSERT INTO agent_session (
id, owner_id, thread_id, originating_message_id, bot_id, model,
- harness, repo_url, workspace, sandbox_size, acp_session_id, status,
- status_event_name, egress_token_hash
+ harness, repo_url, workspace, sandbox_size, instructions,
+ acp_session_id, status, status_event_name, egress_token_hash
)
- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15)
RETURNING
id, name, owner_id, thread_id, originating_message_id, bot_id,
- model, harness, repo_url, workspace, sandbox_size, acp_session_id, status,
+ model, harness, repo_url, workspace, sandbox_size, instructions,
+ acp_session_id, status,
status_event_name, created_at, modified_at,
(SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)
AS "thread_channel_id?",
@@ -208,6 +212,7 @@ impl AgentSessionRepo for PgAgentSessionRepo {
repo_url,
workspace,
sandbox_size.as_str(),
+ instructions,
None::<String>,
status,
status_event_name,
@@ -279,7 +284,8 @@ impl AgentSessionRepo for PgAgentSessionRepo {
r#"
SELECT
id, name, owner_id, thread_id, originating_message_id, bot_id,
- model, harness, repo_url, workspace, sandbox_size, acp_session_id, status,
+ model, harness, repo_url, workspace, sandbox_size, instructions,
+ acp_session_id, status,
status_event_name, agent_session.created_at, modified_at,
(SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)
AS "thread_channel_id?",
@@ -311,7 +317,8 @@ impl AgentSessionRepo for PgAgentSessionRepo {
r#"
SELECT
id, name, owner_id, thread_id, originating_message_id, bot_id,
- model, harness, repo_url, workspace, sandbox_size, acp_session_id, status,
+ model, harness, repo_url, workspace, sandbox_size, instructions,
+ acp_session_id, status,
status_event_name, agent_session.created_at, modified_at,
(SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)
AS "thread_channel_id?",
@@ -349,7 +356,8 @@ impl AgentSessionRepo for PgAgentSessionRepo {
r#"
SELECT
id, name, owner_id, thread_id, originating_message_id, bot_id,
- model, harness, repo_url, workspace, sandbox_size, acp_session_id, status,
+ model, harness, repo_url, workspace, sandbox_size, instructions,
+ acp_session_id, status,
status_event_name, agent_session.created_at, modified_at,
(SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)
AS "thread_channel_id?",
@@ -380,7 +388,8 @@ impl AgentSessionRepo for PgAgentSessionRepo {
r#"
SELECT
id, name, owner_id, thread_id, originating_message_id, bot_id,
- model, harness, repo_url, workspace, sandbox_size, acp_session_id, status,
+ model, harness, repo_url, workspace, sandbox_size, instructions,
+ acp_session_id, status,
status_event_name, agent_session.created_at, modified_at,
(SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)
AS "thread_channel_id?",
diff --git a/crates/agent_session/src/outbound/postgres/test.rs b/crates/agent_session/src/outbound/postgres/test.rs
index dfe843a39f..61e917cdc0 100644
--- a/crates/agent_session/src/outbound/postgres/test.rs
+++ b/crates/agent_session/src/outbound/postgres/test.rs
@@ -93,6 +93,7 @@ fn new_session(
repo_url: Some("https://github.com/example/example".to_string()),
workspace: "/workspace".to_string(),
sandbox_size: SandboxSize::Default,
+ instructions: None,
egress_token_hash: None,
}
}
@@ -191,9 +192,58 @@ async fn create_and_get_round_trips(pool: PgPool) {
);
assert_eq!(session.thread_id, None);
assert_eq!(session.sandbox_size, SandboxSize::Default);
+ assert_eq!(session.instructions, None);
assert!(matches!(session.status, SessionStatus::NoMessages));
}
+/// Instructions survive the round trip, and come back on every read path a
+/// runtime uses to find its session - not just the one `create` returned.
+///
+/// The read paths matter more than the write here: what a session runs under
+/// is resolved at attach, and attach reaches the row through `get`, so a
+/// column the INSERT stores but a SELECT drops would look correct until the
+/// first reconnect.
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn instructions_round_trip_on_every_read_path(pool: PgPool) {
+ const INSTRUCTIONS: &str = "Answer in one sentence.\nNever open a pull request.";
+
+ let repo = PgAgentSessionRepo::new(pool.clone());
+ let bot_id = create_test_bot(&pool).await;
+ let (_channel_id, thread_id, originating_message_id) =
+ insert_originating_thread_fixture(&pool).await;
+ let params = CreateAgentSessionParams {
+ instructions: Some(INSTRUCTIONS.to_owned()),
+ egress_token_hash: Some("token-hash".to_owned()),
+ ..new_session(bot_id, Some(thread_id), Some(originating_message_id))
+ };
+ let id = params.id;
+
+ let created = create_session(&repo, params).await;
+ assert_eq!(created.instructions.as_deref(), Some(INSTRUCTIONS));
+
+ let fetched = AgentSessionRepo::get(&repo, id)
+ .await
+ .expect("get agent session");
+ assert_eq!(fetched.instructions.as_deref(), Some(INSTRUCTIONS));
+
+ let by_token = AgentSessionRepo::find_by_egress_token_hash(&repo, "token-hash")
+ .await
+ .expect("the token lookup should run")
+ .expect("the token should resolve to the session");
+ assert_eq!(by_token.instructions.as_deref(), Some(INSTRUCTIONS));
+
+ let for_thread = AgentSessionRepo::find_all_for_thread(&repo, thread_id)
+ .await
+ .expect("the thread lookup should run");
+ assert_eq!(
+ for_thread
+ .iter()
+ .map(|session| session.instructions.as_deref())
+ .collect::<Vec<_>>(),
+ vec![Some(INSTRUCTIONS)]
+ );
+}
+
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn set_acp_session_id_updates_only_the_resume_identity(pool: PgPool) {
let repo = PgAgentSessionRepo::new(pool.clone());
diff --git a/crates/agent_session/src/testing.rs b/crates/agent_session/src/testing.rs
index b31ef4c08a..622f2aaf1b 100644
--- a/crates/agent_session/src/testing.rs
+++ b/crates/agent_session/src/testing.rs
@@ -118,6 +118,7 @@ impl AgentSessionRepo for InMemoryAgentSessionRepo {
repo_url: params.repo_url,
workspace: params.workspace,
sandbox_size: params.sandbox_size,
+ instructions: params.instructions,
acp_session_id: None,
external: None,
status: SessionStatus::default(),
@@ -416,6 +417,7 @@ pub fn test_agent_session(id: AgentSessionId) -> AgentSession {
repo_url: Some("https://github.com/example/example".to_string()),
workspace: "/workspace".to_string(),
sandbox_size: SandboxSize::Default,
+ instructions: None,
acp_session_id: None,
external: None,
status: SessionStatus::NoMessages,
diff --git a/crates/agent_trigger/src/domain/service/test.rs b/crates/agent_trigger/src/domain/service/test.rs
index 2d75b72402..027a304f90 100644
--- a/crates/agent_trigger/src/domain/service/test.rs
+++ b/crates/agent_trigger/src/domain/service/test.rs
@@ -57,6 +57,7 @@ fn session(id: AgentSessionId, bot_id: BotId) -> AgentSession {
repo_url: Some("https://example.com/repo".to_owned()),
workspace: "/workspace".to_owned(),
sandbox_size: agent_session::domain::model::SandboxSize::Default,
+ instructions: None,
acp_session_id: None,
external: None,
status: SessionStatus::NoMessages,
diff --git a/crates/coding_agent_worker/src/dispatch.rs b/crates/coding_agent_worker/src/dispatch.rs
index 6c9c87b4d3..653b81d347 100644
--- a/crates/coding_agent_worker/src/dispatch.rs
+++ b/crates/coding_agent_worker/src/dispatch.rs
@@ -64,6 +64,10 @@ impl WorkExecutor for Dispatcher {
message_id,
content: content.clone(),
}),
+ // This daemon is the harness: its system prompt is
+ // whatever the binary in its config was built with, so
+ // there is nothing to state here.
+ instructions: None,
};
let created = match self.api.create_session(&request).await {
Ok(created) => created,
diff --git a/crates/macro_db_client/migrations/20260828113718_agent_session_instructions.sql b/crates/macro_db_client/migrations/20260828113718_agent_session_instructions.sql
new file mode 100644
index 0000000000..242e41e74e
--- /dev/null
+++ b/crates/macro_db_client/migrations/20260828113718_agent_session_instructions.sql
@@ -0,0 +1,9 @@
+-- Instructions the session's harness runs under, snapshotted at creation like
+-- model/harness/workspace. Immutable for the session's life: they are the
+-- runtime's system prompt, and a session that changed system prompts mid-way
+-- would have a conversation half its agent never agreed to.
+--
+-- Nullable with no default, unlike `workspace`: a session without instructions
+-- is the normal case, not a row waiting to be backfilled.
+ALTER TABLE agent_session
+ ADD COLUMN instructions TEXT;
diff --git a/packages/sdk/generated/agent-harness/types.gen.ts b/packages/sdk/generated/agent-harness/types.gen.ts
index a3f37a9339..dda25db2fe 100644
--- a/packages/sdk/generated/agent-harness/types.gen.ts
+++ b/packages/sdk/generated/agent-harness/types.gen.ts
@@ -122,6 +122,11 @@ export type AgentSessionResponse = {
* The session id.
*/
id: string;
+ /**
+ * Instructions the session's runtime works under, when any were stated
+ * at creation. Absent otherwise, so existing payloads are unchanged.
+ */
+ instructions?: string | null;
/**
* Model slug.
*/
@@ -208,6 +213,14 @@ export type CreateAgentSessionRequest = {
* bot its deployment is configured for.
*/
botId?: string | null;
+ /**
+ * Instructions the session's runtime works under, for its whole life.
+ *
+ * Recorded on the session whichever runtime serves it. Only the
+ * in-process one acts on them today; `agent_harness`'s `AgentKind`
+ * records what each of the others will need to.
+ */
+ instructions?: string | null;
/**
* The user who owns the session. Ignored for user callers, who always
* own their own sessions; required for bot callers without verified
diff --git a/packages/sdk/specs/agent-harness.json b/packages/sdk/specs/agent-harness.json
index 289f51c93b..37eb500ab3 100644
--- a/packages/sdk/specs/agent-harness.json
+++ b/packages/sdk/specs/agent-harness.json
@@ -743,6 +743,10 @@
"format": "uuid",
"description": "The session id."
},
+ "instructions": {
+ "type": ["string", "null"],
+ "description": "Instructions the session's runtime works under, when any were stated\nat creation. Absent otherwise, so existing payloads are unchanged."
+ },
"model": {
"type": "string",
"description": "Model slug."
@@ -825,6 +829,10 @@
"format": "uuid",
"description": "Bot the session runs for. Bot callers may omit it (their own identity\nis used) and must not name another bot; user callers must supply a\nbot they own. External sessions only: a managed session runs as the\nbot its deployment is configured for."
},
+ "instructions": {
+ "type": ["string", "null"],
+ "description": "Instructions the session's runtime works under, for its whole life.\n\nRecorded on the session whichever runtime serves it. Only the\nin-process one acts on them today; `agent_harness`'s `AgentKind`\nrecords what each of the others will need to."
+ },
"owner": {
"type": ["string", "null"],
"description": "The user who owns the session. Ignored for user callers, who always\nown their own sessions; required for bot callers without verified\nacting-user claims.\n\nFor bot callers this is a claim, not a verified fact: it is scoped to\nthe bot's own sessions, but the named user owns the session on the\nbot's say-so."
diff --git a/packages/sdk/src/entities/agent-sessions/agent-session.ts b/packages/sdk/src/entities/agent-sessions/agent-session.ts
index cfa0133dbf..9f7935e6b7 100644
--- a/packages/sdk/src/entities/agent-sessions/agent-session.ts
+++ b/packages/sdk/src/entities/agent-sessions/agent-session.ts
@@ -19,11 +19,11 @@ export class AgentSession extends MacroEntity<AgentSessionResponse> {
/** Create a managed session, optionally delivering its first prompt. */
static async createManaged(
client: MacroClient,
- opts?: { prompt?: string },
+ opts?: { prompt?: string; instructions?: string },
): Promise<AgentSession> {
const { session } = unwrap(
await client.agentHarness.createAgentSession({
- body: { prompt: opts?.prompt },
+ body: { prompt: opts?.prompt, instructions: opts?.instructions },
}),
);
return new AgentSession(client, session.id, session);
@@ -52,6 +52,12 @@ export class AgentSession extends MacroEntity<AgentSessionResponse> {
/** The directory in which the agent harness runs. */
readonly workspace = this.field('workspace');
+ /**
+ * Instructions the session's runtime works under, when any were stated at
+ * creation. Fixed for the session's life.
+ */
+ readonly instructions = this.field('instructions');
+
/** The session's latest runtime status. */
readonly status = this.field('status');
diff --git a/packages/sdk/src/entities/agent-sessions/namespace.ts b/packages/sdk/src/entities/agent-sessions/namespace.ts
index 08fdde643d..8564e0479e 100644
--- a/packages/sdk/src/entities/agent-sessions/namespace.ts
+++ b/packages/sdk/src/entities/agent-sessions/namespace.ts
@@ -12,7 +12,10 @@ export class AgentSessionNamespace {
}
/** Create a managed agent session. */
- createManaged(opts?: { prompt?: string }): Promise<AgentSession> {
+ createManaged(opts?: {
+ prompt?: string;
+ instructions?: string;
+ }): Promise<AgentSession> {
return AgentSession.createManaged(this.client, opts);
}
diff --git a/services/agent_harness_service/src/containers.rs b/services/agent_harness_service/src/containers.rs
index 7fed9473ae..e6038d7fc4 100644
--- a/services/agent_harness_service/src/containers.rs
+++ b/services/agent_harness_service/src/containers.rs
@@ -127,6 +127,7 @@ where
id: session,
owner: row.owner_id,
model: row.model,
+ instructions: row.instructions,
acp_session_id: row.acp_session_id,
}));
}