> ## Documentation Index
> Fetch the complete documentation index at: https://cadenya.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Create an agent

> The role, not the resume. An agent holds the contract its objectives obey: input schema, output schema, memory, and how variations compete.

An agent is the stable thing your application names. Its [variations](/docs/api-reference/agentvariationservice/create-a-new-variation) carry the prompt and the model, and they come and go. The agent carries the contract.

Only `metadata.name` and `spec.variationSelectionMode` are required.

## Create the agent and its first variation in one call

An agent cannot publish without a variation, so the API lets you supply one inline. This is the shortest path from nothing to a running agent.

<CodeGroup>
  ```typescript TypeScript theme={null}
  const agent = await client.agents.create({
    workspaceId,
    metadata: { name: 'Refund Decider', externalId: 'refund-decider' },
    spec: {
      variationSelectionMode: 'VARIATION_SELECTION_MODE_RANDOM',
      systemPromptDataSchema: {
        type: 'object',
        properties: { company: { type: 'string' } },
        required: ['company'],
      },
      outputDefinition: {
        type: 'object',
        properties: { resolved: { type: 'boolean' } },
        required: ['resolved'],
      },
    },
    defaultVariation: {
      metadata: { name: 'Baseline' },
      spec: {
        systemPromptTemplate: 'Serve {{ system_prompt_data.company }}.',
        modelConfig: { modelId: 'external_id:claude-haiku-4-5' },
      },
    },
  });

  console.log(agent.state);               // STATE_DRAFT
  console.log(agent.info?.variationCount); // 1

  await client.agents.publish(agent.metadata.id, { workspaceId });
  ```

  ```go Go theme={null}
  agent, err := client.Agents.New(ctx, cadenya.AgentNewParams{
  	WorkspaceID: cadenya.String(workspaceID),
  	Metadata: shared.CreateResourceMetadataParam{
  		Name:       "Refund Decider",
  		ExternalID: cadenya.String("refund-decider"),
  	},
  	Spec: cadenya.AgentSpecParam{
  		VariationSelectionMode: cadenya.AgentSpecVariationSelectionModeVariationSelectionModeRandom,
  		SystemPromptDataSchema: map[string]any{
  			"type":       "object",
  			"properties": map[string]any{"company": map[string]any{"type": "string"}},
  			"required":   []string{"company"},
  		},
  		OutputDefinition: map[string]any{
  			"type":       "object",
  			"properties": map[string]any{"resolved": map[string]any{"type": "boolean"}},
  			"required":   []string{"resolved"},
  		},
  	},
  	DefaultVariation: cadenya.AgentNewParamsDefaultVariation{
  		Metadata: shared.CreateResourceMetadataParam{Name: "Baseline"},
  		Spec: cadenya.AgentVariationSpecParam{
  			SystemPromptTemplate: cadenya.String("Serve {{ system_prompt_data.company }}."),
  			ModelConfig: cadenya.AgentVariationSpecModelConfigParam{
  				ModelID: cadenya.String("external_id:claude-haiku-4-5"),
  			},
  		},
  	},
  })
  if err != nil {
  	log.Fatal(err)
  }
  log.Println(agent.State, agent.Info.VariationCount) // STATE_DRAFT 1

  _, err = client.Agents.Publish(ctx, agent.Metadata.ID, cadenya.AgentPublishParams{
  	WorkspaceID: cadenya.String(workspaceID),
  })
  ```

  ```ruby Ruby theme={null}
  agent = cadenya.agents.create(
    workspace_id: workspace_id,
    metadata: {name: "Refund Decider", externalId: "refund-decider"},
    spec: {
      variationSelectionMode: :VARIATION_SELECTION_MODE_RANDOM,
      systemPromptDataSchema: {
        type: "object",
        properties: {company: {type: "string"}},
        required: ["company"]
      },
      outputDefinition: {
        type: "object",
        properties: {resolved: {type: "boolean"}},
        required: ["resolved"]
      }
    },
    default_variation: {
      metadata: {name: "Baseline"},
      spec: {
        systemPromptTemplate: "Serve {{ system_prompt_data.company }}.",
        modelConfig: {modelId: "external_id:claude-haiku-4-5"}
      }
    }
  )

  puts agent.state                # STATE_DRAFT
  puts agent.info.variation_count # 1

  cadenya.agents.publish(agent.metadata.id, workspace_id: workspace_id)
  ```

  ```bash cURL theme={null}
  curl -X POST "https://api.cadenya.com/v1/workspaces/${WORKSPACE_ID}/agents" \
    -H "Authorization: Bearer ${CADENYA_API_KEY}" \
    -H "Content-Type: application/json" \
    -d '{
          "metadata": { "name": "Refund Decider", "externalId": "refund-decider" },
          "spec": {
            "variationSelectionMode": "VARIATION_SELECTION_MODE_RANDOM",
            "systemPromptDataSchema": {
              "type": "object",
              "properties": { "company": { "type": "string" } },
              "required": ["company"]
            },
            "outputDefinition": {
              "type": "object",
              "properties": { "resolved": { "type": "boolean" } },
              "required": ["resolved"]
            }
          },
          "defaultVariation": {
            "metadata": { "name": "Baseline" },
            "spec": {
              "systemPromptTemplate": "Serve {{ system_prompt_data.company }}.",
              "modelConfig": { "modelId": "external_id:claude-haiku-4-5" }
            }
          }
        }'

  curl -X POST "https://api.cadenya.com/v1/workspaces/${WORKSPACE_ID}/agents/${AGENT_ID}:publish" \
    -H "Authorization: Bearer ${CADENYA_API_KEY}" \
    -H "Content-Type: application/json" \
    -d '{}'
  ```
