Skip to content
Merged
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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ Create a ClickUp OAuth application with the callback URL `https://your-domain.ex
## Create a Job

1. Sign in with Linear.
2. Connect exe.dev using an account-level HTTPS API token, repository URL, optional checkout ref, and the VM tags needed to attach integrations.
2. Connect exe.dev using an account-level HTTPS API token and the VM tags needed to attach integrations.
3. Create a Job, choose its execution target, and add authenticated provider triggers. Every Linear matching rule must match.

Matching provider events queue work up to the Job’s configured concurrency. Each run creates a tagged VM, clones the configured repository, runs the agent directly, captures its output, and deletes the VM on every terminal outcome.
Expand Down
28 changes: 23 additions & 5 deletions packages/app/src/exe-vm-backend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ function agentCommand(connection: ExeRunConnection): string {
}

export interface ExePermissionTest { ok: boolean; missingPermissions: string[]; tags: string[]; checks: BackendCommandResult[] }
export interface ExeAgentValidation { models: string[]; command: BackendCommandResult }

export function tagsFromInventory(inventory: unknown): string[] {
const tags = new Set<string>();
Expand All @@ -45,7 +46,7 @@ export class ExeVmBackend implements ExecutionBackend {
readonly kind = "exe-vm";
readonly capabilities = capabilities;

constructor(private readonly connection: ExeConnection | ExeRunConnection) {}
constructor(private readonly connection: Pick<ExeConnection, "apiToken" | "tags"> | ExeRunConnection) {}

private async api(command: string): Promise<BackendCommandResult> {
const response = await fetch(API, { method: "POST", headers: { Authorization: `Bearer ${this.connection.apiToken}`, "Content-Type": "text/plain" }, body: command });
Expand All @@ -70,9 +71,29 @@ export class ExeVmBackend implements ExecutionBackend {

async test(): Promise<BackendCommandResult> { return this.api("ls --json"); }

async validateAgentAndModels(agentKind: "codex" | "claude"): Promise<ExeAgentValidation> {
const vm = vmNameFor(`validate-${crypto.randomUUID()}`);
const tags = [...new Set(this.connection.tags)].map(tag => `--tag=${shellAtom(tag)}`).join(" ");
const created = await this.api(`new --name=${shellAtom(vm)} --no-email --comment=${shellAtom(`Factorize VM ${vm}`)} ${tags}`.trim());
if (!created.ok) throw new Error(`Could not create the validation VM (${created.status}): ${created.body.slice(0, 300)}`);
try {
const binary = agentKind === "codex" ? "codex" : "claude";
const remote = `command -v ${binary} >/dev/null && curl --fail --silent --show-error https://llm.int.exe.xyz/v1/models | jq -cer '[.data[]?.id | strings] | unique'`;
let result = await this.api(`ssh ${shellAtom(vm)} ${shellAtom(remote)}`);
for (let attempt = 1; !result.ok && attempt < 5; attempt++) result = await this.api(`ssh ${shellAtom(vm)} ${shellAtom(remote)}`);
if (!result.ok) throw new Error(`${binary} or its model integration is unavailable on a VM with these tags (${result.status}): ${result.body.slice(0, 300)}`);
const parsed: unknown = JSON.parse(result.body);
if (!Array.isArray(parsed) || parsed.some(model => typeof model !== "string")) throw new Error("The exe.dev model endpoint returned an invalid response");
return { models: [...new Set(parsed.map(model => model.trim()).filter(Boolean))].sort(), command: result };
} finally {
const removed = await this.deleteVm(vm);
if (!removed.ok) throw new Error(`The validation VM could not be deleted (${removed.status}): ${removed.body.slice(0, 300)}`);
}
}

