Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 2 additions & 9 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "aha-develop.assign-devin-ai",
"description": "Devin.ai",
"version": "1.0.2",
"version": "1.1.0",
"author": "Aha! (support@aha.io)",
"repository": {
"type": "git",
Expand Down Expand Up @@ -32,7 +32,8 @@
"entryPoint": "src/events/createDevinSession.ts",
"handles": [
"aha-develop.assign-devin-ai.createDevinSession"
]
],
"automatable": true
}
},
"settings": {
Expand Down Expand Up @@ -104,7 +105,6 @@
}
},
"dependencies": {
"base-64": "^1.0.0",
"zod": "^4.3.5"
}
}
203 changes: 26 additions & 177 deletions src/events/createDevinSession.ts
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({
Expand All @@ -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)

Copy link
Copy Markdown
Contributor Author

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

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> {
Expand All @@ -207,7 +38,11 @@ registerEventHandler({
schema: CreateSessionSchema,
resultSchema: DevinSessionDataSchema,
handler: async (args, { settings: rawSettings }) => {
const { prompt, title, attachments = [] } = args;
const { record } = args;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The 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,

record: {id:string, typename: 'Feature' | 'Requirement' }


console.log(
`Received createDevinSession event for record ${record.typename} with ID ${record.id}`,
);

const parsedSettings = ExtensionSettingsSchema.safeParse(rawSettings);
if (!parsedSettings.success) {
Expand All @@ -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}"`)
Expand All @@ -245,6 +92,8 @@ registerEventHandler({
apiKey,
});

await model.setExtensionField(EXTENSION_ID, SESSION_FIELD, result);

return result;
},
});
Loading