</CodeGroup>

Agents are born `STATE_DRAFT` and refuse objectives until published. `publish`, `unpublish`, `archive`, and `unarchive` are dedicated actions; `state` is read-only and a `PATCH` cannot set it.

## `outputDefinition` decides whether an objective ever ends

This is the most consequential field on the spec, and the least obvious.

**Without an `outputDefinition`,** an objective answers and parks in `STATE_WAITING`, holding its context window open for your next turn. It never finalizes on its own. That is right for a chat agent and surprising for everything else.

**With an `outputDefinition`,** Cadenya runs an extraction pass once the agent stops working, validates the result against your schema, and moves the objective to `STATE_FINALIZED` with the result on `output`.

```typescript theme={null}
const objective = await client.objectives.create({
  workspaceId,
  agentId: agent.metadata.id,
  systemPromptData: { company: 'Acme' },
  firstUserMessage: 'Refund order A-1007, the package arrived broken.',
});

// A few seconds later:
const done = await client.objectives.retrieve(objective.metadata.id, { workspaceId });
console.log(done.state);  // STATE_FINALIZED
console.log(done.output); // { resolved: true }
```

The same value rides on the `finalized` event, at `finalized.output`, so a webhook or [stream](/docs/api-reference/objectiveeventstreamsservice/stream-objective-events) consumer never has to fetch the objective.

<Note>
  If you are polling for a terminal state and your agent has no `outputDefinition`, you are waiting for something that never arrives. Either add the schema, or treat `STATE_WAITING` as done.
</Note>

## `systemPromptDataSchema` catches bad data at the door

Declare a JSON Schema and every objective's `systemPromptData` is validated against it before the run starts.

```
systemPromptData: {}                  -> 400  the data provided does not conform to the
                                              system prompt data schema defined on the agent
systemPromptData: { company: 123 }    -> 400  (wrong type)
systemPromptData: { company: 'Acme' } -> 200
```

Reach for this. Prompt data flows into a Liquid template, and a missing key renders as an empty string rather than an error, so the agent runs with a hole in its prompt and answers anyway. A schema is what turns that silent failure into a `400` on the call that caused it.

It validates the data, not the template. A typo in `{{ system_prompt_data.compnay }}` still renders empty.

## Memory and webhooks

`enableEpisodicMemory` turns the agent into one that remembers across runs. Once set, **every objective must carry an `episodicMemory.key`**, and omitting it is a `400`. Objectives sharing a key share one system-managed [memory layer](/docs/api-reference/memoryservice/create-a-new-memory-layer). `episodicMemoryTtl` slides that layer's expiry forward on each new objective; leave it unset and memories persist indefinitely.

Memory is agent-level, so every variation reads and writes the same memories, and a learning survives a variation swap.

`webhookEventsUrl` sends every objective event for this agent to your endpoint. It must be `https`, and deliveries are recorded in [webhook deliveries](/docs/api-reference/agentservice/list-webhook-deliveries).

## `variationSelectionMode`

