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
45 changes: 45 additions & 0 deletions packages/api-client/src/schema.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2555,6 +2555,11 @@ export interface components {
};
})[];
skillIds?: string[];
portableIntegrationIds?: string[];
/** @enum {string} */
modelAccess?: "native" | "portable";
/** Format: uuid */
modelAccountId?: string;
};
ManualInvocation: {
/** @default */
Expand Down Expand Up @@ -5848,11 +5853,18 @@ export interface operations {
cwd?: string;
agentKind: string;
image?: string;
region?: string;
size?: string;
/** @enum {string} */
executionType?: "agent" | "code";
script?: string;
};
runScopes: ("projects:read" | "projects:write" | "jobs:read" | "jobs:write" | "runs:read" | "runs:invoke" | "runs:cancel" | "runs:write" | "integrations:read" | "integrations:write" | "skills:read" | "skills:write")[];
portableIntegrationIds?: string[];
/** @enum {string} */
modelAccess?: "native" | "portable";
/** Format: uuid */
modelAccountId?: string;
executionConfigId: string;
agentKind: string;
concurrencyLimit: number;
Expand Down Expand Up @@ -6137,11 +6149,18 @@ export interface operations {
cwd?: string;
agentKind: string;
image?: string;
region?: string;
size?: string;
/** @enum {string} */
executionType?: "agent" | "code";
script?: string;
};
runScopes: ("projects:read" | "projects:write" | "jobs:read" | "jobs:write" | "runs:read" | "runs:invoke" | "runs:cancel" | "runs:write" | "integrations:read" | "integrations:write" | "skills:read" | "skills:write")[];
portableIntegrationIds?: string[];
/** @enum {string} */
modelAccess?: "native" | "portable";
/** Format: uuid */
modelAccountId?: string;
executionConfigId: string;
agentKind: string;
concurrencyLimit: number;
Expand Down Expand Up @@ -6338,11 +6357,18 @@ export interface operations {
cwd?: string;
agentKind: string;
image?: string;
region?: string;
size?: string;
/** @enum {string} */
executionType?: "agent" | "code";
script?: string;
};
runScopes: ("projects:read" | "projects:write" | "jobs:read" | "jobs:write" | "runs:read" | "runs:invoke" | "runs:cancel" | "runs:write" | "integrations:read" | "integrations:write" | "skills:read" | "skills:write")[];
portableIntegrationIds?: string[];
/** @enum {string} */
modelAccess?: "native" | "portable";
/** Format: uuid */
modelAccountId?: string;
executionConfigId: string;
agentKind: string;
concurrencyLimit: number;
Expand Down Expand Up @@ -6821,11 +6847,18 @@ export interface operations {
cwd?: string;
agentKind: string;
image?: string;
region?: string;
size?: string;
/** @enum {string} */
executionType?: "agent" | "code";
script?: string;
};
runScopes: ("projects:read" | "projects:write" | "jobs:read" | "jobs:write" | "runs:read" | "runs:invoke" | "runs:cancel" | "runs:write" | "integrations:read" | "integrations:write" | "skills:read" | "skills:write")[];
portableIntegrationIds?: string[];
/** @enum {string} */
modelAccess?: "native" | "portable";
/** Format: uuid */
modelAccountId?: string;
executionConfigId: string;
agentKind: string;
concurrencyLimit: number;
Expand Down Expand Up @@ -7110,6 +7143,11 @@ export interface operations {
};
})[];
skillIds?: string[];
portableIntegrationIds?: string[];
/** @enum {string} */
modelAccess?: "native" | "portable";
/** Format: uuid */
modelAccountId?: string;
/** Format: date-time */
expectedUpdatedAt?: string;
};
Expand Down Expand Up @@ -7144,11 +7182,18 @@ export interface operations {
cwd?: string;
agentKind: string;
image?: string;
region?: string;
size?: string;
/** @enum {string} */
executionType?: "agent" | "code";
script?: string;
};
runScopes: ("projects:read" | "projects:write" | "jobs:read" | "jobs:write" | "runs:read" | "runs:invoke" | "runs:cancel" | "runs:write" | "integrations:read" | "integrations:write" | "skills:read" | "skills:write")[];
portableIntegrationIds?: string[];
/** @enum {string} */
modelAccess?: "native" | "portable";
/** Format: uuid */
modelAccountId?: string;
executionConfigId: string;
agentKind: string;
concurrencyLimit: number;
Expand Down
7 changes: 7 additions & 0 deletions packages/api/src/flow-schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,9 +75,16 @@ export const jobInputSchema = z.object({
effort: z.string().trim().max(40).optional(),
triggers: z.array(triggerSchema).max(50).default([]),
skillIds: z.array(z.guid()).max(50).optional(),
portableIntegrationIds: z.array(z.guid()).max(100).refine(ids => new Set(ids).size === ids.length, "Portable integrations must be unique").optional(),
modelAccess: z.enum(["native", "portable"]).optional(),
modelAccountId: z.guid().optional(),
}).strict().superRefine((value, context) => {
if (value.executionType !== "code" && !value.promptTemplate?.trim()) context.addIssue({ code: "custom", path: ["promptTemplate"], message: "Agent jobs require a prompt template." });
if (value.executionType === "code" && !value.script?.trim()) context.addIssue({ code: "custom", path: ["script"], message: "Code jobs require a script." });
if (value.executionType === "code" && value.modelAccountId) context.addIssue({ code: "custom", path: ["modelAccountId"], message: "Code jobs cannot select a model account." });
if (value.executionType === "code" && value.modelAccess === "portable") context.addIssue({ code: "custom", path: ["modelAccess"], message: "Code jobs cannot select model access." });
if (value.modelAccess === "portable" && !value.modelAccountId && value.executionType !== "code") context.addIssue({ code: "custom", path: ["modelAccountId"], message: "Portable model access requires a model account." });
if (value.modelAccountId && value.modelAccess === "native") context.addIssue({ code: "custom", path: ["modelAccountId"], message: "Native model access cannot select a portable model account." });
});
export const vmImageVerificationInput = z.object({
connectionId: z.string().min(1).max(200),
Expand Down
36 changes: 31 additions & 5 deletions packages/api/src/flow-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,14 +83,36 @@ export class ApiService {
return { targetId: id, connectionId, workspace: value.project, cwd: "", agentKind: "Amp", tags: [] };
}
const value = await this.connections().get<{ agentKind: string; tags?: string[] }>(`exe:${id}`);
if (!value) throw new ServiceError(400, "invalid_request", "execution integration not found");
return { targetId: id, connectionId: id, workspace: "ephemeral", cwd: "/home/exedev/workspace", agentKind: value.agentKind, tags: value.tags ?? [] };
if (value) return { targetId: id, connectionId: id, workspace: "ephemeral", cwd: "/home/exedev/workspace", agentKind: value.agentKind, tags: value.tags ?? [], executionProvider: "exe" as const };
const fly = await this.flyExecutionConfigs().get(id);
if (!fly) throw new ServiceError(400, "invalid_request", "execution integration not found");
if (!await this.flyConnections().get()) throw new ServiceError(409, "fly_connection_required", "Connect a Fly account before selecting this execution configuration.");
return { targetId: id, connectionId: id, workspace: "", cwd: "", agentKind: "codex", tags: [], image: fly.image, region: fly.region, size: fly.size, executionProvider: "fly" as const };
}

private async portableSelections(config: Awaited<ReturnType<ApiService["executionConfig"]>>, executionType: "agent" | "code", input: JobInput, current?: Job) {
const portableIntegrationIds = input.portableIntegrationIds ?? current?.portableIntegrationIds ?? current?.executionConfig.portableIntegrationIds ?? [];
if (executionType === "code" && input.modelAccess === "portable") throw new ServiceError(400, "invalid_request", "Code jobs cannot select model access.");
const modelAccess = executionType === "code" ? "native" : input.modelAccess ?? current?.modelAccess ?? current?.executionConfig.modelAccess ?? (config.executionProvider === "fly" ? "portable" : "native");
if (modelAccess === "native" && input.modelAccountId) throw new ServiceError(400, "invalid_request", "Native model access cannot select a portable model account.");
const modelAccountId = modelAccess === "portable" ? input.modelAccountId ?? current?.modelAccountId ?? current?.executionConfig.modelAccountId : undefined;
if (executionType === "code" && modelAccountId) throw new ServiceError(400, "invalid_request", "Code jobs cannot select a model account.");
if (config.executionProvider === "fly" && executionType === "agent" && config.agentKind === "codex" && (!modelAccountId || modelAccess !== "portable")) throw new ServiceError(400, "invalid_request", "Fly Codex jobs require a portable model account.");
const records = await new EncryptedIntegrationRepository(databaseFor(this.env), this.auth.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY).records();
const byId = new Map(records.map(record => [record.id, record]));
if (new Set(portableIntegrationIds).size !== portableIntegrationIds.length || portableIntegrationIds.some(id => byId.get(id)?.kind !== "bearer")) throw new ServiceError(400, "invalid_request", "One or more selected portable integrations are unavailable.");
if (modelAccountId && byId.get(modelAccountId)?.kind !== "model") throw new ServiceError(400, "invalid_request", "The selected model account is unavailable.");
if (modelAccess === "portable" && executionType !== "code" && !modelAccountId) throw new ServiceError(400, "invalid_request", "Portable model access requires a model account.");
return { portableIntegrationIds, modelAccess, ...(modelAccountId ? { modelAccountId } : {}) };
}

private async validateExecutionOptions(id: string, model: string, effort: string, tags: string[]) {
if (id.startsWith("amp:")) return;
const connection = await this.connections().get<ExeConnection>(`exe:${id}`);
if (!connection) throw new ServiceError(400, "invalid_request", "execution integration not found");
if (!connection) {
if (await this.flyExecutionConfigs().get(id)) return;
throw new ServiceError(400, "invalid_request", "execution integration not found");
}
const availableModels = connection.modelsByAgent?.[connection.agentKind ?? "codex"] ?? connection.models ?? [];
const availableEfforts = effortOptions[connection.agentKind ?? "codex"] ?? [];
if (model && availableModels.length && !availableModels.includes(model)) throw new ServiceError(400, "invalid_request", "Model is not available on this agent.");
Expand Down Expand Up @@ -357,10 +379,12 @@ export class ApiService {
const executionType = input.executionType ?? "agent";
if (executionType === "code" && input.executionConfigId.startsWith("amp:")) throw new ServiceError(400, "invalid_request", "Code jobs require an exe.dev integration.");
if (executionType !== "code") await this.validateExecutionOptions(input.executionConfigId, input.model ?? "", input.effort ?? "", input.tags ?? []);
const executionConfig = await this.executionConfig(input.executionConfigId);
const portable = await this.portableSelections(executionConfig, executionType, input);
const triggers = this.normalizedTriggers(input.triggers).map(trigger => ({ ...trigger, jobId: id }));
const projectId = input.projectId ?? await this.projects().defaultProjectId();
const selectedSkills = executionType === "code" ? [] : input.skillIds ? await this.skillSelections(input.skillIds) : [];
const job: Job = { id, projectId, runScopes: input.runScopes ?? [...DEFAULT_RUN_SCOPES], name: input.name, slug: input.slug, promptTemplate: input.promptTemplate ?? "", executionType, script: executionType === "code" ? input.script : undefined, runNameTemplate: input.runNameTemplate ?? "", tags: input.tags ?? [], model: input.model ?? "", ...(input.effort ? { effort: input.effort } : {}), executionConfig: { ...await this.executionConfig(input.executionConfigId), executionType, ...(input.script ? { script: input.script } : {}), ...(vmImage ? { image: vmImage } : {}) }, concurrencyLimit: input.concurrencyLimit, enabled: true, triggers, selectedSkills, createdAt: timestamp, updatedAt: timestamp };
const job: Job = { id, projectId, runScopes: input.runScopes ?? [...DEFAULT_RUN_SCOPES], name: input.name, slug: input.slug, promptTemplate: input.promptTemplate ?? "", executionType, script: executionType === "code" ? input.script : undefined, runNameTemplate: input.runNameTemplate ?? "", tags: input.tags ?? [], model: input.model ?? "", ...portable, ...(input.effort ? { effort: input.effort } : {}), executionConfig: { ...executionConfig, ...portable, executionType, ...(input.script ? { script: input.script } : {}), ...(vmImage ? { image: vmImage } : {}) }, concurrencyLimit: input.concurrencyLimit, enabled: true, triggers, selectedSkills, createdAt: timestamp, updatedAt: timestamp };
try { return this.presentJob(await this.jobs().create(job)); } catch (error: any) { if (error?.code === "23505") throw new ServiceError(409, "conflict", "Job slug is already in use"); throw error; }
}
async updateJob(jobId: string, input: JobInput & { expectedUpdatedAt?: string }) {
Expand All @@ -369,9 +393,11 @@ export class ApiService {
const executionType = input.executionType ?? current.executionType ?? "agent";
if (executionType === "code" && input.executionConfigId.startsWith("amp:")) throw new ServiceError(400, "invalid_request", "Code jobs require an exe.dev integration.");
if (executionType !== "code") await this.validateExecutionOptions(input.executionConfigId, input.model ?? "", input.effort ?? "", input.tags ?? []);
const executionConfig = await this.executionConfig(input.executionConfigId);
const portable = await this.portableSelections(executionConfig, executionType, input, current);
const triggers = this.normalizedTriggers(input.triggers, current.triggers).map(trigger => ({ ...trigger, jobId }));
const selectedSkills = executionType === "code" ? [] : input.skillIds === undefined ? current.selectedSkills : await this.skillSelections(input.skillIds);
const updated = await repository.update({ ...current, runScopes: input.runScopes ?? current.runScopes ?? [...DEFAULT_RUN_SCOPES], projectId: input.projectId ?? current.projectId, name: input.name, slug: input.slug, promptTemplate: input.promptTemplate ?? "", executionType, script: executionType === "code" ? input.script : undefined, runNameTemplate: input.runNameTemplate ?? "", tags: input.tags ?? [], model: input.model ?? "", effort: input.effort, executionConfig: { ...await this.executionConfig(input.executionConfigId), executionType, ...(input.script ? { script: input.script } : {}), ...(vmImage ? { image: vmImage } : {}) }, concurrencyLimit: input.concurrencyLimit, triggers, selectedSkills, updatedAt: new Date().toISOString() }, input.expectedUpdatedAt).catch(error => { if (error instanceof StaleJobEdit) throw new ServiceError(409, "stale_job", "This job changed. Reload its configuration before saving."); throw error; });
const updated = await repository.update({ ...current, ...portable, runScopes: input.runScopes ?? current.runScopes ?? [...DEFAULT_RUN_SCOPES], projectId: input.projectId ?? current.projectId, name: input.name, slug: input.slug, promptTemplate: input.promptTemplate ?? "", executionType, script: executionType === "code" ? input.script : undefined, runNameTemplate: input.runNameTemplate ?? "", tags: input.tags ?? [], model: input.model ?? "", effort: input.effort, executionConfig: { ...executionConfig, ...portable, executionType, ...(input.script ? { script: input.script } : {}), ...(vmImage ? { image: vmImage } : {}) }, concurrencyLimit: input.concurrencyLimit, triggers, selectedSkills, updatedAt: new Date().toISOString() }, input.expectedUpdatedAt).catch(error => { if (error instanceof StaleJobEdit) throw new ServiceError(409, "stale_job", "This job changed. Reload its configuration before saving."); throw error; });
await this.wakeScheduler();
return this.presentJob(updated);
}
Expand Down
3 changes: 2 additions & 1 deletion packages/api/src/job-contracts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,9 @@ export const triggerResponse = z.discriminatedUnion("kind", [
export const jobResponse = z.object({
id: z.guid(), projectId: z.guid().optional(), name: z.string(), slug: z.string(), enabled: z.boolean(),
executionType: z.enum(["agent", "code"]).optional(), promptTemplate: z.string(), script: z.string().optional(), runNameTemplate: z.string(), tags: z.array(z.string()).optional(), model: z.string(), effort: z.string().optional(),
executionConfig: z.object({ connectionId: z.string(), workspace: z.string().optional(), cwd: z.string().optional(), agentKind: z.string(), image: z.string().optional(), executionType: z.enum(["agent", "code"]).optional(), script: z.string().optional() }),
executionConfig: z.object({ connectionId: z.string(), workspace: z.string().optional(), cwd: z.string().optional(), agentKind: z.string(), image: z.string().optional(), region: z.string().optional(), size: z.string().optional(), executionType: z.enum(["agent", "code"]).optional(), script: z.string().optional() }),
runScopes: z.array(scopeSchema),
portableIntegrationIds: z.array(z.guid()).optional(), modelAccess: z.enum(["native", "portable"]).optional(), modelAccountId: z.guid().optional(),
executionConfigId: z.string(), agentKind: z.string(), concurrencyLimit: z.number().int(),
runningCount: z.number().int(), currentRuns: z.number().int(), maxConcurrency: z.number().int(), lastRunState: z.enum(["queued", "reserved", "starting", "running", "blocked", "stopping", "succeeded", "failed", "stopped", "done", "ignored"]).nullable(),
triggers: z.array(triggerResponse),
Expand Down
Loading
Loading