From 33c9b052226102380e2604d44e159fe2b586c7e8 Mon Sep 17 00:00:00 2001 From: Brendan Date: Thu, 17 Sep 2026 05:27:17 +0000 Subject: [PATCH] Implement integration model and effort selection --- packages/app/src/exe.ts | 4 ++++ packages/app/src/flow-schemas.ts | 1 + packages/app/src/job-domain.ts | 1 + packages/app/src/tenant.ts | 32 ++++++++++++++++++++++++----- packages/app/src/types.ts | 1 + packages/app/src/ui.ts | 11 +++++----- packages/app/test/workspace.test.ts | 5 +++++ 7 files changed, 45 insertions(+), 10 deletions(-) diff --git a/packages/app/src/exe.ts b/packages/app/src/exe.ts index 0481fd4a..5d6c4faf 100644 --- a/packages/app/src/exe.ts +++ b/packages/app/src/exe.ts @@ -9,9 +9,12 @@ export interface ExeConnection { agentCommand?: string; /** Per-job harness model. Empty means the harness chooses its default. */ model?: string; + /** Per-job reasoning effort. Empty means the harness chooses its default. */ + effort?: string; /** Models returned by the VM's attached exe.dev LLM integration. */ models?: string[]; modelsRefreshedAt?: string; + efforts?: string[]; } export interface ExeResponse { @@ -188,6 +191,7 @@ function agentCommand(connection: ExeConnection, prompt?: string, cwd?: string): const command = connection.agentCommand?.trim() || defaultAgentCommand(connection.agentKind); const args = command ? shellWords(command).map(shellAtom) : []; if (connection.model?.trim()) args.push(shellAtom("--model"), shellAtom(connection.model.trim())); + if (connection.effort?.trim() && connection.agentKind === "codex") args.push(shellAtom("-c"), shellAtom(`model_reasoning_effort=${connection.effort.trim()}`)); if (connection.agentKind === "codex" && cwd) args.push("--dangerously-bypass-hook-trust", "--cd", shellAtom(cwd), "-c", shellAtom(`projects.${JSON.stringify(cwd)}.trust_level="trusted"`)); if (prompt !== undefined) args.push("--", shellAtom(prompt)); return args.length ? ` -- ${args.join(" ")}` : ""; diff --git a/packages/app/src/flow-schemas.ts b/packages/app/src/flow-schemas.ts index 98abf6cb..e94e89db 100644 --- a/packages/app/src/flow-schemas.ts +++ b/packages/app/src/flow-schemas.ts @@ -37,6 +37,7 @@ export const jobInputSchema = z.object({ concurrencyLimit: z.number().int().min(1).max(50).default(1), executionTargetId: z.string().min(1), model: z.string().trim().max(120).optional(), + effort: z.string().trim().max(40).optional(), triggers: z.array(triggerSchema).max(50).default([]), }).strict(); export const jobIdSchema = z.object({ jobId: z.string().min(1) }); diff --git a/packages/app/src/job-domain.ts b/packages/app/src/job-domain.ts index ceeb210a..08bf6bcc 100644 --- a/packages/app/src/job-domain.ts +++ b/packages/app/src/job-domain.ts @@ -28,6 +28,7 @@ export interface Job { slug: string; promptTemplate: string; model: string; + effort?: string; executionTarget: ExecutionTarget; concurrencyLimit: number; enabled: boolean; diff --git a/packages/app/src/tenant.ts b/packages/app/src/tenant.ts index 3ee23a64..158552ae 100644 --- a/packages/app/src/tenant.ts +++ b/packages/app/src/tenant.ts @@ -465,8 +465,27 @@ export class TenantV2 extends DurableObject { private async executionTargets(): Promise { const connections = await this.exeConnections(); + const populated = await Promise.all(connections.map(async connection => { + // A missing models field means this connection predates discovery. Once a + // discovery has run, even an empty result is left for the explicit refresh action. + if (Array.isArray(connection.models)) return connection; + try { + const models = await this.discoverExeModels(connection); + const saved = { ...connection, models, modelsRefreshedAt: now() }; + await this.putConnection(`exe:${connection.connectionId}`, saved); + const legacy = await this.connection("exe"); + if (legacy?.vmName === connection.vmName && legacy.cwd === connection.cwd && legacy.agentKind === connection.agentKind) await this.putConnection("exe", saved); + return saved; + } catch { + // Mark the attempted discovery as populated so a transient/unavailable + // integration does not turn every job-editor load into a remote call. + const saved = { ...connection, models: [], modelsRefreshedAt: now() }; + await this.putConnection(`exe:${connection.connectionId}`, saved); + return saved; + } + })); const ampConnections = await this.ampConnections(); - return json([...connections.map(connection => ({ + return json([...populated.map(connection => ({ id: connection.connectionId, kind: "exe-herdr", name: connection.vmName, @@ -475,6 +494,7 @@ export class TenantV2 extends DurableObject { agentKind: connection.agentKind, models: connection.models ?? [], modelsRefreshedAt: connection.modelsRefreshedAt ?? null, + efforts: connection.efforts ?? (connection.agentKind === "codex" ? ["minimal", "low", "medium", "high", "xhigh"] : []), capabilities: ["output", "prompt-delivery", "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"] }))]); } @@ -486,7 +506,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 ?? "", cwd: target.cwd, execution_backend_kind: target.backendKind ?? "exe-herdr", 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-herdr", execution_connection_id: target.connectionId, exe_connection_id: target.connectionId, enabled: job.enabled }; } private async publicJob(row: Row): Promise> { @@ -510,6 +530,7 @@ export class TenantV2 extends DurableObject { id: row.id, name: row.name, slug: row.slug, promptTemplate: await decrypt(String(row.encrypted_prompt_template), this.env.CREDENTIAL_ENCRYPTION_KEY), model: String(executionTarget.model ?? ""), + effort: String(executionTarget.effort ?? ""), concurrencyLimit: Number(row.concurrency_limit), runningCount: Number(runSummary?.running_count ?? 0), maxConcurrency: Number(row.concurrency_limit), @@ -537,6 +558,7 @@ export class TenantV2 extends DurableObject { 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 (!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); for (const trigger of input.triggers) { @@ -624,7 +646,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), model: text(input.model).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,execution_target,concurrency_limit,enabled,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?)", jobId, input.name, input.slug, await encrypt(input.promptTemplate, this.env.CREDENTIAL_ENCRYPTION_KEY), JSON.stringify(target), input.concurrencyLimit, 1, timestamp, timestamp); @@ -646,7 +668,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), model: text(input.model).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=?,execution_target=?,concurrency_limit=?,updated_at=? WHERE id=?", input.name, input.slug, await encrypt(input.promptTemplate, this.env.CREDENTIAL_ENCRYPTION_KEY), JSON.stringify(target), input.concurrencyLimit, timestamp, jobId); const retained = new Set(); for (const trigger of triggers) { @@ -1584,7 +1606,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, ...(pipe.cwd ? { cwd: workingDirectoryFor(String(pipe.cwd), String(pipe.workspace_name)) } : {}), model: String(pipe.model ?? "") }; + return { ...connection, ...(pipe.cwd ? { cwd: workingDirectoryFor(String(pipe.cwd), String(pipe.workspace_name)) } : {}), 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 602aa4a6..9875d2e3 100644 --- a/packages/app/src/types.ts +++ b/packages/app/src/types.ts @@ -57,6 +57,7 @@ export interface ExeConnectionInput { agentCommand?: string; models?: string[]; modelsRefreshedAt?: string; + efforts?: string[]; } 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 efa33c9b..34e74e8b 100644 --- a/packages/app/src/ui.ts +++ b/packages/app/src/ui.ts @@ -67,7 +67,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 connected environment and model that will run this job.

+

Step 4

Execution target

Select the connected environment, model, and effort that will run this job.

Add trigger

Provider credentials stay managed by Factorize.

@@ -107,7 +107,8 @@ $('#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){const target=resources.targets.find(x=>String(x.id)===form.executionTargetId.value),models=target?.models||[];form.model.replaceChildren(new Option('Harness default',''),...models.map(value=>new Option(value,value)));form.model.disabled=target?.kind==='amp';form.model.value=form.model.disabled?'':selected;if(selected&&!form.model.value){form.model.append(new Option(selected+' (unavailable)',selected));form.model.value=selected}$('#model-help').textContent=form.model.disabled?'This target manages its model in Amp.':models.length?'Models cached from this connection. Refresh them in Settings → Integrations.':'No models are cached for this connection. Refresh them in Settings → Integrations.'} +function syncModels(selected=form.model.value,selectedEffort=form.effort.value){const target=resources.targets.find(x=>String(x.id)===form.executionTargetId.value),models=target?.models||[],efforts=target?.efforts||[];form.model.replaceChildren(new Option('Harness default',''),...models.map(value=>new Option(value,value)));form.model.disabled=target?.kind==='amp';form.model.value=form.model.disabled?'':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=form.model.disabled||!efforts.length;form.effort.value=form.effort.disabled?'':selectedEffort;$('#model-help').textContent=form.model.disabled?'This target manages its model in Amp.':models.length?'Models cached from this connection. Refresh them in Settings → Integrations.':'No models are cached for this connection. Refresh them in Settings → Integrations.';$('#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]')]} function syncLinearRuleButtons(){const rows=linearRuleRows();rows.forEach(row=>row.querySelector('[data-remove-linear-rule]').classList.toggle('invisible',rows.length===1))} @@ -130,10 +131,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;triggers=current.triggers.map(t=>({...t,config:{...t.config}}))}else triggers=[{kind:'manual',slug:'trigger-1',enabled:true,config:{}}];syncModels(current?.model||'');highlightPrompt();reservedSlugs=new Set(triggers.map(t=>t.slug));await refreshAvailability();render()} -form.executionTargetId.addEventListener('change',()=>syncModels('')); +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,model:form.model.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} diff --git a/packages/app/test/workspace.test.ts b/packages/app/test/workspace.test.ts index 0a76e512..65239225 100644 --- a/packages/app/test/workspace.test.ts +++ b/packages/app/test/workspace.test.ts @@ -87,6 +87,11 @@ describe("flow workspaces", () => { expect(command).toContain("-- '--dangerously-bypass-approvals-and-sandbox' '--model' 'gpt-5.5 codex'"); }); + it("passes a per-job reasoning effort to Codex", () => { + const command = startAgentCommand("factorize-1", { vmName: "vm", apiToken: "token", agentKind: "codex", cwd: "/repo", effort: "high" }, "fix it", "factorize", "/repo/.factorize-runs/run", "lease"); + expect(command).toContain("'-c' 'model_reasoning_effort=high'"); + }); + it("garbage collects the pane and run directory only after ownership revalidation", () => { const command = garbageCollectPaneCommand({ vmName: "vm", apiToken: "token", agentKind: "codex", cwd: "/repo" }, "w1:p2", "term-7", "/repo/.factorize-runs/run", "lease-7"); expect(command).toContain(".terminal_id == $terminal");