> ## 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 objective

> Hand a task to an agent. The objective runs on its own: calling tools, reading memory, looping until it finishes or stops for input.

This is the endpoint that puts an agent to work. You name an agent, pass the data its prompt templates need, and Cadenya picks a variation, snapshots the configuration, and starts running.

The call returns as soon as the objective is created, in `STATE_PENDING`. Work happens in the background. Read the result by [polling the objective](/docs/api-reference/objectiveservice/get-an-objective-by-id), [streaming its events](/docs/api-reference/objectiveeventstreamsservice/stream-objective-events), or receiving [webhooks](/docs/guides/webhooks).

## The shortest call that works

Two fields are required: `agentId` and `systemPromptData`. Pass `{}` for the data when the agent's prompt has no template slots.

<CodeGroup>
  ```typescript TypeScript theme={null}
  const objective = await client.objectives.create({
    workspaceId,
    agentId: 'external_id:support',
    systemPromptData: {},
    firstUserMessage: 'A customer cannot log in. What should I check first?',
  });

  console.log(objective.metadata.id); // obj_01KX18K1TQRC2CKS6880FH2GCR
  console.log(objective.state);       // STATE_PENDING
  ```

  ```go Go theme={null}
  objective, err := client.Objectives.New(ctx, cadenya.ObjectiveNewParams{
  	WorkspaceID:      cadenya.String(workspaceID),
  	AgentID:          "external_id:support",
  	SystemPromptData: map[string]any{},
  	FirstUserMessage: cadenya.String("A customer cannot log in. What should I check first?"),
  })
  if err != nil {
  	log.Fatal(err)
  }
  log.Println(objective.Metadata.ID, objective.State)
  ```

  ```ruby Ruby theme={null}
  objective = cadenya.objectives.create(
    workspace_id: workspace_id,
    agent_id: "external_id:support",
    system_prompt_data: {},
    first_user_message: "A customer cannot log in. What should I check first?"
  )

  puts objective.metadata.id
  puts objective.state
  ```

  ```bash cURL theme={null}
  curl -X POST "https://api.cadenya.com/v1/workspaces/${WORKSPACE_ID}/objectives" \
    -H "Authorization: Bearer ${CADENYA_API_KEY}" \
    -H "Content-Type: application/json" \
    -d '{
          "agentId": "external_id:support",
          "systemPromptData": {},
          "firstUserMessage": "A customer cannot log in. What should I check first?"
        }'
  ```
</CodeGroup>

<Warning>
  In `bash` and `zsh`, brace the variable before a custom method: write `"${OBJECTIVE_ID}:cancel"`, not `"$OBJECTIVE_ID:cancel"`. The shell reads `:c` as a modifier and eats it, and the request lands on a path that does not exist.
</Warning>

## Where the two messages come from

