{"version":3,"sources":["../../src/googleai/antigravity.ts"],"sourcesContent":["/**\n * Copyright 2026 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ActionMetadata, modelActionMetadata, z } from 'genkit';\nimport { ModelAction, ModelInfo, ModelReference, modelRef } from 'genkit/model';\nimport { model as pluginModel } from 'genkit/plugin';\nimport {\n  ensureToolIds,\n  fromInteractionSync,\n  toInteractionConfigTool,\n  toInteractionSteps,\n  toInteractionTool,\n} from '../common/interaction-converters.mjs';\nimport {\n  InteractionTool,\n  ResponseModality,\n} from '../common/interaction-types.mjs';\nimport { isKnownKey } from '../common/utils.mjs';\nimport { createInteraction } from './client.mjs';\nimport {\n  ClientOptions,\n  CreateInteractionRequest,\n  GoogleAIPluginOptions,\n  Model,\n} from './types.mjs';\nimport {\n  calculateApiKey,\n  calculateRequestOptions,\n  checkApiKey,\n  checkModelName,\n  extractVersion,\n  modelName,\n  removeClientOptionOverrides,\n} from './utils.mjs';\n\nexport const AntigravityConfigSchema = z\n  .object({\n    apiKey: z\n      .string()\n      .describe('Override the API key provided at plugin initialization.')\n      .optional(),\n    baseUrl: z\n      .string()\n      .describe(\n        'Overrides the plugin-configured or default baseUrl, if specified.'\n      )\n      .optional(),\n    apiVersion: z\n      .string()\n      .describe(\n        'Overrides the plugin-configured or default apiVersion, if specified.'\n      )\n      .optional(),\n    previousInteractionId: z\n      .string()\n      .describe('The ID of the previous interaction, if any.')\n      .optional(),\n    store: z\n      .boolean()\n      .describe(\n        'Whether to store the response and request for later retrieval.'\n      )\n      .optional(),\n    environment: z\n      .union([z.string(), z.record(z.unknown())])\n      .describe('The environment configuration for the sandbox.')\n      .optional(),\n    responseModalities: z\n      .array(z.enum(['TEXT', 'IMAGE']))\n      .describe('The modalities to be used in response.')\n      .optional(),\n    model: z\n      .union([\n        z.enum([\n          'gemini-4-argon',\n          'gemini-3.8-flash',\n          'gemini-3.6-flash',\n          'gemini-3.5-flash-lite',\n        ]),\n        // Allows newer models. `string & {}` (rather than z.string()) keeps\n        // the listed names in TypeScript autocomplete: a plain `string` in the\n        // union would absorb the literals.\n        z.custom<string & {}>((val) => typeof val === 'string'),\n      ])\n      .describe(\n        'The Gemini model the agent runs on. The server picks a default ' +\n          'if not set.'\n      )\n      .optional(),\n  })\n  .passthrough();\n\nexport type AntigravityConfigSchemaType = typeof AntigravityConfigSchema;\nexport type AntigravityConfig = z.infer<AntigravityConfigSchemaType>;\n\ntype ConfigSchemaType = AntigravityConfigSchemaType;\n\nfunction commonRef(\n  name: string,\n  info?: ModelInfo,\n  configSchema: ConfigSchemaType = AntigravityConfigSchema\n): ModelReference<ConfigSchemaType> {\n  return modelRef({\n    name: `googleai/${name}`,\n    configSchema,\n    info:\n      info ??\n      ({\n        supports: {\n          multiturn: true,\n          media: true,\n          tools: true,\n          toolChoice: false,\n          systemRole: false,\n          output: ['text'],\n        },\n      } as ModelInfo),\n  });\n}\n\nconst GENERIC_MODEL = commonRef('antigravity');\n\nconst KNOWN_MODELS = {\n  'antigravity-preview-09-2026': commonRef('antigravity-preview-09-2026'),\n} as const;\n\nexport type KnownModels = keyof typeof KNOWN_MODELS;\n\nexport type AntigravityModelName = `antigravity-${string}`;\nexport function isAntigravityModelName(\n  value?: string\n): value is AntigravityModelName {\n  return !!value?.startsWith('antigravity-');\n}\n\nexport function model(\n  version: string,\n  config: AntigravityConfig = {}\n): ModelReference<ConfigSchemaType> {\n  const name = checkModelName(version);\n\n  if (isKnownKey(name, KNOWN_MODELS)) {\n    return KNOWN_MODELS[name].withConfig(config);\n  }\n\n  return modelRef({\n    name: `googleai/${name}`,\n    config,\n    configSchema: AntigravityConfigSchema,\n    info: { ...GENERIC_MODEL.info },\n  });\n}\n\nexport function listActions(models: Model[]): ActionMetadata[] {\n  return models\n    .filter((m) => isAntigravityModelName(modelName(m.name)))\n    .filter((m) => !m.description || !m.description.includes('deprecated'))\n    .map((m) => {\n      const ref = model(m.name);\n      return modelActionMetadata({\n        name: ref.name,\n        info: ref.info,\n        configSchema: ref.configSchema,\n      });\n    });\n}\n\nexport function listKnownModels(options?: GoogleAIPluginOptions) {\n  return Object.keys(KNOWN_MODELS).map((name: string) =>\n    defineModel(name, options)\n  );\n}\n\nexport function defineModel(\n  name: string,\n  pluginOptions?: GoogleAIPluginOptions\n): ModelAction<AntigravityConfigSchemaType> {\n  checkApiKey(pluginOptions?.apiKey);\n  const ref = model(name);\n  const clientOptions: ClientOptions = {\n    apiVersion: pluginOptions?.apiVersion,\n    baseUrl: pluginOptions?.baseUrl,\n    customHeaders: pluginOptions?.customHeaders,\n    experimental_debugTraces: pluginOptions?.experimental_debugTraces,\n  };\n\n  return pluginModel(\n    {\n      name: ref.name,\n      ...ref.info,\n      configSchema: ref.configSchema,\n    },\n    async (request, { abortSignal }) => {\n      const clientOpt = calculateRequestOptions(\n        { ...clientOptions, signal: abortSignal },\n        request.config\n      );\n\n      const requestOptions = removeClientOptionOverrides(request.config || {});\n      const {\n        previousInteractionId,\n        store,\n        environment,\n        responseModalities,\n        // Sent as agent_config.model; a top-level `model` would conflict with\n        // `agent`.\n        model: agentModel,\n        tools: toolsFromConfig,\n        ...rest\n      } = requestOptions;\n\n      // Built-in tools from config.tools (e.g. { type: 'google_search' }),\n      // followed by the request's function tools.\n      const tools: InteractionTool[] = [\n        ...(Array.isArray(toolsFromConfig)\n          ? toolsFromConfig.map(toInteractionConfigTool)\n          : []),\n        ...(request.tools ?? []).map(toInteractionTool),\n      ];\n\n      const apiKey = calculateApiKey(\n        pluginOptions?.apiKey,\n        request.config?.apiKey\n      );\n\n      const messages = structuredClone(request.messages);\n\n      // Antigravity does not support system instructions, so we map them to user messages.\n      for (const message of messages) {\n        if (message.role === 'system') {\n          message.role = 'user';\n        }\n      }\n\n      // Unlike Gemini models, Antigravity doesn't default to `store: false`:\n      // the agent doesn't work at all with `store: false` (the server rejects\n      // it), so that default would break every existing Antigravity app.\n      // `store` is only sent when set; an explicit `store: false` (request\n      // config, or else plugin options) is passed through as requested.\n      const storeSetting =\n        store ?? (pluginOptions?.store === false ? false : undefined);\n\n      // Continue from the last model message: send its interaction ID and only\n      // the messages after it, in the same environment (a new 'remote' sandbox\n      // wouldn't have the previous turn's files). The agent also rejects tool\n      // calls in `input`, so this is how a tool result is sent.\n      // The message metadata doesn't record which model or agent created the\n      // interaction, so a history that mixes stored Gemini turns and\n      // Antigravity turns would continue the wrong interaction here (and the\n      // Gemini path has the same issue in reverse).\n      // TODO: record the creating model/agent in the metadata and check it.\n      let previousId = previousInteractionId;\n      let newMessages = messages;\n      let environmentToUse = environment;\n      if (!previousId) {\n        for (let i = messages.length - 1; i >= 0; i--) {\n          const { role, metadata } = messages[i];\n          const prevId = metadata?.interactionId;\n          if (role === 'model' && typeof prevId === 'string' && prevId) {\n            previousId = prevId;\n            newMessages = messages.slice(i + 1);\n            const prevEnvironment = metadata?.environmentId;\n            if (\n              (environment === undefined || environment === 'remote') &&\n              typeof prevEnvironment === 'string' &&\n              prevEnvironment\n            ) {\n              environmentToUse = prevEnvironment;\n            }\n            break;\n          }\n        }\n      } else {\n        // As for Gemini models: an explicit previousInteractionId wins, but\n        // history up to the last model turn is already on the server.\n        for (let i = messages.length - 1; i >= 0; i--) {\n          if (messages[i].role === 'model') {\n            newMessages = messages.slice(i + 1);\n            break;\n          }\n        }\n      }\n\n      let responseModalitiesConverted: ResponseModality[] | undefined;\n      if (responseModalities) {\n        responseModalitiesConverted = responseModalities.map(\n          (m) => m.toLowerCase() as ResponseModality\n        );\n      }\n\n      const req: CreateInteractionRequest = {\n        agent: extractVersion(ref),\n        input: toInteractionSteps(ensureToolIds(newMessages)),\n        previous_interaction_id: previousId,\n        store: storeSetting,\n        environment: environmentToUse,\n        response_modalities: responseModalitiesConverted,\n        ...(agentModel\n          ? { agent_config: { type: 'antigravity', model: agentModel } }\n          : {}),\n        ...(tools.length > 0 ? { tools } : {}),\n        ...rest,\n      };\n\n      const response = await createInteraction(apiKey, req, clientOpt);\n\n      return fromInteractionSync(response);\n    }\n  );\n}\n\nexport const TEST_ONLY = { KNOWN_MODELS };\n"],"mappings":"AAgBA,SAAyB,qBAAqB,SAAS;AACvD,SAAiD,gBAAgB;AACjE,SAAS,SAAS,mBAAmB;AACrC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAKP,SAAS,kBAAkB;AAC3B,SAAS,yBAAyB;AAOlC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEA,MAAM,0BAA0B,EACpC,OAAO;AAAA,EACN,QAAQ,EACL,OAAO,EACP,SAAS,yDAAyD,EAClE,SAAS;AAAA,EACZ,SAAS,EACN,OAAO,EACP;AAAA,IACC;AAAA,EACF,EACC,SAAS;AAAA,EACZ,YAAY,EACT,OAAO,EACP;AAAA,IACC;AAAA,EACF,EACC,SAAS;AAAA,EACZ,uBAAuB,EACpB,OAAO,EACP,SAAS,6CAA6C,EACtD,SAAS;AAAA,EACZ,OAAO,EACJ,QAAQ,EACR;AAAA,IACC;AAAA,EACF,EACC,SAAS;AAAA,EACZ,aAAa,EACV,MAAM,CAAC,EAAE,OAAO,GAAG,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAC,CAAC,EACzC,SAAS,gDAAgD,EACzD,SAAS;AAAA,EACZ,oBAAoB,EACjB,MAAM,EAAE,KAAK,CAAC,QAAQ,OAAO,CAAC,CAAC,EAC/B,SAAS,wCAAwC,EACjD,SAAS;AAAA,EACZ,OAAO,EACJ,MAAM;AAAA,IACL,EAAE,KAAK;AAAA,MACL;AAAA,MACA;AAAA,MACA;AA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