Skip to content

armgit / E2B

Public Imported from GitHub
0

Open-source, secure environment with real-world tools for enterprise-grade agents.

Indicate agent progress and state [WIP]

Tomas Valentabf876781ae7d
diff --git a/api-service/agent/smol_agent.py b/api-service/agent/smol_agent.py
index 3feeb4874..e391443a6 100644
--- a/api-service/agent/smol_agent.py
+++ b/api-service/agent/smol_agent.py
@@ -289,6 +289,13 @@ class SmolAgent(AgentBase):
if self._dev_loop:
print("Agent run already in progress - restarting")
await self.stop()
+ await self.on_interaction_request(
+ AgentInteractionRequest(
+ interaction_id=str(uuid.uuid4()),
+ type="cancelled",
+ data={},
+ )
+ )
async def start_with_timeout():
try:
diff --git a/api-service/deployment/in_memory.py b/api-service/deployment/in_memory.py
index 6478ca80a..a68d15e18 100644
--- a/api-service/deployment/in_memory.py
+++ b/api-service/deployment/in_memory.py
@@ -61,5 +61,5 @@ class InMemoryDeploymentManager(AgentDeploymentManager):
async def get_deployment(self, id: str):
return self._deployments.get(id, None)
- async def list_deployments(self):
+ async def list_deployments(self) -> list[AgentDeployment]:
return list(self._deployments.values())
diff --git a/api-service/deployment/manager.py b/api-service/deployment/manager.py
index 78038caf7..b1ca769e3 100644
--- a/api-service/deployment/manager.py
+++ b/api-service/deployment/manager.py
@@ -30,6 +30,12 @@ class AgentEvents:
self, interaction_request: AgentInteractionRequest
):
self.interaction_requests.append(interaction_request)
+ if interaction_request.type == "done":
+ # TODO: Send the interaction request to nexjs backend + GH App
+ pass
+ elif interaction_request.type == "cancelled":
+ # TODO: Send the interaction request to nexjs backend + GH App
+ pass
def remove_interaction_request(self, interaction_id: str):
self.interaction_requests = [
diff --git a/components/Repos.tsx b/components/Repos.tsx
index f4be8ae9e..02f9259e4 100644
--- a/components/Repos.tsx
+++ b/components/Repos.tsx
@@ -48,9 +48,6 @@ function Repos({ onRepoSelection }: Props) {
refetch()
}
-
-
-
const searchEngine = useMemo(() => repos ?
new Fuse(repos, {
keys: ['full_name'],
diff --git a/github/pullRequest.ts b/github/pullRequest.ts
index c76371768..33d161d6e 100644
--- a/github/pullRequest.ts
+++ b/github/pullRequest.ts
@@ -22,7 +22,7 @@ export async function createPR({
owner: string,
repo: string,
branch: string,
-}): Promise<{ issueID: number }> {
+}) {
let baseBranchRefSHA: string | undefined
try {
@@ -96,6 +96,8 @@ export async function createPR({
return {
issueID: pr.data.id,
+ number: pr.data.number,
+ url: pr.data.html_url,
}
}
@@ -191,13 +193,17 @@ export const createAgentDeployment = api
})
export async function triggerSmolDevAgentRun({
+ client,
deployment,
prompt,
accessToken,
commitMessage,
owner,
repo,
+ pullNumber,
}: {
+ pullNumber: number,
+ client: GitHubClient,
owner: string,
repo: string,
commitMessage: string,
@@ -207,6 +213,14 @@ export async function triggerSmolDevAgentRun({
}) {
console.log('Triggering smol dev agent run:', prompt)
+ await addCommentToPR({
+ body: 'Started smol dev agent run',
+ client,
+ owner,
+ repo,
+ pullNumber,
+ })
+
await interactWithAgent({
id: deployment.id,
type: 'start',
@@ -260,3 +274,24 @@ export async function getGHAppInfo({
email: `${id}+${name}@users.noreply.github.com`
}
}
+
+export async function addCommentToPR({
+ pullNumber,
+ repo,
+ owner,
+ client,
+ body,
+}: {
+ pullNumber: number,
+ repo: string,
+ owner: string,
+ client: GitHubClient,
+ body: string,
+}) {
+ await client.issues.createComment({
+ owner,
+ repo,
+ issue_number: pullNumber,
+ body,
+ })
+}
diff --git a/github/webhooks.ts b/github/webhooks.ts
index 23c93458f..f1f732317 100644
--- a/github/webhooks.ts
+++ b/github/webhooks.ts
@@ -69,6 +69,8 @@ const pullRequestEditHandler: HandlerFunction<'pull_request.edited', unknown> =
commitMessage: 'Update based on PR comments',
owner,
repo,
+ client,
+ pullNumber: issueNumber,
})
}))
@@ -100,8 +102,7 @@ const issueCommentHandler: HandlerFunction<'issue_comment', unknown> = async (ev
const client = getGHInstallationClient({ installationID })
const pullNumber = getPRNumber(payload.issue.pull_request?.url)
if (!pullNumber) {
- console.log('Not a PR comment')
- return
+ throw new Error('PR number not found')
}
const pr = await client.pulls.get({
@@ -136,6 +137,8 @@ const issueCommentHandler: HandlerFunction<'issue_comment', unknown> = async (ev
owner,
repo,
commitMessage: 'Update based on PR comments',
+ client,
+ pullNumber,
})
}))
diff --git a/pages/agent/smol-developer/setup.tsx b/pages/agent/smol-developer/setup.tsx
index 0f266d946..b06f222ca 100644
--- a/pages/agent/smol-developer/setup.tsx
+++ b/pages/agent/smol-developer/setup.tsx
@@ -56,6 +56,14 @@ export const getServerSideProps: GetServerSideProps = async (ctx) => {
return { props: {} }
}
+export interface PostAgentResponse {
+ issueID: number
+ owner: string
+ repo: string
+ pullURL: string
+ pullNumber: number
+}
+
async function handlePostAgent(url: string, { arg }: { arg: PostAgentBody }) {
const response = await fetch(url, {
method: 'POST',
@@ -64,7 +72,7 @@ async function handlePostAgent(url: string, { arg }: { arg: PostAgentBody }) {
'Content-Type': 'application/json',
},
})
- return await response.json() as { issueID: string, owner: string, repo: string }
+ return await response.json() as PostAgentResponse
}
function getSmolDevModelConfig(creds: Creds): ModelConfig & { templateID: TemplateID } {
diff --git a/pages/api/agent.ts b/pages/api/agent/index.ts
similarity index 86%
rename from pages/api/agent.ts
rename to pages/api/agent/index.ts
index b4cf55cbb..b1f966fd1 100644
--- a/pages/api/agent.ts
+++ b/pages/api/agent/index.ts
@@ -1,12 +1,25 @@
import { createServerSupabaseClient } from '@supabase/auth-helpers-nextjs'
import { NextApiRequest, NextApiResponse } from 'next'
+import { nanoid } from 'nanoid'
+import { PostAgentResponse } from 'pages/agent/smol-developer/setup'
import { prisma } from 'db/prisma'
import { serverCreds } from 'db/credentials'
import { PostAgentBody } from 'pages/agent/smol-developer/setup'
import { getGHInstallationClient } from 'github/installationClient'
import { createAgentDeployment, createPR, getGHAccessToken, getGHAppInfo, triggerSmolDevAgentRun } from 'github/pullRequest'
-import { nanoid } from 'nanoid'
+
+export interface GitHubAuthData {
+ app_name: string,
+ app_email: string,
+ installation_id: number,
+ repository_id: number,
+ issue_id: number,
+ pull_number: number,
+ branch: string,
+ owner: string,
+ repo: string,
+}
async function postAgent(req: NextApiRequest, res: NextApiResponse) {
const {
@@ -61,7 +74,7 @@ async function postAgent(req: NextApiRequest, res: NextApiResponse) {
repositoryID,
})
- const { issueID } = await createPR({
+ const { issueID, number: pullNumber, url: pullURL } = await createPR({
client,
title,
defaultBranch,
@@ -86,7 +99,10 @@ async function postAgent(req: NextApiRequest, res: NextApiResponse) {
installation_id: installationID,
repository_id: repositoryID,
issue_id: issueID,
+ pull_number: pullNumber,
branch,
+ owner,
+ repo,
},
},
enabled: false,
@@ -135,13 +151,19 @@ async function postAgent(req: NextApiRequest, res: NextApiResponse) {
commitMessage: 'Add code based on the PR description',
owner,
repo,
+ client,
+ pullNumber,
})
- res.status(200).json({
+ const response: PostAgentResponse = {
+ pullNumber,
+ pullURL,
issueID,
owner,
repo,
- })
+ }
+
+ res.status(200).json(response)
} catch (err: any) {
console.error(err)
res.status(500).json({ statusCode: 500, message: err.message })
@@ -157,7 +179,7 @@ async function handler(
return
}
- res.setHeader('Allow', 'POST')
+ res.setHeader('Allow', ['POST'])
res.status(405).json({ statusCode: 405, message: 'Method Not Allowed' })
return
}
diff --git a/pages/api/agent/run.ts b/pages/api/agent/run.ts
new file mode 100644
index 000000000..8d5f6cf23
--- /dev/null
+++ b/pages/api/agent/run.ts
@@ -0,0 +1,99 @@
+import { NextApiRequest, NextApiResponse } from 'next'
+
+import { prisma } from 'db/prisma'
+import { getGHInstallationClient } from 'github/installationClient'
+import { addCommentToPR } from 'github/pullRequest'
+import { GitHubAuthData } from '.'
+
+
+// Indicate that the agent state changed (run finished)
+async function postRun(req: NextApiRequest, res: NextApiResponse) {
+ const {
+ deployment_id,
+ prompt,
+
+ } = req.body as { prompt: string, deployment_id: string }
+
+ const header = req.headers['Authorization'] as string | undefined
+ // Extract the token from the header
+ const token = header?.split(' ')[1]
+ if (process.env.SECRET_TOKEN && token !== process.env.SECRET_TOKEN) {
+ throw new Error('Invalid token')
+ }
+
+ const deployment = await prisma.deployments.update({
+ where: {
+ id: deployment_id,
+ },
+ data: {
+ last_finished_prompt: prompt,
+ },
+ })
+
+ const ghData = deployment.auth as unknown as GitHubAuthData
+ const client = getGHInstallationClient({ installationID: ghData.installation_id })
+
+
+ // TODO: Should we maybe just edit the previous comment?
+ // Or should we do that only if the previous run was cancelled
+ await addCommentToPR({
+ body: 'Finished running the agent',
+ client,
+ owner: ghData.owner,
+ repo: ghData.repo,
+ pullNumber: ghData.pull_number,
+ })
+}
+
+// Indicate that the agent state changed (run cancelled)
+async function deleteRun(req: NextApiRequest, res: NextApiResponse) {
+ const {
+ deployment_id,
+ } = req.body as { deployment_id: string }
+
+ const header = req.headers['Authorization'] as string | undefined
+ // Extract the token from the header
+ const token = header?.split(' ')[1]
+ if (process.env.SECRET_TOKEN && token !== process.env.SECRET_TOKEN) {
+ throw new Error('Invalid token')
+ }
+
+ const deployment = await prisma.deployments.findUniqueOrThrow({
+ where: {
+ id: deployment_id,
+ },
+ })
+
+ const ghData = deployment.auth as unknown as GitHubAuthData
+ const client = getGHInstallationClient({ installationID: ghData.installation_id })
+
+ // Add comment about the run being cancelled
+ // TODO: Maybe just edit the previous comment?
+ await addCommentToPR({
+ body: 'Run cancelled',
+ client,
+ owner: ghData.owner,
+ repo: ghData.repo,
+ pullNumber: ghData.pull_number,
+ })
+}
+
+async function handler(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ if (req.method === 'POST') {
+ await postRun(req, res)
+ return
+ }
+ if (req.method === 'DELETE') {
+ await deleteRun(req, res)
+ return
+ }
+
+ res.setHeader('Allow', ['POST', 'DELETE'])
+ res.status(405).json({ statusCode: 405, message: 'Method Not Allowed' })
+ return
+}
+
+export default handler