An objective opens with a system prompt and a first user message. Both render from Liquid templates on the selected [variation](/docs/guides/sdk/agents#prompts-are-templates), and both take their data from this request.

| Request field          | Renders                                    | Rule                                                                              |
| ---------------------- | ------------------------------------------ | --------------------------------------------------------------------------------- |
| `systemPromptData`     | The variation's `systemPromptTemplate`     | Required. Validated against the agent's `systemPromptDataSchema` when it has one. |
| `firstUserMessageData` | The variation's `firstUserMessageTemplate` | Used when `firstUserMessage` is absent.                                           |
| `firstUserMessage`     | Nothing. Used verbatim.                    | Overrides the template.                                                           |

Pass neither `firstUserMessage` nor a variation with a `firstUserMessageTemplate` and the request fails with `InvalidArgument`. The rendered results come back on the response as the read-only `systemPrompt` and `firstUserMessage` fields.

```typescript theme={null}
// The variation's templates carry the shape. The objective carries the facts.
await client.objectives.create({
  workspaceId,
  agentId: 'external_id:support',
  systemPromptData: { company: 'Acme', tier: 'enterprise' },
  firstUserMessageData: { ticket_id: '4521', summary: 'Cannot log in.' },
});
```

## Pick the variation, or let the agent pick

Omit `variationId` and the agent's `variationSelectionMode` chooses: equal odds under `VARIATION_SELECTION_MODE_RANDOM`, feedback-weighted odds under `VARIATION_SELECTION_MODE_WEIGHTED`. Name a `variationId` and it overrides the mode, which is how you smoke-test a new variation before giving it weight.

```typescript theme={null}
await client.objectives.create({
  workspaceId,
  agentId: 'external_id:support',
  variationId: 'external_id:concise', // canonical agentvar_... works too
  systemPromptData: {},
  firstUserMessage: 'Pin this run to the Concise variation.',
});
```

Whichever variation wins, the response's `configSnapshot` freezes the agent and variation as they were at create time. Edit the variation tomorrow and this objective's record still shows what ran.

## Per-run secrets

`secrets` scope to this one objective and shadow tool set and workspace secrets on a name clash. Resolution runs objective, then tool set, then workspace. That precedence suits short-lived, per-user tokens: the workspace holds the service credential, the objective carries the caller's.

```typescript theme={null}
await client.objectives.create({
  workspaceId,
  agentId: 'external_id:support',
  systemPromptData: {},
  firstUserMessage: 'Fetch this user\'s recent orders.',
  secrets: [{ name: 'USER_TOKEN', value: userToken }],
});
```

Reference the name in an adapter header as `${USER_TOKEN}` and Cadenya swaps in the value at call time. Secrets never come back on a read: the response lists their names and nothing else. To see which source won for a given key, read `resolvedSecrets` on a [tool call](/docs/api-reference/objectiveservice/get-an-objective-tool-call-by-id).

## Memory

Two independent controls, both optional.

`memoryCascade` layers memory over the baseline the variation already carries. Array order is resolution order, and earlier elements win. Pin a single entry by passing `memoryEntryId` alongside its `memoryLayerId`. The total effective cascade, this field plus the variation's assignments, caps at 10 entries.

`episodicMemory.key` groups objectives that should share what the agent writes about itself. Objectives created with the same key, for the same agent, read and write one system-managed layer that sits at the most specific end of the cascade. The agent must have `enableEpisodicMemory` set.

```typescript theme={null}
await client.objectives.create({
  workspaceId,
  agentId: 'external_id:support',
  systemPromptData: {},
  firstUserMessage: 'Pick up where we left off.',
  episodicMemory: { key: `customer-${customerId}` },
  memoryCascade: [{ memoryLayerId: 'external_id:enterprise-playbook' }],
});
```

See [Memory cascade](/docs/guides/memory-layers) for how the layers resolve.

## What comes back, and what happens next

The response is the objective: `metadata.id` (an `obj_` prefixed ULID), the rendered `systemPrompt` and `firstUserMessage`, the `configSnapshot`, and a `state` that starts at `STATE_PENDING`.

An objective walks through eight states:

| State               | Meaning                                                                                                                       |
| ------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
| `STATE_PENDING`     | Created, not yet picked up.                                                                                                   |
| `STATE_RUNNING`     | The agent is working: calling tools, reading memory, looping.                                                                 |
| `STATE_WAITING`     | The agent answered and awaits another turn. [Continue it](/docs/api-reference/objectiveservice/continue-an-objective) to send one. |
| `STATE_FINALIZED`   | Done. `output` is populated when the agent has an output definition.                                                          |
| `STATE_FAILED`      | Stopped on an error. Read `stateMessage` for the reason.                                                                      |
| `STATE_CANCELLED`   | [Cancelled](/docs/api-reference/objectiveservice/cancel-an-objective) by a caller while it was running.                            |
| `STATE_TIMED_OUT`   | Hit the variation's inactivity timeout.                                                                                       |
| `STATE_UNSPECIFIED` | Never returned in practice.                                                                                                   |

**The agent's `outputDefinition` decides whether an objective ever finalizes.** With one, Cadenya extracts a result against that schema when the agent stops working, and the objective reaches `STATE_FINALIZED` with `output` populated. Without one, the objective parks in `STATE_WAITING` instead: it has answered, and it is holding the context window open for your next message. It never finalizes on its own.

So if you are polling for a terminal state against an agent that has no [`outputDefinition`](/docs/api-reference/agentservice/create-a-new-agent), you are waiting for something that never happens. Either declare the schema, or treat `STATE_WAITING` as done.

Cancelling interrupts work in flight. The call returns the objective in whatever state it was in, then the state settles to `STATE_CANCELLED` a moment later, so read it back rather than trusting the response. Cancelling a `STATE_WAITING` objective does nothing: there is no work to stop, and it stays waiting.

To watch the work as it happens, stream the events rather than polling:

```typescript theme={null}
const objective = await client.objectives.create({
  workspaceId,
  agentId: 'external_id:support',
  systemPromptData: {},
  firstUserMessage: 'A customer cannot log in. What should I check first?',
});

const stream = await client.objectives.streamEvents(objective.metadata.id, { workspaceId });
for await (const event of stream) {
  console.log(event.data?.type);
  // assistantMessage
  // toolCalled
  // toolResult
}
```

<Note>
  A tool that needs approval parks the objective and emits a `toolApprovalRequested` event. Nothing moves until you [approve or deny](/docs/guides/callbacks/approving-a-tool) the call.
</Note>

## Bring your own ID

Set `metadata.externalId` here and you never have to store the `obj_` ID. Every later call takes `external_id:your-value` in its place.

```typescript theme={null}
await client.objectives.create({
  workspaceId,
  agentId: 'external_id:support',
  systemPromptData: {},
  firstUserMessage: 'Handle ticket 4521.',
  metadata: { externalId: 'ticket-4521', labels: { team: 'support' } },
});

// Later, from anywhere, with no ID bookkeeping:
const objective = await client.objectives.retrieve('external_id:ticket-4521', { workspaceId });
```

Labels come along for the ride: filter the [objectives list](/docs/api-reference/objectiveservice/list-objectives) by them to group runs however your system thinks about them.


## OpenAPI

````yaml post /v1/workspaces/{workspaceId}/objectives
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}/objectives:
    post:
      tags:
        - ObjectiveService
        - Objectives
      summary: Create a new objective
      description: Creates a new objective in the workspace
      operationId: ObjectiveService_CreateObjective
      parameters:
        - name: workspaceId
          in: path
          required: true
          schema:
            type: string
            example: workspace_01HXKD2E5NQM3T9AYWCF133E3Q
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateObjectiveRequest'
        required: true
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Objective'
        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 objective = await client.objectives.create({
              workspaceId: 'workspace_01HXKD2E5NQM3T9AYWCF133E3Q',
              agentId: 'agent_01HXKD2E5NQM3T9AYWCFMGWT9Y',
              systemPromptData: { foo: 'bar' },
            });

            console.log(objective.configSnapshot);
        - 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
            )
            objective = client.objectives.create(
                workspace_id="workspace_01HXKD2E5NQM3T9AYWCF133E3Q",
                agent_id="agent_01HXKD2E5NQM3T9AYWCFMGWT9Y",
                system_prompt_data={
                    "foo": "bar"
                },
            )
            print(objective.config_snapshot)
        - 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)\n\nfunc main() {\n\tclient := cadenya.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tobjective, err := client.Objectives.New(context.TODO(), cadenya.ObjectiveNewParams{\n\t\tWorkspaceID: cadenya.String(\"workspace_01HXKD2E5NQM3T9AYWCF133E3Q\"),\n\t\tAgentID:     \"agent_01HXKD2E5NQM3T9AYWCFMGWT9Y\",\n\t\tSystemPromptData: map[string]any{\n\t\t\t\"foo\": \"bar\",\n\t\t},\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", objective.ConfigSnapshot)\n}\n"
        - lang: Ruby
          source: |-
            require "cadenya"

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

            objective = cadenya.objectives.create(
              workspace_id: "workspace_01HXKD2E5NQM3T9AYWCF133E3Q",
              agent_id: "agent_01HXKD2E5NQM3T9AYWCFMGWT9Y",
              system_prompt_data: {foo: "bar"}
            )

            puts(objective)
        - lang: CLI
          source: |-
            cadenya objectives create \
              --api-key 'My API Key' \
              --workspace-id workspace_01HXKD2E5NQM3T9AYWCF133E3Q \
              --agent-id agent_01HXKD2E5NQM3T9AYWCFMGWT9Y \
              --system-prompt-data '{foo: bar}'
components:
  schemas:
    CreateObjectiveRequest:
      required:
        - agentId
        - workspaceId
        - systemPromptData
      type: object
      properties:
        workspaceId:
          readOnly: true
          example: workspace_01HXKD2E5NQM3T9AYWCF133E3Q
          type: string
        agentId:
          example: agent_01HXKD2E5NQM3T9AYWCFMGWT9Y
          type: string
        variationId:
          example: agentvar_01HXKD2E5NQM3T9AYWCF32BSPP
          type: string
          description: >-
            Optional explicit variation selection. Overrides the agent's
            variation_selection_mode.
        metadata:
          $ref: '#/components/schemas/CreateOperationMetadata'
        systemPromptData:
          type: object
          additionalProperties: true
          description: >-
            Arbitrary data rendered into the selected variation's
            system_prompt_template
             (liquid) to produce the objective's system prompt. If the agent has a
             system_prompt_data_schema, this must satisfy it.
        firstUserMessage:
          type: string
          description: >-
            Optional explicit first user message for the LLM chat history. When
            not set,
             the selected variation's first_user_message_template is rendered with
             first_user_message_data instead. If neither this field nor a
             first_user_message_template is present, the request is rejected with InvalidArgument.
        secrets:
          type: array
          items:
            $ref: '#/components/schemas/CreateObjectiveRequest_Secret'
          description: >-
            Secrets that can be used in the headers for tool calls using the
            secret interpolation format.
        memoryCascade:
          type: array
          items:
            $ref: '#/components/schemas/MemoryReference'
          description: |-
            Memory layers/entries layered over the baseline cascade inherited
             from the selected variation — element-level rules over inherited
             styles, in CSS terms.

             Array order is resolution order: EARLIER elements are more specific
             and are consulted first. Entries pinned via memory_entry_id behave
             as single-entry layers at their position.

             System-managed layers (e.g., episodic) cannot be referenced here;
             they attach themselves automatically based on the episodic key.

             Size cap: the TOTAL effective cascade (this field + the variation's
             memory layer assignments) must not exceed 10 entries. A request
             that would produce a larger cascade is rejected with
             InvalidArgument.
        firstUserMessageData:
          type: object
          additionalProperties: true
          description: >-
            Arbitrary data rendered into the selected variation's
            first_user_message_template
             (liquid) to produce the first user message. Separate from `system_prompt_data`,
             which renders the system prompt template.
        episodicMemory:
          allOf:
            - $ref: '#/components/schemas/ObjectiveEpisodicConfig'
          description: >-
            If the agent variation that is selected has episodic memory enabled,
            then this key is used to create/update a memory layer
             specific to the episodic memory. The layer may have a TTL configured by the variation.
        tenant:
          allOf:
            - $ref: '#/components/schemas/TenantAssertion'
          description: >-
            Optional tenant assertion — the customer's org/company identifier
            for the
             end user this objective serves. Upserts the tenant record in the
             workspace and associates the objective with it.
        subject:
          allOf:
            - $ref: '#/components/schemas/SubjectAssertion'
          description: >-
            Optional subject assertion — the person within the tenant this
            objective
             serves. Requires `tenant`; a subject asserted without a tenant is
             rejected with InvalidArgument.
        pinnedParameters:
          type: object
          additionalProperties:
            type: string
          description: >-
            Parameters forced onto this objective's tool calls. A pinned
            parameter
             is an overlay on a tool's JSON schema: the parameter is removed from
             what the LLM sees, and its value is always overwritten server-side with
             the pinned value — the model cannot choose a different value for it.
    Objective:
      required:
        - metadata
        - configSnapshot
        - state
        - systemPrompt
        - firstUserMessage
      type: object
      properties:
        metadata:
          $ref: '#/components/schemas/OperationMetadata'
        configSnapshot:
          readOnly: true
          allOf:
            - $ref: '#/components/schemas/ObjectiveConfigSnapshot'
          description: >-
            The snapshot of the agent and the variation selected (either
            explicitly or by sampling) will be set here. Cadenya stores
             the point-in-time snapshot of the configuration used to start an objective and maintains it throughout the entire lifecycle
             so that changes to agents and variations in the middle of a cycle don't impact the objective itself
        state:
          readOnly: true
          enum:
            - STATE_UNSPECIFIED
            - STATE_PENDING
            - STATE_RUNNING
            - STATE_WAITING
            - STATE_FAILED
            - STATE_CANCELLED
            - STATE_FINALIZED
            - STATE_TIMED_OUT
          type: string
          description: The current lifecycle state of the objective.
          format: enum
        stateMessage:
          readOnly: true
          type: string
          description: >-
            Optional human-readable detail about the current state (e.g. a
            failure reason).
        info:
          readOnly: true
          allOf:
            - $ref: '#/components/schemas/ObjectiveInfo'
          description: Read-only aggregated info about this objective's execution
        systemPrompt:
          readOnly: true
          type: string
          description: >-
            system_prompt is read-only, derived from the selected variation's
            prompt
        firstUserMessage:
          type: string
          description: >-
            The first user message in the LLM chat history, either provided
            explicitly at
             creation or rendered from the variation's first_user_message_template.
        parentObjectiveId:
          readOnly: true
          example: obj_01HXKD2E5NQM3T9AYWCFQAZGFV
          type: string
          description: >-
            A parent objective means the objective was spawned off using a
            separate agent to complete an objective
        secrets:
          type: array
          items:
            $ref: '#/components/schemas/Objective_Secret'
          description: >-
            Secrets that can be used in the headers for tool calls using the
            secret interpolation format.
        systemPromptData:
          readOnly: true
          type: object
          additionalProperties: true
          description: Arbitrary data rendered into the variation's system_prompt_template
        memoryCascade:
          type: array
          items:
            $ref: '#/components/schemas/MemoryReference'
          description: |-
            Memory layers/entries layered over the baseline cascade inherited
             from the selected variation — element-level rules over inherited
             styles, in CSS terms.

             Array order is resolution order: EARLIER elements are more specific
             and are consulted first. Entries pinned via memory_entry_id behave
             as single-entry layers at their position.

             System-managed layers (e.g., episodic) cannot be referenced here;
             they attach themselves automatically based on the episodic key.

             Size cap: the TOTAL effective cascade (this field + the variation's
             memory layer assignments) must not exceed 10 entries. A request
             that would produce a larger cascade is rejected with
             InvalidArgument.
        output:
          readOnly: true
          type: object
          additionalProperties: true
          description: >-
            The output of the objective, populated when the objective completes.
            Will match the schema of output_json_schema or output_json_inferred.
             This will only be set if the state of the objective is set to STATE_FINALIZED
        firstUserMessageData:
          readOnly: true
          type: object
          additionalProperties: true
          description: >-
            Arbitrary data rendered into the variation's
            first_user_message_template
        episodicMemory:
          allOf:
            - $ref: '#/components/schemas/ObjectiveEpisodicConfig'
          description: >-
            If the agent variation that is selected has episodic memory enabled,
            then this key is used to create/update a memory layer
             specific to the episodic memory. The layer may have a TTL configured by the variation.
        pinnedParameters:
          readOnly: true
          type: object
          additionalProperties:
            type: string
          description: |-
            Parameters forced onto this objective's tool calls, as provided at
             creation. See CreateObjectiveRequest.pinned_parameters for semantics.
      description: >-
        Objective is the data for an objective. It contains the snapshotted
        fields for the selected agent and variation. Secrets are returned
         only with their names, and the output definition is copied from the agent's configuration.
    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).
    CreateOperationMetadata:
      type: object
      properties:
        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: {"priority": "high", "source": "api", "workflow": "onboarding"}
        externalId:
          type: string
          description: >-
            External ID for the operation (e.g., a workflow ID from an external
            system)
      description: |-
        CreateOperationMetadata contains the user-provided fields for creating
         an operation. Read-only fields (id, account_id, workspace_id, created_at, profile_id)
         are excluded since they are set by the server.
    CreateObjectiveRequest_Secret:
      type: object
      properties:
        name:
          type: string
        value:
          type: string
    MemoryReference:
      required:
        - memoryLayerId
      type: object
      properties:
        memoryLayerId:
          example: memlyr_01HXKD2E5NQM3T9AYWCFFFBMJH
          type: string
        memoryEntryId:
          example: mementry_01HXKD2E5NQM3T9AYWCF5E52Z0
          type: string
          description: >-
            When set, inserts only this entry from memory_layer_id into the
            cascade —
             behaves as a single-entry layer (only this key resolves at this
             position). The entry must belong to memory_layer_id; mismatches are
             rejected with InvalidArgument.
      description: |-
        MemoryReference identifies a memory layer or a specific entry within
         one, for composition into a memory cascade. Used on objectives (where
         entry pinning is permitted).

         memory_layer_id accepts both the canonical form (memlyr_…) and the
         external-id form (external_id:my-custom-id). The same applies to
         memory_entry_id when set.
    ObjectiveEpisodicConfig:
      required:
        - key
      type: object
      properties:
        key:
          type: string
          description: >-
            The caller-supplied episodic key. Objectives created with the same
            key
             (for the same agent) share one episodic memory layer.
        memoryLayerId:
          readOnly: true
          example: memlyr_01HXKD2E5NQM3T9AYWCFFFBMJH
          type: string
          description: |-
            The episodic memory layer resolved (created or reused) for this
             objective's key. Populated by the system at objective creation.
      description: Episodic is used to configure the episodic memory for the objective
    TenantAssertion:
      required:
        - id
      type: object
      properties:
        id:
          example: acme-corp
          type: string
          description: >-
            The tenant identifier in the customer's namespace (e.g.
            "acme-corp").
             Stored as the tenant record's external_id; stable across requests.
        name:
          example: Acme Corp
          type: string
          description: >-
            Optional human-readable name for the tenant. Updates the tenant
            record's
             name on every assertion that provides it.
      description: >-
        TenantAssertion identifies a tenant in the customer's own namespace —
        their
         org, company, or team identifier for an end user. Asserting a tenant
         upserts the tenant record in the workspace (keyed on `id` as the tenant's
         external_id) and associates the created resource with it.
    SubjectAssertion:
      required:
        - id
      type: object
      properties:
        id:
          example: customer-user-42
          type: string
          description: >-
            The subject identifier in the customer's namespace (e.g. their user
            id).
             Stored as the subject record's external_id; unique within the tenant.
        name:
          example: Jane Doe
          type: string
          description: |-
            Optional human-readable name for the subject. Updates the subject
             record's name on every assertion that provides it.
      description: >-
        SubjectAssertion identifies a person within a tenant in the customer's
        own
         namespace — typically their user id. Asserting a subject upserts the
         subject record under the asserted tenant and associates the created
         resource with it. A subject assertion is only valid alongside a tenant
         assertion: subject identifiers are scoped to their tenant.
    OperationMetadata:
      required:
        - id
        - accountId
        - workspaceId
        - profileId
        - createdAt
      type: object
      properties:
        id:
          readOnly: true
          type: string
          description: >-
            Unique identifier for the operation (prefixed ULID, e.g.,
            "obj_01HXK...")
        accountId:
          readOnly: true
          example: account_01HXKD2E5NQM3T9AYWCFTJHJVF
          type: string
          description: >-
            Account this operation belongs to for multi-tenant isolation
            (prefixed ULID)
        workspaceId:
          readOnly: true
          example: workspace_01HXKD2E5NQM3T9AYWCF133E3Q
          type: string
          description: >-
            Workspace this operation belongs to for organizational grouping
            (prefixed ULID)
        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: {"priority": "high", "source": "api", "workflow": "onboarding"}
        createdAt:
          readOnly: true
          type: string
          description: |-
            Timestamp when this operation was created
             ULID includes timestamp information, but this explicit field enables easier querying
          format: date-time
        externalId:
          type: string
          description: >-
            External ID for the operation (e.g., a workflow ID from an external
            system)
        profileId:
          readOnly: true
          example: profile_01HXKD2E5NQM3T9AYWCFS0AP08
          type: string
          description: >-
            ID of the actor (user or service account) that created this
            operation
      description: >-
        Metadata for ephemeral operations and activities (e.g., objectives,
        executions, runs)
    ObjectiveConfigSnapshot:
      type: object
      properties:
        agent:
          $ref: '#/components/schemas/Agent'
        agentVariation:
          $ref: '#/components/schemas/AgentVariation'
        agentSchedule:
          $ref: '#/components/schemas/AgentSchedule'
      description: >-
        ObjectiveConfigSnapshot is the point-in-time snapshot of the agent,
        variation, and
         (when applicable) schedule that an objective was started with.
    ObjectiveInfo:
      required:
        - totalEvents
        - totalToolCalls
        - totalInputTokens
        - totalOutputTokens
        - totalContextWindows
        - totalIterations
        - createdBy
        - effectiveMemoryCascade
        - agent
        - agentVariation
        - currentContextWindowId
      type: object
      properties:
        totalEvents:
          readOnly: true
          type: integer
          description: Total number of events generated during this objective's execution
          format: int32
        totalToolCalls:
          readOnly: true
          type: integer
          description: Total number of tool calls made during execution
          format: int32
        totalInputTokens:
          readOnly: true
          type: integer
          description: >-
            Total input tokens consumed across all LLM completions across all
            context windows
          format: int32
        totalOutputTokens:
          readOnly: true
          type: integer
          description: >-
            Total output tokens generated across all LLM completions across all
            context windows
          format: int32
        totalContextWindows:
          readOnly: true
          type: integer
          description: Total number of context windows that this objective has generated
          format: int32
        totalIterations:
          readOnly: true
          type: integer
          format: int32
        createdBy:
          $ref: '#/components/schemas/Profile'
        effectiveMemoryCascade:
          readOnly: true
          type: array
          items:
            $ref: '#/components/schemas/MemoryReference'
          description: |-
            The effective memory cascade at objective creation time: the
             episodic layer (when present), then Objective.memory_cascade, then
             the variation's baseline layers by ascending position. Order is
             resolution order — index 0 is the most specific and is consulted
             first; the first layer containing a key wins. Returned on reads so
             clients can see exactly what the objective resolves against without
             re-joining variation state.
        agent:
          readOnly: true
          allOf:
            - $ref: '#/components/schemas/ResourceMetadata'
          description: Agent details (not snapshotted).
        agentVariation:
          readOnly: true
          allOf:
            - $ref: '#/components/schemas/ResourceMetadata'
          description: Agent variation details (not snapshotted).
        currentContextWindowId:
          readOnly: true
          example: objwin_01HXKD2E5NQM3T9AYWCFN7BSTR
          type: string
          description: >-
            ID of the objective's current (most recent) context window. Hydrated
            on
             demand; empty when the objective has not yet produced a context window.
        tenant:
          readOnly: true
          allOf:
            - $ref: '#/components/schemas/TenantReference'
          description: >-
            The tenant this objective is associated with, when one was asserted
            at
             creation (directly or via a widget session).
        subject:
          readOnly: true
          allOf:
            - $ref: '#/components/schemas/SubjectReference'
          description: |-
            The subject (person within the tenant) this objective is associated
             with, when one was asserted at creation.
        widget:
          readOnly: true
          allOf:
            - $ref: '#/components/schemas/BareMetadata'
          description: |-
            The widget this objective's conversation ran through, when it was
             created via a widget session.
      description: >-
        ObjectiveInfo provides read-only aggregated statistics about an
        objective's execution
    Objective_Secret:
      type: object
      properties:
        name:
          type: string
    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.
    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
    AgentVariation:
      required:
        - metadata
        - spec
      type: object
      properties:
        metadata:
          allOf:
            - $ref: '#/components/schemas/ResourceMetadata'
          description: Resource metadata
        spec:
          allOf:
            - $ref: '#/components/schemas/AgentVariationSpec'
          description: Variation specification
        info:
          readOnly: true
          allOf:
            - $ref: '#/components/schemas/AgentVariationInfo'
          description: Read-only summary information
      description: AgentVariation resource
    AgentSchedule:
      required:
        - metadata
        - spec
        - state
      type: object
      properties:
        metadata:
          $ref: '#/components/schemas/ResourceMetadata'
        spec:
          $ref: '#/components/schemas/AgentScheduleSpec'
        info:
          $ref: '#/components/schemas/AgentScheduleInfo'
        state:
          readOnly: true
          enum:
            - STATE_UNSPECIFIED
            - STATE_ACTIVE
            - STATE_PAUSED
            - STATE_ARCHIVED
          type: string
          description: >-
            The current lifecycle state of the schedule. Output only. Schedules
            are
             created STATE_ACTIVE; use the :pause, :resume, and :archive actions to
             transition between states.
          format: enum
      description: |-
        AgentSchedule resource — a recurring trigger attached to an agent that
         creates objectives on its cadence.
    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.
    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)
    TenantReference:
      required:
        - id
        - externalId
      type: object
      properties:
        id:
          readOnly: true
          example: tenant_01HXKD2E5NQM3T9AYWCF133E3Q
          type: string
          description: Cadenya's canonical tenant id.
        externalId:
          readOnly: true
          example: acme-corp
          type: string
          description: The tenant identifier in the customer's namespace, as asserted.
        name:
          readOnly: true
          example: Acme Corp
          type: string
          description: Human-readable name of the tenant, when one has been asserted.
      description: >-
        TenantReference is the read-only echo of a resource's tenant
        association,
         carrying both Cadenya's canonical id and the customer's own key.
    SubjectReference:
      required:
        - id
        - externalId
      type: object
      properties:
        id:
          readOnly: true
          example: subj_01HXKD2E5NQM3T9AYWCFQAZGFV
          type: string
          description: Cadenya's canonical subject id.
        externalId:
          readOnly: true
          example: customer-user-42
          type: string
          description: >-
            The subject identifier in the customer's namespace, as asserted.
            Unique
             within the subject's tenant.
        name:
          readOnly: true
          example: Jane Doe
          type: string
          description: Human-readable name of the subject, when one has been asserted.
      description: >-
        SubjectReference is the read-only echo of a resource's subject
        association,
         carrying both Cadenya's canonical id and the customer's own key.
    BareMetadata:
      type: object
      properties:
        id:
          readOnly: true
          type: string
        name:
          readOnly: true
          type: string
          description: >-
            Human-readable name of the referenced resource, populated by the
            server
             on reads for convenience. Absent on references to resources that do not
             have a name (e.g., objective tasks).
      description: |-
        BareMetadata contains the minimal metadata for a resource: the ID and an
         optional human-readable name. These are used for reference fields where the
         full metadata (account scoping, timestamps, labels, external IDs) is not
         needed — e.g., the tool references inside an agent variation spec or the
         tools assigned to an objective. Both fields are server-populated; clients
         provide IDs through sibling fields rather than by constructing a
         BareMetadata themselves.
    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)
    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
    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
    AgentVariationInfo:
      type: object
      properties:
        toolCount:
          readOnly: true
          type: integer
          description: Number of individual tools assigned to this variation
          format: int32
        toolSetCount:
          readOnly: true
          type: integer
          description: Number of tool sets assigned to this variation
          format: int32
        subAgentCount:
          readOnly: true
          type: integer
          description: Number of sub-agents assigned to this variation
          format: int32
        createdBy:
          $ref: '#/components/schemas/Profile'
        model:
          readOnly: true
          allOf:
            - $ref: '#/components/schemas/ResourceMetadata'
          description: Metadata for the model assigned to this variation
        score:
          type: number
          description: |-
            Thompson Sampling score: posterior mean of Beta(ts_alpha, ts_beta).
             Range [0, 1] where 0.5 = neutral, >0.5 = positive, <0.5 = negative.
          format: float
        feedbackCount:
          type: integer
          description: Total number of objective feedbacks received for this variation
          format: int32
        assignments:
          readOnly: true
          type: array
          items:
            $ref: '#/components/schemas/VariationAssignment'
          description: |-
            All tools, tool sets, and sub-agents assigned to this variation.
             Populated on reads so clients can render a variation's full assignment
             list without calling the add/remove endpoints just to enumerate.
        memoryLayerAssignments:
          readOnly: true
          type: array
          items:
            $ref: '#/components/schemas/VariationMemoryLayerAssignment'
          description: |-
            Read-only list of memory layer assignments for this variation,
             returned in ascending `position` (most specific first — resolution
             order). Capped at 10 entries.
        memoryLayerCount:
          readOnly: true
          type: integer
          description: Count of memory layer assignments.
          format: int32
      description: >-
        AgentVariationInfo provides read-only summary information about a
        variation
    AgentScheduleSpec:
      required:
        - schedule
      type: object
      properties:
        schedule:
          allOf:
            - $ref: '#/components/schemas/AgentScheduleSpec_Schedule'
          description: When to fire. Required.
        overlapPolicy:
          enum:
            - OVERLAP_POLICY_UNSPECIFIED
            - OVERLAP_POLICY_ALLOW
            - OVERLAP_POLICY_SKIP
          type: string
          description: >-
            What to do when the previous run is still in flight. Defaults to
            SKIP.
          format: enum
        firstUserMessage:
          type: string
          description: >-
            Optional explicit first user message passed to CreateObjective on
            each fire.
             Becomes the first user message in the objective's chat history. When unset, the
             fired objective defers to the selected variation's first_user_message_template.
        variationId:
          example: agentvar_01HXKD2E5NQM3T9AYWCF32BSPP
          type: string
          description: >-
            Optional explicit variation. When unset, the agent's
            variation_selection_mode
             chooses per fire.
        systemPromptData:
          type: object
          description: >-
            Optional data rendered into the variation's system_prompt_template
            when each
             fired objective is created. If the agent has a system_prompt_data_schema,
             this must satisfy it.
          x-stainless-any: true
        firstUserMessageData:
          type: object
          description: >-
            Optional data rendered into the variation's
            first_user_message_template when
             each fired objective is created. Separate from `system_prompt_data`, which
             renders the system prompt template.
          x-stainless-any: true
      description: AgentScheduleSpec is the user-provided configuration for a schedule.
    AgentScheduleInfo:
      type: object
      properties:
        nextFireAt:
          readOnly: true
          type: string
          description: >-
            When the schedule will next fire. Computed from the spec; absent
            when
             the schedule is STATE_PAUSED/STATE_ARCHIVED or has no future fire times.
          format: date-time
        lastFireAt:
          readOnly: true
          type: string
          description: When the schedule last fired (regardless of objective outcome).
          format: date-time
        lastObjectiveId:
          readOnly: true
          example: obj_01HXKD2E5NQM3T9AYWCFQAZGFV
          type: string
          description: ID of the most recent objective the schedule created.
        lastSkippedAt:
          readOnly: true
          type: string
          description: >-
            When the schedule most recently skipped a fire (SKIP policy + prior
            in flight).
          format: date-time
        lastSkipReason:
          readOnly: true
          type: string
          description: >-
            Reason for the most recent skip (e.g. "previous objective still
            running").
        totalFires:
          readOnly: true
          type: integer
          description: Lifetime count of objectives created by this schedule.
          format: int32
        createdBy:
          $ref: '#/components/schemas/Profile'
      description: AgentScheduleInfo provides read-only runtime data about a schedule.
    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.
    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.
    VariationAssignment:
      oneOf:
        - $ref: '#/components/schemas/VariationAssignment_Tool'
        - $ref: '#/components/schemas/VariationAssignment_ToolSet'
        - $ref: '#/components/schemas/VariationAssignment_Agent'
      discriminator:
        propertyName: type
        mapping:
          tool:
            $ref: '#/components/schemas/VariationAssignment_Tool'
          toolSet:
            $ref: '#/components/schemas/VariationAssignment_ToolSet'
          agent:
            $ref: '#/components/schemas/VariationAssignment_Agent'
      description: >-
        A read-only reference to a single tool, tool set, or sub-agent attached
        to
         a variation. Read the full set of assignments via `AgentVariationInfo.assignments`;
         mutations go through the dedicated add/remove assignment endpoints.

         The `id` identifies the assignment itself (not the referenced resource) and
         is the handle used to remove the assignment. It is returned by the add
         endpoint and present on every entry in `AgentVariationInfo.assignments`.
    VariationMemoryLayerAssignment:
      type: object
      properties:
        id:
          readOnly: true
          example: avml_01HXKD2E5NQM3T9AYWCFX8AF59
          type: string
          description: |-
            Assignment row id — handle for removing the assignment. Distinct
             from the referenced memory layer's id.
        memoryLayer:
          allOf:
            - $ref: '#/components/schemas/BareMetadata'
          description: The attached memory layer.
        position:
          type: integer
          description: |-
            Position in the variation's baseline cascade. Position is
             specificity, CSS-style: a LOWER position is more specific and is
             consulted first; the highest-position assignment is the most
             general fallback. Gaps are fine — only relative position matters.
             Positions must be unique within a variation; a request that would
             collide with an existing assignment's position is rejected with
             InvalidArgument.
          format: int32
      description: |-
        VariationMemoryLayerAssignment attaches a single MemoryLayer to a
         variation at a given position in the variation's baseline memory
         cascade. A variation has at most one assignment per memory_layer_id.

         Variations only support whole-layer attachments — entry pinning is an
         objective-level capability.
    AgentScheduleSpec_Schedule:
      type: object
      properties:
        calendars:
          type: array
          items:
            $ref: '#/components/schemas/Schedule_Calendar'
          description: Wall-clock rules. May be empty if `intervals` is non-empty.
        intervals:
          type: array
          items:
            $ref: '#/components/schemas/Schedule_Interval'
          description: Duration-based rules. May be empty if `calendars` is non-empty.
        timezone:
          type: string
          description: >-
            IANA tz name (e.g. "America/New_York"). Required. Applies to
            calendars;
             intervals fire on wall-clock cadence anchored in this zone.
      description: >-
        Schedule defines WHEN the schedule fires. Temporal-style structured
        form:
         a list of calendar rules (wall-clock) and/or interval rules (duration),
         OR'd together. At least one rule is required.
    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.
    VariationAssignment_Tool:
      type: object
      required:
        - type
        - tool
      properties:
        type:
          type: string
          enum:
            - tool
        tool:
          $ref: '#/components/schemas/BareMetadata'
        id:
          readOnly: true
          example: avt_01HXKD2E5NQM3T9AYWCFJE6K89
          type: string
    VariationAssignment_ToolSet:
      type: object
      required:
        - type
        - toolSet
      properties:
        type:
          type: string
          enum:
            - toolSet
        toolSet:
          $ref: '#/components/schemas/BareMetadata'
        id:
          readOnly: true
          example: avt_01HXKD2E5NQM3T9AYWCFJE6K89
          type: string
    VariationAssignment_Agent:
      type: object
      required:
        - type
        - agent
      properties:
        type:
          type: string
          enum:
            - agent
        agent:
          $ref: '#/components/schemas/BareMetadata'
        id:
          readOnly: true
          example: avt_01HXKD2E5NQM3T9AYWCFJE6K89
          type: string
    Schedule_Calendar:
      type: object
      properties:
        second:
          type: array
          items:
            $ref: '#/components/schemas/Schedule_Range'
        minute:
          type: array
          items:
            $ref: '#/components/schemas/Schedule_Range'
        hour:
          type: array
          items:
            $ref: '#/components/schemas/Schedule_Range'
        dayOfMonth:
          type: array
          items:
            $ref: '#/components/schemas/Schedule_Range'
        month:
          type: array
          items:
            $ref: '#/components/schemas/Schedule_Range'
        dayOfWeek:
          type: array
          items:
            $ref: '#/components/schemas/Schedule_Range'
        comment:
          type: string
      description: |-
        Calendar is a wall-clock rule. Empty field-list semantics:
           - second/minute/hour: empty means [{start: 0}] (top of the unit)
           - day_of_month/month/day_of_week: empty means "any value"
         Fire times = cartesian product across all fields.
    Schedule_Interval:
      type: object
      properties:
        every:
          pattern: ^-?(?:0|[1-9][0-9]{0,11})(?:\.[0-9]{1,9})?s$
          type: string
        offset:
          pattern: ^-?(?:0|[1-9][0-9]{0,11})(?:\.[0-9]{1,9})?s$
          type: string
          description: Phase shift within `every`. Must be < `every` (enforced at runtime).
      description: |-
        Interval is a duration-based rule. Fires every `every` from a stable
         anchor (workspace epoch), optionally phase-shifted by `offset`.
    Schedule_Range:
      type: object
      properties:
        start:
          type: integer
          format: int32
        end:
          type: integer
          format: int32
        step:
          type: integer
          format: int32
      description: |-
        Inclusive numeric range with optional step.
           {start: 9}                    → 9
           {start: 9, end: 17}           → 9..17
           {start: 0, end: 59, step: 15} → 0,15,30,45
         `end` defaults to `start`; `step` defaults to 1.
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT

````