* `VARIATION_SELECTION_MODE_RANDOM` picks uniformly at random, forever. The default.
* `VARIATION_SELECTION_MODE_WEIGHTED` learns. Cadenya runs Thompson Sampling over each variation's [feedback](/docs/api-reference/objectiveservice/submit-feedback-for-an-objective), so variations that score well get picked more often while every variation keeps a shrinking chance to prove itself.

With one variation the mode is moot. Set `WEIGHTED` anyway, since the second variation is the reason the field exists.

## The lifecycle

```typescript theme={null}
await client.agents.publish(agent.metadata.id, { workspaceId });   // draft -> published
await client.agents.unpublish(agent.metadata.id, { workspaceId }); // stop taking objectives
await client.agents.archive(agent.metadata.id, { workspaceId });   // retire, keep history
await client.agents.delete(agent.metadata.id, { workspaceId });    // gone
```

Published agents take objectives and fire [schedules](/docs/api-reference/agentscheduleservice/create-a-new-schedule). Draft agents take edits. Archived agents take neither, but their objectives and feedback stay queryable.

<Note>
  Deleting an agent clears its variations' assignments, so the tool sets and memory layers it referenced stay deletable. Delete discards the variations' feedback history; [archive](/docs/api-reference/agentservice/archive-an-agent) keeps it.
</Note>

## Related

<CardGroup cols={2}>
  <Card title="Agents and variations" icon="code" href="/docs/guides/sdk/agents">
    The lifecycle in code, in four languages.
  </Card>

  <Card title="Create a variation" icon="sliders" href="/docs/api-reference/agentvariationservice/create-a-new-variation">
    Prompt, model, compaction, and the constraints that bound a run.
  </Card>

  <Card title="Get structured output" icon="brackets-curly" href="/docs/guides/get-structured-output">
    The hands-on lesson for `outputDefinition`.
  </Card>

  <Card title="Memory layers" icon="brain" href="/docs/guides/memory-layers">
    What `enableEpisodicMemory` switches on.
  </Card>
</CardGroup>


## OpenAPI

````yaml post /v1/workspaces/{workspaceId}/agents
openapi: 3.1.0
info:
  title: Cadenya API
  description: API for the Cadenya Agent Runtime platform.
  version: '1.0'
servers:
  - url: https://api.cadenya.com
    description: Production server
security:
  - bearerAuth: []
tags:
  - name: AIProviderKeyService
  - name: APIKeyService
    description: |-
      Issue, rotate, disable, and revoke a workspace's API keys. Every key
       belongs to exactly one workspace; the system-managed global account key is
       managed via GlobalAPIKeyService instead.
  - name: AccountService
    description: >-
      Manage the authenticated account. Accounts are the top-level
      organizational
       unit and contain one or more workspaces.
  - name: AgentScheduleService
    description: >-
      Manage recurring schedules attached to agents. Schedules trigger
      objectives
       on a cadence defined by AgentScheduleSpec.Schedule.
  - name: AgentService
    description: >-
      Manage AI agents within a workspace. Agents define AI behavior and tool
      access.
  - name: AgentVariationService
    description: >-
      Manage variations of an agent and their tool, sub-agent, and memory layer
      assignments.
  - name: GlobalAPIKeyService
    description: |-
      Manage the account's system-provisioned global API key. The global key is
       the only key that spans every workspace; it is created by the system and
       cannot be deleted, so the surface is retrieve, rotate, and the
       disable/enable kill switch.
  - name: MemoryService
    description: >-
      Manage memory layers and their entries. Layers are named containers that
      can
       be composed into an objective's memory cascade; entries are the keyed values
       within a layer. System-managed layers (e.g., episodic layers created by the
       runtime) cannot be mutated through this API.
  - name: ModelService
    description: |-
      Manage LLM models available to a workspace. Models represent provider and
       family pairs (e.g., "anthropic/claude-sonnet-4.6"). Workspaces are seeded
       with the supported models and you can enable or disable each one.
  - name: ObjectiveEventStreamsService
  - name: ObjectiveService
  - name: ProfilesService
    description: |-
      Operations on profiles, the account-level principals (users, API keys,
       system) that authenticate against the API.
  - name: SearchService
  - name: TenantService
    description: >-
      Read and erase tenants and the subjects under them. Tenants and subjects
      are
       created by assertion — on objective creation or widget session mint — never
       directly, so this service has no create or update: it exists to enumerate what
       assertions have produced, and to destroy it on request.
  - name: ToolService
    description: >-
      Manage tool sets and the tools they contain. Tool sets group related
      tools,
       and tools define specific capabilities available to agents.

       When a tool set is managed, only API key actors can modify its tools; human
       (profile) actors cannot.
  - name: UploadService
    description: |-
      Issue short-lived presigned URLs for direct client-to-object-storage
       uploads. Created uploads can be referenced by id when creating or updating
       resources that accept binary content (e.g., MemoryEntry).
  - name: WidgetService
    description: |-
      Manage embeddable chat widgets. A widget binds an agent to a globally
       unique hostname with a per-widget origin allowlist; browsers reach it with
       session tokens minted via WidgetSessionService.
  - name: WidgetSessionService
    description: >-
      Mint and manage widget sessions. Session creation is server-to-server
      only:
       the customer's backend authenticates its visitor, asserts tenant/subject
       context, attaches any per-visitor secrets, and receives a short-lived
       bearer token the browser uses against the widget host.
  - name: WorkspaceAdminService
    description: >-
      Administer workspaces across the account: create and archive workspaces
      and
       manage their membership. These operations are account-scoped and require the
       admin role (a token whose profile holds the WorkOS admin role); they live
       under /v1/account/workspaces rather than the workspace-scoped /v1/workspaces
       tree so an admin can manage any workspace in the account, including ones they
       are not themselves a member of.
  - name: WorkspaceSecretService
  - name: WorkspaceService
    description: |-
      Manage workspaces within an account. Workspaces provide organizational
       grouping and isolation for resources such as agents, tools, and API keys.

       This is the workspace-scoped, end-user surface. Administrative operations
       (create / archive workspaces, manage members) live in WorkspaceAdminService
       under /v1/account/workspaces and require the admin role.
