-
Notifications
You must be signed in to change notification settings - Fork 0
DEVELOP-2280-15: Devin.ai is now able to respond to automation events. #4
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
tim-field
wants to merge
3
commits into
main
Choose a base branch
from
DEVELOP-2280-15-idea-enable-automation-rules-delegate-extension-agents
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,30 +1,15 @@ | ||
| import * as z from "zod/mini"; | ||
| import base64 from "base-64"; | ||
| import { DEVIN_API_URL, EXTENSION_ID, EXTENSION_NAME } from "../lib/constants"; | ||
| import { buildSessionPrompt } from "../lib/buildSessionPrompt"; | ||
| import { EXTENSION_ID, EXTENSION_NAME, SESSION_FIELD } from "../lib/constants"; | ||
| import { createSession, uploadAttachments } from "../lib/devin"; | ||
| import { callEventHandler, registerEventHandler } from "../lib/events"; | ||
| import type { RecordAttachment } from "../lib/buildSessionPrompt"; | ||
| import { ExtensionSettingsSchema, parseTags } from "../lib/settings"; | ||
|
|
||
| const AttachmentSchema = z.object({ | ||
| fileName: z.string(), | ||
| contentType: z.string(), | ||
| downloadUrl: z.string(), | ||
| base64Data: z.optional(z.string()), | ||
| }); | ||
|
|
||
| const DEVIN_SESSIONS_URL = `${DEVIN_API_URL}sessions`; | ||
| const DEVIN_ATTACHMENTS_URL = `${DEVIN_API_URL}attachments`; | ||
|
|
||
| const CreateSessionSchema = z.object({ | ||
| title: z.string(), | ||
| prompt: z.string(), | ||
| attachments: z.optional(z.array(AttachmentSchema)), | ||
| }); | ||
|
|
||
| const DevinResponseSchema = z.object({ | ||
| session_id: z.string(), | ||
| url: z.string(), | ||
| is_new_session: z.nullable(z.boolean()), | ||
| record: z.object({ | ||
| typename: z.enum(["Feature", "Requirement"]), | ||
| id: z.string(), | ||
| }), | ||
| }); | ||
|
|
||
| export const DevinSessionDataSchema = z.object({ | ||
|
|
@@ -37,160 +22,6 @@ export type DevinSessionData = z.infer<typeof DevinSessionDataSchema>; | |
|
|
||
| export type CreateSession = z.infer<typeof CreateSessionSchema>; | ||
|
|
||
| // Converts a string to bytes (replacement for TextEncoder which isn't available) | ||
| function stringToBytes(str: string): Uint8Array { | ||
| const bytes = new Uint8Array(str.length); | ||
| for (let i = 0; i < str.length; i++) { | ||
| bytes[i] = str.charCodeAt(i); | ||
| } | ||
| return bytes; | ||
| } | ||
|
|
||
| // We need to resort to this manual multipart/form-data construction | ||
| // as the lambda environment doesn't support Blob or FormData APIs. | ||
| function buildMultipartBody( | ||
| fileBytes: Uint8Array, | ||
| fileName: string, | ||
| contentType: string, | ||
| boundary: string, | ||
| ): Uint8Array { | ||
| const header = | ||
| `--${boundary}\r\n` + | ||
| `Content-Disposition: form-data; name="file"; filename="${fileName}"\r\n` + | ||
| `Content-Type: ${contentType}\r\n\r\n`; | ||
| const footer = `\r\n--${boundary}--\r\n`; | ||
|
|
||
| const headerBytes = stringToBytes(header); | ||
| const footerBytes = stringToBytes(footer); | ||
|
|
||
| const body = new Uint8Array( | ||
| headerBytes.length + fileBytes.length + footerBytes.length, | ||
| ); | ||
| body.set(headerBytes, 0); | ||
| body.set(fileBytes, headerBytes.length); | ||
| body.set(footerBytes, headerBytes.length + fileBytes.length); | ||
|
|
||
| return body; | ||
| } | ||
|
|
||
| async function uploadAttachment( | ||
| attachment: RecordAttachment, | ||
| apiKey: string, | ||
| ): Promise<string> { | ||
| if (!attachment.base64Data) { | ||
| throw new Error(`Attachment ${attachment.fileName} is missing base64 data`); | ||
| } | ||
|
|
||
| const fileBytes = stringToBytes(base64.decode(attachment.base64Data)); | ||
| const boundary = `----FormBoundary${Date.now()}`; | ||
| const body = buildMultipartBody( | ||
| fileBytes, | ||
| attachment.fileName, | ||
| attachment.contentType, | ||
| boundary, | ||
| ); | ||
|
|
||
| const uploadResponse = await fetch(DEVIN_ATTACHMENTS_URL, { | ||
| method: "POST", | ||
| headers: { | ||
| Authorization: `Bearer ${apiKey}`, | ||
| "Content-Type": `multipart/form-data; boundary=${boundary}`, | ||
| }, | ||
| body: body as unknown as BodyInit, | ||
| }); | ||
|
|
||
| const bodyText = await uploadResponse.text().catch(() => ""); | ||
|
|
||
| if (!uploadResponse.ok) { | ||
| const message = bodyText | ||
| ? `${EXTENSION_NAME} attachment upload failed: ${bodyText}` | ||
| : `${EXTENSION_NAME} attachment upload failed (${uploadResponse.status})`; | ||
| throw new Error(message); | ||
| } | ||
|
|
||
| const trimmed = bodyText.trim(); | ||
| if (!trimmed) { | ||
| throw new Error(`${EXTENSION_NAME} attachment upload returned no URL`); | ||
| } | ||
|
|
||
| return trimmed; | ||
| } | ||
|
|
||
| async function uploadAttachments( | ||
| attachments: RecordAttachment[], | ||
| apiKey: string, | ||
| ): Promise<string[]> { | ||
| if (!attachments.length) { | ||
| return []; | ||
| } | ||
|
|
||
| const uploads = attachments.map((attachment) => | ||
| uploadAttachment(attachment, apiKey), | ||
| ); | ||
|
|
||
| return Promise.all(uploads); | ||
| } | ||
|
|
||
| async function createSession({ | ||
| prompt, | ||
| title, | ||
| tags, | ||
| playbookId, | ||
| apiKey, | ||
| }: { | ||
| prompt: string; | ||
| title: string; | ||
| tags?: string[]; | ||
| playbookId?: string; | ||
| apiKey: string; | ||
| }): Promise<DevinSessionData> { | ||
| const sessionPayload: Record<string, unknown> = { | ||
| title, | ||
| prompt, | ||
| idempotent: true, | ||
| }; | ||
|
|
||
| if (tags?.length) { | ||
| sessionPayload.tags = tags; | ||
| } | ||
| if (playbookId) { | ||
| sessionPayload.playbook_id = playbookId; | ||
| } | ||
|
|
||
| const response = await fetch(DEVIN_SESSIONS_URL, { | ||
| method: "POST", | ||
| headers: { | ||
| Authorization: `Bearer ${apiKey}`, | ||
| "Content-Type": "application/json", | ||
| }, | ||
| body: JSON.stringify(sessionPayload), | ||
| }); | ||
|
|
||
| const data = await response.json().catch(() => ({})); | ||
|
|
||
| if (!response.ok) { | ||
| const message = | ||
| typeof data === "object" && data && "detail" in data | ||
| ? String((data as { detail: unknown }).detail) | ||
| : `${EXTENSION_NAME} API error (${response.status})`; | ||
| throw new Error(message); | ||
| } | ||
|
|
||
| const result = DevinResponseSchema.safeParse(data); | ||
| if (!result.success) { | ||
| console.error( | ||
| `Invalid Devin API response ${JSON.stringify(data)} ${result.error}`, | ||
| ); | ||
| throw new Error(`Invalid response from ${EXTENSION_NAME} API`); | ||
| } | ||
|
|
||
| return { | ||
| sessionId: result.data.session_id, | ||
| sessionUrl: result.data.url, | ||
| assignedAt: new Date().toISOString(), | ||
| }; | ||
| } | ||
|
|
||
| export async function createDevinSession( | ||
| args: CreateSession, | ||
| ): Promise<DevinSessionData> { | ||
|
|
@@ -207,7 +38,11 @@ registerEventHandler({ | |
| schema: CreateSessionSchema, | ||
| resultSchema: DevinSessionDataSchema, | ||
| handler: async (args, { settings: rawSettings }) => { | ||
| const { prompt, title, attachments = [] } = args; | ||
| const { record } = args; | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Updated to so that the automation rule and the UI pass the same payload,
|
||
|
|
||
| console.log( | ||
| `Received createDevinSession event for record ${record.typename} with ID ${record.id}`, | ||
| ); | ||
|
|
||
| const parsedSettings = ExtensionSettingsSchema.safeParse(rawSettings); | ||
| if (!parsedSettings.success) { | ||
|
|
@@ -228,6 +63,18 @@ registerEventHandler({ | |
| throw new Error(`${EXTENSION_NAME} API key is not configured`); | ||
| } | ||
|
|
||
| const repository = settings.repository?.trim(); | ||
| const baseBranch = settings.baseBranch?.trim() || "main"; | ||
|
|
||
| const { title, prompt, attachments, model } = await buildSessionPrompt( | ||
| record, | ||
| { | ||
| repository, | ||
| baseBranch, | ||
| customInstructions: settings.customInstructions, | ||
| }, | ||
| ); | ||
|
|
||
| const attachmentUrls = await uploadAttachments(attachments, apiKey); | ||
| const attachmentLines = attachmentUrls | ||
| .map((url) => `ATTACHMENT:"${url}"`) | ||
|
|
@@ -245,6 +92,8 @@ registerEventHandler({ | |
| apiKey, | ||
| }); | ||
|
|
||
| await model.setExtensionField(EXTENSION_ID, SESSION_FIELD, result); | ||
|
|
||
| return result; | ||
| }, | ||
| }); | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Moved to devin.ts
Dropped base64 related image handling functions which we no longer need