diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index 608423b5..8e8bc087 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -2555,6 +2555,11 @@ export interface components { }; })[]; skillIds?: string[]; + portableIntegrationIds?: string[]; + /** @enum {string} */ + modelAccess?: "native" | "portable"; + /** Format: uuid */ + modelAccountId?: string; }; ManualInvocation: { /** @default */ @@ -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; @@ -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; @@ -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; @@ -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; @@ -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; }; @@ -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; diff --git a/packages/api/src/flow-schemas.ts b/packages/api/src/flow-schemas.ts index 27e97abb..0b2cd545 100644 --- a/packages/api/src/flow-schemas.ts +++ b/packages/api/src/flow-schemas.ts @@ -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), diff --git a/packages/api/src/flow-service.ts b/packages/api/src/flow-service.ts index a44f620f..0ea60078 100644 --- a/packages/api/src/flow-service.ts +++ b/packages/api/src/flow-service.ts @@ -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>, 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(`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."); @@ -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 }) { @@ -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); } diff --git a/packages/api/src/job-contracts.ts b/packages/api/src/job-contracts.ts index fe83d482..58836bdb 100644 --- a/packages/api/src/job-contracts.ts +++ b/packages/api/src/job-contracts.ts @@ -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), diff --git a/packages/api/src/job-domain.ts b/packages/api/src/job-domain.ts index 6aff4917..70718645 100644 --- a/packages/api/src/job-domain.ts +++ b/packages/api/src/job-domain.ts @@ -15,6 +15,12 @@ export interface ExecutionConfig { tags?: string[]; image?: string; script?: string; + portableIntegrationIds?: string[]; + modelAccess?: "native" | "portable"; + modelAccountId?: string; + executionProvider?: "exe" | "fly"; + region?: string; + size?: string; } export interface Trigger { @@ -48,6 +54,9 @@ export interface Job { createdAt: string; updatedAt: string; selectedSkills?: { id: string; key: string; revision: number; body: string; position: number }[]; + portableIntegrationIds?: string[]; + modelAccess?: "native" | "portable"; + modelAccountId?: string; } export interface InvocationRequest { diff --git a/packages/api/src/postgres/job-repository.ts b/packages/api/src/postgres/job-repository.ts index 1eb07919..d1245782 100644 --- a/packages/api/src/postgres/job-repository.ts +++ b/packages/api/src/postgres/job-repository.ts @@ -34,7 +34,7 @@ export class PostgresJobRepository implements JobRepository { triggerRows = loadedTriggers ?? await db.select().from(triggers).where(and(eq(triggers.tenantId, this.tenantId), eq(triggers.jobId, row.id), isNull(triggers.removedAt))).orderBy(triggers.position, triggers.createdAt, triggers.id); skillRows = loadedSkills?.filter(skill => skill.job_id === row.id) ?? (await db.execute(sql`SELECT s.id,s.key,s.revision,s.encrypted_body,js.position FROM app.job_skills js JOIN app.skills s ON s.tenant_id=js.tenant_id AND s.id=js.skill_id WHERE js.tenant_id=${this.tenantId}::uuid AND js.job_id=${row.id}::uuid ORDER BY js.position`)).rows; } - return { id: row.id, runScopes: row.runScopes ?? [...DEFAULT_RUN_SCOPES], projectId: row.projectId, name: row.name, slug: row.slug, promptTemplate: await this.decrypt(row.encryptedPromptTemplate), executionType: row.executionConfig.executionType ?? "agent", script: row.executionConfig.script, runNameTemplate: row.encryptedRunNameTemplate ? await this.decrypt(row.encryptedRunNameTemplate) : "", tags: row.tags ?? [], model: row.model, ...(row.effort ? { effort: row.effort } : {}), executionConfig: row.executionConfig, concurrencyLimit: row.concurrencyLimit, enabled: row.enabled, triggers: triggerRows.map(value => this.trigger(value)), selectedSkills: await Promise.all(skillRows.map(async (skill: any) => ({ id: skill.id, key: skill.key, revision: skill.revision, body: await this.decrypt(skill.encrypted_body), position: skill.position }))), createdAt: row.createdAt.toISOString(), updatedAt: row.updatedAt.toISOString() }; + return { id: row.id, runScopes: row.runScopes ?? [...DEFAULT_RUN_SCOPES], projectId: row.projectId, name: row.name, slug: row.slug, promptTemplate: await this.decrypt(row.encryptedPromptTemplate), executionType: row.executionConfig.executionType ?? "agent", script: row.executionConfig.script, runNameTemplate: row.encryptedRunNameTemplate ? await this.decrypt(row.encryptedRunNameTemplate) : "", tags: row.tags ?? [], model: row.model, ...(row.effort ? { effort: row.effort } : {}), executionConfig: row.executionConfig, portableIntegrationIds: row.executionConfig.portableIntegrationIds ?? [], modelAccess: row.executionConfig.modelAccess ?? "native", modelAccountId: row.executionConfig.modelAccountId, concurrencyLimit: row.concurrencyLimit, enabled: row.enabled, triggers: triggerRows.map(value => this.trigger(value)), selectedSkills: await Promise.all(skillRows.map(async (skill: any) => ({ id: skill.id, key: skill.key, revision: skill.revision, body: await this.decrypt(skill.encrypted_body), position: skill.position }))), createdAt: row.createdAt.toISOString(), updatedAt: row.updatedAt.toISOString() }; } async getJob(id: string): Promise { diff --git a/packages/api/test/loading.postgres.test.ts b/packages/api/test/loading.postgres.test.ts index a8d052bb..f05c1657 100644 --- a/packages/api/test/loading.postgres.test.ts +++ b/packages/api/test/loading.postgres.test.ts @@ -5,6 +5,10 @@ import { IdentityRepository } from "../src/postgres/identity-repository"; import { PostgresJobRepository } from "../src/postgres/job-repository"; import { JobSummaryRepository } from "../src/postgres/job-summary-repository"; import { ConnectionRepository } from "../src/postgres/connection-repository"; +import { EncryptedIntegrationRepository } from "../src/postgres/encrypted-integration-repository"; +import { FlyConnectionRepository } from "../src/postgres/fly-connection-repository"; +import { FlyExecutionConfigurationRepository } from "../src/postgres/fly-execution-configuration-repository"; +import { encrypt } from "../src/crypto"; import { ApiService } from "../src/flow-service"; import worker from "../src/worker"; import { signSession } from "../src/index"; @@ -103,12 +107,50 @@ describe.skipIf(!url)("request loading with PostgreSQL", () => { try { const job = await new ApiService(env, auth).createJob({ name: "Migrated target job", slug: "migrated-target-job", promptTemplate: "Do work", executionConfigId: target, vmImage: "ghcr.io/GenerationSoftware/anarack:ReleaseA", concurrencyLimit: 1, triggers: [{ kind: "manual", enabled: true, config: {} }] }); expect(job.executionConfigId).toBe(target); + expect(job).toMatchObject({ portableIntegrationIds: [], modelAccess: "native" }); expect(job.executionConfig).toMatchObject({ connectionId: "local", agentKind: "codex" }); expect(job.executionConfig.image).toBe("ghcr.io/generationsoftware/anarack:ReleaseA"); + const native = await new ApiService(env, auth).createJob({ name: "Native model job", slug: "native-model-job", promptTemplate: "Do work", executionConfigId: target, modelAccess: "native", concurrencyLimit: 1, triggers: [{ kind: "manual", enabled: true, config: {} }] }); + expect(native).toMatchObject({ modelAccess: "native", portableIntegrationIds: [] }); } finally { await db.pool.query("DELETE FROM app.jobs WHERE execution_config->>'targetId'=$1", [target]); } }); + it("persists explicit integration and model selections and snapshots them at invocation", async () => { + const service = new ApiService(env, auth); + const write = async (kind: "bearer" | "model", name: string, owner = tenantId) => { + const repository = new EncryptedIntegrationRepository(db, owner, env.CREDENTIAL_ENCRYPTION_KEY), id = crypto.randomUUID(); + await repository.write({ id, idempotencyKey: crypto.randomUUID(), expectedRevision: await repository.revision(), operation: "upsert", kind, name, origin: kind === "bearer" ? "https://api.example.test" : null, description: null, encryptedPayload: await encrypt("fixture", env.CREDENTIAL_ENCRYPTION_KEY) }); + return id; + }; + const bearerA = await write("bearer", "Tools A"), bearerB = await write("bearer", "Tools B"); + const accountA = await write("model", "Account A"), accountB = await write("model", "Account B"), foreignAccount = await write("model", "Foreign Account", otherTenant); + await new FlyConnectionRepository(db, tenantId, env.CREDENTIAL_ENCRYPTION_KEY).save({ organizationSlug: "fixture", organizationName: "Fixture" }, "fixture-token"); + const execution = await new FlyExecutionConfigurationRepository(db, tenantId).save({ name: "Fixture", image: "ghcr.io/example/agent:latest", region: "iad", size: "shared-cpu-1x" }); + const base = { name: "Portable", slug: `portable-${crypto.randomUUID().slice(0, 8)}`, promptTemplate: "Do work", executionConfigId: execution.id, concurrencyLimit: 1, triggers: [{ kind: "manual" as const, enabled: true, config: {} }] }; + try { + await expect(service.createJob({ ...base, modelAccountId: foreignAccount })).rejects.toMatchObject({ status: 400 }); + const job = await service.createJob({ ...base, portableIntegrationIds: [bearerA], modelAccess: "portable", modelAccountId: accountA }); + expect(job).toMatchObject({ portableIntegrationIds: [bearerA], modelAccess: "portable", modelAccountId: accountA }); + expect(job.executionConfig).toMatchObject({ region: "iad", size: "shared-cpu-1x" }); + const invoked = await service.invokeJob(job.id, { prompt: "run", data: {} }); + const snapshot = (await db.pool.query("SELECT execution_config FROM app.runs WHERE tenant_id=$1 AND id=$2", [tenantId, invoked.runId])).rows[0].execution_config; + expect(snapshot).toMatchObject({ portableIntegrationIds: [bearerA], modelAccess: "portable", modelAccountId: accountA }); + const updated = await service.updateJob(job.id, { ...base, portableIntegrationIds: [bearerB], modelAccess: "portable", modelAccountId: accountB }); + expect(updated).toMatchObject({ portableIntegrationIds: [bearerB], modelAccountId: accountB }); + expect((await db.pool.query("SELECT execution_config FROM app.runs WHERE tenant_id=$1 AND id=$2", [tenantId, invoked.runId])).rows[0].execution_config).toEqual(snapshot); + const omitted = await service.updateJob(job.id, { ...base }); + expect(omitted).toMatchObject({ portableIntegrationIds: [bearerB], modelAccess: "portable", modelAccountId: accountB }); + await expect(service.createJob({ ...base, portableIntegrationIds: [foreignAccount], modelAccess: "native" })).rejects.toMatchObject({ status: 400 }); + const code = await service.createJob({ ...base, name: "Code", slug: `code-${crypto.randomUUID().slice(0, 8)}`, executionType: "code", script: "echo ok" }); + expect(code).toMatchObject({ modelAccess: "native", portableIntegrationIds: [] }); + await expect(service.createJob({ ...base, name: "Needs account", slug: `need-${crypto.randomUUID().slice(0, 8)}`, modelAccess: "portable" })).rejects.toMatchObject({ status: 400 }); + } finally { + await db.pool.query("DELETE FROM app.jobs WHERE tenant_id=$1 AND (slug LIKE 'portable-%' OR slug LIKE 'code-%' OR slug LIKE 'need-%')", [tenantId]); + await db.pool.query("DELETE FROM app.fly_execution_configurations WHERE tenant_id=$1 AND id=$2", [tenantId, execution.id]); + await new FlyConnectionRepository(db, tenantId, env.CREDENTIAL_ENCRYPTION_KEY).remove(); + } + }); it("enforces tenant and scope boundaries, email verification, cookie expiry and session revocation", async () => { await expect(new ApiService(env, { ...auth, tenantId: otherTenant }).listJobs()).rejects.toMatchObject({ status: 401 }); await expect(new ApiService(env, { ...auth, scopes: ["runs:read"] }).listJobs()).rejects.toMatchObject({ status: 403 }); diff --git a/packages/docs/openapi.yaml b/packages/docs/openapi.yaml index e34e8235..074bfb84 100644 --- a/packages/docs/openapi.yaml +++ b/packages/docs/openapi.yaml @@ -1670,6 +1670,22 @@ components: type: string format: uuid pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ + portableIntegrationIds: + maxItems: 100 + type: array + items: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ + modelAccess: + type: string + enum: + - native + - portable + modelAccountId: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ required: - name - slug @@ -7750,6 +7766,10 @@ paths: type: string image: type: string + region: + type: string + size: + type: string executionType: type: string enum: @@ -7778,6 +7798,21 @@ paths: - integrations:write - skills:read - skills:write + portableIntegrationIds: + type: array + items: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ + modelAccess: + type: string + enum: + - native + - portable + modelAccountId: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ executionConfigId: type: string agentKind: @@ -8555,6 +8590,10 @@ paths: type: string image: type: string + region: + type: string + size: + type: string executionType: type: string enum: @@ -8583,6 +8622,21 @@ paths: - integrations:write - skills:read - skills:write + portableIntegrationIds: + type: array + items: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ + modelAccess: + type: string + enum: + - native + - portable + modelAccountId: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ executionConfigId: type: string agentKind: @@ -9127,6 +9181,10 @@ paths: type: string image: type: string + region: + type: string + size: + type: string executionType: type: string enum: @@ -9155,6 +9213,21 @@ paths: - integrations:write - skills:read - skills:write + portableIntegrationIds: + type: array + items: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ + modelAccess: + type: string + enum: + - native + - portable + modelAccountId: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ executionConfigId: type: string agentKind: @@ -10192,6 +10265,10 @@ paths: type: string image: type: string + region: + type: string + size: + type: string executionType: type: string enum: @@ -10220,6 +10297,21 @@ paths: - integrations:write - skills:read - skills:write + portableIntegrationIds: + type: array + items: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ + modelAccess: + type: string + enum: + - native + - portable + modelAccountId: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ executionConfigId: type: string agentKind: @@ -10777,6 +10869,10 @@ paths: type: string image: type: string + region: + type: string + size: + type: string executionType: type: string enum: @@ -10805,6 +10901,21 @@ paths: - integrations:write - skills:read - skills:write + portableIntegrationIds: + type: array + items: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ + modelAccess: + type: string + enum: + - native + - portable + modelAccountId: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ executionConfigId: type: string agentKind: @@ -11674,6 +11785,22 @@ paths: type: string format: uuid pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ + portableIntegrationIds: + maxItems: 100 + type: array + items: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ + modelAccess: + type: string + enum: + - native + - portable + modelAccountId: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ expectedUpdatedAt: type: string format: date-time