async launch(request: LaunchRequest): Promise<LaunchReceipt> {
const connection = this.connection as ExeRunConnection;
if (!connection.agentKind || !connection.repositoryUrl) throw new Error("The job is missing its agent or repository configuration");
if (!connection.agentKind) throw new Error("The job is missing its agent configuration");
const vm = vmNameFor(request.runId);
const tags = [...new Set(this.connection.tags)].map(tag => `--tag=${shellAtom(tag)}`).join(" ");
const created = await this.api(`new --name=${shellAtom(vm)} --no-email --comment=${shellAtom(`Factorize VM ${vm}`)} ${tags}`.trim());
Expand All @@ -82,13 +103,10 @@ export class ExeVmBackend implements ExecutionBackend {
}

const prompt = base64(request.prompt), output = "/tmp/factorize.log", status = "/tmp/factorize.status";
const checkout = connection.checkoutRef ? ` && git checkout --detach ${shellAtom(connection.checkoutRef)}` : "";
const work = [
"set -eu",
"mkdir -p /workspace",
"cd /workspace",
`git clone -- ${shellAtom(connection.repositoryUrl)} repo`,
`cd repo${checkout}`,
`printf '%s' ${shellAtom(prompt)} | base64 -d > /tmp/factorize-prompt.md`,
`setsid nohup sh -c ${shellAtom(`set +e; ${agentCommand(connection)} < /tmp/factorize-prompt.md > ${output} 2>&1; code=$?; printf '%s' "$code" > ${status}`)} >/dev/null 2>&1 &`,
"echo started",
Expand Down
8 changes: 3 additions & 5 deletions packages/app/src/exe.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,15 @@
export interface ExeConnection {
apiToken: string;
tags: string[];
agentKind: "codex" | "claude";
models?: string[];
modelsRefreshedAt?: string;
}

export interface ExeRunConnection extends ExeConnection {
agentKind: string;
repositoryUrl: string;
checkoutRef?: string;
agentCommand?: string;
model?: string;
effort?: string;
models?: string[];
modelsRefreshedAt?: string;
efforts?: string[];
}

Expand Down
40 changes: 20 additions & 20 deletions packages/app/src/tenant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -331,18 +331,20 @@ export class TenantV2 extends DurableObject<Env> {

private async saveExe(input: unknown): Promise<Response> {
const value = input as ExeConnectionInput;
if (!value.apiToken) throw new Error("An account-level exe.dev HTTPS token is required");
if (!value.apiToken || !["codex", "claude"].includes(value.agentKind)) throw new Error("An account-level exe.dev HTTPS token and agent are required");
const tags = Array.isArray(value.tags) ? value.tags.map(tag => String(tag).trim()).filter(Boolean) : [];
if (tags.length > 20 || tags.some(tag => !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/.test(tag))) throw new Error("VM tags may contain only letters, numbers, dot, underscore, colon, and hyphen");
const saved: ExeConnection = { apiToken: value.apiToken, tags };
const verification = await new ExeVmBackend(saved).testPermissions();
const candidate: ExeConnection = { apiToken: value.apiToken, tags, agentKind: value.agentKind, models: [], modelsRefreshedAt: "" };
const backend = new ExeVmBackend(candidate), verification = await backend.testPermissions();
if (!verification.ok) throw new Error(`exe.dev token is missing required permissions: ${verification.missingPermissions.join(", ")}`);
const validation = await backend.validateAgentAndModels(value.agentKind);
const saved: ExeConnection = { ...candidate, models: validation.models, modelsRefreshedAt: now() };
const connectionId = value.connectionId || id();
await this.putConnection(`exe:${connectionId}`, saved);
// Preserve the most recently saved connection for existing flows created
// before connections were selectable.
await this.putConnection("exe", saved);
return json({ ok: true, connectionId });
return json({ ok: true, connectionId, models: saved.models });
}

private async testExe(input: unknown): Promise<Response> {
Expand Down Expand Up @@ -437,13 +439,13 @@ export class TenantV2 extends DurableObject<Env> {
if (!linear) throw new Error("Connect Linear first");
const exe = await this.exeConnection(input.exeConnectionId);
if (!exe) throw new Error("Connect an exe.dev account first");
const cwd = this.cwdTemplate(input.cwd ?? "/workspace/repo", flowId);
const cwd = this.cwdTemplate(input.cwd ?? "/workspace", flowId);
const workspaceName = flowId;
// These legacy fields are retained for compatibility with the v1 Durable Object schema.
// App-wide webhook verification is performed at the Worker edge before reaching this object.
this.ctx.storage.sql.exec(
"INSERT INTO pipes (id,name,project_id,team_id,filter_type,filter_target_id,max_concurrency,capability,webhook_id,signing_secret,workspace_name,agent_kind,context_template,match_rules,exe_connection_id,cwd,source_kind,source_config,trigger_kind,trigger_config,created_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
pipeId, input.name, source.kind === "linear" ? source.projectId : "", "", rules[0].type, rules[0].targetId, maxConcurrency, "app-webhook", null, "app-webhook", workspaceName, "codex", source.kind !== "github" ? this.contextTemplate(input.contextTemplate) : "", JSON.stringify(rules), input.exeConnectionId || "default", cwd, source.kind, JSON.stringify(source), source.kind === "github" ? source.trigger : source.kind === "custom" ? "custom_handler" : "linear_match", "{}", now(),
pipeId, input.name, source.kind === "linear" ? source.projectId : "", "", rules[0].type, rules[0].targetId, maxConcurrency, "app-webhook", null, "app-webhook", workspaceName, exe.agentKind, source.kind !== "github" ? this.contextTemplate(input.contextTemplate) : "", JSON.stringify(rules), input.exeConnectionId || "default", cwd, source.kind, JSON.stringify(source), source.kind === "github" ? source.trigger : source.kind === "custom" ? "custom_handler" : "linear_match", "{}", now(),
);
return Response.json({ id: pipeId }, { status: 201 });
}
Expand All @@ -459,10 +461,10 @@ export class TenantV2 extends DurableObject<Env> {
const workspaceName = flowId;
const exe = await this.exeConnection(input.exeConnectionId);
if (!exe) throw new Error("Choose an exe.dev connection.");
const cwd = this.cwdTemplate(input.cwd ?? "/workspace/repo", flowId);
const cwd = this.cwdTemplate(input.cwd ?? "/workspace", flowId);
this.ctx.storage.sql.exec(
"UPDATE pipes SET name=?, project_id=?, filter_type=?, filter_target_id=?, max_concurrency=?, workspace_name=?, agent_kind=?, context_template=?, match_rules=?, exe_connection_id=?, cwd=?, source_kind=?, source_config=?, trigger_kind=?, trigger_config=? WHERE id=?",
input.name, source.kind === "linear" ? source.projectId : "", rules[0].type, rules[0].targetId, maxConcurrency, workspaceName, "codex", source.kind !== "github" ? this.contextTemplate(input.contextTemplate) : "", JSON.stringify(rules), input.exeConnectionId || "default", cwd, source.kind, JSON.stringify(source), source.kind === "github" ? source.trigger : source.kind === "custom" ? "custom_handler" : "linear_match", "{}", pipeId,
input.name, source.kind === "linear" ? source.projectId : "", rules[0].type, rules[0].targetId, maxConcurrency, workspaceName, exe.agentKind, source.kind !== "github" ? this.contextTemplate(input.contextTemplate) : "", JSON.stringify(rules), input.exeConnectionId || "default", cwd, source.kind, JSON.stringify(source), source.kind === "github" ? source.trigger : source.kind === "custom" ? "custom_handler" : "linear_match", "{}", pipeId,
);
return json({ id: pipeId, ok: true });
}
Expand Down Expand Up @@ -492,8 +494,11 @@ export class TenantV2 extends DurableObject<Env> {
kind: "exe-vm",
name: "Ephemeral exe.dev VMs",
workspace: "ephemeral",
cwd: "/workspace/repo",
agents: ["codex", "claude"],
cwd: "/workspace",
agentKind: connection.agentKind,
models: connection.models ?? [],
modelsRefreshedAt: connection.modelsRefreshedAt ?? null,
efforts: connection.agentKind === "codex" ? ["minimal", "low", "medium", "high", "xhigh"] : [],
capabilities: ["output", "recovery", "stop"],
})), ...ampConnections.map(connection => ({ id: `amp:${connection.connectionId}`, kind: "amp", name: `Amp · ${connection.project}`, workspace: connection.project, cwd: "Cloud orb", agentKind: "Amp", capabilities: ["stop"] }))]);
}
Expand All @@ -505,7 +510,7 @@ export class TenantV2 extends DurableObject<Env> {
if (!job) return undefined;
let target: Record<string, unknown> = {};
try { target = JSON.parse(String(job.execution_target)); } catch { return undefined; }
return { id: job.id, name: job.name, max_concurrency: job.concurrency_limit, workspace_name: job.slug, agent_kind: target.agentKind, model: target.model ?? "", effort: target.effort ?? "", cwd: target.cwd, repository_url: target.repositoryUrl, checkout_ref: target.checkoutRef, execution_backend_kind: target.backendKind ?? "exe-vm", execution_connection_id: target.connectionId, exe_connection_id: target.connectionId, enabled: job.enabled };
return { id: job.id, name: job.name, max_concurrency: job.concurrency_limit, workspace_name: job.slug, agent_kind: target.agentKind, model: target.model ?? "", effort: target.effort ?? "", cwd: target.cwd, execution_backend_kind: target.backendKind ?? "exe-vm", execution_connection_id: target.connectionId, exe_connection_id: target.connectionId, enabled: job.enabled };
}

