From 3f31fbe3e840b64375eab27a8d6d6727b9f2dca7 Mon Sep 17 00:00:00 2001 From: Brendan Date: Thu, 17 Sep 2026 23:50:28 +0000 Subject: [PATCH 1/2] Remove repository configuration from VM runs --- README.md | 2 +- packages/app/src/exe-vm-backend.ts | 5 +---- packages/app/src/exe.ts | 2 -- packages/app/src/tenant.ts | 20 ++++++++------------ packages/app/src/ui.ts | 8 ++++---- packages/app/test/execution-backend.test.ts | 7 ++++--- packages/app/test/run-inspection.test.ts | 2 +- packages/app/test/ui.test.ts | 8 ++++---- packages/app/test/worker.test.ts | 2 +- 9 files changed, 24 insertions(+), 32 deletions(-) diff --git a/README.md b/README.md index e80d61c7..53524e7a 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/packages/app/src/exe-vm-backend.ts b/packages/app/src/exe-vm-backend.ts index 7baf7963..619b21ff 100644 --- a/packages/app/src/exe-vm-backend.ts +++ b/packages/app/src/exe-vm-backend.ts @@ -72,7 +72,7 @@ export class ExeVmBackend implements ExecutionBackend { async launch(request: LaunchRequest): Promise { 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()); @@ -82,13 +82,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", diff --git a/packages/app/src/exe.ts b/packages/app/src/exe.ts index c0550729..fe71a140 100644 --- a/packages/app/src/exe.ts +++ b/packages/app/src/exe.ts @@ -5,8 +5,6 @@ export interface ExeConnection { export interface ExeRunConnection extends ExeConnection { agentKind: string; - repositoryUrl: string; - checkoutRef?: string; agentCommand?: string; model?: string; effort?: string; diff --git a/packages/app/src/tenant.ts b/packages/app/src/tenant.ts index 6a294eb4..acbd29c1 100644 --- a/packages/app/src/tenant.ts +++ b/packages/app/src/tenant.ts @@ -437,7 +437,7 @@ export class TenantV2 extends DurableObject { 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. @@ -459,7 +459,7 @@ export class TenantV2 extends DurableObject { 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, @@ -492,7 +492,7 @@ export class TenantV2 extends DurableObject { kind: "exe-vm", name: "Ephemeral exe.dev VMs", workspace: "ephemeral", - cwd: "/workspace/repo", + cwd: "/workspace", agents: ["codex", "claude"], 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"] }))]); @@ -505,7 +505,7 @@ export class TenantV2 extends DurableObject { if (!job) return undefined; let target: Record = {}; 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[]> { @@ -572,8 +572,6 @@ export class TenantV2 extends DurableObject { 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), @@ -594,7 +592,7 @@ export class TenantV2 extends DurableObject { } 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" }; } private validateJobInput(input: any): void { @@ -603,8 +601,6 @@ export class TenantV2 extends DurableObject { 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)); @@ -692,7 +688,7 @@ export class TenantV2 extends DurableObject { 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), agentKind: text(input.agentKind).trim(), 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); @@ -714,7 +710,7 @@ export class TenantV2 extends DurableObject { 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), agentKind: text(input.agentKind).trim(), 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(); for (const trigger of triggers) { @@ -1644,7 +1640,7 @@ export class TenantV2 extends DurableObject { private async connectionForPipe(pipe: Row): Promise { 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, agentKind: String(pipe.agent_kind ?? ""), model: String(pipe.model ?? ""), effort: String(pipe.effort ?? "") }; } private async upsertMember(input: unknown): Promise { diff --git a/packages/app/src/ui.ts b/packages/app/src/ui.ts index 49622d27..3b16a881 100644 --- a/packages/app/src/ui.ts +++ b/packages/app/src/ui.ts @@ -95,7 +95,7 @@ export const jobPage = (viewer: { email: string }, jobId?: string) => shell(`${j

Step 1

Job details

Name this job and set how many runs it can process at once.

Step 2

Triggers

Choose the events that start this job and expose prompt context.

Context slugTypeConfigurationEnabledActions

Step 3

Prompt and context

Write the instructions for each run using context supplied by your triggers.

-

Step 4

Execution target

Select the VM connection and configure the agent and repository for this job.

+

Step 4

Execution target

Select the VM connection, agent, model, and effort for this job.

Add trigger

Provider credentials stay managed by Factorize.

@@ -136,7 +136,7 @@ $('#context-paths').addEventListener('click',e=>{const hint=e.target.closest('[d function nextSlug(){let n=1;while(reservedSlugs.has('trigger-'+n))n++;const slug='trigger-'+n;reservedSlugs.add(slug);return slug} async function repositories(installationId){const key=String(installationId);if(resources.repositories.has(key))return resources.repositories.get(key);const response=await fetch('/api/github/installations/'+encodeURIComponent(key)+'/repositories');const items=response.ok?await response.json():[];resources.repositories.set(key,items);return items} function options(select,items,label,value='id'){select.replaceChildren(...items.map(x=>new Option(x[label]||x.name,String(x[value]))))} -function syncModels(selected=form.model.value,selectedEffort=form.effort.value){const amp=resources.targets.find(x=>String(x.id)===form.executionTargetId.value)?.kind==='amp';for(const name of ['agentKind','repositoryUrl','checkoutRef','model','effort'])form.elements[name].disabled=amp;form.repositoryUrl.required=!amp;form.model.value=amp?'':selected;form.effort.value=amp?'':selectedEffort;$('#model-help').textContent=amp?'This target manages its agent and model in Amp.':'Leave blank to let the selected harness choose.';$('#effort-help').textContent=amp?'This target manages effort in Amp.':'Codex reasoning effort.'} +function syncModels(selected=form.model.value,selectedEffort=form.effort.value){const amp=resources.targets.find(x=>String(x.id)===form.executionTargetId.value)?.kind==='amp';for(const name of ['agentKind','model','effort'])form.elements[name].disabled=amp;form.model.value=amp?'':selected;form.effort.value=amp?'':selectedEffort;$('#model-help').textContent=amp?'This target manages its agent and model in Amp.':'Leave blank to let the selected harness choose.';$('#effort-help').textContent=amp?'This target manages effort in Amp.':'Codex reasoning effort.'} // Select the connected environment and model that will run this job. syncModels(current?.model||'') async function syncRepositories(selected){const install=triggerForm.elements.installationId.value,repos=await repositories(install);options(triggerForm.elements.repositoryId,repos,'fullName');if(selected)triggerForm.elements.repositoryId.value=String(selected)} function linearRuleRows(){return [...$('#linear-rules').querySelectorAll('[data-linear-rule]')]} @@ -160,10 +160,10 @@ $('#trigger-rows').onchange=e=>{if(e.target.dataset.enable===undefined)return;tr triggerForm.querySelectorAll('[name=scheduleMode]').forEach(input=>input.onchange=syncScheduleEditor);triggerForm.elements.intervalUnit.onchange=syncScheduleEditor;triggerForm.elements.intervalValue.oninput=syncScheduleEditor; triggerForm.onsubmit=e=>{e.preventDefault();try{const value=configFromForm();validate(value);if(editing>=0)triggers[editing]={...triggers[editing],...value};else triggers.push({...value,id:undefined,slug:nextSlug(),enabled:true,_clientId:++clientId});dialog.close();render()}catch(error){$('#dialog-error').textContent=error.message;$('#dialog-error').classList.remove('hidden')}}; $('#test-handler').onclick=async()=>{const output=$('#handler-result');try{const handlerCode=triggerForm.elements.handlerCode.value;if(!handlerCode)throw new Error('Enter handler code first.');const payload=JSON.parse(triggerForm.elements.testPayload.value);const result=await request('/api/v1/job-handlers/test',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({handlerCode,payload})});output.textContent=result.ok?'Accepted: '+JSON.stringify(result.decision):'Rejected: '+result.category}catch(e){output.textContent=e.message}}; -async function init(){const [targets,projects,linearOptions,clickupLists,installResponse,tails,jobs,current]=await Promise.all([request('/api/v1/execution-targets'),request('/api/linear/projects').catch(()=>[]),request('/api/linear/options').catch(()=>({statuses:[]})),request('/api/clickup/lists').catch(()=>[]),fetch('/api/github/installations'),request('/api/connections/cloudflare-tail').catch(()=>[]),request('/api/v1/jobs'),jobId?request('/api/v1/jobs/'+encodeURIComponent(jobId)):null]);resources.targets=targets;resources.projects=projects;resources.options=linearOptions;resources.clickupLists=clickupLists;resources.installations=installResponse.ok?(await installResponse.json()).filter(x=>x.state==='active'):[];resources.tailInstallations=tails;resources.jobs=jobs;options(triggerForm.elements.tailIntegrationId,tails,'name','integrationId');options(form.executionTargetId,targets,'name');if(current){form.name.value=current.name;form.slug.value=current.slug;form.promptTemplate.value=current.promptTemplate;form.concurrencyLimit.value=current.concurrencyLimit;form.executionTargetId.value=current.executionTargetId;form.agentKind.value=current.agentKind||'codex';form.repositoryUrl.value=current.repositoryUrl||'';form.checkoutRef.value=current.checkoutRef||'';triggers=current.triggers.map(t=>({...t,config:{...t.config}}))}else triggers=[{kind:'manual',slug:'trigger-1',enabled:true,config:{}}];syncModels(current?.model||'',current?.effort||'');highlightPrompt();reservedSlugs=new Set(triggers.map(t=>t.slug));await refreshAvailability();render()} +async function init(){const [targets,projects,linearOptions,clickupLists,installResponse,tails,jobs,current]=await Promise.all([request('/api/v1/execution-targets'),request('/api/linear/projects').catch(()=>[]),request('/api/linear/options').catch(()=>({statuses:[]})),request('/api/clickup/lists').catch(()=>[]),fetch('/api/github/installations'),request('/api/connections/cloudflare-tail').catch(()=>[]),request('/api/v1/jobs'),jobId?request('/api/v1/jobs/'+encodeURIComponent(jobId)):null]);resources.targets=targets;resources.projects=projects;resources.options=linearOptions;resources.clickupLists=clickupLists;resources.installations=installResponse.ok?(await installResponse.json()).filter(x=>x.state==='active'):[];resources.tailInstallations=tails;resources.jobs=jobs;options(triggerForm.elements.tailIntegrationId,tails,'name','integrationId');options(form.executionTargetId,targets,'name');if(current){form.name.value=current.name;form.slug.value=current.slug;form.promptTemplate.value=current.promptTemplate;form.concurrencyLimit.value=current.concurrencyLimit;form.executionTargetId.value=current.executionTargetId;form.agentKind.value=current.agentKind||'codex';triggers=current.triggers.map(t=>({...t,config:{...t.config}}))}else triggers=[{kind:'manual',slug:'trigger-1',enabled:true,config:{}}];syncModels(current?.model||'',current?.effort||'');highlightPrompt();reservedSlugs=new Set(triggers.map(t=>t.slug));await refreshAvailability();render()} form.executionTargetId.addEventListener('change',()=>syncModels('','')); window.addEventListener('focus',()=>refreshAvailability().catch(()=>{}));window.addEventListener('pageshow',()=>refreshAvailability().catch(()=>{})); -form.onsubmit=async e=>{e.preventDefault();const error=$('#error');error.classList.add('hidden');try{if(!triggers.length)throw new Error('Add at least one trigger.');const body={name:form.name.value,slug:form.slug.value,promptTemplate:form.promptTemplate.value,agentKind:form.agentKind.value,repositoryUrl:form.repositoryUrl.value.trim(),checkoutRef:form.checkoutRef.value.trim(),model:form.model.value.trim(),effort:form.effort.value.trim(),concurrencyLimit:Number(form.concurrencyLimit.value),executionTargetId:form.executionTargetId.value,triggers:triggers.map(({id,slug,kind,enabled,config})=>({id,slug,kind,enabled,config}))};const result=await request('/api/v1/jobs'+(jobId?'/'+encodeURIComponent(jobId):''),{method:jobId?'PUT':'POST',headers:{'content-type':'application/json'},body:JSON.stringify(body)});location.href='/jobs/'+encodeURIComponent(result.id)}catch(e){error.textContent=e.message;error.classList.remove('hidden');error.scrollIntoView({block:'center'})}};init().catch(e=>{const error=$('#error');error.textContent=e.message;error.classList.remove('hidden')});`); +form.onsubmit=async e=>{e.preventDefault();const error=$('#error');error.classList.add('hidden');try{if(!triggers.length)throw new Error('Add at least one trigger.');const body={name:form.name.value,slug:form.slug.value,promptTemplate:form.promptTemplate.value,agentKind:form.agentKind.value,model:form.model.value.trim(),effort:form.effort.value.trim(),concurrencyLimit:Number(form.concurrencyLimit.value),executionTargetId:form.executionTargetId.value,triggers:triggers.map(({id,slug,kind,enabled,config})=>({id,slug,kind,enabled,config}))};const result=await request('/api/v1/jobs'+(jobId?'/'+encodeURIComponent(jobId):''),{method:jobId?'PUT':'POST',headers:{'content-type':'application/json'},body:JSON.stringify(body)});location.href='/jobs/'+encodeURIComponent(result.id)}catch(e){error.textContent=e.message;error.classList.remove('hidden');error.scrollIntoView({block:'center'})}};init().catch(e=>{const error=$('#error');error.textContent=e.message;error.classList.remove('hidden')});`); export const jobDetailPage = (viewer: { email: string }, jobId: string) => shell("Job — Factorize", viewer, `

Loading job…

Run job manually

Add an optional prompt for this run.

`, `${uiHelpers} diff --git a/packages/app/test/execution-backend.test.ts b/packages/app/test/execution-backend.test.ts index 721c7d38..51d1731c 100644 --- a/packages/app/test/execution-backend.test.ts +++ b/packages/app/test/execution-backend.test.ts @@ -4,7 +4,7 @@ import type { ExecutionBackend, ExecutionObservation, LaunchRequest, RunHandle } afterEach(() => vi.unstubAllGlobals()); -const connection = { apiToken: "secret", agentKind: "codex", repositoryUrl: "https://github.int.exe.xyz/acme/repo.git", checkoutRef: "main", tags: ["github", "llm"], model: "gpt-5.5", effort: "high" }; +const connection = { apiToken: "secret", agentKind: "codex", tags: ["github", "llm"], model: "gpt-5.5", effort: "high" }; describe("ExeVmBackend", () => { it("tests every required permission and discovers sorted unique VM tags", async () => { @@ -35,7 +35,7 @@ describe("ExeVmBackend", () => { expect(result.missingPermissions).toEqual([]); }); - it("creates a tagged VM, clones the repository, and launches Codex directly", async () => { + it("creates a tagged VM and launches Codex directly in the workspace", async () => { const requests: string[] = []; vi.stubGlobal("fetch", vi.fn(async (_url: string, init: RequestInit) => { requests.push(String(init.body)); @@ -46,7 +46,8 @@ describe("ExeVmBackend", () => { expect(requests[0]).toContain("new --name='factorize-run-1'"); expect(requests[0]).toContain("--tag='github'"); expect(requests[0]).toContain("--tag='llm'"); - expect(requests[1]).toContain("git clone --"); + expect(requests[1]).toContain("cd /workspace"); + expect(requests[1]).not.toContain("git clone"); expect(requests[1]).toContain("codex"); }); diff --git a/packages/app/test/run-inspection.test.ts b/packages/app/test/run-inspection.test.ts index 48b597ae..65cc967e 100644 --- a/packages/app/test/run-inspection.test.ts +++ b/packages/app/test/run-inspection.test.ts @@ -135,7 +135,7 @@ describe("run invocation inspection", () => { created_at: "2026-09-16T12:00:00Z", updated_at: "2026-09-16T12:01:00Z", }] : []); (tenant as any).executionConfig = () => ({ id: "job-1" }); - (tenant as any).connectionForPipe = async () => ({ apiToken: "secret", agentKind: "codex", repositoryUrl: "https://example.test/repo.git", tags: [] }); + (tenant as any).connectionForPipe = async () => ({ apiToken: "secret", agentKind: "codex", tags: [] }); const output = vi.spyOn(ExeVmBackend.prototype, "readOutput").mockResolvedValue("work in progress"); const body = await ((tenant as any).getRun("run-1") as Promise).then((response: Response) => response.json()) as any; diff --git a/packages/app/test/ui.test.ts b/packages/app/test/ui.test.ts index fc27c575..b54f5ba6 100644 --- a/packages/app/test/ui.test.ts +++ b/packages/app/test/ui.test.ts @@ -176,14 +176,14 @@ describe("pages", () => { expect(html).not.toContain('min-w-[48rem]'); }); - it("configures agent and repository per job", () => { + it("configures the agent without repository fields", () => { const html = jobPage({ email: "owner@example.com" }, "job-1"); expect(html).toContain('name="model"'); expect(html).toContain('name="agentKind"'); - expect(html).toContain('name="repositoryUrl"'); - expect(html).toContain('name="checkoutRef"'); + expect(html).not.toContain('name="repositoryUrl"'); + expect(html).not.toContain('name="checkoutRef"'); expect(html).toContain("model:form.model.value.trim()"); - expect(html).toContain("repositoryUrl:form.repositoryUrl.value.trim()"); + expect(html).not.toContain("repositoryUrl:"); expectInlineScriptsToParse(html); }); diff --git a/packages/app/test/worker.test.ts b/packages/app/test/worker.test.ts index df676110..9466a09f 100644 --- a/packages/app/test/worker.test.ts +++ b/packages/app/test/worker.test.ts @@ -88,7 +88,7 @@ describe("Worker routes", () => { it("returns secret-free integration status through the owner boundary", async () => { const status = { linear: { organizationName: "Generation", viewerEmail: "owner@example.com" }, - exeConnections: [{ connectionId: "exe-1", repositoryUrl: "https://github.int.exe.xyz/acme/repo.git", tags: ["github"], agentKind: "codex" }], + exeConnections: [{ connectionId: "exe-1", tags: ["github"] }], ampConnections: [{ connectionId: "amp-1", project: "generation/factorize", apiBaseUrl: "https://ampcode.com/api/cloud/v1" }], }; const response = await app.request("https://factorize.test/api/connections/status", { From f53fe7def0acc008aec371906198d66a518c390b Mon Sep 17 00:00:00 2001 From: Brendan Date: Thu, 17 Sep 2026 23:55:38 +0000 Subject: [PATCH 2/2] Validate agents on exe.dev integrations --- packages/app/src/exe-vm-backend.ts | 23 ++++++++++++++++- packages/app/src/exe.ts | 6 ++--- packages/app/src/tenant.ts | 28 ++++++++++++--------- packages/app/src/types.ts | 1 + packages/app/src/ui.ts | 16 ++++++------ packages/app/test/execution-backend.test.ts | 24 +++++++++++++++++- packages/app/test/ui.test.ts | 6 +++-- 7 files changed, 77 insertions(+), 27 deletions(-) diff --git a/packages/app/src/exe-vm-backend.ts b/packages/app/src/exe-vm-backend.ts index 619b21ff..bfd4bb83 100644 --- a/packages/app/src/exe-vm-backend.ts +++ b/packages/app/src/exe-vm-backend.ts @@ -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(); @@ -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 | ExeRunConnection) {} private async api(command: string): Promise { const response = await fetch(API, { method: "POST", headers: { Authorization: `Bearer ${this.connection.apiToken}`, "Content-Type": "text/plain" }, body: command }); @@ -70,6 +71,26 @@ export class ExeVmBackend implements ExecutionBackend { async test(): Promise { return this.api("ls --json"); } + async validateAgentAndModels(agentKind: "codex" | "claude"): Promise { + 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 { const connection = this.connection as ExeRunConnection; if (!connection.agentKind) throw new Error("The job is missing its agent configuration"); diff --git a/packages/app/src/exe.ts b/packages/app/src/exe.ts index fe71a140..5095b29b 100644 --- a/packages/app/src/exe.ts +++ b/packages/app/src/exe.ts @@ -1,15 +1,15 @@ export interface ExeConnection { apiToken: string; tags: string[]; + agentKind: "codex" | "claude"; + models?: string[]; + modelsRefreshedAt?: string; } export interface ExeRunConnection extends ExeConnection { - agentKind: string; agentCommand?: string; model?: string; effort?: string; - models?: string[]; - modelsRefreshedAt?: string; efforts?: string[]; } diff --git a/packages/app/src/tenant.ts b/packages/app/src/tenant.ts index acbd29c1..8b50d581 100644 --- a/packages/app/src/tenant.ts +++ b/packages/app/src/tenant.ts @@ -331,18 +331,20 @@ export class TenantV2 extends DurableObject { private async saveExe(input: unknown): Promise { 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 { @@ -443,7 +445,7 @@ export class TenantV2 extends DurableObject { // 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 }); } @@ -462,7 +464,7 @@ export class TenantV2 extends DurableObject { 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 }); } @@ -493,7 +495,10 @@ export class TenantV2 extends DurableObject { name: "Ephemeral exe.dev VMs", workspace: "ephemeral", cwd: "/workspace", - agents: ["codex", "claude"], + 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"] }))]); } @@ -592,7 +597,7 @@ export class TenantV2 extends DurableObject { } 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" }; + return { connectionId: target.connectionId, backendKind: "exe-vm", workspace: "ephemeral", cwd: "/workspace", agentKind: target.agentKind }; } private validateJobInput(input: any): void { @@ -600,7 +605,6 @@ export class TenantV2 extends DurableObject { 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 (!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)); @@ -688,7 +692,7 @@ export class TenantV2 extends DurableObject { 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(), 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); @@ -710,7 +714,7 @@ export class TenantV2 extends DurableObject { 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(), 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(); for (const trigger of triggers) { @@ -1640,7 +1644,7 @@ export class TenantV2 extends DurableObject { private async connectionForPipe(pipe: Row): Promise { const connection = await this.exeConnection(String(pipe.exe_connection_id || "default")); if (!connection) return null; - return { ...connection, agentKind: String(pipe.agent_kind ?? ""), model: String(pipe.model ?? ""), effort: String(pipe.effort ?? "") }; + return { ...connection, model: String(pipe.model ?? ""), effort: String(pipe.effort ?? "") }; } private async upsertMember(input: unknown): Promise { diff --git a/packages/app/src/types.ts b/packages/app/src/types.ts index 5e542ac2..6cd4a988 100644 --- a/packages/app/src/types.ts +++ b/packages/app/src/types.ts @@ -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; } diff --git a/packages/app/src/ui.ts b/packages/app/src/ui.ts index 3b16a881..b0bfd639 100644 --- a/packages/app/src/ui.ts +++ b/packages/app/src/ui.ts @@ -95,7 +95,7 @@ export const jobPage = (viewer: { email: string }, jobId?: string) => shell(`${j

Step 1

Job details

Name this job and set how many runs it can process at once.

Step 2

Triggers

Choose the events that start this job and expose prompt context.

Context slugTypeConfigurationEnabledActions

Step 3

Prompt and context

Write the instructions for each run using context supplied by your triggers.

-

Step 4

Execution target

Select the VM connection, agent, model, and effort for this job.

+

Step 4

Execution target

Select the VM connection, model, and effort for this job.

Add trigger

Provider credentials stay managed by Factorize.

@@ -136,7 +136,7 @@ $('#context-paths').addEventListener('click',e=>{const hint=e.target.closest('[d function nextSlug(){let n=1;while(reservedSlugs.has('trigger-'+n))n++;const slug='trigger-'+n;reservedSlugs.add(slug);return slug} async function repositories(installationId){const key=String(installationId);if(resources.repositories.has(key))return resources.repositories.get(key);const response=await fetch('/api/github/installations/'+encodeURIComponent(key)+'/repositories');const items=response.ok?await response.json():[];resources.repositories.set(key,items);return items} function options(select,items,label,value='id'){select.replaceChildren(...items.map(x=>new Option(x[label]||x.name,String(x[value]))))} -function syncModels(selected=form.model.value,selectedEffort=form.effort.value){const amp=resources.targets.find(x=>String(x.id)===form.executionTargetId.value)?.kind==='amp';for(const name of ['agentKind','model','effort'])form.elements[name].disabled=amp;form.model.value=amp?'':selected;form.effort.value=amp?'':selectedEffort;$('#model-help').textContent=amp?'This target manages its agent and model in Amp.':'Leave blank to let the selected harness choose.';$('#effort-help').textContent=amp?'This target manages effort in Amp.':'Codex reasoning effort.'} +function syncModels(selected=form.model.value,selectedEffort=form.effort.value){const target=resources.targets.find(x=>String(x.id)===form.executionTargetId.value),amp=target?.kind==='amp',models=target?.models||[],efforts=target?.efforts||[];form.model.replaceChildren(new Option('Harness default',''),...models.map(value=>new Option(value,value)));form.model.disabled=amp;form.model.value=amp?'':selected;if(selected&&!form.model.value){form.model.append(new Option(selected+' (unavailable)',selected));form.model.value=selected}form.effort.replaceChildren(new Option('Harness default',''),...efforts.map(value=>new Option(value,value)));form.effort.disabled=amp||!efforts.length;form.effort.value=form.effort.disabled?'':selectedEffort;$('#model-help').textContent=amp?'This target manages its model in Amp.':models.length?'Models loaded when this VM integration was added.':'No models were returned by this VM integration.';$('#effort-help').textContent=efforts.length?'Select the harness reasoning effort.':'This harness does not expose effort selection.'} // Select the connected environment and model that will run this job. syncModels(current?.model||'') async function syncRepositories(selected){const install=triggerForm.elements.installationId.value,repos=await repositories(install);options(triggerForm.elements.repositoryId,repos,'fullName');if(selected)triggerForm.elements.repositoryId.value=String(selected)} function linearRuleRows(){return [...$('#linear-rules').querySelectorAll('[data-linear-rule]')]} @@ -160,10 +160,10 @@ $('#trigger-rows').onchange=e=>{if(e.target.dataset.enable===undefined)return;tr triggerForm.querySelectorAll('[name=scheduleMode]').forEach(input=>input.onchange=syncScheduleEditor);triggerForm.elements.intervalUnit.onchange=syncScheduleEditor;triggerForm.elements.intervalValue.oninput=syncScheduleEditor; triggerForm.onsubmit=e=>{e.preventDefault();try{const value=configFromForm();validate(value);if(editing>=0)triggers[editing]={...triggers[editing],...value};else triggers.push({...value,id:undefined,slug:nextSlug(),enabled:true,_clientId:++clientId});dialog.close();render()}catch(error){$('#dialog-error').textContent=error.message;$('#dialog-error').classList.remove('hidden')}}; $('#test-handler').onclick=async()=>{const output=$('#handler-result');try{const handlerCode=triggerForm.elements.handlerCode.value;if(!handlerCode)throw new Error('Enter handler code first.');const payload=JSON.parse(triggerForm.elements.testPayload.value);const result=await request('/api/v1/job-handlers/test',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({handlerCode,payload})});output.textContent=result.ok?'Accepted: '+JSON.stringify(result.decision):'Rejected: '+result.category}catch(e){output.textContent=e.message}}; -async function init(){const [targets,projects,linearOptions,clickupLists,installResponse,tails,jobs,current]=await Promise.all([request('/api/v1/execution-targets'),request('/api/linear/projects').catch(()=>[]),request('/api/linear/options').catch(()=>({statuses:[]})),request('/api/clickup/lists').catch(()=>[]),fetch('/api/github/installations'),request('/api/connections/cloudflare-tail').catch(()=>[]),request('/api/v1/jobs'),jobId?request('/api/v1/jobs/'+encodeURIComponent(jobId)):null]);resources.targets=targets;resources.projects=projects;resources.options=linearOptions;resources.clickupLists=clickupLists;resources.installations=installResponse.ok?(await installResponse.json()).filter(x=>x.state==='active'):[];resources.tailInstallations=tails;resources.jobs=jobs;options(triggerForm.elements.tailIntegrationId,tails,'name','integrationId');options(form.executionTargetId,targets,'name');if(current){form.name.value=current.name;form.slug.value=current.slug;form.promptTemplate.value=current.promptTemplate;form.concurrencyLimit.value=current.concurrencyLimit;form.executionTargetId.value=current.executionTargetId;form.agentKind.value=current.agentKind||'codex';triggers=current.triggers.map(t=>({...t,config:{...t.config}}))}else triggers=[{kind:'manual',slug:'trigger-1',enabled:true,config:{}}];syncModels(current?.model||'',current?.effort||'');highlightPrompt();reservedSlugs=new Set(triggers.map(t=>t.slug));await refreshAvailability();render()} +async function init(){const [targets,projects,linearOptions,clickupLists,installResponse,tails,jobs,current]=await Promise.all([request('/api/v1/execution-targets'),request('/api/linear/projects').catch(()=>[]),request('/api/linear/options').catch(()=>({statuses:[]})),request('/api/clickup/lists').catch(()=>[]),fetch('/api/github/installations'),request('/api/connections/cloudflare-tail').catch(()=>[]),request('/api/v1/jobs'),jobId?request('/api/v1/jobs/'+encodeURIComponent(jobId)):null]);resources.targets=targets;resources.projects=projects;resources.options=linearOptions;resources.clickupLists=clickupLists;resources.installations=installResponse.ok?(await installResponse.json()).filter(x=>x.state==='active'):[];resources.tailInstallations=tails;resources.jobs=jobs;options(triggerForm.elements.tailIntegrationId,tails,'name','integrationId');options(form.executionTargetId,targets,'name');if(current){form.name.value=current.name;form.slug.value=current.slug;form.promptTemplate.value=current.promptTemplate;form.concurrencyLimit.value=current.concurrencyLimit;form.executionTargetId.value=current.executionTargetId;triggers=current.triggers.map(t=>({...t,config:{...t.config}}))}else triggers=[{kind:'manual',slug:'trigger-1',enabled:true,config:{}}];syncModels(current?.model||'',current?.effort||'');highlightPrompt();reservedSlugs=new Set(triggers.map(t=>t.slug));await refreshAvailability();render()} form.executionTargetId.addEventListener('change',()=>syncModels('','')); window.addEventListener('focus',()=>refreshAvailability().catch(()=>{}));window.addEventListener('pageshow',()=>refreshAvailability().catch(()=>{})); -form.onsubmit=async e=>{e.preventDefault();const error=$('#error');error.classList.add('hidden');try{if(!triggers.length)throw new Error('Add at least one trigger.');const body={name:form.name.value,slug:form.slug.value,promptTemplate:form.promptTemplate.value,agentKind:form.agentKind.value,model:form.model.value.trim(),effort:form.effort.value.trim(),concurrencyLimit:Number(form.concurrencyLimit.value),executionTargetId:form.executionTargetId.value,triggers:triggers.map(({id,slug,kind,enabled,config})=>({id,slug,kind,enabled,config}))};const result=await request('/api/v1/jobs'+(jobId?'/'+encodeURIComponent(jobId):''),{method:jobId?'PUT':'POST',headers:{'content-type':'application/json'},body:JSON.stringify(body)});location.href='/jobs/'+encodeURIComponent(result.id)}catch(e){error.textContent=e.message;error.classList.remove('hidden');error.scrollIntoView({block:'center'})}};init().catch(e=>{const error=$('#error');error.textContent=e.message;error.classList.remove('hidden')});`); +form.onsubmit=async e=>{e.preventDefault();const error=$('#error');error.classList.add('hidden');try{if(!triggers.length)throw new Error('Add at least one trigger.');const body={name:form.name.value,slug:form.slug.value,promptTemplate:form.promptTemplate.value,model:form.model.value.trim(),effort:form.effort.value.trim(),concurrencyLimit:Number(form.concurrencyLimit.value),executionTargetId:form.executionTargetId.value,triggers:triggers.map(({id,slug,kind,enabled,config})=>({id,slug,kind,enabled,config}))};const result=await request('/api/v1/jobs'+(jobId?'/'+encodeURIComponent(jobId):''),{method:jobId?'PUT':'POST',headers:{'content-type':'application/json'},body:JSON.stringify(body)});location.href='/jobs/'+encodeURIComponent(result.id)}catch(e){error.textContent=e.message;error.classList.remove('hidden');error.scrollIntoView({block:'center'})}};init().catch(e=>{const error=$('#error');error.textContent=e.message;error.classList.remove('hidden')});`); export const jobDetailPage = (viewer: { email: string }, jobId: string) => shell("Job — Factorize", viewer, `

Loading job…

Run job manually

Add an optional prompt for this run.

`, `${uiHelpers} @@ -209,7 +209,7 @@ ${[["linear","Linear","Issues and projects"],["clickup","ClickUp","Tasks and lis

Connect Linear

You’ll leave Factorize to authorize access to your Linear workspace, then return here.

Connect ClickUp

Authorize a ClickUp workspace. Factorize will register the task webhook automatically.

Install the GitHub App

You’ll choose an account and repositories on GitHub, then return to Factorize.

-

Connect Exe.dev

Each run creates and then deletes an isolated VM. The token must allow ls, integrations list, new, ssh, and rm.

+

Connect Exe.dev

Each run creates and then deletes an isolated VM. The token must allow ls, integrations list, new, ssh, and rm.

Connect Amp

This verifies and stores a write-only token for an Amp cloud project.

Install Cloudflare Tail

Name the installation and paste a secret, or have Factorize generate one.

Installed integrations

Check status and manage providers already connected to Factorize.

Loading installed integrations…
`), `${uiHelpers} @@ -218,7 +218,7 @@ const integrationIcons=${JSON.stringify(integrationIcons)}; const testButton=(kind,id)=>''; const installedRow=(name,description,status,tone,actions)=>'
'+integrationIcons[name==='Cloudflare Tail'?'tail':name==='Exe.dev'?'exe':name.toLowerCase()]+'

'+esc(name)+'

Actions
'+actions+'

'+description+'

'+esc(status)+'
'; async function disconnectGitHub(id){if(!confirm('Disconnect this GitHub installation from Factorize?'))return;await request('/api/github/installations/'+encodeURIComponent(id),{method:'DELETE'});await load()} -async function load(){const loading=$('#installed-loading'),list=$('#installed-integrations'),table=$('#installed-table'),empty=$('#installed-empty');loading.classList.remove('hidden');table.classList.add('hidden');empty.classList.add('hidden');$('#integration-error').classList.add('hidden');try{const [s,gh,tails]=await Promise.all([request('/api/connections/status'),fetch('/api/github/installations'),request('/api/connections/cloudflare-tail')]),rows=[];const exe=s.exeConnections||[],amps=s.ampConnections||[];badge('#linear-available-status',(s.linear?1:0)+' installed','neutral');badge('#clickup-available-status',(s.clickup?1:0)+' installed','neutral');badge('#exe-available-status',exe.length+' installed','neutral');badge('#amp-available-status',amps.length+' installed','neutral');badge('#tail-available-status',tails.length+' installed','neutral');$('#linear-action').textContent=s.linear?'Reconnect Linear':'Continue to Linear';if(s.linear)rows.push(installedRow('Linear',esc(s.linear.organizationName||'Linear workspace')+(s.linear.viewerEmail?' · '+esc(s.linear.viewerEmail):''),'Connected','ok',''));if(s.clickup)rows.push(installedRow('ClickUp',esc(s.clickup.teamName||'ClickUp workspace'),'Connected','ok',''));exe.forEach(c=>rows.push(installedRow('Exe.dev',c.tags?.length?'VM tags · '+esc(c.tags.join(', ')):'No VM tags','Connected','ok',testButton('exe',c.connectionId)+'')));amps.forEach(c=>rows.push(installedRow('Amp',esc(c.project),'Connected','ok',testButton('amp',c.connectionId)+'')));tails.forEach(c=>rows.push(installedRow('Cloudflare Tail',esc(c.name)+(c.referencedJobCount?' · '+c.referencedJobCount+' jobs':''),'Connected','ok','')));if(gh.status===404){badge('#github-available-status','Unavailable','neutral');$('#github-install').classList.add('hidden')}else if(!gh.ok){badge('#github-available-status','Action required','warn');rows.push(installedRow('GitHub','Installation status could not be loaded.','Action required','warn',''))}else{const installs=await gh.json(),active=installs.filter(x=>x.state==='active');badge('#github-available-status',active.length+' installed',installs.length&&!active.length?'warn':'neutral');$('#github-install').textContent=active.length?'Add another installation':'Continue to GitHub';installs.forEach(x=>rows.push(installedRow('GitHub',esc(x.accountLogin||'Installation '+x.installationId)+' · '+esc(x.accountType||'GitHub'),x.state==='active'?'Connected':x.state,'active'===x.state?'ok':'warn','Configure ↗')))}list.innerHTML=rows.join('');loading.classList.add('hidden');table.classList.toggle('hidden',!rows.length);empty.classList.toggle('hidden',rows.length>0);bindActions()}catch(e){loading.classList.add('hidden');empty.classList.remove('hidden');const error=$('#integration-error');error.textContent=e.message||'Could not load integration status. Try again.';error.classList.remove('hidden');['linear','clickup','github','exe','amp','tail'].forEach(id=>badge('#'+id+'-available-status','Unavailable','neutral'))}} +async function load(){const loading=$('#installed-loading'),list=$('#installed-integrations'),table=$('#installed-table'),empty=$('#installed-empty');loading.classList.remove('hidden');table.classList.add('hidden');empty.classList.add('hidden');$('#integration-error').classList.add('hidden');try{const [s,gh,tails]=await Promise.all([request('/api/connections/status'),fetch('/api/github/installations'),request('/api/connections/cloudflare-tail')]),rows=[];const exe=s.exeConnections||[],amps=s.ampConnections||[];badge('#linear-available-status',(s.linear?1:0)+' installed','neutral');badge('#clickup-available-status',(s.clickup?1:0)+' installed','neutral');badge('#exe-available-status',exe.length+' installed','neutral');badge('#amp-available-status',amps.length+' installed','neutral');badge('#tail-available-status',tails.length+' installed','neutral');$('#linear-action').textContent=s.linear?'Reconnect Linear':'Continue to Linear';if(s.linear)rows.push(installedRow('Linear',esc(s.linear.organizationName||'Linear workspace')+(s.linear.viewerEmail?' · '+esc(s.linear.viewerEmail):''),'Connected','ok',''));if(s.clickup)rows.push(installedRow('ClickUp',esc(s.clickup.teamName||'ClickUp workspace'),'Connected','ok',''));exe.forEach(c=>rows.push(installedRow('Exe.dev',esc(c.agentKind)+(c.models?.length?' · '+c.models.length+' models':'')+(c.tags?.length?' · tags: '+esc(c.tags.join(', ')):' · no VM tags'),'Connected','ok',testButton('exe',c.connectionId)+'')));amps.forEach(c=>rows.push(installedRow('Amp',esc(c.project),'Connected','ok',testButton('amp',c.connectionId)+'')));tails.forEach(c=>rows.push(installedRow('Cloudflare Tail',esc(c.name)+(c.referencedJobCount?' · '+c.referencedJobCount+' jobs':''),'Connected','ok','')));if(gh.status===404){badge('#github-available-status','Unavailable','neutral');$('#github-install').classList.add('hidden')}else if(!gh.ok){badge('#github-available-status','Action required','warn');rows.push(installedRow('GitHub','Installation status could not be loaded.','Action required','warn',''))}else{const installs=await gh.json(),active=installs.filter(x=>x.state==='active');badge('#github-available-status',active.length+' installed',installs.length&&!active.length?'warn':'neutral');$('#github-install').textContent=active.length?'Add another installation':'Continue to GitHub';installs.forEach(x=>rows.push(installedRow('GitHub',esc(x.accountLogin||'Installation '+x.installationId)+' · '+esc(x.accountType||'GitHub'),x.state==='active'?'Connected':x.state,'active'===x.state?'ok':'warn','Configure ↗')))}list.innerHTML=rows.join('');loading.classList.add('hidden');table.classList.toggle('hidden',!rows.length);empty.classList.toggle('hidden',rows.length>0);bindActions()}catch(e){loading.classList.add('hidden');empty.classList.remove('hidden');const error=$('#integration-error');error.textContent=e.message||'Could not load integration status. Try again.';error.classList.remove('hidden');['linear','clickup','github','exe','amp','tail'].forEach(id=>badge('#'+id+'-available-status','Unavailable','neutral'))}} function openSetup(kind){const dialog=$('#'+kind+'-setup');if(!dialog.open)dialog.showModal()} function closeSetup(kind){const dialog=$('#'+kind+'-setup');if(dialog.open)dialog.close()} async function tailAction(id,method){await request('/api/connections/cloudflare-tail/'+encodeURIComponent(id),{method});await load()} @@ -226,9 +226,9 @@ function bindActions(){bindTests();document.querySelectorAll('[data-open-setup]' function showError(e){const error=$('#integration-error');error.textContent=e.message||'The integration action failed.';error.classList.remove('hidden')} function bindTests(){document.querySelectorAll('[data-test]').forEach(button=>button.onclick=async()=>{const original=button.textContent;button.disabled=true;button.textContent='Testing…';try{const kind=button.dataset.test,result=await request('/api/connections/'+kind+'/test',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({connectionId:button.dataset.id})});button.textContent=result.ok?'Connected':'Action required'}catch(e){button.textContent='Action required'}finally{setTimeout(()=>{button.disabled=false;button.textContent=original},1500)}})} document.addEventListener('click',async event=>{const button=event.target.closest('[data-remove-integration]');if(!button||!confirm('Remove this integration?'))return;button.disabled=true;try{await request('/api/connections/'+button.dataset.removeIntegration+'/'+encodeURIComponent(button.dataset.id),{method:'DELETE'});await load()}catch(error){button.disabled=false;showError(error)}}); -const exePayload=()=>{const form=$('#connection');return {apiToken:form.elements.apiToken.value,tags:[...form.elements.tags.selectedOptions].map(option=>option.value)}}; +const exePayload=()=>{const form=$('#connection');return {apiToken:form.elements.apiToken.value,agentKind:form.elements.agentKind.value,tags:[...form.elements.tags.selectedOptions].map(option=>option.value)}}; let exeTokenTimer=0,exeTokenRequest=0,verifiedExeToken='';async function testExeToken(){const form=$('#connection'),m=$('#settings-message'),status=$('#exe-token-status'),valid=$('#exe-token-valid'),button=$('#test-exe-token'),token=form.elements.apiToken.value.trim(),requestId=++exeTokenRequest;if(!token)return;button.disabled=true;status.textContent='Testing token and loading tags…';try{const result=await request('/api/connections/exe/test',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({apiToken:token})});if(requestId!==exeTokenRequest||token!==form.elements.apiToken.value.trim())return;if(!result.ok){verifiedExeToken='';valid.classList.add('hidden');valid.classList.remove('flex');status.textContent=result.missingPermissions.length?'Missing required permissions: '+result.missingPermissions.join(', '):'The token could not be verified. Check that it is valid and try again.';return}verifiedExeToken=token;valid.classList.remove('hidden');valid.classList.add('flex');form.elements.tags.replaceChildren(...result.tags.map(tag=>new Option(tag,tag)));form.elements.tags.disabled=false;status.textContent=result.tags.length?'Token verified. Select the VM tags to attach.':'Token verified. No integration tags were found.';m.textContent=''}catch(error){if(requestId===exeTokenRequest){verifiedExeToken='';valid.classList.add('hidden');valid.classList.remove('flex');status.textContent=error.message}}finally{if(requestId===exeTokenRequest)button.disabled=false}}$('#test-exe-token').onclick=testExeToken;$('#connection').elements.apiToken.addEventListener('input',event=>{clearTimeout(exeTokenTimer);exeTokenRequest++;verifiedExeToken='';const form=$('#connection'),valid=$('#exe-token-valid'),status=$('#exe-token-status'),token=event.target.value.trim();valid.classList.add('hidden');valid.classList.remove('flex');form.elements.tags.disabled=true;status.textContent=token?'Waiting for you to finish typing…':'Token testing starts automatically after you finish typing.';if(token.length>=16)exeTokenTimer=setTimeout(testExeToken,500)}); -$('#connection').onsubmit=async e=>{e.preventDefault();const form=e.currentTarget,m=$('#settings-message');try{await request('/api/connections/exe',{method:'PUT',headers:{'content-type':'application/json'},body:JSON.stringify(exePayload())});form.reset();verifiedExeToken='';$('#exe-token-valid').classList.add('hidden');$('#exe-token-valid').classList.remove('flex');$('#exe-token-status').textContent='Token testing starts automatically after you finish typing.';form.elements.tags.disabled=true;m.textContent='VM connection saved.';await load()}catch(x){m.textContent=x.message}}; +$('#connection').onsubmit=async e=>{e.preventDefault();const form=e.currentTarget,m=$('#settings-message');try{m.textContent='Creating a temporary VM to validate the agent and load models…';await request('/api/connections/exe',{method:'PUT',headers:{'content-type':'application/json'},body:JSON.stringify(exePayload())});form.reset();verifiedExeToken='';$('#exe-token-valid').classList.add('hidden');$('#exe-token-valid').classList.remove('flex');$('#exe-token-status').textContent='Token testing starts automatically after you finish typing.';form.elements.tags.disabled=true;m.textContent='VM connection saved.';await load()}catch(x){m.textContent=x.message}}; const ampPayload=()=>{const d=new FormData($('#amp-connection'));return {project:d.get('project'),accessToken:d.get('accessToken'),apiBaseUrl:d.get('apiBaseUrl')}};$('#test-amp').onclick=async()=>{const m=$('#amp-message');try{const x=await request('/api/connections/amp/test',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(ampPayload())});m.textContent=x.ok?'Amp connection succeeded.':'Amp connection needs attention.'}catch(x){m.textContent=x.message}};$('#amp-connection').onsubmit=async e=>{e.preventDefault();const form=e.currentTarget,m=$('#amp-message');try{await request('/api/connections/amp',{method:'PUT',headers:{'content-type':'application/json'},body:JSON.stringify(ampPayload())});form.reset();m.textContent='Amp connection saved. The token remains write-only.';await load()}catch(x){m.textContent=x.message}}; $('#tail-connection').onsubmit=async e=>{e.preventDefault();const form=e.currentTarget,d=new FormData(form),m=$('#tail-message'),id=form.dataset.id,url='/api/connections/cloudflare-tail'+(id?'/'+encodeURIComponent(id):'');try{const x=await request(url,{method:id?'PUT':'POST',headers:{'content-type':'application/json'},body:JSON.stringify({name:d.get('name'),signingSecret:d.get('signingSecret')||undefined,generateSecret:d.get('generateSecret')==='on'})});if(x.generatedSecret){$('#tail-generated-value').textContent=x.generatedSecret;$('#tail-generated').classList.remove('hidden')}form.reset();delete form.dataset.id;m.textContent='Tail installation saved. Its secret remains write-only.';await load()}catch(x){m.textContent=x.message}};$('#copy-tail-secret').onclick=async()=>{await navigator.clipboard.writeText($('#tail-generated-value').textContent);$('#copy-tail-secret').textContent='Copied'};bindActions();load();`); diff --git a/packages/app/test/execution-backend.test.ts b/packages/app/test/execution-backend.test.ts index 51d1731c..ced34b46 100644 --- a/packages/app/test/execution-backend.test.ts +++ b/packages/app/test/execution-backend.test.ts @@ -1,10 +1,11 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { ExeVmBackend, isOwnedVmName, tagsFromInventory, vmNameFor } from "../src/exe-vm-backend"; import type { ExecutionBackend, ExecutionObservation, LaunchRequest, RunHandle } from "../src/execution"; +import type { ExeRunConnection } from "../src/exe"; afterEach(() => vi.unstubAllGlobals()); -const connection = { apiToken: "secret", agentKind: "codex", tags: ["github", "llm"], model: "gpt-5.5", effort: "high" }; +const connection = { apiToken: "secret", agentKind: "codex", tags: ["github", "llm"], model: "gpt-5.5", effort: "high" } satisfies ExeRunConnection; describe("ExeVmBackend", () => { it("tests every required permission and discovers sorted unique VM tags", async () => { @@ -51,6 +52,27 @@ describe("ExeVmBackend", () => { expect(requests[1]).toContain("codex"); }); + it("validates Codex and loads models in a temporary tagged VM that is deleted", async () => { + const requests: string[] = []; + let vm = ""; + vi.stubGlobal("fetch", vi.fn(async (_url: string, init: RequestInit) => { + const command = String(init.body); requests.push(command); + if (command.startsWith("new ")) { + vm = command.match(/--name='([^']+)'/)?.[1] ?? ""; + return new Response(JSON.stringify({ name: vm }), { headers: { "X-Exe-Exit": "0" } }); + } + if (command.startsWith("ssh ")) return new Response('["gpt-5.5","gpt-5.6"]', { headers: { "X-Exe-Exit": "0" } }); + if (command === "ls --json") return new Response(JSON.stringify({ vms: [{ name: vm, comment: `Factorize VM ${vm}` }] }), { headers: { "X-Exe-Exit": "0" } }); + return new Response("removed", { headers: { "X-Exe-Exit": "0" } }); + })); + const result = await new ExeVmBackend(connection).validateAgentAndModels("codex"); + expect(result.models).toEqual(["gpt-5.5", "gpt-5.6"]); + expect(requests[0]).toContain("--tag='github'"); + expect(requests[1]).toContain("command -v codex"); + expect(requests[1]).toContain("https://llm.int.exe.xyz/v1/models"); + expect(requests.at(-1)).toBe(`rm '${vm}'`); + }); + it("refuses to delete a VM outside the owned namespace", async () => { await expect(new ExeVmBackend(connection).stop({ backendKind: "exe-vm", id: "production" })).rejects.toThrow("Invalid exe-vm execution handle"); expect(isOwnedVmName("factorize-run-1")).toBe(true); diff --git a/packages/app/test/ui.test.ts b/packages/app/test/ui.test.ts index b54f5ba6..d067d4f2 100644 --- a/packages/app/test/ui.test.ts +++ b/packages/app/test/ui.test.ts @@ -176,10 +176,10 @@ describe("pages", () => { expect(html).not.toContain('min-w-[48rem]'); }); - it("configures the agent without repository fields", () => { + it("uses the integration agent and configures only model and effort per job", () => { const html = jobPage({ email: "owner@example.com" }, "job-1"); expect(html).toContain('name="model"'); - expect(html).toContain('name="agentKind"'); + expect(html).not.toContain('name="agentKind"'); expect(html).not.toContain('name="repositoryUrl"'); expect(html).not.toContain('name="checkoutRef"'); expect(html).toContain("model:form.model.value.trim()"); @@ -194,6 +194,8 @@ describe("pages", () => { expect(dialog).toContain('id="exe-token-valid"'); expect(dialog).toContain('id="exe-token-status"'); expect(dialog).toContain('name="tags" multiple'); + expect(dialog).toContain('name="agentKind"'); + expect(dialog).toContain('temporary tagged VM'); expect(dialog).not.toContain('name="repositoryUrl"'); expect(dialog).not.toContain('name="checkoutRef"'); expect(html).toContain('data-remove-integration=');