paths:
  /v1/workspaces/{workspaceId}/agents:
    post:
      tags:
        - AgentService
        - Agents
      summary: Create a new agent
      description: Creates a new agent in the workspace
      operationId: AgentService_CreateAgent
      parameters:
        - name: workspaceId
          in: path
          description: Workspace ID.
          required: true
          schema:
            type: string
            example: workspace_01HXKD2E5NQM3T9AYWCF133E3Q
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateAgentRequest'
        required: true
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Agent'
        default:
          description: Default error response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Status'
      x-codeSamples:
        - lang: JavaScript
          source: |-
            import Cadenya from '@cadenya/cadenya';

            const client = new Cadenya({
              apiKey: process.env['CADENYA_API_KEY'], // This is the default and can be omitted
            });

            const agent = await client.agents.create({
              workspaceId: 'workspace_01HXKD2E5NQM3T9AYWCF133E3Q',
              metadata: { name: 'name' },
              spec: { variationSelectionMode: 'VARIATION_SELECTION_MODE_UNSPECIFIED' },
            });

            console.log(agent.metadata);
        - lang: Python
          source: |-
            import os
            from cadenya import Cadenya

            client = Cadenya(
                api_key=os.environ.get("CADENYA_API_KEY"),  # This is the default and can be omitted
            )
            agent = client.agents.create(
                workspace_id="workspace_01HXKD2E5NQM3T9AYWCF133E3Q",
                metadata={
                    "name": "name"
                },
                spec={
                    "variation_selection_mode": "VARIATION_SELECTION_MODE_UNSPECIFIED"
                },
            )
            print(agent.metadata)
        - lang: Go
          source: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"go.cadenya.com/cadenya-go\"\n\t\"go.cadenya.com/cadenya-go/option\"\n\t\"go.cadenya.com/cadenya-go/shared\"\n)\n\nfunc main() {\n\tclient := cadenya.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tagent, err := client.Agents.New(context.TODO(), cadenya.AgentNewParams{\n\t\tWorkspaceID: cadenya.String(\"workspace_01HXKD2E5NQM3T9AYWCF133E3Q\"),\n\t\tMetadata: shared.CreateResourceMetadataParam{\n\t\t\tName: \"name\",\n\t\t},\n\t\tSpec: cadenya.AgentSpecParam{\n\t\t\tVariationSelectionMode: cadenya.AgentSpecVariationSelectionModeVariationSelectionModeUnspecified,\n\t\t},\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", agent.Metadata)\n}\n"
        - lang: Ruby
          source: |-
            require "cadenya"

            cadenya = Cadenya::Client.new(api_key: "My API Key")

            agent = cadenya.agents.create(
              workspace_id: "workspace_01HXKD2E5NQM3T9AYWCF133E3Q",
              metadata: {name: "name"},
              spec: {variationSelectionMode: :VARIATION_SELECTION_MODE_UNSPECIFIED}
            )

            puts(agent)
        - lang: CLI
          source: |-
            cadenya agents create \
              --api-key 'My API Key' \
              --workspace-id workspace_01HXKD2E5NQM3T9AYWCF133E3Q \
              --metadata '{name: name}' \
              --spec '{variationSelectionMode: VARIATION_SELECTION_MODE_UNSPECIFIED}'
