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_session): link pull requests to agent sessions (#7108)

dev-rb53e6eadd8b89
diff --git a/.sqlx/query-3ab165b6a10413138d1c91edbd95d3c941f76b4022aee43bed3c5ba141282fe4.json b/.sqlx/query-3ab165b6a10413138d1c91edbd95d3c941f76b4022aee43bed3c5ba141282fe4.json
new file mode 100644
index 0000000000..cd91ed73ed
--- /dev/null
+++ b/.sqlx/query-3ab165b6a10413138d1c91edbd95d3c941f76b4022aee43bed3c5ba141282fe4.json
@@ -0,0 +1,40 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT github_key, source, linked_by, created_at\n FROM agent_session_pull_request\n WHERE agent_session_id = $1\n ORDER BY created_at, github_key\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "github_key",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "source",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "linked_by",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ true,
+ false
+ ]
+ },
+ "hash": "3ab165b6a10413138d1c91edbd95d3c941f76b4022aee43bed3c5ba141282fe4"
+}
diff --git a/.sqlx/query-6431b79f7a285b7975edb07e615ea22f6260b72a10c6f38920bc8174aafecbfc.json b/.sqlx/query-6431b79f7a285b7975edb07e615ea22f6260b72a10c6f38920bc8174aafecbfc.json
new file mode 100644
index 0000000000..ecffeeca9d
--- /dev/null
+++ b/.sqlx/query-6431b79f7a285b7975edb07e615ea22f6260b72a10c6f38920bc8174aafecbfc.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT agent_session_id\n FROM agent_session_pull_request\n WHERE lower(github_key) = lower($1)\n ORDER BY created_at, agent_session_id\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "agent_session_id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "6431b79f7a285b7975edb07e615ea22f6260b72a10c6f38920bc8174aafecbfc"
+}
diff --git a/.sqlx/query-a11acb832e79b39f3943e31d9ee0b6eedec5318dc1bb4938795d5424d6dc9251.json b/.sqlx/query-a11acb832e79b39f3943e31d9ee0b6eedec5318dc1bb4938795d5424d6dc9251.json
new file mode 100644
index 0000000000..79df3e566d
--- /dev/null
+++ b/.sqlx/query-a11acb832e79b39f3943e31d9ee0b6eedec5318dc1bb4938795d5424d6dc9251.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO agent_session_pull_request (agent_session_id, github_key, source, linked_by)\n VALUES ($1, $2, 'user', $3)\n ON CONFLICT (agent_session_id, github_key) DO NOTHING\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "a11acb832e79b39f3943e31d9ee0b6eedec5318dc1bb4938795d5424d6dc9251"
+}
diff --git a/.sqlx/query-c09a8ffd057adf75fc00dd1ad3528f2eb5458a5434f2e9102283007dd642279a.json b/.sqlx/query-c09a8ffd057adf75fc00dd1ad3528f2eb5458a5434f2e9102283007dd642279a.json
new file mode 100644
index 0000000000..ece58258a1
--- /dev/null
+++ b/.sqlx/query-c09a8ffd057adf75fc00dd1ad3528f2eb5458a5434f2e9102283007dd642279a.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n DELETE FROM agent_session_pull_request\n WHERE agent_session_id = $1 AND lower(github_key) = lower($2) AND source = 'user'\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "c09a8ffd057adf75fc00dd1ad3528f2eb5458a5434f2e9102283007dd642279a"
+}
diff --git a/.sqlx/query-f7e0f64b4097b1dd5569d27f648917d52de9c6d6e384ff7a4e7c5e837149090e.json b/.sqlx/query-f7e0f64b4097b1dd5569d27f648917d52de9c6d6e384ff7a4e7c5e837149090e.json
new file mode 100644
index 0000000000..fd7d707636
--- /dev/null
+++ b/.sqlx/query-f7e0f64b4097b1dd5569d27f648917d52de9c6d6e384ff7a4e7c5e837149090e.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO agent_session_pull_request (agent_session_id, github_key, source)\n SELECT $1, $2, 'agent'\n WHERE EXISTS (SELECT 1 FROM agent_session WHERE id = $1 AND owner_id = $3)\n ON CONFLICT (agent_session_id, github_key) DO UPDATE SET source = 'agent', linked_by = NULL\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "f7e0f64b4097b1dd5569d27f648917d52de9c6d6e384ff7a4e7c5e837149090e"
+}
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/client.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/client.ts
index 86609da6c2..b038bc1ead 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/client.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/client.ts
@@ -27,12 +27,16 @@ import type {
LoadAgentModelsResponse,
PreviewAgentSessionsRequest,
PreviewAgentSessionsResponse,
+ PullRequestSessionsResponse,
+ PullRequestUrl,
RenameAgentSessionRequest,
SandboxSizeBody,
+ SessionPullRequestsResponse,
SetAgentSessionArchivedRequest,
SharePermissionV2,
StartResponse,
StatusResponse,
+ UnlinkAgentSessionPullRequestParams,
UpdateSharePermissionRequestV2,
} from './schemas';
@@ -555,6 +559,72 @@ export const createAgentSession = async (
} as createAgentSessionResponse;
};
+/**
+ * @summary List the sessions associated with a pull request that the caller can view.
+ */
+export type agentSessionsForPullRequestResponse200 = {
+ data: PullRequestSessionsResponse;
+ status: 200;
+};
+
+export type agentSessionsForPullRequestResponse400 = {
+ data: string;
+ status: 400;
+};
+
+export type agentSessionsForPullRequestResponse401 = {
+ data: string;
+ status: 401;
+};
+
+export type agentSessionsForPullRequestResponse500 = {
+ data: string;
+ status: 500;
+};
+
+export type agentSessionsForPullRequestResponseSuccess =
+ agentSessionsForPullRequestResponse200 & {
+ headers: Headers;
+ };
+export type agentSessionsForPullRequestResponseError = (
+ | agentSessionsForPullRequestResponse400
+ | agentSessionsForPullRequestResponse401
+ | agentSessionsForPullRequestResponse500
+) & {
+ headers: Headers;
+};
+
+export type agentSessionsForPullRequestResponse =
+ | agentSessionsForPullRequestResponseSuccess
+ | agentSessionsForPullRequestResponseError;
+
+export const getAgentSessionsForPullRequestUrl = () => {
+ return `/agent-sessions/by-pull-request`;
+};
+
+export const agentSessionsForPullRequest = async (
+ pullRequestUrl: PullRequestUrl,
+ options?: RequestInit
+): Promise<agentSessionsForPullRequestResponse> => {
+ const res = await fetch(getAgentSessionsForPullRequestUrl(), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(pullRequestUrl),
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: agentSessionsForPullRequestResponse['data'] = body
+ ? JSON.parse(body)
+ : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as agentSessionsForPullRequestResponse;
+};
+
/**
* No per-id access extractor: a chip has to render for a session the caller
cannot open, so access is answered per id in the body rather than
@@ -1388,6 +1458,233 @@ export const updateAgentSessionPermissions = async (
} as updateAgentSessionPermissionsResponse;
};
+/**
+ * @summary List the pull requests associated with a session the caller can view.
+ */
+export type listAgentSessionPullRequestsResponse200 = {
+ data: SessionPullRequestsResponse;
+ status: 200;
+};
+
+export type listAgentSessionPullRequestsResponse401 = {
+ data: string;
+ status: 401;
+};
+
+export type listAgentSessionPullRequestsResponse403 = {
+ data: string;
+ status: 403;
+};
+
+export type listAgentSessionPullRequestsResponse500 = {
+ data: string;
+ status: 500;
+};
+
+export type listAgentSessionPullRequestsResponseSuccess =
+ listAgentSessionPullRequestsResponse200 & {
+ headers: Headers;
+ };
+export type listAgentSessionPullRequestsResponseError = (
+ | listAgentSessionPullRequestsResponse401
+ | listAgentSessionPullRequestsResponse403
+ | listAgentSessionPullRequestsResponse500
+) & {
+ headers: Headers;
+};
+
+export type listAgentSessionPullRequestsResponse =
+ | listAgentSessionPullRequestsResponseSuccess
+ | listAgentSessionPullRequestsResponseError;
+
+export const getListAgentSessionPullRequestsUrl = (sessionId: string) => {
+ return `/agent-sessions/${sessionId}/pull-requests`;
+};
+
+export const listAgentSessionPullRequests = async (
+ sessionId: string,
+ options?: RequestInit
+): Promise<listAgentSessionPullRequestsResponse> => {
+ const res = await fetch(getListAgentSessionPullRequestsUrl(sessionId), {
+ ...options,
+ method: 'GET',
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: listAgentSessionPullRequestsResponse['data'] = body
+ ? JSON.parse(body)
+ : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as listAgentSessionPullRequestsResponse;
+};
+
+/**
+ * @summary Link a pull request to a session the caller can edit.
+ */
+export type linkAgentSessionPullRequestResponse204 = {
+ data: void;
+ status: 204;
+};
+
+export type linkAgentSessionPullRequestResponse400 = {
+ data: string;
+ status: 400;
+};
+
+export type linkAgentSessionPullRequestResponse401 = {
+ data: string;
+ status: 401;
+};
+
+export type linkAgentSessionPullRequestResponse403 = {
+ data: string;
+ status: 403;
+};
+
+export type linkAgentSessionPullRequestResponse500 = {
+ data: string;
+ status: 500;
+};
+
+export type linkAgentSessionPullRequestResponseSuccess =
+ linkAgentSessionPullRequestResponse204 & {
+ headers: Headers;
+ };
+export type linkAgentSessionPullRequestResponseError = (
+ | linkAgentSessionPullRequestResponse400
+ | linkAgentSessionPullRequestResponse401
+ | linkAgentSessionPullRequestResponse403
+ | linkAgentSessionPullRequestResponse500
+) & {
+ headers: Headers;
+};
+
+export type linkAgentSessionPullRequestResponse =
+ | linkAgentSessionPullRequestResponseSuccess
+ | linkAgentSessionPullRequestResponseError;
+
+export const getLinkAgentSessionPullRequestUrl = (sessionId: string) => {
+ return `/agent-sessions/${sessionId}/pull-requests`;
+};
+
+export const linkAgentSessionPullRequest = async (
+ sessionId: string,
+ pullRequestUrl: PullRequestUrl,
+ options?: RequestInit
+): Promise<linkAgentSessionPullRequestResponse> => {
+ const res = await fetch(getLinkAgentSessionPullRequestUrl(sessionId), {
+ ...options,
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(pullRequestUrl),
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: linkAgentSessionPullRequestResponse['data'] = body
+ ? JSON.parse(body)
+ : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as linkAgentSessionPullRequestResponse;
+};
+
+/**
+ * @summary Unlink a pull request a person linked to a session the caller can edit. The pull request
+the session's agent opened stays linked.
+ */
+export type unlinkAgentSessionPullRequestResponse204 = {
+ data: void;
+ status: 204;
+};
+
+export type unlinkAgentSessionPullRequestResponse400 = {
+ data: string;
+ status: 400;
+};
+
+export type unlinkAgentSessionPullRequestResponse401 = {
+ data: string;
+ status: 401;
+};
+
+export type unlinkAgentSessionPullRequestResponse403 = {
+ data: string;
+ status: 403;
+};
+
+export type unlinkAgentSessionPullRequestResponse500 = {
+ data: string;
+ status: 500;
+};
+
+export type unlinkAgentSessionPullRequestResponseSuccess =
+ unlinkAgentSessionPullRequestResponse204 & {
+ headers: Headers;
+ };
+export type unlinkAgentSessionPullRequestResponseError = (
+ | unlinkAgentSessionPullRequestResponse400
+ | unlinkAgentSessionPullRequestResponse401
+ | unlinkAgentSessionPullRequestResponse403
+ | unlinkAgentSessionPullRequestResponse500
+) & {
+ headers: Headers;
+};
+
+export type unlinkAgentSessionPullRequestResponse =
+ | unlinkAgentSessionPullRequestResponseSuccess
+ | unlinkAgentSessionPullRequestResponseError;
+
+export const getUnlinkAgentSessionPullRequestUrl = (
+ sessionId: string,
+ params: UnlinkAgentSessionPullRequestParams
+) => {
+ const normalizedParams = new URLSearchParams();
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : value.toString());
+ }
+ });
+
+ const stringifiedParams = normalizedParams.toString();
+
+ return stringifiedParams.length > 0
+ ? `/agent-sessions/${sessionId}/pull-requests?${stringifiedParams}`
+ : `/agent-sessions/${sessionId}/pull-requests`;
+};
+
+export const unlinkAgentSessionPullRequest = async (
+ sessionId: string,
+ params: UnlinkAgentSessionPullRequestParams,
+ options?: RequestInit
+): Promise<unlinkAgentSessionPullRequestResponse> => {
+ const res = await fetch(
+ getUnlinkAgentSessionPullRequestUrl(sessionId, params),
+ {
+ ...options,
+ method: 'DELETE',
+ }
+ );
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: unlinkAgentSessionPullRequestResponse['data'] = body
+ ? JSON.parse(body)
+ : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as unlinkAgentSessionPullRequestResponse;
+};
+
/**
* @summary The actions waiting to dispatch in this session, oldest first.
*/
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 4c9bc6f1c8..17c1f00e5d 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
@@ -178,6 +178,9 @@ export * from './previewAgentSessionsResponse';
export * from './promptAttachment';
export * from './promptAttachmentMimeType';
export * from './promptAttachmentSize';
+export * from './pullRequestLinkSource';
+export * from './pullRequestSessionsResponse';
+export * from './pullRequestUrl';
export * from './queuedActionDto';
export * from './queuedActionDtoActorUserId';
export * from './queuedActionDtoPrompt';
@@ -186,6 +189,9 @@ export * from './sandboxSize';
export * from './sandboxSizeBody';
export * from './sessionBot';
export * from './sessionBotAvatarUrl';
+export * from './sessionPullRequestLink';
+export * from './sessionPullRequestLinkLinkedBy';
+export * from './sessionPullRequestsResponse';
export * from './sessionStatusDto';
export * from './sessionStatusDtoOneOf';
export * from './sessionStatusDtoOneOfFive';
@@ -201,6 +207,7 @@ export * from './sharePermissionV2LinkShareAccessLevel';
export * from './sharePermissionV2TeamShareAccessLevel';
export * from './startResponse';
export * from './statusResponse';
+export * from './unlinkAgentSessionPullRequestParams';
export * from './updateChannelSharePermission';
export * from './updateChannelSharePermissionAccessLevel';
export * from './updateOperation';
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/pullRequestLinkSource.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/pullRequestLinkSource.ts
new file mode 100644
index 0000000000..a48b95cb8a
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/pullRequestLinkSource.ts
@@ -0,0 +1,18 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Who associated a pull request with a session.
+ */
+export type PullRequestLinkSource =
+ (typeof PullRequestLinkSource)[keyof typeof PullRequestLinkSource];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const PullRequestLinkSource = {
+ agent: 'agent',
+ user: 'user',
+} as const;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/pullRequestSessionsResponse.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/pullRequestSessionsResponse.ts
new file mode 100644
index 0000000000..d579c74195
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/pullRequestSessionsResponse.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The sessions associated with a pull request.
+ */
+export interface PullRequestSessionsResponse {
+ /** Sessions associated with the pull request that the caller can view. */
+ sessionIds: string[];
+}
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/pullRequestUrl.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/pullRequestUrl.ts
new file mode 100644
index 0000000000..dcd54083f2
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/pullRequestUrl.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * A GitHub pull request, by URL.
+ */
+export interface PullRequestUrl {
+ /** The pull request's GitHub URL, such as `https://github.com/owner/repo/pull/12`. */
+ url: string;
+}
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/sessionPullRequestLink.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/sessionPullRequestLink.ts
new file mode 100644
index 0000000000..b060636b72
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/sessionPullRequestLink.ts
@@ -0,0 +1,25 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+import type { PullRequestLinkSource } from './pullRequestLinkSource';
+import type { SessionPullRequestLinkLinkedBy } from './sessionPullRequestLinkLinkedBy';
+
+/**
+ * A pull request associated with a session.
+ */
+export interface SessionPullRequestLink {
+ /** When the pull request was associated with the session. */
+ createdAt: string;
+ /** The pull request's `owner/repo/pull/number` key. */
+ githubKey: string;
+ /** The Macro user who linked it, for links a person made. */
+ linkedBy?: SessionPullRequestLinkLinkedBy;
+ /** Who associated the pull request with the session. */
+ source: PullRequestLinkSource;
+ /** The pull request's GitHub URL. */
+ url: string;
+}
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/sessionPullRequestLinkLinkedBy.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/sessionPullRequestLinkLinkedBy.ts
new file mode 100644
index 0000000000..1e9ffbd38b
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/sessionPullRequestLinkLinkedBy.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The Macro user who linked it, for links a person made.
+ */
+export type SessionPullRequestLinkLinkedBy = string | null;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/sessionPullRequestsResponse.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/sessionPullRequestsResponse.ts
new file mode 100644
index 0000000000..2916e7630d
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/sessionPullRequestsResponse.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 { SessionPullRequestLink } from './sessionPullRequestLink';
+
+/**
+ * The pull requests associated with a session.
+ */
+export interface SessionPullRequestsResponse {
+ /** Pull requests, oldest link first. */
+ pullRequests: SessionPullRequestLink[];
+}
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/unlinkAgentSessionPullRequestParams.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/unlinkAgentSessionPullRequestParams.ts
new file mode 100644
index 0000000000..aeb1b4a408
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/unlinkAgentSessionPullRequestParams.ts
@@ -0,0 +1,13 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type UnlinkAgentSessionPullRequestParams = {
+ /**
+ * The pull request's GitHub URL
+ */
+ url: string;
+};
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 1c2020da63..30957b96f7 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
@@ -377,6 +377,65 @@
}
}
},
+ "/agent-sessions/by-pull-request": {
+ "post": {
+ "tags": ["agent-sessions"],
+ "summary": "List the sessions associated with a pull request that the caller can view.",
+ "operationId": "agent_sessions_for_pull_request",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PullRequestUrl"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PullRequestSessionsResponse"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/agent-sessions/preview": {
"post": {
"tags": ["agent-sessions"],
@@ -1190,6 +1249,210 @@
}
}
},
+ "/agent-sessions/{session_id}/pull-requests": {
+ "get": {
+ "tags": ["agent-sessions"],
+ "summary": "List the pull requests associated with a session the caller can view.",
+ "operationId": "list_agent_session_pull_requests",
+ "parameters": [
+ {
+ "name": "session_id",
+ "in": "path",
+ "description": "ID of the agent session",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/SessionPullRequestsResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ },
+ "put": {
+ "tags": ["agent-sessions"],
+ "summary": "Link a pull request to a session the caller can edit.",
+ "operationId": "link_agent_session_pull_request",
+ "parameters": [
+ {
+ "name": "session_id",
+ "in": "path",
+ "description": "ID of the agent session",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PullRequestUrl"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "204": {
+ "description": ""
+ },
+ "400": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ },
+ "delete": {
+ "tags": ["agent-sessions"],
+ "summary": "Unlink a pull request a person linked to a session the caller can edit. The pull request\nthe session's agent opened stays linked.",
+ "operationId": "unlink_agent_session_pull_request",
+ "parameters": [
+ {
+ "name": "session_id",
+ "in": "path",
+ "description": "ID of the agent session",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ },
+ {
+ "name": "url",
+ "in": "query",
+ "description": "The pull request's GitHub URL",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "204": {
+ "description": ""
+ },
+ "400": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/agent-sessions/{session_id}/queue": {
"get": {
"tags": ["agent-sessions"],
@@ -3157,6 +3420,37 @@
}
}
},
+ "PullRequestLinkSource": {
+ "type": "string",
+ "description": "Who associated a pull request with a session.",
+ "enum": ["agent", "user"]
+ },
+ "PullRequestSessionsResponse": {
+ "type": "object",
+ "description": "The sessions associated with a pull request.",
+ "required": ["sessionIds"],
+ "properties": {
+ "sessionIds": {
+ "type": "array",
+ "items": {
+ "type": "string",
+ "format": "uuid"
+ },
+ "description": "Sessions associated with the pull request that the caller can view."
+ }
+ }
+ },
+ "PullRequestUrl": {
+ "type": "object",
+ "description": "A GitHub pull request, by URL.",
+ "required": ["url"],
+ "properties": {
+ "url": {
+ "type": "string",
+ "description": "The pull request's GitHub URL, such as `https://github.com/owner/repo/pull/12`."
+ }
+ }
+ },
"QueuedActionDto": {
"type": "object",
"description": "One action waiting in a session's queue.\n\nClients deserialize this, so both derives are used.",
@@ -3242,6 +3536,48 @@
}
}
},
+ "SessionPullRequestLink": {
+ "type": "object",
+ "description": "A pull request associated with a session.",
+ "required": ["githubKey", "url", "source", "createdAt"],
+ "properties": {
+ "createdAt": {
+ "type": "string",
+ "format": "date-time",
+ "description": "When the pull request was associated with the session."
+ },
+ "githubKey": {
+ "type": "string",
+ "description": "The pull request's `owner/repo/pull/number` key."
+ },
+ "linkedBy": {
+ "type": ["string", "null"],
+ "description": "The Macro user who linked it, for links a person made."
+ },
+ "source": {
+ "$ref": "#/components/schemas/PullRequestLinkSource",
+ "description": "Who associated the pull request with the session."
+ },
+ "url": {
+ "type": "string",
+ "description": "The pull request's GitHub URL."
+ }
+ }
+ },
+ "SessionPullRequestsResponse": {
+ "type": "object",
+ "description": "The pull requests associated with a session.",
+ "required": ["pullRequests"],
+ "properties": {
+ "pullRequests": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/SessionPullRequestLink"
+ },
+ "description": "Pull requests, oldest link first."
+ }
+ }
+ },
"SessionStatusDto": {
"oneOf": [
{
diff --git a/crates/agent_session/src/domain/mod.rs b/crates/agent_session/src/domain/mod.rs
index fa2fcb19ce..e2095d4366 100644
--- a/crates/agent_session/src/domain/mod.rs
+++ b/crates/agent_session/src/domain/mod.rs
@@ -11,6 +11,7 @@ pub mod model;
pub mod name_generation;
pub mod ports;
pub mod pull_request;
+pub mod pull_request_links;
mod sandbox_size;
pub mod search;
pub mod service;
diff --git a/crates/agent_session/src/domain/pull_request.rs b/crates/agent_session/src/domain/pull_request.rs
index ed76f9ec41..b909b33a61 100644
--- a/crates/agent_session/src/domain/pull_request.rs
+++ b/crates/agent_session/src/domain/pull_request.rs
@@ -112,7 +112,7 @@ where
}
/// Normalize a GitHub PR link, rejecting credentials and removing queries and fragments.
-fn canonical_url(input: &str) -> Result<String> {
+pub(crate) fn canonical_url(input: &str) -> Result<String> {
let invalid = || AgentSessionError::InvalidPullRequestUrl;
let (_, owner, repo, number) = lazy_regex::regex_captures!(
r"\A(?i:https://github\.com)(?::443)?/([a-zA-Z0-9_.-]+)/([a-zA-Z0-9_.-]+)/pull/([0-9]+)/*(?:[?#][^\r\n]*)?\z",
diff --git a/crates/agent_session/src/domain/pull_request_links.rs b/crates/agent_session/src/domain/pull_request_links.rs
new file mode 100644
index 0000000000..ad423d27ea
--- /dev/null
+++ b/crates/agent_session/src/domain/pull_request_links.rs
@@ -0,0 +1,195 @@
+//! Pull requests associated with sessions: the one a session's agent opened, and any a person
+//! linked afterwards.
+
+use std::sync::Arc;
+
+use chrono::{DateTime, Utc};
+use entity_access::domain::models::{
+ EditAccessLevel, EntityAccessAuth, EntityAccessReceipt, EntityType, RequiredPermission,
+ ViewAccessLevel,
+};
+use macro_user_id::user_id::MacroUserIdStr;
+use macro_uuid::Uuid;
+
+use super::error::{AgentSessionError, Result};
+use super::model::AgentSessionId;
+use super::ports::SessionViewAccess;
+use super::pull_request::canonical_url;
+
+#[cfg(test)]
+mod test;
+
+/// Who associated a pull request with a session.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
+#[serde(rename_all = "snake_case")]
+pub enum PullRequestLinkSource {
+ /// The session's agent opened it.
+ Agent,
+ /// A person linked it.
+ User,
+}
+
+/// A pull request associated with a session.
+#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
+#[serde(rename_all = "camelCase")]
+pub struct SessionPullRequestLink {
+ /// The pull request's `owner/repo/pull/number` key.
+ pub github_key: String,
+ /// The pull request's GitHub URL.
+ pub url: String,
+ /// Who associated the pull request with the session.
+ pub source: PullRequestLinkSource,
+ /// The Macro user who linked it, for links a person made.
+ pub linked_by: Option<String>,
+ /// When the pull request was associated with the session.
+ pub created_at: DateTime<Utc>,
+}
+
+/// The `owner/repo/pull/number` key of a GitHub pull request URL.
+pub(crate) fn pull_request_key(url: &str) -> Result<String> {
+ let url = canonical_url(url)?;
+ Ok(url.trim_start_matches("https://github.com/").to_owned())
+}
+
+/// Stores the pull requests associated with sessions.
+pub trait SessionPullRequestLinkRepo: Send + Sync + 'static {
+ /// Link `github_key` to `session` on behalf of `linked_by`. An existing link is kept as is.
+ fn link_pull_request(
+ &self,
+ session: AgentSessionId,
+ github_key: &str,
+ linked_by: &MacroUserIdStr<'static>,
+ ) -> impl Future<Output = Result<()>> + Send;
+
+ /// Remove a link a person made; the pull request the session's agent opened stays. Returns
+ /// whether a link was removed.
+ fn unlink_pull_request(
+ &self,
+ session: AgentSessionId,
+ github_key: &str,
+ ) -> impl Future<Output = Result<bool>> + Send;
+
+ /// The pull requests associated with `session`, oldest first.
+ fn session_pull_requests(
+ &self,
+ session: AgentSessionId,
+ ) -> impl Future<Output = Result<Vec<SessionPullRequestLink>>> + Send;
+
+ /// The sessions associated with the pull request `github_key`, compared case-insensitively.
+ fn sessions_for_pull_request(
+ &self,
+ github_key: &str,
+ ) -> impl Future<Output = Result<Vec<AgentSessionId>>> + Send;
+}
+
+/// Associating pull requests with sessions and finding them again.
+pub trait SessionPullRequestLinks: Send + Sync + 'static {
+ /// Link the pull request at `url` to the session `access` covers. Linking a pull request
+ /// that is already linked changes nothing.
+ fn link_pull_request(
+ &self,
+ access: &EntityAccessReceipt<EditAccessLevel>,
+ url: &str,
+ ) -> impl Future<Output = Result<()>> + Send;
+
+ /// Unlink a pull request a person linked to the session `access` covers.
+ fn unlink_pull_request(
+ &self,
+ access: &EntityAccessReceipt<EditAccessLevel>,
+ url: &str,
+ ) -> impl Future<Output = Result<()>> + Send;
+
+ /// The pull requests associated with the session `access` covers.
+ fn session_pull_requests(
+ &self,
+ access: &EntityAccessReceipt<ViewAccessLevel>,
+ ) -> impl Future<Output = Result<Vec<SessionPullRequestLink>>> + Send;
+
+ /// The sessions associated with the pull request at `url` that `viewer` may view.
+ fn sessions_for_pull_request(
+ &self,
+ viewer: &MacroUserIdStr<'static>,
+ url: &str,
+ ) -> impl Future<Output = Result<Vec<AgentSessionId>>> + Send;
+}
+
+/// Pull request links over the session store, answering session visibility with `view_access`.
+pub struct SessionPullRequestLinkService<R> {
+ repo: R,
+ view_access: Arc<dyn SessionViewAccess>,
+}
+
+impl<R> SessionPullRequestLinkService<R> {
+ /// Build the service over the session store and the access check read routes use.
+ pub fn new(repo: R, view_access: Arc<dyn SessionViewAccess>) -> Self {
+ Self { repo, view_access }
+ }
+}
+
+impl<R: SessionPullRequestLinkRepo> SessionPullRequestLinks for SessionPullRequestLinkService<R> {
+ #[tracing::instrument(err, skip(self, access))]
+ async fn link_pull_request(
+ &self,
+ access: &EntityAccessReceipt<EditAccessLevel>,
+ url: &str,
+ ) -> Result<()> {
+ let session = session_id(access)?;
+ let EntityAccessAuth::Authenticated(user) = access.auth() else {
+ return Err(AgentSessionError::Forbidden);
+ };
+ let github_key = pull_request_key(url)?;
+ self.repo
+ .link_pull_request(session, &github_key, user)
+ .await
+ }
+
+ #[tracing::instrument(err, skip(self, access))]
+ async fn unlink_pull_request(
+ &self,
+ access: &EntityAccessReceipt<EditAccessLevel>,
+ url: &str,
+ ) -> Result<()> {
+ let session = session_id(access)?;
+ let github_key = pull_request_key(url)?;
+ self.repo.unlink_pull_request(session, &github_key).await?;
+ Ok(())
+ }
+
+ #[tracing::instrument(err, skip(self, access))]
+ async fn session_pull_requests(
+ &self,
+ access: &EntityAccessReceipt<ViewAccessLevel>,
+ ) -> Result<Vec<SessionPullRequestLink>> {
+ self.repo.session_pull_requests(session_id(access)?).await
+ }
+
+ #[tracing::instrument(err, skip(self))]
+ async fn sessions_for_pull_request(
+ &self,
+ viewer: &MacroUserIdStr<'static>,
+ url: &str,
+ ) -> Result<Vec<AgentSessionId>> {
+ let github_key = pull_request_key(url)?;
+ let mut visible = Vec::new();
+ for session in self.repo.sessions_for_pull_request(&github_key).await? {
+ if self.view_access.can_view(viewer, session).await? {
+ visible.push(session);
+ }
+ }
+ Ok(visible)
+ }
+}
+
+fn session_id<T: RequiredPermission>(access: &EntityAccessReceipt<T>) -> Result<AgentSessionId> {
+ if access.entity().entity_type != EntityType::AgentSession {
+ return Err(AgentSessionError::Unknown(anyhow::anyhow!(
+ "session pull request links received access for another entity type"
+ )));
+ }
+ Ok(AgentSessionId::new_from_uuid(
+ Uuid::parse_str(&access.entity().entity_id)
+ .map_err(|error| anyhow::anyhow!("invalid agent session access receipt: {error}"))?,
+ ))
+}
diff --git a/crates/agent_session/src/domain/pull_request_links/test.rs b/crates/agent_session/src/domain/pull_request_links/test.rs
new file mode 100644
index 0000000000..514998b7be
--- /dev/null
+++ b/crates/agent_session/src/domain/pull_request_links/test.rs
@@ -0,0 +1,262 @@
+use std::collections::HashSet;
+use std::pin::Pin;
+use std::sync::Mutex;
+
+use super::*;
+
+#[derive(Default)]
+struct StubLinks {
+ links: Mutex<
+ Vec<(
+ AgentSessionId,
+ String,
+ PullRequestLinkSource,
+ Option<String>,
+ )>,
+ >,
+}
+
+impl StubLinks {
+ fn with_agent_link(session: AgentSessionId, github_key: &str) -> Self {
+ let links = Self::default();
+ links.links.lock().unwrap().push((
+ session,
+ github_key.to_owned(),
+ PullRequestLinkSource::Agent,
+ None,
+ ));
+ links
+ }
+}
+
+impl SessionPullRequestLinkRepo for Arc<StubLinks> {
+ async fn link_pull_request(
+ &self,
+ session: AgentSessionId,
+ github_key: &str,
+ linked_by: &MacroUserIdStr<'static>,
+ ) -> Result<()> {
+ let mut links = self.links.lock().unwrap();
+ if !links
+ .iter()
+ .any(|(linked, key, ..)| *linked == session && key.eq_ignore_ascii_case(github_key))
+ {
+ links.push((
+ session,
+ github_key.to_owned(),
+ PullRequestLinkSource::User,
+ Some(linked_by.as_ref().to_owned()),
+ ));
+ }
+ Ok(())
+ }
+
+ async fn unlink_pull_request(&self, session: AgentSessionId, github_key: &str) -> Result<bool> {
+ let mut links = self.links.lock().unwrap();
+ let before = links.len();
+ links.retain(|(linked, key, source, _)| {
+ !(*linked == session
+ && key.eq_ignore_ascii_case(github_key)
+ && *source == PullRequestLinkSource::User)
+ });
+ Ok(links.len() != before)
+ }
+
+ async fn session_pull_requests(
+ &self,
+ session: AgentSessionId,
+ ) -> Result<Vec<SessionPullRequestLink>> {
+ Ok(self
+ .links
+ .lock()
+ .unwrap()
+ .iter()
+ .filter(|(linked, ..)| *linked == session)
+ .map(|(_, key, source, linked_by)| SessionPullRequestLink {
+ github_key: key.clone(),
+ url: format!("https://github.com/{key}"),
+ source: *source,
+ linked_by: linked_by.clone(),
+ created_at: DateTime::<Utc>::default(),
+ })
+ .collect())
+ }
+
+ async fn sessions_for_pull_request(&self, github_key: &str) -> Result<Vec<AgentSessionId>> {
+ Ok(self
+ .links
+ .lock()
+ .unwrap()
+ .iter()
+ .filter(|(_, key, ..)| key.eq_ignore_ascii_case(github_key))
+ .map(|(session, ..)| *session)
+ .collect())
+ }
+}
+
+struct ViewableSessions(HashSet<AgentSessionId>);
+
+impl SessionViewAccess for ViewableSessions {
+ fn can_view<'a>(
+ &'a self,
+ _viewer: &'a MacroUserIdStr<'static>,
+ session: AgentSessionId,
+ ) -> Pin<Box<dyn Future<Output = Result<bool>> + Send + 'a>> {
+ Box::pin(async move { Ok(self.0.contains(&session)) })
+ }
+}
+
+fn user() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from_email("[email protected]").unwrap()
+}
+
+fn edit_access(session: AgentSessionId) -> EntityAccessReceipt<EditAccessLevel> {
+ EntityAccessReceipt::dangerously_assert_authenticated_user(
+ user(),
+ &session.to_string(),
+ EntityType::AgentSession,
+ )
+}
+
+fn view_access(session: AgentSessionId) -> EntityAccessReceipt<ViewAccessLevel> {
+ EntityAccessReceipt::dangerously_assert_authenticated_user(
+ user(),
+ &session.to_string(),
+ EntityType::AgentSession,
+ )
+}
+
+fn service(
+ links: &Arc<StubLinks>,
+ viewable: &[AgentSessionId],
+) -> SessionPullRequestLinkService<Arc<StubLinks>> {
+ SessionPullRequestLinkService::new(
+ links.clone(),
+ Arc::new(ViewableSessions(viewable.iter().copied().collect())),
+ )
+}
+
+#[tokio::test]
+async fn links_a_pull_request_by_its_canonical_key_on_behalf_of_the_caller() {
+ let session = AgentSessionId::new();
+ let links = Arc::new(StubLinks::default());
+ let service = service(&links, &[]);
+
+ service
+ .link_pull_request(
+ &edit_access(session),
+ "https://github.com/macro-inc/macro/pull/12/files?diff=split",
+ )
+ .await
+ .unwrap_err();
+ service
+ .link_pull_request(
+ &edit_access(session),
+ "https://github.com/macro-inc/macro/pull/12#discussion",
+ )
+ .await
+ .unwrap();
+ service
+ .link_pull_request(
+ &edit_access(session),
+ "https://github.com/macro-inc/macro/pull/12",
+ )
+ .await
+ .unwrap();
+
+ let linked = service
+ .session_pull_requests(&view_access(session))
+ .await
+ .unwrap();
+ assert_eq!(linked.len(), 1);
+ assert_eq!(linked[0].github_key, "macro-inc/macro/pull/12");
+ assert_eq!(linked[0].source, PullRequestLinkSource::User);
+ assert_eq!(linked[0].linked_by.as_deref(), Some(user().as_ref()));
+}
+
+#[tokio::test]
+async fn rejects_links_that_are_not_github_pull_requests() {
+ let session = AgentSessionId::new();
+ let links = Arc::new(StubLinks::default());
+ let service = service(&links, &[]);
+
+ let result = service
+ .link_pull_request(
+ &edit_access(session),
+ "https://github.com/macro-inc/macro/issues/12",
+ )
+ .await;
+
+ assert!(matches!(
+ result,
+ Err(AgentSessionError::InvalidPullRequestUrl)
+ ));
+}
+
+#[tokio::test]
+async fn unlinking_keeps_the_pull_request_the_agent_opened() {
+ let session = AgentSessionId::new();
+ let links = Arc::new(StubLinks::with_agent_link(
+ session,
+ "macro-inc/macro/pull/1",
+ ));
+ let service = service(&links, &[]);
+ service
+ .link_pull_request(
+ &edit_access(session),
+ "https://github.com/macro-inc/macro/pull/2",
+ )
+ .await
+ .unwrap();
+
+ for url in [
+ "https://github.com/macro-inc/macro/pull/1",
+ "https://github.com/macro-inc/macro/pull/2",
+ ] {
+ service
+ .unlink_pull_request(&edit_access(session), url)
+ .await
+ .unwrap();
+ }
+
+ let linked = service
+ .session_pull_requests(&view_access(session))
+ .await
+ .unwrap();
+ assert_eq!(linked.len(), 1);
+ assert_eq!(linked[0].github_key, "macro-inc/macro/pull/1");
+ assert_eq!(linked[0].source, PullRequestLinkSource::Agent);
+}
+
+#[tokio::test]
+async fn sessions_for_a_pull_request_are_the_linked_ones_the_viewer_can_view() {
+ let visible = AgentSessionId::new();
+ let hidden = AgentSessionId::new();
+ let unrelated = AgentSessionId::new();
+ let links = Arc::new(StubLinks::with_agent_link(
+ visible,
+ "Macro-Inc/Macro/pull/7",
+ ));
+ links.links.lock().unwrap().extend([
+ (
+ hidden,
+ "macro-inc/macro/pull/7".to_owned(),
+ PullRequestLinkSource::User,
+ None,
+ ),
+ (
+ unrelated,
+ "macro-inc/macro/pull/8".to_owned(),
+ PullRequestLinkSource::User,
+ None,
+ ),
+ ]);
+ let service = service(&links, &[visible, unrelated]);
+
+ let sessions = service
+ .sessions_for_pull_request(&user(), "https://github.com/macro-inc/macro/pull/7")
+ .await
+ .unwrap();
+
+ assert_eq!(sessions, vec![visible]);
+}
diff --git a/crates/agent_session/src/inbound/axum_router.rs b/crates/agent_session/src/inbound/axum_router.rs
index e369d26c54..909312889f 100644
--- a/crates/agent_session/src/inbound/axum_router.rs
+++ b/crates/agent_session/src/inbound/axum_router.rs
@@ -66,6 +66,9 @@ mod test;
/// Link, channel, and team sharing routes.
pub mod sharing;
+/// Routes associating pull requests with sessions.
+pub mod pull_requests;
+
/// Shared state for the agent session router: the agent session service plus
/// the authorization state the request extractors authenticate against.
pub struct AgentSessionRouterState<T, Access, Auth> {
@@ -376,9 +379,10 @@ impl IntoResponse for AgentSessionApiError {
Self::Domain(error @ AgentSessionError::ControlQueueFull(_)) => {
(StatusCode::UNPROCESSABLE_ENTITY, error.to_string()).into_response()
}
- Self::Domain(error @ AgentSessionError::TooManyPreviewIds(_)) => {
- (StatusCode::BAD_REQUEST, error.to_string()).into_response()
- }
+ Self::Domain(
+ error @ (AgentSessionError::TooManyPreviewIds(_)
+ | AgentSessionError::InvalidPullRequestUrl),
+ ) => (StatusCode::BAD_REQUEST, error.to_string()).into_response(),
Self::Domain(error @ AgentSessionError::Archived(_)) => {
(StatusCode::CONFLICT, error.to_string()).into_response()
}
diff --git a/crates/agent_session/src/inbound/axum_router/pull_requests.rs b/crates/agent_session/src/inbound/axum_router/pull_requests.rs
new file mode 100644
index 0000000000..b1041ee2ec
--- /dev/null
+++ b/crates/agent_session/src/inbound/axum_router/pull_requests.rs
@@ -0,0 +1,206 @@
+//! Thin transport adapters for associating pull requests with sessions.
+
+use axum::{
+ Json, Router,
+ extract::{Query, State},
+ http::StatusCode,
+ routing::{get, post},
+};
+use entity_access::{
+ domain::{
+ models::{EditAccessLevel, ViewAccessLevel},
+ ports::EntityAccessService,
+ },
+ inbound::axum_extractors::AgentSessionAccessLevelExtractor,
+};
+use macro_authorization::{ActingUser, MacroAuthorizationExtractor, MacroAuthorizationService};
+use macro_uuid::Uuid;
+use serde::{Deserialize, Serialize};
+use utoipa::ToSchema;
+
+use super::{AgentSessionApiError, AgentSessionRouterState};
+use crate::domain::pull_request_links::{SessionPullRequestLink, SessionPullRequestLinks};
+
+/// Pull request routes, mounted below `/agent-sessions`.
+pub fn agent_session_pull_request_router<T, Access, Auth, S>(
+ state: AgentSessionRouterState<T, Access, Auth>,
+) -> Router<S>
+where
+ T: SessionPullRequestLinks,
+ Access: EntityAccessService,
+ Auth: MacroAuthorizationService,
+ S: Clone + Send + Sync + 'static,
+{
+ Router::new()
+ .route(
+ "/{session_id}/pull-requests",
+ get(list_session_pull_requests::<T, Access, Auth>)
+ .put(link_session_pull_request::<T, Access, Auth>)
+ .delete(unlink_session_pull_request::<T, Access, Auth>),
+ )
+ .route(
+ "/by-pull-request",
+ post(sessions_for_pull_request::<T, Access, Auth>),
+ )
+ .with_state(state)
+}
+
+/// A GitHub pull request, by URL.
+#[derive(Debug, Deserialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct PullRequestUrl {
+ /// The pull request's GitHub URL, such as `https://github.com/owner/repo/pull/12`.
+ pub url: String,
+}
+
+/// The pull requests associated with a session.
+#[derive(Debug, Serialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct SessionPullRequestsResponse {
+ /// Pull requests, oldest link first.
+ pub pull_requests: Vec<SessionPullRequestLink>,
+}
+
+/// The sessions associated with a pull request.
+#[derive(Debug, Serialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct PullRequestSessionsResponse {
+ /// Sessions associated with the pull request that the caller can view.
+ pub session_ids: Vec<Uuid>,
+}
+
+#[utoipa::path(
+ get,
+ path = "/agent-sessions/{session_id}/pull-requests",
+ tag = "agent-sessions",
+ operation_id = "list_agent_session_pull_requests",
+ params(("session_id" = Uuid, Path, description = "ID of the agent session")),
+ responses(
+ (status = 200, body = SessionPullRequestsResponse),
+ (status = 401, body = String),
+ (status = 403, body = String),
+ (status = 500, body = String),
+ )
+)]
+/// List the pull requests associated with a session the caller can view.
+#[tracing::instrument(skip_all, err(Debug))]
+pub async fn list_session_pull_requests<
+ T: SessionPullRequestLinks,
+ Access: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ access: AgentSessionAccessLevelExtractor<ViewAccessLevel, Access, Auth>,
+ State(state): State<AgentSessionRouterState<T, Access, Auth>>,
+) -> Result<Json<SessionPullRequestsResponse>, AgentSessionApiError> {
+ Ok(Json(SessionPullRequestsResponse {
+ pull_requests: state
+ .service
+ .session_pull_requests(&access.entity_access_receipt)
+ .await?,
+ }))
+}
+
+#[utoipa::path(
+ put,
+ path = "/agent-sessions/{session_id}/pull-requests",
+ tag = "agent-sessions",
+ operation_id = "link_agent_session_pull_request",
+ params(("session_id" = Uuid, Path, description = "ID of the agent session")),
+ request_body = PullRequestUrl,
+ responses(
+ (status = 204),
+ (status = 400, body = String),
+ (status = 401, body = String),
+ (status = 403, body = String),
+ (status = 500, body = String),
+ )
+)]
+/// Link a pull request to a session the caller can edit.
+#[tracing::instrument(skip_all, err(Debug))]
+pub async fn link_session_pull_request<
+ T: SessionPullRequestLinks,
+ Access: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ access: AgentSessionAccessLevelExtractor<EditAccessLevel, Access, Auth>,
+ State(state): State<AgentSessionRouterState<T, Access, Auth>>,
+ Json(request): Json<PullRequestUrl>,
+) -> Result<StatusCode, AgentSessionApiError> {
+ state
+ .service
+ .link_pull_request(&access.entity_access_receipt, &request.url)
+ .await?;
+ Ok(StatusCode::NO_CONTENT)
+}
+
+#[utoipa::path(
+ delete,
+ path = "/agent-sessions/{session_id}/pull-requests",
+ tag = "agent-sessions",
+ operation_id = "unlink_agent_session_pull_request",
+ params(
+ ("session_id" = Uuid, Path, description = "ID of the agent session"),
+ ("url" = String, Query, description = "The pull request's GitHub URL"),
+ ),
+ responses(
+ (status = 204),
+ (status = 400, body = String),
+ (status = 401, body = String),
+ (status = 403, body = String),
+ (status = 500, body = String),
+ )
+)]
+/// Unlink a pull request a person linked to a session the caller can edit. The pull request
+/// the session's agent opened stays linked.
+#[tracing::instrument(skip_all, err(Debug))]
+pub async fn unlink_session_pull_request<
+ T: SessionPullRequestLinks,
+ Access: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ access: AgentSessionAccessLevelExtractor<EditAccessLevel, Access, Auth>,
+ State(state): State<AgentSessionRouterState<T, Access, Auth>>,
+ Query(request): Query<PullRequestUrl>,
+) -> Result<StatusCode, AgentSessionApiError> {
+ state
+ .service
+ .unlink_pull_request(&access.entity_access_receipt, &request.url)
+ .await?;
+ Ok(StatusCode::NO_CONTENT)
+}
+
+#[utoipa::path(
+ post,
+ path = "/agent-sessions/by-pull-request",
+ tag = "agent-sessions",
+ operation_id = "agent_sessions_for_pull_request",
+ request_body = PullRequestUrl,
+ responses(
+ (status = 200, body = PullRequestSessionsResponse),
+ (status = 400, body = String),
+ (status = 401, body = String),
+ (status = 500, body = String),
+ )
+)]
+/// List the sessions associated with a pull request that the caller can view.
+#[tracing::instrument(skip_all, err(Debug))]
+pub async fn sessions_for_pull_request<
+ T: SessionPullRequestLinks,
+ Access: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<AgentSessionRouterState<T, Access, Auth>>,
+ caller: MacroAuthorizationExtractor<Auth, ActingUser>,
+ Json(request): Json<PullRequestUrl>,
+) -> Result<Json<PullRequestSessionsResponse>, AgentSessionApiError> {
+ let sessions = state
+ .service
+ .sessions_for_pull_request(&caller.authorization.user.macro_user_id, &request.url)
+ .await?;
+ Ok(Json(PullRequestSessionsResponse {
+ session_ids: sessions
+ .into_iter()
+ .map(|session| session.as_uuid())
+ .collect(),
+ }))
+}
diff --git a/crates/agent_session/src/outbound/postgres/pull_request.rs b/crates/agent_session/src/outbound/postgres/pull_request.rs
index 2979b8713d..4f62d3f82c 100644
--- a/crates/agent_session/src/outbound/postgres/pull_request.rs
+++ b/crates/agent_session/src/outbound/postgres/pull_request.rs
@@ -43,7 +43,115 @@ impl<B: BotFacts + 'static> crate::domain::pull_request::SessionPullRequestRepo
.execute(&mut *transaction)
.await
.map_err(anyhow::Error::from)?;
+ // The pull request the agent opened is linked like any other, and outranks a person's
+ // earlier link to it.
+ sqlx::query!(
+ r#"
+ INSERT INTO agent_session_pull_request (agent_session_id, github_key, source)
+ SELECT $1, $2, 'agent'
+ WHERE EXISTS (SELECT 1 FROM agent_session WHERE id = $1 AND owner_id = $3)
+ ON CONFLICT (agent_session_id, github_key) DO UPDATE SET source = 'agent', linked_by = NULL
+ "#,
+ session.as_uuid(),
+ url.trim_start_matches("https://github.com/"),
+ owner.as_ref(),
+ )
+ .execute(&mut *transaction)
+ .await
+ .map_err(anyhow::Error::from)?;
transaction.commit().await.map_err(anyhow::Error::from)?;
Ok(result.rows_affected() == 1)
}
}
+
+impl<B: BotFacts + 'static> crate::domain::pull_request_links::SessionPullRequestLinkRepo
+ for PgAgentSessionRepo<B>
+{
+ async fn link_pull_request(
+ &self,
+ session: AgentSessionId,
+ github_key: &str,
+ linked_by: &MacroUserIdStr<'static>,
+ ) -> Result<()> {
+ sqlx::query!(
+ r#"
+ INSERT INTO agent_session_pull_request (agent_session_id, github_key, source, linked_by)
+ VALUES ($1, $2, 'user', $3)
+ ON CONFLICT (agent_session_id, github_key) DO NOTHING
+ "#,
+ session.as_uuid(),
+ github_key,
+ linked_by.as_ref(),
+ )
+ .execute(&self.pool)
+ .await
+ .map_err(anyhow::Error::from)?;
+ Ok(())
+ }
+
+ async fn unlink_pull_request(&self, session: AgentSessionId, github_key: &str) -> Result<bool> {
+ let result = sqlx::query!(
+ r#"
+ DELETE FROM agent_session_pull_request
+ WHERE agent_session_id = $1 AND lower(github_key) = lower($2) AND source = 'user'
+ "#,
+ session.as_uuid(),
+ github_key,
+ )
+ .execute(&self.pool)
+ .await
+ .map_err(anyhow::Error::from)?;
+ Ok(result.rows_affected() > 0)
+ }
+
+ async fn session_pull_requests(
+ &self,
+ session: AgentSessionId,
+ ) -> Result<Vec<crate::domain::pull_request_links::SessionPullRequestLink>> {
+ use crate::domain::pull_request_links::{PullRequestLinkSource, SessionPullRequestLink};
+
+ let rows = sqlx::query!(
+ r#"
+ SELECT github_key, source, linked_by, created_at
+ FROM agent_session_pull_request
+ WHERE agent_session_id = $1
+ ORDER BY created_at, github_key
+ "#,
+ session.as_uuid(),
+ )
+ .fetch_all(&self.pool)
+ .await
+ .map_err(anyhow::Error::from)?;
+
+ Ok(rows
+ .into_iter()
+ .map(|row| SessionPullRequestLink {
+ url: format!("https://github.com/{}", row.github_key),
+ github_key: row.github_key,
+ source: if row.source == "agent" {
+ PullRequestLinkSource::Agent
+ } else {
+ PullRequestLinkSource::User
+ },
+ linked_by: row.linked_by,
+ created_at: row.created_at,
+ })
+ .collect())
+ }
+
+ async fn sessions_for_pull_request(&self, github_key: &str) -> Result<Vec<AgentSessionId>> {
+ let ids = sqlx::query_scalar!(
+ r#"
+ SELECT agent_session_id
+ FROM agent_session_pull_request
+ WHERE lower(github_key) = lower($1)
+ ORDER BY created_at, agent_session_id
+ "#,
+ github_key,
+ )
+ .fetch_all(&self.pool)
+ .await
+ .map_err(anyhow::Error::from)?;
+ Ok(ids.into_iter().map(AgentSessionId::new_from_uuid).collect())
+ }
+}
diff --git a/crates/agent_session/src/outbound/postgres/test.rs b/crates/agent_session/src/outbound/postgres/test.rs
index b8d1c476fe..1842d952c5 100644
--- a/crates/agent_session/src/outbound/postgres/test.rs
+++ b/crates/agent_session/src/outbound/postgres/test.rs
@@ -2285,6 +2285,69 @@ async fn pull_request_is_atomic_and_survives_history_selection(pool: PgPool) {
);
}
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn pull_request_links_keep_the_pull_request_the_agent_opened(pool: PgPool) {
+ use crate::domain::pull_request::SessionPullRequestRepo;
+ use crate::domain::pull_request_links::{PullRequestLinkSource, SessionPullRequestLinkRepo};
+ let repo = test_repo(&pool);
+ let bot = create_test_bot(&pool).await;
+ let session = create_session(&repo, new_session(bot, None, None)).await;
+ let owner = session.owner_user().unwrap();
+
+ repo.link_pull_request(session.id, "org/repo/pull/7", owner)
+ .await
+ .unwrap();
+ repo.record_pull_request(
+ session.id,
+ owner,
+ "https://github.com/org/repo/pull/7",
+ None,
+ )
+ .await
+ .unwrap();
+ repo.link_pull_request(session.id, "org/repo/pull/8", owner)
+ .await
+ .unwrap();
+
+ let links = repo.session_pull_requests(session.id).await.unwrap();
+ assert_eq!(
+ links
+ .iter()
+ .map(|link| (link.github_key.as_str(), link.source))
+ .collect::<Vec<_>>(),
+ vec![
+ ("org/repo/pull/7", PullRequestLinkSource::Agent),
+ ("org/repo/pull/8", PullRequestLinkSource::User),
+ ]
+ );
+ assert_eq!(links[0].linked_by, None);
+ assert_eq!(links[1].linked_by.as_deref(), Some(owner.as_ref()));
+
+ assert!(
+ !repo
+ .unlink_pull_request(session.id, "org/repo/pull/7")
+ .await
+ .unwrap()
+ );
+ assert!(
+ repo.unlink_pull_request(session.id, "ORG/repo/pull/8")
+ .await
+ .unwrap()
+ );
+ assert_eq!(
+ repo.sessions_for_pull_request("org/REPO/pull/7")
+ .await
+ .unwrap(),
+ vec![session.id]
+ );
+ assert!(
+ repo.sessions_for_pull_request("org/repo/pull/8")
+ .await
+ .unwrap()
+ .is_empty()
+ );
+}
+
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn rotating_a_session_credential_revokes_the_previous_one(pool: PgPool) {
let repo = test_repo(&pool);
diff --git a/crates/macro_db_client/migrations/20260926183402_agent_session_pull_request.sql b/crates/macro_db_client/migrations/20260926183402_agent_session_pull_request.sql
new file mode 100644
index 0000000000..bdd57bbb1f
--- /dev/null
+++ b/crates/macro_db_client/migrations/20260926183402_agent_session_pull_request.sql
@@ -0,0 +1,25 @@
+-- Pull requests associated with agent sessions: the one a session's agent opened, and any a
+-- person linked afterwards. Keyed by the pull request's owner/repo/pull/number key, the key its
+-- foreign entity records and github_pull_request row are stored under.
+CREATE TABLE agent_session_pull_request (
+ agent_session_id UUID NOT NULL REFERENCES agent_session (id) ON DELETE CASCADE,
+ github_key TEXT NOT NULL,
+ source TEXT NOT NULL CHECK (source IN ('agent', 'user')),
+ -- The Macro user who linked it, for links a person made.
+ linked_by TEXT,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ PRIMARY KEY (agent_session_id, github_key)
+);
+
+CREATE INDEX idx_agent_session_pull_request_github_key
+ ON agent_session_pull_request (lower(github_key));
+
+-- Sessions already carry the pull request their agent opened.
+INSERT INTO agent_session_pull_request (agent_session_id, github_key, source)
+SELECT s.id, link.github_key, 'agent'
+FROM agent_session s
+CROSS JOIN LATERAL (
+ SELECT substring(s.pull_request_url FROM '^https://github\.com/(.+)$') AS github_key
+) link
+WHERE link.github_key IS NOT NULL
+ON CONFLICT DO NOTHING;
diff --git a/packages/sdk/generated/agent-harness/index.ts b/packages/sdk/generated/agent-harness/index.ts
index 94ee40831e..916db1281b 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 { AccessLevel, AgentAction, AgentActionId, AgentConfigKindDto, AgentConfigOptionDto, AgentConfigSelectOptionDto, AgentModelDto, AgentModelsStatusDto, AgentPermissionAction, AgentPromptAction, AgentRepositoriesResponse, AgentRepositoryBranchesResponse, AgentRepositoryDto, AgentRespondElicitationAction, AgentSessionChangesPatchResponse, AgentSessionChangesResponse, AgentSessionLogEntryDto, AgentSessionLogResponse, AgentSessionPreviewData, AgentSessionPreviewDto, AgentSessionQueueResponse, AgentSessionResponse, AgentSetConfigOptionAction, AgentSetModelAction, AiAdmissionErrorBody, BotId, CapabilityHarnessDto, CaptureAttemptDto, CaptureOutcomeDto, ChangedFileDto, ChangesetDto, ChangesetSourceDto, ChannelSharePermission, 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, DiscoverAgentCapabilitiesHandlerData, DiscoverAgentCapabilitiesHandlerErrors, DiscoverAgentCapabilitiesHandlerResponse, DiscoverAgentCapabilitiesHandlerResponses, DiscoverAgentCapabilitiesRequest, DiscoverAgentCapabilitiesResponse, 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, GetAgentSessionPermissionsData, GetAgentSessionPermissionsError, GetAgentSessionPermissionsErrors, GetAgentSessionPermissionsResponse, GetAgentSessionPermissionsResponses, GetAgentSessionQueueData, GetAgentSessionQueueError, GetAgentSessionQueueErrors, GetAgentSessionQueueResponse, GetAgentSessionQueueResponses, GetAgentSessionResponse, GetAgentSessionResponses, GitRefDto, LinkShare, ListAgentRepositoriesData, ListAgentRepositoriesErrors, ListAgentRepositoriesResponse, ListAgentRepositoriesResponses, ListAgentRepositoryBranchesData, ListAgentRepositoryBranchesErrors, ListAgentRepositoryBranchesResponse, ListAgentRepositoryBranchesResponses, 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, SetAgentSessionArchivedData, SetAgentSessionArchivedError, SetAgentSessionArchivedErrors, SetAgentSessionArchivedRequest, SetAgentSessionArchivedResponse, SetAgentSessionArchivedResponses, SharePermissionV2, StartData, StartErrors, StartResponse, StartResponse2, StartResponses, StatusData, StatusErrors, StatusResponse, StatusResponse2, StatusResponses, UpdateAgentSessionPermissionsData, UpdateAgentSessionPermissionsError, UpdateAgentSessionPermissionsErrors, UpdateAgentSessionPermissionsResponse, UpdateAgentSessionPermissionsResponses, UpdateChannelSharePermission, UpdateOperation, UpdateSharePermissionRequestV2, WithAgentSessionId } from './types.gen';
+export type { AccessLevel, AgentAction, AgentActionId, AgentConfigKindDto, AgentConfigOptionDto, AgentConfigSelectOptionDto, AgentModelDto, AgentModelsStatusDto, AgentPermissionAction, AgentPromptAction, AgentRepositoriesResponse, AgentRepositoryBranchesResponse, AgentRepositoryDto, AgentRespondElicitationAction, AgentSessionChangesPatchResponse, AgentSessionChangesResponse, AgentSessionLogEntryDto, AgentSessionLogResponse, AgentSessionPreviewData, AgentSessionPreviewDto, AgentSessionQueueResponse, AgentSessionResponse, AgentSessionsForPullRequestData, AgentSessionsForPullRequestError, AgentSessionsForPullRequestErrors, AgentSessionsForPullRequestResponse, AgentSessionsForPullRequestResponses, AgentSetConfigOptionAction, AgentSetModelAction, AiAdmissionErrorBody, BotId, CapabilityHarnessDto, CaptureAttemptDto, CaptureOutcomeDto, ChangedFileDto, ChangesetDto, ChangesetSourceDto, ChannelSharePermission, 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, DiscoverAgentCapabilitiesHandlerData, DiscoverAgentCapabilitiesHandlerErrors, DiscoverAgentCapabilitiesHandlerResponse, DiscoverAgentCapabilitiesHandlerResponses, DiscoverAgentCapabilitiesRequest, DiscoverAgentCapabilitiesResponse, 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, GetAgentSessionPermissionsData, GetAgentSessionPermissionsError, GetAgentSessionPermissionsErrors, GetAgentSessionPermissionsResponse, GetAgentSessionPermissionsResponses, GetAgentSessionQueueData, GetAgentSessionQueueError, GetAgentSessionQueueErrors, GetAgentSessionQueueResponse, GetAgentSessionQueueResponses, GetAgentSessionResponse, GetAgentSessionResponses, GitRefDto, LinkAgentSessionPullRequestData, LinkAgentSessionPullRequestError, LinkAgentSessionPullRequestErrors, LinkAgentSessionPullRequestResponse, LinkAgentSessionPullRequestResponses, LinkShare, ListAgentRepositoriesData, ListAgentRepositoriesErrors, ListAgentRepositoriesResponse, ListAgentRepositoriesResponses, ListAgentRepositoryBranchesData, ListAgentRepositoryBranchesErrors, ListAgentRepositoryBranchesResponse, ListAgentRepositoryBranchesResponses, ListAgentSessionPullRequestsData, ListAgentSessionPullRequestsError, ListAgentSessionPullRequestsErrors, ListAgentSessionPullRequestsResponse, ListAgentSessionPullRequestsResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponse, LoadAgentModelsHandlerResponses, LoadAgentModelsRequest, LoadAgentModelsResponse, LogDirectionDto, LogFrameDto, MessageParent, ModelHarnessDto, PermissionAnswer, PreviewAgentSessionsData, PreviewAgentSessionsError, PreviewAgentSessionsErrors, PreviewAgentSessionsRequest, PreviewAgentSessionsResponse, PreviewAgentSessionsResponse2, PreviewAgentSessionsResponses, PromptAttachment, PullRequestLinkSource, PullRequestSessionsResponse, PullRequestUrl, 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, SessionPullRequestLink, SessionPullRequestsResponse, SessionStatusDto, SetAgentSessionArchivedData, SetAgentSessionArchivedError, SetAgentSessionArchivedErrors, SetAgentSessionArchivedRequest, SetAgentSessionArchivedResponse, SetAgentSessionArchivedResponses, SharePermissionV2, StartData, StartErrors, StartResponse, StartResponse2, StartResponses, StatusData, StatusErrors, StatusResponse, StatusResponse2, StatusResponses, UnlinkAgentSessionPullRequestData, UnlinkAgentSessionPullRequestError, UnlinkAgentSessionPullRequestErrors, UnlinkAgentSessionPullRequestResponse, UnlinkAgentSessionPullRequestResponses, UpdateAgentSessionPermissionsData, UpdateAgentSessionPermissionsError, UpdateAgentSessionPermissionsErrors, UpdateAgentSessionPermissionsResponse, UpdateAgentSessionPermissionsResponses, UpdateChannelSharePermission, UpdateOperation, UpdateSharePermissionRequestV2, WithAgentSessionId } from './types.gen';
diff --git a/packages/sdk/generated/agent-harness/sdk.gen.ts b/packages/sdk/generated/agent-harness/sdk.gen.ts
index ab5860cca3..fbc17b187e 100644
--- a/packages/sdk/generated/agent-harness/sdk.gen.ts
+++ b/packages/sdk/generated/agent-harness/sdk.gen.ts
@@ -2,7 +2,7 @@
import type { Client, ClientMeta, Options as Options2, RequestResult, TDataShape } from './client';
import { client } from './client.gen';
-import type { CompleteData, CompleteErrors, CompleteResponses, ControlAgentSessionData, ControlAgentSessionErrors, ControlAgentSessionResponses, CreateAgentSessionData, CreateAgentSessionErrors, CreateAgentSessionResponses, DeleteAgentSessionData, DeleteAgentSessionErrors, DeleteAgentSessionResponses, DisconnectData, DisconnectErrors, DisconnectResponses, DiscoverAgentCapabilitiesHandlerData, DiscoverAgentCapabilitiesHandlerErrors, DiscoverAgentCapabilitiesHandlerResponses, EditQueuedActionData, EditQueuedActionErrors, EditQueuedActionResponses, GetAgentSandboxSizeData, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponses, GetAgentSessionChangesData, GetAgentSessionChangesErrors, GetAgentSessionChangesPatchData, GetAgentSessionChangesPatchErrors, GetAgentSessionChangesPatchResponses, GetAgentSessionChangesResponses, GetAgentSessionData, GetAgentSessionErrors, GetAgentSessionLogData, GetAgentSessionLogErrors, GetAgentSessionLogResponses, GetAgentSessionPermissionsData, GetAgentSessionPermissionsErrors, GetAgentSessionPermissionsResponses, GetAgentSessionQueueData, GetAgentSessionQueueErrors, GetAgentSessionQueueResponses, GetAgentSessionResponses, ListAgentRepositoriesData, ListAgentRepositoriesErrors, ListAgentRepositoriesResponses, ListAgentRepositoryBranchesData, ListAgentRepositoryBranchesErrors, ListAgentRepositoryBranchesResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponses, PreviewAgentSessionsData, PreviewAgentSessionsErrors, PreviewAgentSessionsResponses, PutAgentSandboxSizeData, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponses, RefreshAgentSessionChangesData, RefreshAgentSessionChangesErrors, RefreshAgentSessionChangesResponses, RemoveQueuedActionData, RemoveQueuedActionErrors, RemoveQueuedActionResponses, RenameAgentSessionData, RenameAgentSessionErrors, RenameAgentSessionResponses, SetAgentSessionArchivedData, SetAgentSessionArchivedErrors, SetAgentSessionArchivedResponses, StartData, StartErrors, StartResponses, StatusData, StatusErrors, StatusResponses, UpdateAgentSessionPermissionsData, UpdateAgentSessionPermissionsErrors, UpdateAgentSessionPermissionsResponses } from './types.gen';
+import type { AgentSessionsForPullRequestData, AgentSessionsForPullRequestErrors, AgentSessionsForPullRequestResponses, CompleteData, CompleteErrors, CompleteResponses, ControlAgentSessionData, ControlAgentSessionErrors, ControlAgentSessionResponses, CreateAgentSessionData, CreateAgentSessionErrors, CreateAgentSessionResponses, DeleteAgentSessionData, DeleteAgentSessionErrors, DeleteAgentSessionResponses, DisconnectData, DisconnectErrors, DisconnectResponses, DiscoverAgentCapabilitiesHandlerData, DiscoverAgentCapabilitiesHandlerErrors, DiscoverAgentCapabilitiesHandlerResponses, EditQueuedActionData, EditQueuedActionErrors, EditQueuedActionResponses, GetAgentSandboxSizeData, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponses, GetAgentSessionChangesData, GetAgentSessionChangesErrors, GetAgentSessionChangesPatchData, GetAgentSessionChangesPatchErrors, GetAgentSessionChangesPatchResponses, GetAgentSessionChangesResponses, GetAgentSessionData, GetAgentSessionErrors, GetAgentSessionLogData, GetAgentSessionLogErrors, GetAgentSessionLogResponses, GetAgentSessionPermissionsData, GetAgentSessionPermissionsErrors, GetAgentSessionPermissionsResponses, GetAgentSessionQueueData, GetAgentSessionQueueErrors, GetAgentSessionQueueResponses, GetAgentSessionResponses, LinkAgentSessionPullRequestData, LinkAgentSessionPullRequestErrors, LinkAgentSessionPullRequestResponses, ListAgentRepositoriesData, ListAgentRepositoriesErrors, ListAgentRepositoriesResponses, ListAgentRepositoryBranchesData, ListAgentRepositoryBranchesErrors, ListAgentRepositoryBranchesResponses, ListAgentSessionPullRequestsData, ListAgentSessionPullRequestsErrors, ListAgentSessionPullRequestsResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponses, PreviewAgentSessionsData, PreviewAgentSessionsErrors, PreviewAgentSessionsResponses, PutAgentSandboxSizeData, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponses, RefreshAgentSessionChangesData, RefreshAgentSessionChangesErrors, RefreshAgentSessionChangesResponses, RemoveQueuedActionData, RemoveQueuedActionErrors, RemoveQueuedActionResponses, RenameAgentSessionData, RenameAgentSessionErrors, RenameAgentSessionResponses, SetAgentSessionArchivedData, SetAgentSessionArchivedErrors, SetAgentSessionArchivedResponses, StartData, StartErrors, StartResponses, StatusData, StatusErrors, StatusResponses, UnlinkAgentSessionPullRequestData, UnlinkAgentSessionPullRequestErrors, UnlinkAgentSessionPullRequestResponses, UpdateAgentSessionPermissionsData, UpdateAgentSessionPermissionsErrors, UpdateAgentSessionPermissionsResponses } from './types.gen';
export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {
/**
@@ -150,6 +150,20 @@ export class Sdk extends HeyApiClient {
});
}
+ /**
+ * List the sessions associated with a pull request that the caller can view.
+ */
+ public agentSessionsForPullRequest<ThrowOnError extends boolean = false>(options: Options<AgentSessionsForPullRequestData, ThrowOnError>): RequestResult<AgentSessionsForPullRequestResponses, AgentSessionsForPullRequestErrors, ThrowOnError> {
+ return (options.client ?? this.client).post<AgentSessionsForPullRequestResponses, AgentSessionsForPullRequestErrors, ThrowOnError>({
+ url: '/agent-sessions/by-pull-request',
+ ...options,
+ headers: {
+ 'Content-Type': 'application/json',
+ ...options.headers
+ }
+ });
+ }
+
/**
* Preview a batch of agent sessions for rendering chips.
*
@@ -290,6 +304,35 @@ export class Sdk extends HeyApiClient {
});
}
+ /**
+ * Unlink a pull request a person linked to a session the caller can edit. The pull request
+ * the session's agent opened stays linked.
+ */
+ public unlinkAgentSessionPullRequest<ThrowOnError extends boolean = false>(options: Options<UnlinkAgentSessionPullRequestData, ThrowOnError>): RequestResult<UnlinkAgentSessionPullRequestResponses, UnlinkAgentSessionPullRequestErrors, ThrowOnError> {
+ return (options.client ?? this.client).delete<UnlinkAgentSessionPullRequestResponses, UnlinkAgentSessionPullRequestErrors, ThrowOnError>({ url: '/agent-sessions/{session_id}/pull-requests', ...options });
+ }
+
+ /**
+ * List the pull requests associated with a session the caller can view.
+ */
+ public listAgentSessionPullRequests<ThrowOnError extends boolean = false>(options: Options<ListAgentSessionPullRequestsData, ThrowOnError>): RequestResult<ListAgentSessionPullRequestsResponses, ListAgentSessionPullRequestsErrors, ThrowOnError> {
+ return (options.client ?? this.client).get<ListAgentSessionPullRequestsResponses, ListAgentSessionPullRequestsErrors, ThrowOnError>({ url: '/agent-sessions/{session_id}/pull-requests', ...options });
+ }
+
+ /**
+ * Link a pull request to a session the caller can edit.
+ */
+ public linkAgentSessionPullRequest<ThrowOnError extends boolean = false>(options: Options<LinkAgentSessionPullRequestData, ThrowOnError>): RequestResult<LinkAgentSessionPullRequestResponses, LinkAgentSessionPullRequestErrors, ThrowOnError> {
+ return (options.client ?? this.client).put<LinkAgentSessionPullRequestResponses, LinkAgentSessionPullRequestErrors, ThrowOnError>({
+ url: '/agent-sessions/{session_id}/pull-requests',
+ ...options,
+ headers: {
+ 'Content-Type': 'application/json',
+ ...options.headers
+ }
+ });
+ }
+
/**
* The actions waiting to dispatch in this session, oldest first.
*/
diff --git a/packages/sdk/generated/agent-harness/types.gen.ts b/packages/sdk/generated/agent-harness/types.gen.ts
index 32d99df5be..78e19072c5 100644
--- a/packages/sdk/generated/agent-harness/types.gen.ts
+++ b/packages/sdk/generated/agent-harness/types.gen.ts
@@ -1144,6 +1144,31 @@ export type PromptAttachment = {
uri: string;
};
+/**
+ * Who associated a pull request with a session.
+ */
+export type PullRequestLinkSource = 'agent' | 'user';
+
+/**
+ * The sessions associated with a pull request.
+ */
+export type PullRequestSessionsResponse = {
+ /**
+ * Sessions associated with the pull request that the caller can view.
+ */
+ sessionIds: Array<string>;
+};
+
+/**
+ * A GitHub pull request, by URL.
+ */
+export type PullRequestUrl = {
+ /**
+ * The pull request's GitHub URL, such as `https://github.com/owner/repo/pull/12`.
+ */
+ url: string;
+};
+
/**
* One action waiting in a session's queue.
*
@@ -1229,6 +1254,42 @@ export type SessionBot = {
name: string;
};
+/**
+ * A pull request associated with a session.
+ */
+export type SessionPullRequestLink = {
+ /**
+ * When the pull request was associated with the session.
+ */
+ createdAt: string;
+ /**
+ * The pull request's `owner/repo/pull/number` key.
+ */
+ githubKey: string;
+ /**
+ * The Macro user who linked it, for links a person made.
+ */
+ linkedBy?: string | null;
+ /**
+ * Who associated the pull request with the session.
+ */
+ source: PullRequestLinkSource;
+ /**
+ * The pull request's GitHub URL.
+ */
+ url: string;
+};
+
+/**
+ * The pull requests associated with a session.
+ */
+export type SessionPullRequestsResponse = {
+ /**
+ * Pull requests, oldest link first.
+ */
+ pullRequests: Array<SessionPullRequestLink>;
+};
+
/**
* Transport representation of a session's status, mirroring
* [`SessionStatus`].
@@ -1570,6 +1631,27 @@ export type CreateAgentSessionResponses = {
export type CreateAgentSessionResponse2 = CreateAgentSessionResponses[keyof CreateAgentSessionResponses];
+export type AgentSessionsForPullRequestData = {
+ body: PullRequestUrl;
+ path?: never;
+ query?: never;
+ url: '/agent-sessions/by-pull-request';
+};
+
+export type AgentSessionsForPullRequestErrors = {
+ 400: string;
+ 401: string;
+ 500: string;
+};
+
+export type AgentSessionsForPullRequestError = AgentSessionsForPullRequestErrors[keyof AgentSessionsForPullRequestErrors];
+
+export type AgentSessionsForPullRequestResponses = {
+ 200: PullRequestSessionsResponse;
+};
+
+export type AgentSessionsForPullRequestResponse = AgentSessionsForPullRequestResponses[keyof AgentSessionsForPullRequestResponses];
+
export type PreviewAgentSessionsData = {
body: PreviewAgentSessionsRequest;
path?: never;
@@ -1896,6 +1978,91 @@ export type UpdateAgentSessionPermissionsResponses = {
export type UpdateAgentSessionPermissionsResponse = UpdateAgentSessionPermissionsResponses[keyof UpdateAgentSessionPermissionsResponses];
+export type UnlinkAgentSessionPullRequestData = {
+ body?: never;
+ path: {
+ /**
+ * ID of the agent session
+ */
+ session_id: string;
+ };
+ query: {
+ /**
+ * The pull request's GitHub URL
+ */
+ url: string;
+ };
+ url: '/agent-sessions/{session_id}/pull-requests';
+};
+
+export type UnlinkAgentSessionPullRequestErrors = {
+ 400: string;
+ 401: string;
+ 403: string;
+ 500: string;
+};
+
+export type UnlinkAgentSessionPullRequestError = UnlinkAgentSessionPullRequestErrors[keyof UnlinkAgentSessionPullRequestErrors];
+
+export type UnlinkAgentSessionPullRequestResponses = {
+ 204: void;
+};
+
+export type UnlinkAgentSessionPullRequestResponse = UnlinkAgentSessionPullRequestResponses[keyof UnlinkAgentSessionPullRequestResponses];
+
+export type ListAgentSessionPullRequestsData = {
+ body?: never;
+ path: {
+ /**
+ * ID of the agent session
+ */
+ session_id: string;
+ };
+ query?: never;
+ url: '/agent-sessions/{session_id}/pull-requests';
+};
+
+export type ListAgentSessionPullRequestsErrors = {
+ 401: string;
+ 403: string;
+ 500: string;
+};
+
+export type ListAgentSessionPullRequestsError = ListAgentSessionPullRequestsErrors[keyof ListAgentSessionPullRequestsErrors];
+
+export type ListAgentSessionPullRequestsResponses = {
+ 200: SessionPullRequestsResponse;
+};
+
+export type ListAgentSessionPullRequestsResponse = ListAgentSessionPullRequestsResponses[keyof ListAgentSessionPullRequestsResponses];
+
+export type LinkAgentSessionPullRequestData = {
+ body: PullRequestUrl;
+ path: {
+ /**
+ * ID of the agent session
+ */
+ session_id: string;
+ };
+ query?: never;
+ url: '/agent-sessions/{session_id}/pull-requests';
+};
+
+export type LinkAgentSessionPullRequestErrors = {
+ 400: string;
+ 401: string;
+ 403: string;
+ 500: string;
+};
+
+export type LinkAgentSessionPullRequestError = LinkAgentSessionPullRequestErrors[keyof LinkAgentSessionPullRequestErrors];
+
+export type LinkAgentSessionPullRequestResponses = {
+ 204: void;
+};
+
+export type LinkAgentSessionPullRequestResponse = LinkAgentSessionPullRequestResponses[keyof LinkAgentSessionPullRequestResponses];
+
export type GetAgentSessionQueueData = {
body?: never;
path: {
diff --git a/packages/sdk/specs/agent-harness.json b/packages/sdk/specs/agent-harness.json
index 1c2020da63..30957b96f7 100644
--- a/packages/sdk/specs/agent-harness.json
+++ b/packages/sdk/specs/agent-harness.json
@@ -377,6 +377,65 @@
}
}
},
+ "/agent-sessions/by-pull-request": {
+ "post": {
+ "tags": ["agent-sessions"],
+ "summary": "List the sessions associated with a pull request that the caller can view.",
+ "operationId": "agent_sessions_for_pull_request",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PullRequestUrl"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PullRequestSessionsResponse"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/agent-sessions/preview": {
"post": {
"tags": ["agent-sessions"],
@@ -1190,6 +1249,210 @@
}
}
},
+ "/agent-sessions/{session_id}/pull-requests": {
+ "get": {
+ "tags": ["agent-sessions"],
+ "summary": "List the pull requests associated with a session the caller can view.",
+ "operationId": "list_agent_session_pull_requests",
+ "parameters": [
+ {
+ "name": "session_id",
+ "in": "path",
+ "description": "ID of the agent session",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/SessionPullRequestsResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ },
+ "put": {
+ "tags": ["agent-sessions"],
+ "summary": "Link a pull request to a session the caller can edit.",
+ "operationId": "link_agent_session_pull_request",
+ "parameters": [
+ {
+ "name": "session_id",
+ "in": "path",
+ "description": "ID of the agent session",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PullRequestUrl"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "204": {
+ "description": ""
+ },
+ "400": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ },
+ "delete": {
+ "tags": ["agent-sessions"],
+ "summary": "Unlink a pull request a person linked to a session the caller can edit. The pull request\nthe session's agent opened stays linked.",
+ "operationId": "unlink_agent_session_pull_request",
+ "parameters": [
+ {
+ "name": "session_id",
+ "in": "path",
+ "description": "ID of the agent session",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ },
+ {
+ "name": "url",
+ "in": "query",
+ "description": "The pull request's GitHub URL",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "204": {
+ "description": ""
+ },
+ "400": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/agent-sessions/{session_id}/queue": {
"get": {
"tags": ["agent-sessions"],
@@ -3157,6 +3420,37 @@
}
}
},
+ "PullRequestLinkSource": {
+ "type": "string",
+ "description": "Who associated a pull request with a session.",
+ "enum": ["agent", "user"]
+ },
+ "PullRequestSessionsResponse": {
+ "type": "object",
+ "description": "The sessions associated with a pull request.",
+ "required": ["sessionIds"],
+ "properties": {
+ "sessionIds": {
+ "type": "array",
+ "items": {
+ "type": "string",
+ "format": "uuid"
+ },
+ "description": "Sessions associated with the pull request that the caller can view."
+ }
+ }
+ },
+ "PullRequestUrl": {
+ "type": "object",
+ "description": "A GitHub pull request, by URL.",
+ "required": ["url"],
+ "properties": {
+ "url": {
+ "type": "string",
+ "description": "The pull request's GitHub URL, such as `https://github.com/owner/repo/pull/12`."
+ }
+ }
+ },
"QueuedActionDto": {
"type": "object",
"description": "One action waiting in a session's queue.\n\nClients deserialize this, so both derives are used.",
@@ -3242,6 +3536,48 @@
}
}
},
+ "SessionPullRequestLink": {
+ "type": "object",
+ "description": "A pull request associated with a session.",
+ "required": ["githubKey", "url", "source", "createdAt"],
+ "properties": {
+ "createdAt": {
+ "type": "string",
+ "format": "date-time",
+ "description": "When the pull request was associated with the session."
+ },
+ "githubKey": {
+ "type": "string",
+ "description": "The pull request's `owner/repo/pull/number` key."
+ },
+ "linkedBy": {
+ "type": ["string", "null"],
+ "description": "The Macro user who linked it, for links a person made."
+ },
+ "source": {
+ "$ref": "#/components/schemas/PullRequestLinkSource",
+ "description": "Who associated the pull request with the session."
+ },
+ "url": {
+ "type": "string",
+ "description": "The pull request's GitHub URL."
+ }
+ }
+ },
+ "SessionPullRequestsResponse": {
+ "type": "object",
+ "description": "The pull requests associated with a session.",
+ "required": ["pullRequests"],
+ "properties": {
+ "pullRequests": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/SessionPullRequestLink"
+ },
+ "description": "Pull requests, oldest link first."
+ }
+ }
+ },
"SessionStatusDto": {
"oneOf": [
{
diff --git a/packages/sdk/src/entities/agent-sessions/agent-session.ts b/packages/sdk/src/entities/agent-sessions/agent-session.ts
index 2d569d62fa..bc80392328 100644
--- a/packages/sdk/src/entities/agent-sessions/agent-session.ts
+++ b/packages/sdk/src/entities/agent-sessions/agent-session.ts
@@ -5,13 +5,29 @@ import type {
AgentSessionResponse,
ControlResponse,
PromptAttachment,
+ PullRequestLinkSource,
SandboxSize,
} from '../../../generated/agent-harness/types.gen';
import { unwrap } from '../../utils';
import type { MacroClient } from '../../utils/client';
import { MacroEntity } from '../entity';
+import { User } from '../users/user';
import { QueuedAction } from './queued-action';
+/** A GitHub pull request linked to a session. */
+export type SessionPullRequest = {
+ /** The pull request's `owner/repo/pull/number` key. */
+ githubKey: string;
+ /** The pull request's GitHub URL. */
+ url: string;
+ /** Whether the session's agent opened it or a person linked it. */
+ source: PullRequestLinkSource;
+ /** Who linked it, for pull requests a person linked. */
+ linkedBy?: User;
+ /** When it was linked. */
+ createdAt: string;
+};
+
/** A GitHub repository the caller can point a managed session at. */
export type SelectableRepository = {
/** The canonical `https://github.com/owner/name` URL, as `createManaged` takes it. */
@@ -153,6 +169,67 @@ export class AgentSession extends MacroEntity<AgentSessionResponse> {
/** When the session was last modified. */
readonly modifiedAt = this.field('modifiedAt');
+ /**
+ * The sessions linked to the GitHub pull request at `url` that the caller
+ * can view, oldest link first.
+ */
+ static async forPullRequest(
+ client: MacroClient,
+ url: string
+ ): Promise<AgentSession[]> {
+ const { sessionIds } = unwrap(
+ await client.agentHarness.agentSessionsForPullRequest({ body: { url } })
+ );
+ return sessionIds.map((id) => AgentSession.byId(client, id));
+ }
+
+ /**
+ * The GitHub pull requests linked to this session: the one its agent
+ * opened and any a person linked, oldest first.
+ */
+ async pullRequests(): Promise<SessionPullRequest[]> {
+ const { pullRequests } = unwrap(
+ await this.client.agentHarness.listAgentSessionPullRequests({
+ path: { session_id: this.id },
+ })
+ );
+ return pullRequests.map((link) => ({
+ githubKey: link.githubKey,
+ url: link.url,
+ source: link.source,
+ linkedBy: link.linkedBy
+ ? User.byId(this.client, link.linkedBy)
+ : undefined,
+ createdAt: link.createdAt,
+ }));
+ }
+
+ /**
+ * Link the GitHub pull request at `url` to this session. Linking one that
+ * is already linked changes nothing.
+ */
+ async linkPullRequest(url: string): Promise<void> {
+ unwrap(
+ await this.client.agentHarness.linkAgentSessionPullRequest({
+ path: { session_id: this.id },
+ body: { url },
+ })
+ );
+ }
+
+ /**
+ * Unlink a GitHub pull request a person linked to this session. The pull
+ * request the session's agent opened stays linked.
+ */
+ async unlinkPullRequest(url: string): Promise<void> {
+ unwrap(
+ await this.client.agentHarness.unlinkAgentSessionPullRequest({
+ path: { session_id: this.id },
+ query: { url },
+ })
+ );
+ }
+
/** Rename this session. */
async rename(name: string): Promise<void> {
await this.mutate((client) =>
diff --git a/packages/sdk/src/entities/agent-sessions/namespace.ts b/packages/sdk/src/entities/agent-sessions/namespace.ts
index 5855c2be2d..a6f1899fb3 100644
--- a/packages/sdk/src/entities/agent-sessions/namespace.ts
+++ b/packages/sdk/src/entities/agent-sessions/namespace.ts
@@ -37,6 +37,14 @@ export class AgentSessionNamespace {
return AgentSession.repositoryBranches(this.client, repoUrl);
}
+ /**
+ * The sessions linked to the GitHub pull request at `url` that the caller
+ * can view.
+ */
+ forPullRequest(url: string): Promise<AgentSession[]> {
+ return AgentSession.forPullRequest(this.client, url);
+ }
+
/** The caller's default sandbox size for new `@coder` sessions. */
defaultSandboxSize(): Promise<SandboxSize> {
return AgentSession.defaultSandboxSize(this.client);
diff --git a/services/agent_harness_service/src/api.rs b/services/agent_harness_service/src/api.rs
index 6f9d3212a3..b01ca18e71 100644
--- a/services/agent_harness_service/src/api.rs
+++ b/services/agent_harness_service/src/api.rs
@@ -72,6 +72,7 @@ pub struct ApiStates<T, R, Opener, Bots, Requests, Access, Auth, Models, Changes
sharing: Router,
routine_sessions: Router,
capabilities: Router,
+ pull_requests: Router,
changes: AgentChangesRouterState<Changes, Access, Auth>,
}
@@ -99,6 +100,7 @@ impl<T, R, Opener, Bots, Requests, Access, Auth, Models, Changes>
sharing: Router::new(),
routine_sessions: Router::new(),
capabilities: Router::new(),
+ pull_requests: Router::new(),
changes,
}
}
@@ -126,6 +128,12 @@ impl<T, R, Opener, Bots, Requests, Access, Auth, Models, Changes>
self.sharing = router;
self
}
+
+ /// Attach the routes associating pull requests with sessions.
+ pub fn with_pull_requests(mut self, router: Router) -> Self {
+ self.pull_requests = router;
+ self
+ }
}
/// Serve session egress and Macro Internal MCP on the existing egress listener.
@@ -217,6 +225,7 @@ where
.merge(agent_session_control_router(states.control))
.merge(agent_session_create_router(states.create))
.merge(states.sharing)
+ .merge(states.pull_requests)
.merge(agent_changes_router(states.changes));
Router::new()
.nest("/agent-sessions", agent_sessions)
diff --git a/services/agent_harness_service/src/api/swagger.rs b/services/agent_harness_service/src/api/swagger.rs
index 542d1cdaf9..34adabee36 100644
--- a/services/agent_harness_service/src/api/swagger.rs
+++ b/services/agent_harness_service/src/api/swagger.rs
@@ -15,6 +15,10 @@ use agent_harness::inbound::repositories::{
};
use agent_runtime_protocol::domain::action::{AgentAction, AgentActionId, PromptAttachment};
use agent_session::domain::model::{SandboxSize, SessionBot};
+use agent_session::domain::pull_request_links::{PullRequestLinkSource, SessionPullRequestLink};
+use agent_session::inbound::axum_router::pull_requests::{
+ PullRequestSessionsResponse, PullRequestUrl, SessionPullRequestsResponse,
+};
use agent_session::inbound::axum_router::{
self, AgentSessionLogEntryDto, AgentSessionLogResponse, AgentSessionPreviewData,
AgentSessionPreviewDto, AgentSessionQueueResponse, AgentSessionResponse, ControlRequest,
@@ -59,6 +63,10 @@ impl Modify for SecurityAddon {
axum_router::set_agent_session_archived_handler,
axum_router::sharing::get_agent_session_permissions,
axum_router::sharing::update_agent_session_permissions,
+ axum_router::pull_requests::list_session_pull_requests,
+ axum_router::pull_requests::link_session_pull_request,
+ axum_router::pull_requests::unlink_session_pull_request,
+ axum_router::pull_requests::sessions_for_pull_request,
axum_router::get_agent_session_log_handler,
axum_router::control_agent_session_handler,
axum_router::get_agent_session_queue_handler,
@@ -101,6 +109,11 @@ impl Modify for SecurityAddon {
WithAgentSessionId,
RenameAgentSessionRequest,
SetAgentSessionArchivedRequest,
+ PullRequestUrl,
+ SessionPullRequestsResponse,
+ PullRequestSessionsResponse,
+ SessionPullRequestLink,
+ PullRequestLinkSource,
SessionStatusDto,
AgentSessionLogResponse,
AgentSessionLogEntryDto,
diff --git a/services/agent_harness_service/src/main.rs b/services/agent_harness_service/src/main.rs
index ce42306039..4877ca0fba 100644
--- a/services/agent_harness_service/src/main.rs
+++ b/services/agent_harness_service/src/main.rs
@@ -1137,6 +1137,21 @@ async fn run() -> anyhow::Result<()> {
),
);
let http_port = config.port;
+ let pull_requests =
+ agent_session::inbound::axum_router::pull_requests::agent_session_pull_request_router(
+ AgentSessionRouterState::new(
+ agent_session::domain::pull_request_links::SessionPullRequestLinkService::new(
+ session_repo.clone(),
+ Arc::new(
+ agent_session::domain::audience::EntityAccessSessionView::new(
+ (*entity_access).clone(),
+ ),
+ ),
+ ),
+ entity_access.clone(),
+ MacroAuthorizationState::new(Arc::new(authorization_service.clone())),
+ ),
+ );
let sharing = agent_session::inbound::axum_router::sharing::agent_session_sharing_router(
AgentSessionRouterState::new(
agent_session::domain::sharing::SessionSharingService::new(session_repo.clone()),
@@ -1158,7 +1173,8 @@ async fn run() -> anyhow::Result<()> {
.with_claude_auth(claude_auth)
.with_sharing(sharing)
.with_routine_sessions(routine_sessions)
- .with_capabilities(capabilities),
+ .with_capabilities(capabilities)
+ .with_pull_requests(pull_requests),
http_runtime_commands_readiness,
http_port,
shutdown_signal(),