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

# Gravar a memória de trabalho

> O estado de trabalho de um agente, escrito pelo código dele e nunca por um modelo: `cas` troca o estado inteiro numa versão, `merge_by_key` troca os campos nomeados. Acima do teto responde `stored: false`, nunca erro. Funcionalidade `agent_state`.



## OpenAPI

````yaml openapi/pt/cell.json PUT /v1/agent-state
openapi: 3.1.0
info:
  title: API de dados da Niadra
  version: '1'
  description: >-
    Escrita, contexto, histórico, objetos, identidade, privacidade e governança
    de um espaço. Cada espaço tem um endereço estável, com o espaço e a região
    no nome.
servers:
  - url: https://{space}.{region}.api.niadra.com
    variables:
      space:
        default: acme-prod
        description: O espaço, que vem na chave de fonte.
      region:
        default: us-east-2
        description: A região do espaço, que também vem na chave.
security: []
paths:
  /v1/agent-state:
    put:
      tags:
        - state
      summary: Gravar a memória de trabalho
      description: >-
        Uma escrita pelo código do agente: acima do teto responde `stored:
        false`, nunca erro.


        **Autenticação.** Chave de fonte: `Authorization: Bearer nia_sk_...`.
        Escopo exigido: `agent_state`. Só responde num espaço com a
        funcionalidade `agent_state` ligada (o documento `features`); num espaço
        sem ela, 404.
      operationId: write_agent_state_v1_agent_state_put
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/AgentStateWrite'
        required: true
      responses:
        '200':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/AgentStateWriteResult'
          description: Resposta de sucesso.
        '412':
          description: '`agent_state_conflict`: a versão mudou desde `if_version`.'
        '422':
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
          description: O pedido não bate com o contrato.
      security:
        - sourceKey: []
      x-codeSamples:
        - lang: python
          label: Python
          source: >-
            # Written by the agent's code, never by a model; merge by key keeps
            the other fields

            written = conversation.agent_state.put({"offer": {"plan":
            "familia-plus", "status": "shown"}})

            if not written.stored:
                print(written.reason)  # over_cap or not_declared_field, never an exception
        - lang: typescript
          label: TypeScript
          source: >-
            // Written by the agent's code, never by a model; merge by key keeps
            the other fields

            const written = await convo.agentState.put({ offer: { plan:
            "familia-plus", status: "shown" } });

            if (!written.stored) console.log(written.reason); // over_cap or
            not_declared_field, never a rejection
components:
  schemas:
    AgentStateWrite:
      additionalProperties: false
      description: >-
        Uma escrita do estado de trabalho de um agente, pelo código dele e nunca
        por um modelo: `cas` troca o estado inteiro em `if_version` (0 quando
        ele ainda não pode existir); `merge_by_key` troca cada campo de primeiro
        nível que nomeia e remove um campo escrito exatamente como `{"$delete":
        true}`.
      properties:
        agent:
          maxLength: 256
          minLength: 1
          title: Agent
          type: string
        body:
          additionalProperties: true
          title: Body
          type: object
        if_version:
          anyOf:
            - minimum: 0
              type: integer
            - type: 'null'
          title: If Version
        mode:
          enum:
            - cas
            - merge_by_key
          title: Mode
          type: string
        scope:
          $ref: '#/components/schemas/AgentStateScope'
        subject:
          anyOf:
            - $ref: '#/components/schemas/Handle'
            - type: 'null'
          description: >-
            O cliente de que o estado trata, quando o escopo não o nomeia:
            apagar o cliente e o pacote de dados dele acham o estado por aqui.
      required:
        - scope
        - agent
        - mode
        - body
      title: AgentStateWrite
      type: object
    AgentStateWriteResult:
      additionalProperties: false
      properties:
        reason:
          anyOf:
            - enum:
                - over_cap
                - not_declared_field
              type: string
            - type: 'null'
          title: Reason
        stored:
          title: Stored
          type: boolean
        version:
          title: Version
          type: integer
      required:
        - stored
        - version
      title: AgentStateWriteResult
      type: object
    Problem:
      additionalProperties: false
      description: >-
        Detalhes do problema no formato da RFC 9457; `code` vem do catálogo de
        erros versionado.
      properties:
        code:
          title: Code
          type: string
        detail:
          anyOf:
            - type: string
            - type: 'null'
          default: null
          title: Detail
        request_id:
          anyOf:
            - type: string
            - type: 'null'
          default: null
          title: Request Id
        status:
          title: Status
          type: integer
        title:
          title: Title
          type: string
        type:
          default: about:blank
          title: Type
          type: string
      required:
        - title
        - status
        - code
      title: Problem
      type: object
    AgentStateScope:
      additionalProperties: false
      description: >-
        A que um estado de trabalho pertence. O id viaja no corpo, nunca numa
        URL: um id de conversa pode parecer um telefone.
      properties:
        id:
          maxLength: 512
          minLength: 1
          title: Id
          type: string
        kind:
          enum:
            - conversation
            - task
            - object
            - subject
          title: Kind
          type: string
      required:
        - kind
        - id
      title: AgentStateScope
      type: object
    Handle:
      additionalProperties: false
      description: >-
        Um identificador de um sujeito num canal ou sistema: um telefone, um
        e-mail, um id do CRM.
      properties:
        scope:
          anyOf:
            - maxLength: 256
              minLength: 1
              type: string
            - type: 'null'
          description: >-
            Espaço de nomes dos identificadores com escopo: a conta do WhatsApp
            Business para `wa_bsuid`, o sistema para `system_id`, o país para
            `gov_id_hmac`.
          title: Scope
        subject_kind:
          anyOf:
            - $ref: '#/components/schemas/SubjectKind'
            - type: 'null'
          description: >-
            O padrão é `person`, exceto nos tipos de handle que só identificam
            organizações.
        type:
          $ref: '#/components/schemas/HandleType'
        value:
          maxLength: 320
          minLength: 1
          title: Value
          type: string
          description: >-
            O identificador. Normalizado no servidor: E.164 para telefone,
            minúsculas para e-mail.
      required:
        - type
        - value
      title: Handle
      type: object
    SubjectKind:
      enum:
        - person
        - account
        - partner
      title: SubjectKind
      type: string
      description: >-
        Uma pessoa, uma organização cliente (`account`) ou uma organização que
        participa sem ser cliente (`partner`).
    HandleType:
      enum:
        - phone_e164
        - wa_id
        - wa_jid
        - wa_lid
        - wa_bsuid
        - email
        - gov_id_hmac
        - app_user_id
        - system_id
        - org_registry_hmac
        - email_domain
        - anon_id
      title: HandleType
      type: string
      description: >-
        O tipo de identificador. O valor é classificado pelo formato, nunca pelo
        campo de onde veio.
  securitySchemes:
    sourceKey:
      type: http
      scheme: bearer
      description: nia_sk_...

````