components:
  schemas:
    CreateAgentRequest:
      required:
        - metadata
        - spec
      type: object
      properties:
        workspaceId:
          readOnly: true
          example: workspace_01HXKD2E5NQM3T9AYWCF133E3Q
          type: string
          description: Workspace ID.
        metadata:
          $ref: '#/components/schemas/CreateResourceMetadata'
        spec:
          $ref: '#/components/schemas/AgentSpec'
        defaultVariation:
          allOf:
            - $ref: '#/components/schemas/CreateAgentVariationRequest'
          description: Optional default variation to add to the agent on create
      description: Create agent request
    Agent:
      required:
        - metadata
        - spec
        - state
      type: object
      properties:
        metadata:
          allOf:
            - $ref: '#/components/schemas/ResourceMetadata'
          description: Resource metadata
        spec:
          allOf:
            - $ref: '#/components/schemas/AgentSpec'
          description: Agent specification
        info:
          readOnly: true
          allOf:
            - $ref: '#/components/schemas/AgentInfo'
          description: Agent information
        state:
          readOnly: true
          enum:
            - STATE_UNSPECIFIED
            - STATE_DRAFT
            - STATE_PUBLISHED
            - STATE_ARCHIVED
          type: string
          description: >-
            The current lifecycle state of the agent. Output only. Agents are
            created
             in STATE_DRAFT; use the :publish, :unpublish, :archive, and :unarchive
             actions to transition between states.
          format: enum
      description: Agent resource
    Status:
      type: object
      properties:
        code:
          type: integer
          description: >-
            The status code, which should be an enum value of
            [google.rpc.Code][google.rpc.Code].
          format: int32
        message:
          type: string
          description: >-
            A developer-facing error message, which should be in English. Any
            user-facing error message should be localized and sent in the
            [google.rpc.Status.details][google.rpc.Status.details] field, or
            localized by the client.
        details:
          type: array
          items:
            $ref: '#/components/schemas/GoogleProtobufAny'
          description: >-
            A list of messages that carry the error details.  There is a common
            set of message types for APIs to use.
      description: >-
        The `Status` type defines a logical error model that is suitable for
        different programming environments, including REST APIs and RPC APIs. It
        is used by [gRPC](https://github.com/grpc). Each `Status` message
        contains three pieces of data: error code, error message, and error
        details. You can find out more about this error model and how to work
        with it in the [API Design
        Guide](https://cloud.google.com/apis/design/errors).
    CreateResourceMetadata:
      required:
        - name
      type: object
      properties:
        name:
          type: string
          description: >-
            Human-readable name for the resource (e.g., "Customer Support
            Agent", "Email Tool")
        externalId:
          type: string
          description: >-
            External ID for the resource (e.g., a workflow ID from an external
            system)
        labels:
          type: object
          additionalProperties:
            type: string
          description: |-
            Key-value pairs for categorization and filtering. Values are 0-63
             alphanumeric characters with "-", "_", or "." allowed between; keys
             follow the same shape and additionally accept an optional DNS-subdomain
             prefix (e.g. "cadenya.com/") of at most 253 characters.
             Examples: {"environment": "production", "team": "platform", "version": "v2"}
      description: |-
        CreateResourceMetadata contains the user-provided fields for creating
         a workspace-scoped resource. Read-only fields (id, account_id, workspace_id, profile_id,
         created_at) are excluded since they are set by the server.
    AgentSpec:
      required:
        - variationSelectionMode
      type: object
      properties:
        description:
          type: string
          description: Description of the agent's purpose
        webhookEventsUrl:
          type: string
          description: >-
            The URL that Cadenya will send events for any objective assigned to
            the agent.
        variationSelectionMode:
          enum:
            - VARIATION_SELECTION_MODE_UNSPECIFIED
            - VARIATION_SELECTION_MODE_RANDOM
            - VARIATION_SELECTION_MODE_WEIGHTED
          type: string
          description: >-
            Controls how variations are automatically selected when creating
            objectives
             Defaults to RANDOM when unspecified
          format: enum
        systemPromptDataSchema:
          type: object
          additionalProperties: true
          description: >-
            SystemPromptDataSchema enforces the shape of system_prompt_data when
            objectives are created. This is valuable when using liquid
            formatting in agent
             variation system prompt templates. The schema is also used when the agent is attached as a sub-agent, as it becomes the tool's input parameter schema.
             If omitted, the sub-agent schema will be loaded with a simple "prompt" free text string as its schema.
        outputDefinition:
          type: object
          additionalProperties: true
          description: |-
            Optional output definition for objectives created for this agent.
             When provided, Cadenya will append a tool to that will be called by the LLM in use by the variant to extract information in the format provided here.
             Use this option when you want structured data to be created by your objectives.
        enableEpisodicMemory:
          type: boolean
          description: |-
            Enable episodic memory for objectives created for this agent.
             When true, objective creation requires an episodic_memory key and the
             system finds or creates a memory layer for that (agent, key) pair, letting
             the agent store and retrieve memories across objectives that share the key.
             Memory is agent-level so all variations of the agent share the same layers.
        episodicMemoryTtl:
          pattern: ^-?(?:0|[1-9][0-9]{0,11})(?:\.[0-9]{1,9})?s$
          type: integer
          description: |-
            How long episodic memories should be retained.
             Each new objective slides the layer's expiry forward by this duration, and
             stored entries expire this long after they are written.
             If not set, episodic memories are retained indefinitely.
      description: Agent specification (user-provided configuration)
    CreateAgentVariationRequest:
      required:
        - metadata
        - spec
      type: object
      properties:
        workspaceId:
          readOnly: true
          example: workspace_01HXKD2E5NQM3T9AYWCF133E3Q
          type: string
          description: Workspace ID.
        agentId:
          readOnly: true
          example: agent_01HXKD2E5NQM3T9AYWCFMGWT9Y
          type: string
          description: >-
            Agent ID. Accepts the canonical `agent_…` form or the
            `external_id:<value>` form.
        metadata:
          $ref: '#/components/schemas/CreateResourceMetadata'
        spec:
          $ref: '#/components/schemas/AgentVariationSpec'
      description: Create agent variation request
    ResourceMetadata:
      required:
        - id
        - accountId
        - workspaceId
        - name
        - profileId
        - createdAt
      type: object
      properties:
        id:
          readOnly: true
          type: string
          description: >-
            Unique identifier for the resource (prefixed ULID, e.g.,
            "agent_01HXK...")
        accountId:
          readOnly: true
          example: account_01HXKD2E5NQM3T9AYWCFTJHJVF
          type: string
          description: >-
            Account this resource belongs to for multi-tenant isolation
            (prefixed ULID)
        workspaceId:
          readOnly: true
          example: workspace_01HXKD2E5NQM3T9AYWCF133E3Q
          type: string
          description: >-
            Workspace this resource belongs to for organizational grouping
            (prefixed ULID)
        name:
          type: string
          description: >-
            Human-readable name for the resource (e.g., "Customer Support
            Agent", "Email Tool")
             Required for resources that users interact with directly
        externalId:
          type: string
          description: >-
            External ID for the resource (e.g., a workflow ID from an external
            system)
        labels:
          type: object
          additionalProperties:
            type: string
          description: |-
            Key-value pairs for categorization and filtering. Values are 0-63
             alphanumeric characters with "-", "_", or "." allowed between; keys
             follow the same shape and additionally accept an optional DNS-subdomain
             prefix (e.g. "cadenya.com/") of at most 253 characters.
             Examples: {"environment": "production", "team": "platform", "version": "v2"}
        profileId:
          readOnly: true
          example: profile_01HXKD2E5NQM3T9AYWCFS0AP08
          type: string
          description: ID of the actor (user or service account) that created this resource
        createdAt:
          readOnly: true
          type: string
          description: Timestamp when this resource was created
          format: date-time
        updatedAt:
          readOnly: true
          type: string
          description: Timestamp when this resource was last updated
          format: date-time
      description: >-
        Standard metadata for persistent, named resources (e.g., agents, tools,
        prompts)
    AgentInfo:
      type: object
      properties:
        variationCount:
          readOnly: true
          type: integer
          format: int32
        createdBy:
          $ref: '#/components/schemas/Profile'
      description: >-
        AgentInfo contains simple information about an agent for display or
        quick reference
    GoogleProtobufAny:
      type: object
      properties:
        '@type':
          type: string
          description: The type of the serialized message.
      additionalProperties: true
      description: >-
        Contains an arbitrary serialized message along with a @type that
        describes the type of the serialized message.
    AgentVariationSpec:
      type: object
      properties:
        systemPromptTemplate:
          type: string
          description: >-
            Liquid template for the system prompt of objectives using this
            variation.
             Rendered with CreateObjectiveRequest.system_prompt_data into Objective.system_prompt.
        progressiveDiscovery:
          allOf:
            - $ref: '#/components/schemas/AgentVariationSpec_ProgressiveDiscovery'
          description: >-
            ProgressiveDiscovery is an optional config that, when set, will load
            a Cadenya provided tool that
             can search for tools in the assigned tool sets or tools.

             Note: Sub-agents are always loaded as a tool regardless of this value.
        constraints:
          allOf:
            - $ref: '#/components/schemas/AgentVariationSpec_Constraints'
          description: Execution constraints
        description:
          type: string
          description: >-
            Human-readable description of what this variation does or when it
            should be used
        modelConfig:
          allOf:
            - $ref: '#/components/schemas/AgentVariationSpec_ModelConfig'
          description: Model configuration for this variation
        compactionConfig:
          allOf:
            - $ref: '#/components/schemas/AgentVariationSpec_CompactionConfig'
          description: >-
            Compaction configuration for managing context window limits during
            long-running objectives.
             When not set, the system uses a default summarization strategy at 75% context window usage.
        firstUserMessageTemplate:
          type: string
          description: >-
            Liquid template for the first user message of objectives using this
            variation.
             Rendered with CreateObjectiveRequest.first_user_message_data into
             Objective.first_user_message, the first user message in the LLM chat history.
             CreateObjectiveRequest.first_user_message, when set, overrides the rendered
             result. If neither this template nor first_user_message is present, objective
             creation is rejected with InvalidArgument.
      description: AgentVariationSpec defines the operational configuration for a variation
    Profile:
      required:
        - metadata
        - spec
      type: object
      properties:
        metadata:
          $ref: '#/components/schemas/AccountResourceMetadata'
        spec:
          $ref: '#/components/schemas/ProfileSpec'
      description: |-
        A profile identifies a user or non-human principal (such as an API key)
         at the account level. Profiles are account-scoped and can be granted access
         to multiple workspaces.
    AgentVariationSpec_ProgressiveDiscovery:
      type: object
      properties:
        maxTools:
          type: integer
          description: >-
            The most tool names tool_search will load in a single call.
            Requesting more
             than this returns an error telling the model to retry in smaller batches --
             it is a per-call batch limit, not a ceiling on how many tools an objective
             may end up with.
          format: int32
        hints:
          type: array
          items:
            type: string
          description: >-
            Free-text guidance appended to the discoverable-tools appendix in
            the
             system prompt. Hints steer the model's choice of tool names; they do not
             filter or rank anything, because tool_search matches names exactly rather
             than searching.
      description: >-
        ProgressiveDiscovery is used to indicate that the agent should
        automatically discover tools that are not explicitly assigned to it.
         Max tools is the maximum number of tools that can be discovered per search.
         Hints are optional hints for tool search. These are used in conjunction with the context-aware tool search and can help select the best tools for the task.
    AgentVariationSpec_Constraints:
      type: object
      properties:
        maxToolCalls:
          type: integer
          description: The maximum number of tool calls that can be made. 0 means no limit.
          format: int32
        maxSubObjectives:
          type: integer
          description: >-
            The maximum number of sub-objectives that can be created. 0 means no
            limit.
          format: int32
        inactivityTimeout:
          pattern: ^-?(?:0|[1-9][0-9]{0,11})(?:\.[0-9]{1,9})?s$
          type: string
          description: |-
            How long an objective may sit with no activity (no user messages, no
             LLM calls) before it is finalized as timed out. Between 1 minute and
             24 hours, expressed as a duration string in seconds (e.g. "7200s").
             When not set, objectives are still swept at the system-wide 24 hour
             maximum — every objective eventually reaches a terminal state.

             Note: no gnostic integer hint here on purpose. The Envoy gRPC-JSON
             transcoder only accepts the canonical protobuf JSON form for
             Durations — a "<seconds>s" string — so the SDKs must type this as a
             string (like AgentScheduleSpec.every), not an integer.
    AgentVariationSpec_ModelConfig:
      type: object
      properties:
        modelId:
          example: claude/opus-4.6
          type: string
          description: >-
            The model identifier in family/model format (e.g.,
            "claude/opus-4.6", "claude/sonnet-4.5")
        temperature:
          type: number
          description: |-
            Sampling temperature for model inference (0.0 to 1.0)
             Lower values produce more deterministic outputs, higher values increase randomness
          format: float
      description: ModelConfig defines the model configuration for a variation
    AgentVariationSpec_CompactionConfig:
      type: object
      properties:
        triggerThreshold:
          type: number
          description: >-
            Trigger threshold as a percentage of the model's context window (0.0
            to 1.0).
             When input tokens reach this percentage of the model's limit, compaction triggers.
             Default: 0.75 (75%)
          format: float
        summarization:
          allOf:
            - $ref: '#/components/schemas/CompactionConfig_SummarizationStrategy'
          description: >-
            Strategies — set one or more. When multiple are set, they execute in
            order:
             tool_result_clearing → summarization.
             When none are set, defaults to summarization with the system default prompt.
        toolResultClearing:
          $ref: '#/components/schemas/CompactionConfig_ToolResultClearingStrategy'
      description: >-
        CompactionConfig defines how context window compaction behaves for
        objectives using this variation.
    AccountResourceMetadata:
      required:
        - id
        - accountId
        - name
        - profileId
      type: object
      properties:
        id:
          readOnly: true
          type: string
          description: >-
            Unique identifier for the resource (prefixed ULID, e.g.,
            "apikey_01HXK...")
        accountId:
          readOnly: true
          example: account_01HXKD2E5NQM3T9AYWCFTJHJVF
          type: string
          description: >-
            Account this resource belongs to for multi-tenant isolation
            (prefixed ULID)
        name:
          type: string
          description: >-
            Human-readable name for the resource (e.g., "Customer Support
            Agent", "Email Tool")
             Required for resources that users interact with directly
        externalId:
          type: string
          description: >-
            External ID for the resource (e.g., a workflow ID from an external
            system)
        labels:
          type: object
          additionalProperties:
            type: string
          description: |-
            Key-value pairs for categorization and filtering. Values are 0-63
             alphanumeric characters with "-", "_", or "." allowed between; keys
             follow the same shape and additionally accept an optional DNS-subdomain
             prefix (e.g. "cadenya.com/") of at most 253 characters.
             Examples: {"environment": "production", "team": "platform", "version": "v2"}
        profileId:
          readOnly: true
          example: profile_01HXKD2E5NQM3T9AYWCFS0AP08
          type: string
        createdAt:
          readOnly: true
          type: string
          format: date-time
      description: >-
        AccountResourceMetadata is used to represent a resource that is
        associated to an account but not to a workspace.
    ProfileSpec:
      required:
        - type
      type: object
      properties:
        email:
          type: string
          description: >-
            Email address of the profile. Required and unique within an account
            for
             user profiles.
        name:
          type: string
          description: Display name (e.g., "Bobby Tables").
        type:
          enum:
            - PROFILE_TYPE_UNSPECIFIED
            - PROFILE_TYPE_USER
            - PROFILE_TYPE_API_KEY
            - PROFILE_TYPE_SYSTEM
          type: string
          description: >-
            Whether this profile represents a human user, an API key, or a
            system
             principal.
          format: enum
      description: Configuration for a profile.
    CompactionConfig_SummarizationStrategy:
      type: object
      properties:
        instructions:
          type: string
          description: |-
            Custom instructions that guide what the summarizer preserves.
             Replaces the default summarization prompt entirely.
             Example: "Preserve all code snippets, variable names, and technical decisions."
      description: >-
        SummarizationStrategy configures LLM-powered summarization of older
        conversation turns.
    CompactionConfig_ToolResultClearingStrategy:
      type: object
      properties:
        preserveRecentResults:
          type: integer
          description: |-
            Number of most recent tool call results to keep intact.
             Older tool results have their content replaced with "[result cleared]"
             while preserving the assistant tool call message (function name, arguments).
             Default: 2
          format: int32
      description: >-
        ToolResultClearingStrategy configures clearing of older tool result
        content.
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT

````