private async publicJobs(rows: Row[]): Promise<Record<string, unknown>[]> {
Expand Down Expand Up @@ -572,8 +577,6 @@ export class TenantV2 extends DurableObject<Env> {
model: String(executionTarget.model ?? ""),
effort: String(executionTarget.effort ?? ""),
agentKind: String(executionTarget.agentKind ?? ""),
repositoryUrl: String(executionTarget.repositoryUrl ?? ""),
checkoutRef: String(executionTarget.checkoutRef ?? ""),
concurrencyLimit: Number(row.concurrency_limit),
runningCount: Number(runSummary?.running_count ?? 0),
maxConcurrency: Number(row.concurrency_limit),
Expand All @@ -594,17 +597,14 @@ export class TenantV2 extends DurableObject<Env> {
}
const target = (await this.exeConnections()).find(item => item.connectionId === targetId);
if (!target) throw new Error("Execution target not found");
return { connectionId: target.connectionId, backendKind: "exe-vm", workspace: "ephemeral", cwd: "/workspace/repo" };
return { connectionId: target.connectionId, backendKind: "exe-vm", workspace: "ephemeral", cwd: "/workspace", agentKind: target.agentKind };
}

private validateJobInput(input: any): void {
if (!input?.name || !input.promptTemplate) throw new Error("Job name and prompt template are required");
if (!JOB_SLUG.test(String(input.slug ?? ""))) throw new Error("Job slug must start with a lowercase letter and contain only lowercase letters, digits, hyphens, or underscores (30 characters maximum).");
if (input.model !== undefined && (typeof input.model !== "string" || input.model.trim().length > 120)) throw new Error("Job model must be a string of 120 characters or fewer");
if (input.effort !== undefined && (typeof input.effort !== "string" || input.effort.trim().length > 40)) throw new Error("Job effort must be a string of 40 characters or fewer");
if (!input.executionTargetId?.startsWith?.("amp:") && !["codex", "claude"].includes(input.agentKind)) throw new Error("Choose a supported agent");
if (!input.executionTargetId?.startsWith?.("amp:") && (!/^https:\/\//i.test(input.repositoryUrl) || input.repositoryUrl.length > 2000)) throw new Error("Repository URL must be an HTTPS URL");
if (input.checkoutRef && (String(input.checkoutRef).length > 255 || /[\0\r\n]/.test(String(input.checkoutRef)))) throw new Error("Checkout ref is invalid");
if (!Array.isArray(input.triggers) || input.triggers.some((trigger: any) => !["manual", "schedule", "webhook", "jobLifecycle"].includes(trigger?.kind))) throw new Error("Job triggers are invalid");
Mustache.parse(input.promptTemplate);
if (input.runNameTemplate !== undefined) Mustache.parse(String(input.runNameTemplate));
Expand Down Expand Up @@ -692,7 +692,7 @@ export class TenantV2 extends DurableObject<Env> {
this.validateJobInput(input);
if (this.one("SELECT id FROM jobs WHERE slug=?", input.slug)) throw new Error("Job slug is already in use");
await this.validateProviderIntegrations(input.triggers);
const target = { ...await this.jobTarget(input.executionTargetId), agentKind: text(input.agentKind).trim(), repositoryUrl: text(input.repositoryUrl).trim(), checkoutRef: text(input.checkoutRef).trim(), model: text(input.model).trim(), effort: text(input.effort).trim() }, jobId = id(), timestamp = now();
const target = { ...await this.jobTarget(input.executionTargetId), model: text(input.model).trim(), effort: text(input.effort).trim() }, jobId = id(), timestamp = now();
const triggers = this.normalizedTriggers(input.triggers);
this.validateLifecycleGraph(jobId, triggers);
this.ctx.storage.sql.exec("INSERT INTO jobs (id,name,slug,encrypted_prompt_template,encrypted_run_name_template,execution_target,concurrency_limit,enabled,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?)", jobId, input.name, input.slug, await encrypt(input.promptTemplate, this.env.CREDENTIAL_ENCRYPTION_KEY), await encrypt(String(input.runNameTemplate ?? ""), this.env.CREDENTIAL_ENCRYPTION_KEY), JSON.stringify(target), input.concurrencyLimit, 1, timestamp, timestamp);
Expand All @@ -714,7 +714,7 @@ export class TenantV2 extends DurableObject<Env> {
await this.validateProviderIntegrations(input.triggers, existing);
const triggers = this.normalizedTriggers(input.triggers, existing);
this.validateLifecycleGraph(jobId, triggers);
const target = { ...await this.jobTarget(input.executionTargetId), agentKind: text(input.agentKind).trim(), repositoryUrl: text(input.repositoryUrl).trim(), checkoutRef: text(input.checkoutRef).trim(), model: text(input.model).trim(), effort: text(input.effort).trim() }, timestamp = now();
const target = { ...await this.jobTarget(input.executionTargetId), model: text(input.model).trim(), effort: text(input.effort).trim() }, timestamp = now();
this.ctx.storage.sql.exec("UPDATE jobs SET name=?,slug=?,encrypted_prompt_template=?,encrypted_run_name_template=?,execution_target=?,concurrency_limit=?,updated_at=? WHERE id=?", input.name, input.slug, await encrypt(input.promptTemplate, this.env.CREDENTIAL_ENCRYPTION_KEY), await encrypt(String(input.runNameTemplate ?? ""), this.env.CREDENTIAL_ENCRYPTION_KEY), JSON.stringify(target), input.concurrencyLimit, timestamp, jobId);
const retained = new Set<string>();
for (const trigger of triggers) {
Expand Down Expand Up @@ -1644,7 +1644,7 @@ export class TenantV2 extends DurableObject<Env> {
private async connectionForPipe(pipe: Row): Promise<ExeRunConnection | null> {
const connection = await this.exeConnection(String(pipe.exe_connection_id || "default"));
if (!connection) return null;
return { ...connection, agentKind: String(pipe.agent_kind ?? ""), repositoryUrl: String(pipe.repository_url ?? ""), checkoutRef: String(pipe.checkout_ref ?? "") || undefined, model: String(pipe.model ?? ""), effort: String(pipe.effort ?? "") };
return { ...connection, model: String(pipe.model ?? ""), effort: String(pipe.effort ?? "") };
}

private async upsertMember(input: unknown): Promise<Response> {
Expand Down
1 change: 1 addition & 0 deletions packages/app/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ export interface ExeConnectionInput {
connectionId?: string;
apiToken: string;
tags?: string[];
agentKind: "codex" | "claude";
}

export interface AmpConnectionInput { connectionId?: string; accessToken: string; project: string; apiBaseUrl?: string; }
Expand Down
Loading
Loading