Skip to content

Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.

50.6 KB
Raw Blame
// Code generated by sqlc. DO NOT EDIT.
// versions:
//   sqlc v1.29.0
// source: agent_registration.sql

package store

import (
	"context"

	"github.com/jackc/pgx/v5/pgtype"
)

const agentRegistrationCursorExists = `-- name: AgentRegistrationCursorExists :one
SELECT EXISTS (
  SELECT 1 FROM agent_registrations registration
  JOIN actors caller
    ON caller.tenant_id=registration.tenant_id
   AND caller.account_id=$1::text
   AND caller.kind='human'
  WHERE registration.actor_id=$2::text
    AND registration.tenant_id=$3::text
    AND registration.status='active'
    AND (
      registration.visibility_scope='workspace' OR
      registration.created_by_actor_id=caller.id OR
      EXISTS (
        SELECT 1
        FROM active_room_members caller_membership
        JOIN active_room_members agent_membership
          ON agent_membership.room_id=caller_membership.room_id
         AND agent_membership.actor_id=registration.actor_id
        WHERE caller_membership.actor_id=caller.id
      )
    )
)
`

type AgentRegistrationCursorExistsParams struct {
	AccountID string `json:"account_id"`
	ActorID   string `json:"actor_id"`
	TenantID  string `json:"tenant_id"`
}

func (q *Queries) AgentRegistrationCursorExists(ctx context.Context, arg AgentRegistrationCursorExistsParams) (bool, error) {
	row := q.db.QueryRow(ctx, agentRegistrationCursorExists, arg.AccountID, arg.ActorID, arg.TenantID)
	var exists bool
	err := row.Scan(&exists)
	return exists, err
}

const applyAgentConfigurationUpdate = `-- name: ApplyAgentConfigurationUpdate :execrows
UPDATE agent_registrations
SET description=$1::text,runtime_model=$2::text,
    runtime_reasoning_effort=$3::text,
    assignment_revision=assignment_revision+CASE WHEN
        computer_id IS DISTINCT FROM $4::text
        OR local_runtime_type IS DISTINCT FROM $5::text
        OR workspace_grant_id IS DISTINCT FROM $6::text
        THEN 1 ELSE 0 END,
    computer_id=$4::text,local_runtime_type=$5::text,
    workspace_grant_id=$6::text,
    configuration_revision=$7::bigint,
    runtime_configuration_revision=$7::bigint,
    instructions=$8::text,updated_at=now()
WHERE actor_id=$9::text AND tenant_id=$10::text AND status='active'
  AND configuration_revision=$11::bigint
`

type ApplyAgentConfigurationUpdateParams struct {
	Description            string      `json:"description"`
	RuntimeModel           string      `json:"runtime_model"`
	RuntimeReasoningEffort pgtype.Text `json:"runtime_reasoning_effort"`
	ComputerID             string      `json:"computer_id"`
	LocalRuntimeType       string      `json:"local_runtime_type"`
	WorkspaceGrantID       string      `json:"workspace_grant_id"`
	NextRevision           int64       `json:"next_revision"`
	Instructions           string      `json:"instructions"`
	ActorID                string      `json:"actor_id"`
	TenantID               string      `json:"tenant_id"`
	ExpectedRevision       int64       `json:"expected_revision"`
}

// A new Computer, local Runtime or workspace grant is a new Runtime
// Assignment: its revision fences the Runners and Operations of the old one.
func (q *Queries) ApplyAgentConfigurationUpdate(ctx context.Context, arg ApplyAgentConfigurationUpdateParams) (int64, error) {
	result, err := q.db.Exec(ctx, applyAgentConfigurationUpdate,
		arg.Description,
		arg.RuntimeModel,
		arg.RuntimeReasoningEffort,
		arg.ComputerID,
		arg.LocalRuntimeType,
		arg.WorkspaceGrantID,
		arg.NextRevision,
		arg.Instructions,
		arg.ActorID,
		arg.TenantID,
		arg.ExpectedRevision,
	)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected(), nil
}

const applyAgentProfileUpdate = `-- name: ApplyAgentProfileUpdate :execrows
UPDATE agent_registrations
SET instructions=$1::text,
    description=$2::text,
    configuration_revision=configuration_revision+1,
    updated_at=now()
WHERE actor_id=$3::text
  AND tenant_id=$4::text
  AND status='active'
  AND configuration_revision=$5::bigint
`

type ApplyAgentProfileUpdateParams struct {
	Instructions     string `json:"instructions"`
	Description      string `json:"description"`
	ActorID          string `json:"actor_id"`
	TenantID         string `json:"tenant_id"`
	ExpectedRevision int64  `json:"expected_revision"`
}

// A profile-only change: it advances the revision without
// replacing the execution definition.
func (q *Queries) ApplyAgentProfileUpdate(ctx context.Context, arg ApplyAgentProfileUpdateParams) (int64, error) {
	result, err := q.db.Exec(ctx, applyAgentProfileUpdate,
		arg.Instructions,
		arg.Description,
		arg.ActorID,
		arg.TenantID,
		arg.ExpectedRevision,
	)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected(), nil
}

const countLocalAgentRegistrationsByComputer = `-- name: CountLocalAgentRegistrationsByComputer :one
SELECT count(*)
FROM agent_registrations
WHERE tenant_id=$1::text
  AND computer_id=$2::text
  AND status<>'revoked'
`

type CountLocalAgentRegistrationsByComputerParams struct {
	TenantID   string `json:"tenant_id"`
	ComputerID string `json:"computer_id"`
}

func (q *Queries) CountLocalAgentRegistrationsByComputer(ctx context.Context, arg CountLocalAgentRegistrationsByComputerParams) (int64, error) {
	row := q.db.QueryRow(ctx, countLocalAgentRegistrationsByComputer, arg.TenantID, arg.ComputerID)
	var count int64
	err := row.Scan(&count)
	return count, err
}

const countSponsorGeneralAgents = `-- name: CountSponsorGeneralAgents :one
SELECT count(*)::bigint
FROM agent_registrations
WHERE tenant_id=$1::text
  AND created_by_actor_id=$2::text
  AND agent_type='general'
  AND status='active'
`

type CountSponsorGeneralAgentsParams struct {
	TenantID       string `json:"tenant_id"`
	SponsorActorID string `json:"sponsor_actor_id"`
}

func (q *Queries) CountSponsorGeneralAgents(ctx context.Context, arg CountSponsorGeneralAgentsParams) (int64, error) {
	row := q.db.QueryRow(ctx, countSponsorGeneralAgents, arg.TenantID, arg.SponsorActorID)
	var column_1 int64
	err := row.Scan(&column_1)
	return column_1, err
}

const createAgentActor = `-- name: CreateAgentActor :execrows

INSERT INTO actors(id,tenant_id,kind,display_name,handle)
VALUES($1::text,$2::text,'agent',$3::text,$4)
ON CONFLICT (id) DO NOTHING
`

type CreateAgentActorParams struct {
	ID          string      `json:"id"`
	TenantID    string      `json:"tenant_id"`
	DisplayName string      `json:"display_name"`
	Handle      pgtype.Text `json:"handle"`
}

// Both creation paths write an Agent through these two inserts. A retry that
// finds the rows already written reads them back instead.
func (q *Queries) CreateAgentActor(ctx context.Context, arg CreateAgentActorParams) (int64, error) {
	result, err := q.db.Exec(ctx, createAgentActor,
		arg.ID,
		arg.TenantID,
		arg.DisplayName,
		arg.Handle,
	)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected(), nil
}

const createAgentRegistration = `-- name: CreateAgentRegistration :one
INSERT INTO agent_registrations(
    actor_id,tenant_id,agent_management_id,status,description,avatar_key,instructions,
    runtime_model,runtime_reasoning_effort,computer_id,local_runtime_type,workspace_grant_id,
    created_by_actor_id,visibility_scope,agent_type,represented_human_actor_id,receives_all_messages
)
VALUES(
    $1::text,$2::text,$3::text,'active',
    $4::text,$5::text,$6::text,
    $7::text,$8::text,
    $9::text,$10::text,$11::text,
    $12::text,$13::text,$14::text,
    $15::text,$16::boolean
)
ON CONFLICT (actor_id) DO NOTHING
RETURNING actor_id,tenant_id,agent_management_id,status,instructions,runtime_model,created_by_actor_id,
          created_at,updated_at,computer_id,local_runtime_type,workspace_grant_id,visibility_scope,
          description,configuration_revision,agent_type,represented_human_actor_id,
          user_artifact_owner_actor_id,runtime_reasoning_effort,avatar_key,
          runtime_configuration_revision,assignment_revision
`

type CreateAgentRegistrationParams struct {
	ActorID                 string      `json:"actor_id"`
	TenantID                string      `json:"tenant_id"`
	AgentManagementID       string      `json:"agent_management_id"`
	Description             string      `json:"description"`
	AvatarKey               pgtype.Text `json:"avatar_key"`
	Instructions            string      `json:"instructions"`
	RuntimeModel            string      `json:"runtime_model"`
	RuntimeReasoningEffort  pgtype.Text `json:"runtime_reasoning_effort"`
	ComputerID              string      `json:"computer_id"`
	LocalRuntimeType        string      `json:"local_runtime_type"`
	WorkspaceGrantID        string      `json:"workspace_grant_id"`
	CreatedByActorID        string      `json:"created_by_actor_id"`
	VisibilityScope         string      `json:"visibility_scope"`
	AgentType               string      `json:"agent_type"`
	RepresentedHumanActorID pgtype.Text `json:"represented_human_actor_id"`
	ReceivesAllMessages     bool        `json:"receives_all_messages"`
}

type CreateAgentRegistrationRow struct {
	ActorID                      string             `json:"actor_id"`
	TenantID                     string             `json:"tenant_id"`
	AgentManagementID            pgtype.Text        `json:"agent_management_id"`
	Status                       string             `json:"status"`
	Instructions                 string             `json:"instructions"`
	RuntimeModel                 string             `json:"runtime_model"`
	CreatedByActorID             string             `json:"created_by_actor_id"`
	CreatedAt                    pgtype.Timestamptz `json:"created_at"`
	UpdatedAt                    pgtype.Timestamptz `json:"updated_at"`
	ComputerID                   pgtype.Text        `json:"computer_id"`
	LocalRuntimeType             pgtype.Text        `json:"local_runtime_type"`
	WorkspaceGrantID             pgtype.Text        `json:"workspace_grant_id"`
	VisibilityScope              string             `json:"visibility_scope"`
	Description                  string             `json:"description"`
	ConfigurationRevision        int64              `json:"configuration_revision"`
	AgentType                    string             `json:"agent_type"`
	RepresentedHumanActorID      pgtype.Text        `json:"represented_human_actor_id"`
	UserArtifactOwnerActorID     pgtype.Text        `json:"user_artifact_owner_actor_id"`
	RuntimeReasoningEffort       pgtype.Text        `json:"runtime_reasoning_effort"`
	AvatarKey                    pgtype.Text        `json:"avatar_key"`
	RuntimeConfigurationRevision int64              `json:"runtime_configuration_revision"`
	AssignmentRevision           int64              `json:"assignment_revision"`
}

// Registration reads name their columns so the avatar image and template
// Routines are never loaded with them.
func (q *Queries) CreateAgentRegistration(ctx context.Context, arg CreateAgentRegistrationParams) (CreateAgentRegistrationRow, error) {
	row := q.db.QueryRow(ctx, createAgentRegistration,
		arg.ActorID,
		arg.TenantID,
		arg.AgentManagementID,
		arg.Description,
		arg.AvatarKey,
		arg.Instructions,
		arg.RuntimeModel,
		arg.RuntimeReasoningEffort,
		arg.ComputerID,
		arg.LocalRuntimeType,
		arg.WorkspaceGrantID,
		arg.CreatedByActorID,
		arg.VisibilityScope,
		arg.AgentType,
		arg.RepresentedHumanActorID,
		arg.ReceivesAllMessages,
	)
	var i CreateAgentRegistrationRow
	err := row.Scan(
		&i.ActorID,
		&i.TenantID,
		&i.AgentManagementID,
		&i.Status,
		&i.Instructions,
		&i.RuntimeModel,
		&i.CreatedByActorID,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.ComputerID,
		&i.LocalRuntimeType,
		&i.WorkspaceGrantID,
		&i.VisibilityScope,
		&i.Description,
		&i.ConfigurationRevision,
		&i.AgentType,
		&i.RepresentedHumanActorID,
		&i.UserArtifactOwnerActorID,
		&i.RuntimeReasoningEffort,
		&i.AvatarKey,
		&i.RuntimeConfigurationRevision,
		&i.AssignmentRevision,
	)
	return i, err
}

const deleteAgentAvatarImage = `-- name: DeleteAgentAvatarImage :exec
UPDATE agent_registrations
SET avatar_image=NULL,avatar_updated_at=NULL
WHERE actor_id=$1::text AND tenant_id=$2::text
`

type DeleteAgentAvatarImageParams struct {
	ActorID  string `json:"actor_id"`
	TenantID string `json:"tenant_id"`
}

func (q *Queries) DeleteAgentAvatarImage(ctx context.Context, arg DeleteAgentAvatarImageParams) error {
	_, err := q.db.Exec(ctx, deleteAgentAvatarImage, arg.ActorID, arg.TenantID)
	return err
}

const getActiveAgentRegistrationByExternalID = `-- name: GetActiveAgentRegistrationByExternalID :one
SELECT actor_id,tenant_id,agent_management_id,status,description,avatar_key,configuration_revision,instructions,runtime_model,runtime_reasoning_effort,
       computer_id,local_runtime_type,workspace_grant_id,
       created_by_actor_id,visibility_scope,agent_type,created_at,updated_at
FROM agent_registrations
WHERE agent_management_id=$1 AND status='active'
`

type GetActiveAgentRegistrationByExternalIDRow struct {
	ActorID                string             `json:"actor_id"`
	TenantID               string             `json:"tenant_id"`
	AgentManagementID      pgtype.Text        `json:"agent_management_id"`
	Status                 string             `json:"status"`
	Description            string             `json:"description"`
	AvatarKey              pgtype.Text        `json:"avatar_key"`
	ConfigurationRevision  int64              `json:"configuration_revision"`
	Instructions           string             `json:"instructions"`
	RuntimeModel           string             `json:"runtime_model"`
	RuntimeReasoningEffort pgtype.Text        `json:"runtime_reasoning_effort"`
	ComputerID             pgtype.Text        `json:"computer_id"`
	LocalRuntimeType       pgtype.Text        `json:"local_runtime_type"`
	WorkspaceGrantID       pgtype.Text        `json:"workspace_grant_id"`
	CreatedByActorID       string             `json:"created_by_actor_id"`
	VisibilityScope        string             `json:"visibility_scope"`
	AgentType              string             `json:"agent_type"`
	CreatedAt              pgtype.Timestamptz `json:"created_at"`
	UpdatedAt              pgtype.Timestamptz `json:"updated_at"`
}

func (q *Queries) GetActiveAgentRegistrationByExternalID(ctx context.Context, agentManagementID pgtype.Text) (GetActiveAgentRegistrationByExternalIDRow, error) {
	row := q.db.QueryRow(ctx, getActiveAgentRegistrationByExternalID, agentManagementID)
	var i GetActiveAgentRegistrationByExternalIDRow
	err := row.Scan(
		&i.ActorID,
		&i.TenantID,
		&i.AgentManagementID,
		&i.Status,
		&i.Description,
		&i.AvatarKey,
		&i.ConfigurationRevision,
		&i.Instructions,
		&i.RuntimeModel,
		&i.RuntimeReasoningEffort,
		&i.ComputerID,
		&i.LocalRuntimeType,
		&i.WorkspaceGrantID,
		&i.CreatedByActorID,
		&i.VisibilityScope,
		&i.AgentType,
		&i.CreatedAt,
		&i.UpdatedAt,
	)
	return i, err
}

const getActiveAgentRegistrationForAdmission = `-- name: GetActiveAgentRegistrationForAdmission :one
SELECT actor_id,tenant_id,agent_management_id,status,description,avatar_key,configuration_revision,instructions,runtime_model,runtime_reasoning_effort,
       computer_id,local_runtime_type,workspace_grant_id,
       created_by_actor_id,visibility_scope,agent_type,created_at,updated_at
FROM agent_registrations
WHERE actor_id=$1 AND tenant_id=$2 AND status='active'
FOR SHARE
`

type GetActiveAgentRegistrationForAdmissionParams struct {
	ActorID  string `json:"actor_id"`
	TenantID string `json:"tenant_id"`
}

type GetActiveAgentRegistrationForAdmissionRow struct {
	ActorID                string             `json:"actor_id"`
	TenantID               string             `json:"tenant_id"`
	AgentManagementID      pgtype.Text        `json:"agent_management_id"`
	Status                 string             `json:"status"`
	Description            string             `json:"description"`
	AvatarKey              pgtype.Text        `json:"avatar_key"`
	ConfigurationRevision  int64              `json:"configuration_revision"`
	Instructions           string             `json:"instructions"`
	RuntimeModel           string             `json:"runtime_model"`
	RuntimeReasoningEffort pgtype.Text        `json:"runtime_reasoning_effort"`
	ComputerID             pgtype.Text        `json:"computer_id"`
	LocalRuntimeType       pgtype.Text        `json:"local_runtime_type"`
	WorkspaceGrantID       pgtype.Text        `json:"workspace_grant_id"`
	CreatedByActorID       string             `json:"created_by_actor_id"`
	VisibilityScope        string             `json:"visibility_scope"`
	AgentType              string             `json:"agent_type"`
	CreatedAt              pgtype.Timestamptz `json:"created_at"`
	UpdatedAt              pgtype.Timestamptz `json:"updated_at"`
}

func (q *Queries) GetActiveAgentRegistrationForAdmission(ctx context.Context, arg GetActiveAgentRegistrationForAdmissionParams) (GetActiveAgentRegistrationForAdmissionRow, error) {
	row := q.db.QueryRow(ctx, getActiveAgentRegistrationForAdmission, arg.ActorID, arg.TenantID)
	var i GetActiveAgentRegistrationForAdmissionRow
	err := row.Scan(
		&i.ActorID,
		&i.TenantID,
		&i.AgentManagementID,
		&i.Status,
		&i.Description,
		&i.AvatarKey,
		&i.ConfigurationRevision,
		&i.Instructions,
		&i.RuntimeModel,
		&i.RuntimeReasoningEffort,
		&i.ComputerID,
		&i.LocalRuntimeType,
		&i.WorkspaceGrantID,
		&i.CreatedByActorID,
		&i.VisibilityScope,
		&i.AgentType,
		&i.CreatedAt,
		&i.UpdatedAt,
	)
	return i, err
}

const getAgentLocalComputerPlacement = `-- name: GetAgentLocalComputerPlacement :one
SELECT registration.computer_id::text AS computer_id, computer.owner_actor_id
FROM agent_registrations registration
JOIN local_computers computer
  ON computer.computer_id=registration.computer_id AND computer.removed_at IS NULL
 AND computer.owner_tenant_id=registration.tenant_id AND computer.owner_actor_id=registration.created_by_actor_id
WHERE registration.actor_id=$1::text AND registration.tenant_id=$2::text
  AND coalesce(registration.computer_id,'')<>''
`

type GetAgentLocalComputerPlacementParams struct {
	ActorID  string `json:"actor_id"`
	TenantID string `json:"tenant_id"`
}

type GetAgentLocalComputerPlacementRow struct {
	ComputerID   string `json:"computer_id"`
	OwnerActorID string `json:"owner_actor_id"`
}

// The Computer an Agent runs on, while its Sponsor still owns it.
func (q *Queries) GetAgentLocalComputerPlacement(ctx context.Context, arg GetAgentLocalComputerPlacementParams) (GetAgentLocalComputerPlacementRow, error) {
	row := q.db.QueryRow(ctx, getAgentLocalComputerPlacement, arg.ActorID, arg.TenantID)
	var i GetAgentLocalComputerPlacementRow
	err := row.Scan(&i.ComputerID, &i.OwnerActorID)
	return i, err
}

const getAgentRegistration = `-- name: GetAgentRegistration :one
SELECT actor_id,tenant_id,agent_management_id,status,instructions,runtime_model,created_by_actor_id,
       created_at,updated_at,computer_id,local_runtime_type,workspace_grant_id,visibility_scope,
       description,configuration_revision,agent_type,represented_human_actor_id,
       user_artifact_owner_actor_id,runtime_reasoning_effort,avatar_key,
       runtime_configuration_revision,assignment_revision
FROM agent_registrations
WHERE actor_id=$1::text AND tenant_id=$2::text
`

type GetAgentRegistrationParams struct {
	ActorID  string `json:"actor_id"`
	TenantID string `json:"tenant_id"`
}

type GetAgentRegistrationRow struct {
	ActorID                      string             `json:"actor_id"`
	TenantID                     string             `json:"tenant_id"`
	AgentManagementID            pgtype.Text        `json:"agent_management_id"`
	Status                       string             `json:"status"`
	Instructions                 string             `json:"instructions"`
	RuntimeModel                 string             `json:"runtime_model"`
	CreatedByActorID             string             `json:"created_by_actor_id"`
	CreatedAt                    pgtype.Timestamptz `json:"created_at"`
	UpdatedAt                    pgtype.Timestamptz `json:"updated_at"`
	ComputerID                   pgtype.Text        `json:"computer_id"`
	LocalRuntimeType             pgtype.Text        `json:"local_runtime_type"`
	WorkspaceGrantID             pgtype.Text        `json:"workspace_grant_id"`
	VisibilityScope              string             `json:"visibility_scope"`
	Description                  string             `json:"description"`
	ConfigurationRevision        int64              `json:"configuration_revision"`
	AgentType                    string             `json:"agent_type"`
	RepresentedHumanActorID      pgtype.Text        `json:"represented_human_actor_id"`
	UserArtifactOwnerActorID     pgtype.Text        `json:"user_artifact_owner_actor_id"`
	RuntimeReasoningEffort       pgtype.Text        `json:"runtime_reasoning_effort"`
	AvatarKey                    pgtype.Text        `json:"avatar_key"`
	RuntimeConfigurationRevision int64              `json:"runtime_configuration_revision"`
	AssignmentRevision           int64              `json:"assignment_revision"`
}

func (q *Queries) GetAgentRegistration(ctx context.Context, arg GetAgentRegistrationParams) (GetAgentRegistrationRow, error) {
	row := q.db.QueryRow(ctx, getAgentRegistration, arg.ActorID, arg.TenantID)
	var i GetAgentRegistrationRow
	err := row.Scan(
		&i.ActorID,
		&i.TenantID,
		&i.AgentManagementID,
		&i.Status,
		&i.Instructions,
		&i.RuntimeModel,
		&i.CreatedByActorID,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.ComputerID,
		&i.LocalRuntimeType,
		&i.WorkspaceGrantID,
		&i.VisibilityScope,
		&i.Description,
		&i.ConfigurationRevision,
		&i.AgentType,
		&i.RepresentedHumanActorID,
		&i.UserArtifactOwnerActorID,
		&i.RuntimeReasoningEffort,
		&i.AvatarKey,
		&i.RuntimeConfigurationRevision,
		&i.AssignmentRevision,
	)
	return i, err
}

const getAgentRegistrationByActor = `-- name: GetAgentRegistrationByActor :one
SELECT actor_id,tenant_id,agent_management_id,status,description,avatar_key,configuration_revision,instructions,runtime_model,runtime_reasoning_effort,
       computer_id,local_runtime_type,workspace_grant_id,
       created_by_actor_id,visibility_scope,agent_type,created_at,updated_at
FROM agent_registrations
WHERE actor_id=$1 AND tenant_id=$2
`

type GetAgentRegistrationByActorParams struct {
	ActorID  string `json:"actor_id"`
	TenantID string `json:"tenant_id"`
}

type GetAgentRegistrationByActorRow struct {
	ActorID                string             `json:"actor_id"`
	TenantID               string             `json:"tenant_id"`
	AgentManagementID      pgtype.Text        `json:"agent_management_id"`
	Status                 string             `json:"status"`
	Description            string             `json:"description"`
	AvatarKey              pgtype.Text        `json:"avatar_key"`
	ConfigurationRevision  int64              `json:"configuration_revision"`
	Instructions           string             `json:"instructions"`
	RuntimeModel           string             `json:"runtime_model"`
	RuntimeReasoningEffort pgtype.Text        `json:"runtime_reasoning_effort"`
	ComputerID             pgtype.Text        `json:"computer_id"`
	LocalRuntimeType       pgtype.Text        `json:"local_runtime_type"`
	WorkspaceGrantID       pgtype.Text        `json:"workspace_grant_id"`
	CreatedByActorID       string             `json:"created_by_actor_id"`
	VisibilityScope        string             `json:"visibility_scope"`
	AgentType              string             `json:"agent_type"`
	CreatedAt              pgtype.Timestamptz `json:"created_at"`
	UpdatedAt              pgtype.Timestamptz `json:"updated_at"`
}

func (q *Queries) GetAgentRegistrationByActor(ctx context.Context, arg GetAgentRegistrationByActorParams) (GetAgentRegistrationByActorRow, error) {
	row := q.db.QueryRow(ctx, getAgentRegistrationByActor, arg.ActorID, arg.TenantID)
	var i GetAgentRegistrationByActorRow
	err := row.Scan(
		&i.ActorID,
		&i.TenantID,
		&i.AgentManagementID,
		&i.Status,
		&i.Description,
		&i.AvatarKey,
		&i.ConfigurationRevision,
		&i.Instructions,
		&i.RuntimeModel,
		&i.RuntimeReasoningEffort,
		&i.ComputerID,
		&i.LocalRuntimeType,
		&i.WorkspaceGrantID,
		&i.CreatedByActorID,
		&i.VisibilityScope,
		&i.AgentType,
		&i.CreatedAt,
		&i.UpdatedAt,
	)
	return i, err
}

const getAgentRegistrationForDeletion = `-- name: GetAgentRegistrationForDeletion :one
SELECT actor_id,tenant_id,agent_management_id,status,description,avatar_key,configuration_revision,instructions,runtime_model,runtime_reasoning_effort,
       computer_id,local_runtime_type,workspace_grant_id,
       created_by_actor_id,visibility_scope,agent_type,created_at,updated_at
FROM agent_registrations
WHERE actor_id=$1 AND tenant_id=$2
FOR UPDATE
`

type GetAgentRegistrationForDeletionParams struct {
	ActorID  string `json:"actor_id"`
	TenantID string `json:"tenant_id"`
}

type GetAgentRegistrationForDeletionRow struct {
	ActorID                string             `json:"actor_id"`
	TenantID               string             `json:"tenant_id"`
	AgentManagementID      pgtype.Text        `json:"agent_management_id"`
	Status                 string             `json:"status"`
	Description            string             `json:"description"`
	AvatarKey              pgtype.Text        `json:"avatar_key"`
	ConfigurationRevision  int64              `json:"configuration_revision"`
	Instructions           string             `json:"instructions"`
	RuntimeModel           string             `json:"runtime_model"`
	RuntimeReasoningEffort pgtype.Text        `json:"runtime_reasoning_effort"`
	ComputerID             pgtype.Text        `json:"computer_id"`
	LocalRuntimeType       pgtype.Text        `json:"local_runtime_type"`
	WorkspaceGrantID       pgtype.Text        `json:"workspace_grant_id"`
	CreatedByActorID       string             `json:"created_by_actor_id"`
	VisibilityScope        string             `json:"visibility_scope"`
	AgentType              string             `json:"agent_type"`
	CreatedAt              pgtype.Timestamptz `json:"created_at"`
	UpdatedAt              pgtype.Timestamptz `json:"updated_at"`
}

func (q *Queries) GetAgentRegistrationForDeletion(ctx context.Context, arg GetAgentRegistrationForDeletionParams) (GetAgentRegistrationForDeletionRow, error) {
	row := q.db.QueryRow(ctx, getAgentRegistrationForDeletion, arg.ActorID, arg.TenantID)
	var i GetAgentRegistrationForDeletionRow
	err := row.Scan(
		&i.ActorID,
		&i.TenantID,
		&i.AgentManagementID,
		&i.Status,
		&i.Description,
		&i.AvatarKey,
		&i.ConfigurationRevision,
		&i.Instructions,
		&i.RuntimeModel,
		&i.RuntimeReasoningEffort,
		&i.ComputerID,
		&i.LocalRuntimeType,
		&i.WorkspaceGrantID,
		&i.CreatedByActorID,
		&i.VisibilityScope,
		&i.AgentType,
		&i.CreatedAt,
		&i.UpdatedAt,
	)
	return i, err
}

const getAgentRegistrationForIdentityByExternalID = `-- name: GetAgentRegistrationForIdentityByExternalID :one
SELECT actor_id,tenant_id,agent_management_id,status,instructions,runtime_model,created_by_actor_id,
       created_at,updated_at,computer_id,local_runtime_type,workspace_grant_id,visibility_scope,
       description,configuration_revision,agent_type,represented_human_actor_id,
       user_artifact_owner_actor_id,runtime_reasoning_effort,avatar_key,
       runtime_configuration_revision,assignment_revision
FROM agent_registrations
WHERE agent_management_id=$1 AND status='active'
`

type GetAgentRegistrationForIdentityByExternalIDRow struct {
	ActorID                      string             `json:"actor_id"`
	TenantID                     string             `json:"tenant_id"`
	AgentManagementID            pgtype.Text        `json:"agent_management_id"`
	Status                       string             `json:"status"`
	Instructions                 string             `json:"instructions"`
	RuntimeModel                 string             `json:"runtime_model"`
	CreatedByActorID             string             `json:"created_by_actor_id"`
	CreatedAt                    pgtype.Timestamptz `json:"created_at"`
	UpdatedAt                    pgtype.Timestamptz `json:"updated_at"`
	ComputerID                   pgtype.Text        `json:"computer_id"`
	LocalRuntimeType             pgtype.Text        `json:"local_runtime_type"`
	WorkspaceGrantID             pgtype.Text        `json:"workspace_grant_id"`
	VisibilityScope              string             `json:"visibility_scope"`
	Description                  string             `json:"description"`
	ConfigurationRevision        int64              `json:"configuration_revision"`
	AgentType                    string             `json:"agent_type"`
	RepresentedHumanActorID      pgtype.Text        `json:"represented_human_actor_id"`
	UserArtifactOwnerActorID     pgtype.Text        `json:"user_artifact_owner_actor_id"`
	RuntimeReasoningEffort       pgtype.Text        `json:"runtime_reasoning_effort"`
	AvatarKey                    pgtype.Text        `json:"avatar_key"`
	RuntimeConfigurationRevision int64              `json:"runtime_configuration_revision"`
	AssignmentRevision           int64              `json:"assignment_revision"`
}

func (q *Queries) GetAgentRegistrationForIdentityByExternalID(ctx context.Context, agentManagementID pgtype.Text) (GetAgentRegistrationForIdentityByExternalIDRow, error) {
	row := q.db.QueryRow(ctx, getAgentRegistrationForIdentityByExternalID, agentManagementID)
	var i GetAgentRegistrationForIdentityByExternalIDRow
	err := row.Scan(
		&i.ActorID,
		&i.TenantID,
		&i.AgentManagementID,
		&i.Status,
		&i.Instructions,
		&i.RuntimeModel,
		&i.CreatedByActorID,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.ComputerID,
		&i.LocalRuntimeType,
		&i.WorkspaceGrantID,
		&i.VisibilityScope,
		&i.Description,
		&i.ConfigurationRevision,
		&i.AgentType,
		&i.RepresentedHumanActorID,
		&i.UserArtifactOwnerActorID,
		&i.RuntimeReasoningEffort,
		&i.AvatarKey,
		&i.RuntimeConfigurationRevision,
		&i.AssignmentRevision,
	)
	return i, err
}

const getAgentRegistrationForUpdate = `-- name: GetAgentRegistrationForUpdate :one
SELECT actor_id,tenant_id,agent_management_id,status,description,avatar_key,configuration_revision,instructions,runtime_model,runtime_reasoning_effort,
       computer_id,local_runtime_type,workspace_grant_id,
       created_by_actor_id,visibility_scope,agent_type,created_at,updated_at,
       runtime_configuration_revision,assignment_revision
FROM agent_registrations
WHERE actor_id=$1 AND tenant_id=$2
FOR UPDATE
`

type GetAgentRegistrationForUpdateParams struct {
	ActorID  string `json:"actor_id"`
	TenantID string `json:"tenant_id"`
}

type GetAgentRegistrationForUpdateRow struct {
	ActorID                      string             `json:"actor_id"`
	TenantID                     string             `json:"tenant_id"`
	AgentManagementID            pgtype.Text        `json:"agent_management_id"`
	Status                       string             `json:"status"`
	Description                  string             `json:"description"`
	AvatarKey                    pgtype.Text        `json:"avatar_key"`
	ConfigurationRevision        int64              `json:"configuration_revision"`
	Instructions                 string             `json:"instructions"`
	RuntimeModel                 string             `json:"runtime_model"`
	RuntimeReasoningEffort       pgtype.Text        `json:"runtime_reasoning_effort"`
	ComputerID                   pgtype.Text        `json:"computer_id"`
	LocalRuntimeType             pgtype.Text        `json:"local_runtime_type"`
	WorkspaceGrantID             pgtype.Text        `json:"workspace_grant_id"`
	CreatedByActorID             string             `json:"created_by_actor_id"`
	VisibilityScope              string             `json:"visibility_scope"`
	AgentType                    string             `json:"agent_type"`
	CreatedAt                    pgtype.Timestamptz `json:"created_at"`
	UpdatedAt                    pgtype.Timestamptz `json:"updated_at"`
	RuntimeConfigurationRevision int64              `json:"runtime_configuration_revision"`
	AssignmentRevision           int64              `json:"assignment_revision"`
}

func (q *Queries) GetAgentRegistrationForUpdate(ctx context.Context, arg GetAgentRegistrationForUpdateParams) (GetAgentRegistrationForUpdateRow, error) {
	row := q.db.QueryRow(ctx, getAgentRegistrationForUpdate, arg.ActorID, arg.TenantID)
	var i GetAgentRegistrationForUpdateRow
	err := row.Scan(
		&i.ActorID,
		&i.TenantID,
		&i.AgentManagementID,
		&i.Status,
		&i.Description,
		&i.AvatarKey,
		&i.ConfigurationRevision,
		&i.Instructions,
		&i.RuntimeModel,
		&i.RuntimeReasoningEffort,
		&i.ComputerID,
		&i.LocalRuntimeType,
		&i.WorkspaceGrantID,
		&i.CreatedByActorID,
		&i.VisibilityScope,
		&i.AgentType,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.RuntimeConfigurationRevision,
		&i.AssignmentRevision,
	)
	return i, err
}

const getAnotherMeRepresentedHumanIdentityByExternalID = `-- name: GetAnotherMeRepresentedHumanIdentityByExternalID :one
SELECT human.id AS actor_id,
       human.display_name,
       -- Version 0 means the Human has no memory.md yet.
       COALESCE(memory.version, 0)::integer AS memory_version,
       COALESCE(memory.markdown, '')::text AS memory_markdown
FROM agent_registrations registration
JOIN actors human
  ON human.id=registration.represented_human_actor_id
 AND human.tenant_id=registration.tenant_id
 AND human.kind='human'
LEFT JOIN LATERAL (
    SELECT revision.version, revision.markdown
    FROM user_memory_revisions revision
    WHERE revision.tenant_id=registration.tenant_id
      AND revision.owner_actor_id=registration.represented_human_actor_id
    ORDER BY revision.version DESC
    LIMIT 1
) memory ON true
WHERE registration.agent_management_id=$1
  AND registration.status='active'
  AND registration.agent_type='anotherme'
`

type GetAnotherMeRepresentedHumanIdentityByExternalIDRow struct {
	ActorID        string `json:"actor_id"`
	DisplayName    string `json:"display_name"`
	MemoryVersion  int32  `json:"memory_version"`
	MemoryMarkdown string `json:"memory_markdown"`
}

func (q *Queries) GetAnotherMeRepresentedHumanIdentityByExternalID(ctx context.Context, agentManagementID pgtype.Text) (GetAnotherMeRepresentedHumanIdentityByExternalIDRow, error) {
	row := q.db.QueryRow(ctx, getAnotherMeRepresentedHumanIdentityByExternalID, agentManagementID)
	var i GetAnotherMeRepresentedHumanIdentityByExternalIDRow
	err := row.Scan(
		&i.ActorID,
		&i.DisplayName,
		&i.MemoryVersion,
		&i.MemoryMarkdown,
	)
	return i, err
}

const getVisibleAgentAvatarImage = `-- name: GetVisibleAgentAvatarImage :one
SELECT registration.avatar_image::text AS avatar_image,registration.avatar_updated_at::timestamptz AS updated_at
FROM agent_registrations registration
JOIN actors caller
  ON caller.tenant_id=registration.tenant_id
 AND caller.account_id=$1::text
 AND caller.kind='human'
WHERE registration.tenant_id=$2::text
  AND registration.actor_id=$3::text
  AND registration.avatar_image IS NOT NULL
  AND registration.status='active'
  AND (
    registration.visibility_scope='workspace' OR
    registration.created_by_actor_id=caller.id OR
    EXISTS (
      SELECT 1
      FROM active_room_members caller_membership
      JOIN active_room_members agent_membership
        ON agent_membership.room_id=caller_membership.room_id
       AND agent_membership.actor_id=registration.actor_id
      WHERE caller_membership.actor_id=caller.id
    )
  )
`

type GetVisibleAgentAvatarImageParams struct {
	AccountID string `json:"account_id"`
	TenantID  string `json:"tenant_id"`
	ActorID   string `json:"actor_id"`
}

type GetVisibleAgentAvatarImageRow struct {
	AvatarImage string             `json:"avatar_image"`
	UpdatedAt   pgtype.Timestamptz `json:"updated_at"`
}

// The image is visible exactly when its Agent is in the caller's Tenant Agent
// directory (ListTenantAgentsForAccount).
func (q *Queries) GetVisibleAgentAvatarImage(ctx context.Context, arg GetVisibleAgentAvatarImageParams) (GetVisibleAgentAvatarImageRow, error) {
	row := q.db.QueryRow(ctx, getVisibleAgentAvatarImage, arg.AccountID, arg.TenantID, arg.ActorID)
	var i GetVisibleAgentAvatarImageRow
	err := row.Scan(&i.AvatarImage, &i.UpdatedAt)
	return i, err
}

const hasPendingAgentLocalWork = `-- name: HasPendingAgentLocalWork :one
SELECT EXISTS (
  SELECT 1 FROM agent_execution_contexts context
  WHERE context.tenant_id=$1 AND context.agent_actor_id=$2
    AND (EXISTS (SELECT 1 FROM agent_local_runs run
                 WHERE run.context_key=context.context_key AND run.status='running')
      OR EXISTS (SELECT 1 FROM agent_runtime_inputs input
                 WHERE input.context_key=context.context_key AND input.status='steering'))
)
`

type HasPendingAgentLocalWorkParams struct {
	TenantID     string `json:"tenant_id"`
	AgentActorID string `json:"agent_actor_id"`
}

// Work a Computer holds: running Runs and their steers. Queued Runs belong to
// no Computer and run after the update.
func (q *Queries) HasPendingAgentLocalWork(ctx context.Context, arg HasPendingAgentLocalWorkParams) (bool, error) {
	row := q.db.QueryRow(ctx, hasPendingAgentLocalWork, arg.TenantID, arg.AgentActorID)
	var exists bool
	err := row.Scan(&exists)
	return exists, err
}

const isActiveRoomMember = `-- name: IsActiveRoomMember :one
SELECT EXISTS(
  SELECT 1 FROM active_room_members
  WHERE room_id=$1::text AND tenant_id=$2::text AND actor_id=$3::text
)::boolean
`

type IsActiveRoomMemberParams struct {
	RoomID   string `json:"room_id"`
	TenantID string `json:"tenant_id"`
	ActorID  string `json:"actor_id"`
}

func (q *Queries) IsActiveRoomMember(ctx context.Context, arg IsActiveRoomMemberParams) (bool, error) {
	row := q.db.QueryRow(ctx, isActiveRoomMember, arg.RoomID, arg.TenantID, arg.ActorID)
	var column_1 bool
	err := row.Scan(&column_1)
	return column_1, err
}

const isTenantDirectRoom = `-- name: IsTenantDirectRoom :one
SELECT EXISTS(
  SELECT 1 FROM rooms
  WHERE id=$1::text AND tenant_id=$2::text AND direct_agent_actor_id IS NOT NULL
)::boolean
`

type IsTenantDirectRoomParams struct {
	RoomID   string `json:"room_id"`
	TenantID string `json:"tenant_id"`
}

func (q *Queries) IsTenantDirectRoom(ctx context.Context, arg IsTenantDirectRoomParams) (bool, error) {
	row := q.db.QueryRow(ctx, isTenantDirectRoom, arg.RoomID, arg.TenantID)
	var column_1 bool
	err := row.Scan(&column_1)
	return column_1, err
}

const listAgentAvatarImageVersions = `-- name: ListAgentAvatarImageVersions :many
SELECT actor_id,avatar_updated_at::timestamptz AS updated_at
FROM agent_registrations
WHERE tenant_id=$1::text AND actor_id=ANY($2::text[])
  AND avatar_image IS NOT NULL
`

type ListAgentAvatarImageVersionsParams struct {
	TenantID string   `json:"tenant_id"`
	ActorIds []string `json:"actor_ids"`
}

type ListAgentAvatarImageVersionsRow struct {
	ActorID   string             `json:"actor_id"`
	UpdatedAt pgtype.Timestamptz `json:"updated_at"`
}

// Agent directories carry only each image's version; the bytes are fetched by
// URL, once per version.
func (q *Queries) ListAgentAvatarImageVersions(ctx context.Context, arg ListAgentAvatarImageVersionsParams) ([]ListAgentAvatarImageVersionsRow, error) {
	rows, err := q.db.Query(ctx, listAgentAvatarImageVersions, arg.TenantID, arg.ActorIds)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []ListAgentAvatarImageVersionsRow{}
	for rows.Next() {
		var i ListAgentAvatarImageVersionsRow
		if err := rows.Scan(&i.ActorID, &i.UpdatedAt); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listAgentRoomIDsForDeletion = `-- name: ListAgentRoomIDsForDeletion :many
SELECT membership.room_id
FROM room_members membership
WHERE membership.tenant_id=$1 AND membership.actor_id=$2
  AND NOT EXISTS (SELECT 1 FROM rooms direct
    WHERE direct.id=membership.room_id AND direct.direct_agent_actor_id IS NOT NULL)
ORDER BY membership.room_id
`

type ListAgentRoomIDsForDeletionParams struct {
	TenantID string `json:"tenant_id"`
	ActorID  string `json:"actor_id"`
}

func (q *Queries) ListAgentRoomIDsForDeletion(ctx context.Context, arg ListAgentRoomIDsForDeletionParams) ([]string, error) {
	rows, err := q.db.Query(ctx, listAgentRoomIDsForDeletion, arg.TenantID, arg.ActorID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []string{}
	for rows.Next() {
		var room_id string
		if err := rows.Scan(&room_id); err != nil {
			return nil, err
		}
		items = append(items, room_id)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listAgentRoomIDsForPendingDecisionCheck = `-- name: ListAgentRoomIDsForPendingDecisionCheck :many
SELECT membership.room_id
FROM room_members membership
WHERE membership.tenant_id=$1 AND membership.actor_id=$2
ORDER BY membership.room_id
`

type ListAgentRoomIDsForPendingDecisionCheckParams struct {
	TenantID string `json:"tenant_id"`
	ActorID  string `json:"actor_id"`
}

func (q *Queries) ListAgentRoomIDsForPendingDecisionCheck(ctx context.Context, arg ListAgentRoomIDsForPendingDecisionCheckParams) ([]string, error) {
	rows, err := q.db.Query(ctx, listAgentRoomIDsForPendingDecisionCheck, arg.TenantID, arg.ActorID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []string{}
	for rows.Next() {
		var room_id string
		if err := rows.Scan(&room_id); err != nil {
			return nil, err
		}
		items = append(items, room_id)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listLocalAgentComputerObservations = `-- name: ListLocalAgentComputerObservations :many
SELECT registration.actor_id, computer.computer_id, computer.display_name,
       computer.status, computer.runtime_diagnostics, computer.last_seen_at
FROM agent_registrations registration
JOIN local_computers computer ON computer.computer_id=registration.computer_id
  AND computer.owner_tenant_id=registration.tenant_id
  AND computer.owner_actor_id=registration.created_by_actor_id
WHERE registration.tenant_id=$1::text
  AND registration.actor_id=ANY($2::text[])
  AND computer.status<>'removed'
`

type ListLocalAgentComputerObservationsParams struct {
	TenantID string   `json:"tenant_id"`
	ActorIds []string `json:"actor_ids"`
}

type ListLocalAgentComputerObservationsRow struct {
	ActorID            string             `json:"actor_id"`
	ComputerID         string             `json:"computer_id"`
	DisplayName        string             `json:"display_name"`
	Status             string             `json:"status"`
	RuntimeDiagnostics []byte             `json:"runtime_diagnostics"`
	LastSeenAt         pgtype.Timestamptz `json:"last_seen_at"`
}

func (q *Queries) ListLocalAgentComputerObservations(ctx context.Context, arg ListLocalAgentComputerObservationsParams) ([]ListLocalAgentComputerObservationsRow, error) {
	rows, err := q.db.Query(ctx, listLocalAgentComputerObservations, arg.TenantID, arg.ActorIds)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []ListLocalAgentComputerObservationsRow{}
	for rows.Next() {
		var i ListLocalAgentComputerObservationsRow
		if err := rows.Scan(
			&i.ActorID,
			&i.ComputerID,
			&i.DisplayName,
			&i.Status,
			&i.RuntimeDiagnostics,
			&i.LastSeenAt,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listTenantAgentsForAccount = `-- name: ListTenantAgentsForAccount :many
SELECT registration.actor_id,
       registration.tenant_id,
       registration.agent_management_id,
       registration.status,
       registration.description,
       registration.avatar_key,
       registration.configuration_revision,
       registration.instructions,
       
       registration.runtime_model,
       registration.runtime_reasoning_effort,
       registration.computer_id,
       registration.local_runtime_type,
       registration.workspace_grant_id,
       registration.created_by_actor_id,
       registration.visibility_scope,
       registration.agent_type,
       registration.created_at,
       registration.updated_at,
       agent.kind AS agent_kind,
       agent.display_name AS agent_display_name,
       agent.account_id AS agent_account_id,
       agent.handle AS agent_handle,
       agent.created_at AS agent_created_at,
       creator.kind AS creator_kind,
       creator.display_name AS creator_display_name,
       creator.account_id AS creator_account_id,
       creator.handle AS creator_handle,
       creator.created_at AS creator_created_at,
       coalesce(active_tasks.count,0)::bigint AS active_task_count
FROM agent_registrations registration
JOIN actors agent
  ON agent.id=registration.actor_id AND agent.tenant_id=registration.tenant_id
JOIN actors creator
  ON creator.id=registration.created_by_actor_id AND creator.tenant_id=registration.tenant_id
JOIN actors caller
  ON caller.tenant_id=registration.tenant_id
 AND caller.account_id=$1::text
 AND caller.kind='human'
LEFT JOIN LATERAL (
  SELECT count(*)::bigint AS count
  FROM task_execution_participants participant
  JOIN work_items item
    ON item.id=participant.task_id AND item.tenant_id=participant.tenant_id
   AND item.task_execution_generation=participant.generation
  WHERE participant.tenant_id=registration.tenant_id
    AND participant.actor_id=registration.actor_id
    AND item.task_execution_status='running'
) active_tasks ON true
WHERE registration.tenant_id=$2::text
  AND registration.status='active'
  AND (
    registration.visibility_scope='workspace' OR
    registration.created_by_actor_id=caller.id OR
    EXISTS (
      SELECT 1
      FROM active_room_members caller_membership
      JOIN active_room_members agent_membership
        ON agent_membership.room_id=caller_membership.room_id
       AND agent_membership.actor_id=registration.actor_id
      WHERE caller_membership.actor_id=caller.id
    )
  )
  AND (
    $3::text='' OR
    (registration.created_at,registration.actor_id)>(
      SELECT created_at,actor_id
      FROM agent_registrations
      WHERE actor_id=$3::text AND tenant_id=$2::text
    )
  )
ORDER BY registration.created_at,registration.actor_id
LIMIT $4::int
`

type ListTenantAgentsForAccountParams struct {
	AccountID string `json:"account_id"`
	TenantID  string `json:"tenant_id"`
	Cursor    string `json:"cursor"`
	PageLimit int32  `json:"page_limit"`
}

type ListTenantAgentsForAccountRow struct {
	ActorID                string             `json:"actor_id"`
	TenantID               string             `json:"tenant_id"`
	AgentManagementID      pgtype.Text        `json:"agent_management_id"`
	Status                 string             `json:"status"`
	Description            string             `json:"description"`
	AvatarKey              pgtype.Text        `json:"avatar_key"`
	ConfigurationRevision  int64              `json:"configuration_revision"`
	Instructions           string             `json:"instructions"`
	RuntimeModel           string             `json:"runtime_model"`
	RuntimeReasoningEffort pgtype.Text        `json:"runtime_reasoning_effort"`
	ComputerID             pgtype.Text        `json:"computer_id"`
	LocalRuntimeType       pgtype.Text        `json:"local_runtime_type"`
	WorkspaceGrantID       pgtype.Text        `json:"workspace_grant_id"`
	CreatedByActorID       string             `json:"created_by_actor_id"`
	VisibilityScope        string             `json:"visibility_scope"`
	AgentType              string             `json:"agent_type"`
	CreatedAt              pgtype.Timestamptz `json:"created_at"`
	UpdatedAt              pgtype.Timestamptz `json:"updated_at"`
	AgentKind              string             `json:"agent_kind"`
	AgentDisplayName       string             `json:"agent_display_name"`
	AgentAccountID         pgtype.Text        `json:"agent_account_id"`
	AgentHandle            pgtype.Text        `json:"agent_handle"`
	AgentCreatedAt         pgtype.Timestamptz `json:"agent_created_at"`
	CreatorKind            string             `json:"creator_kind"`
	CreatorDisplayName     string             `json:"creator_display_name"`
	CreatorAccountID       pgtype.Text        `json:"creator_account_id"`
	CreatorHandle          pgtype.Text        `json:"creator_handle"`
	CreatorCreatedAt       pgtype.Timestamptz `json:"creator_created_at"`
	ActiveTaskCount        int64              `json:"active_task_count"`
}

func (q *Queries) ListTenantAgentsForAccount(ctx context.Context, arg ListTenantAgentsForAccountParams) ([]ListTenantAgentsForAccountRow, error) {
	rows, err := q.db.Query(ctx, listTenantAgentsForAccount,
		arg.AccountID,
		arg.TenantID,
		arg.Cursor,
		arg.PageLimit,
	)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []ListTenantAgentsForAccountRow{}
	for rows.Next() {
		var i ListTenantAgentsForAccountRow
		if err := rows.Scan(
			&i.ActorID,
			&i.TenantID,
			&i.AgentManagementID,
			&i.Status,
			&i.Description,
			&i.AvatarKey,
			&i.ConfigurationRevision,
			&i.Instructions,
			&i.RuntimeModel,
			&i.RuntimeReasoningEffort,
			&i.ComputerID,
			&i.LocalRuntimeType,
			&i.WorkspaceGrantID,
			&i.CreatedByActorID,
			&i.VisibilityScope,
			&i.AgentType,
			&i.CreatedAt,
			&i.UpdatedAt,
			&i.AgentKind,
			&i.AgentDisplayName,
			&i.AgentAccountID,
			&i.AgentHandle,
			&i.AgentCreatedAt,
			&i.CreatorKind,
			&i.CreatorDisplayName,
			&i.CreatorAccountID,
			&i.CreatorHandle,
			&i.CreatorCreatedAt,
			&i.ActiveTaskCount,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const revokeAgentRegistration = `-- name: RevokeAgentRegistration :execrows
UPDATE agent_registrations
SET status='revoked',updated_at=now()
WHERE actor_id=$1 AND tenant_id=$2 AND status='active'
`

type RevokeAgentRegistrationParams struct {
	ActorID  string `json:"actor_id"`
	TenantID string `json:"tenant_id"`
}

func (q *Queries) RevokeAgentRegistration(ctx context.Context, arg RevokeAgentRegistrationParams) (int64, error) {
	result, err := q.db.Exec(ctx, revokeAgentRegistration, arg.ActorID, arg.TenantID)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected(), nil
}

const updateAgentActorDisplayName = `-- name: UpdateAgentActorDisplayName :execrows
UPDATE actors SET display_name=$3
WHERE id=$1 AND tenant_id=$2 AND kind='agent'
`

type UpdateAgentActorDisplayNameParams struct {
	ID          string `json:"id"`
	TenantID    string `json:"tenant_id"`
	DisplayName string `json:"display_name"`
}

func (q *Queries) UpdateAgentActorDisplayName(ctx context.Context, arg UpdateAgentActorDisplayNameParams) (int64, error) {
	result, err := q.db.Exec(ctx, updateAgentActorDisplayName, arg.ID, arg.TenantID, arg.DisplayName)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected(), nil
}

const updateAgentRegistrationAvatarKey = `-- name: UpdateAgentRegistrationAvatarKey :exec
UPDATE agent_registrations
SET avatar_key=$1::text,updated_at=now()
WHERE actor_id=$2::text AND tenant_id=$3::text
`

type UpdateAgentRegistrationAvatarKeyParams struct {
	AvatarKey string `json:"avatar_key"`
	ActorID   string `json:"actor_id"`
	TenantID  string `json:"tenant_id"`
}

func (q *Queries) UpdateAgentRegistrationAvatarKey(ctx context.Context, arg UpdateAgentRegistrationAvatarKeyParams) error {
	_, err := q.db.Exec(ctx, updateAgentRegistrationAvatarKey, arg.AvatarKey, arg.ActorID, arg.TenantID)
	return err
}

const upsertAgentAvatarImage = `-- name: UpsertAgentAvatarImage :exec
UPDATE agent_registrations
SET avatar_image=$1::text,avatar_updated_at=now()
WHERE actor_id=$2::text AND tenant_id=$3::text
`

type UpsertAgentAvatarImageParams struct {
	AvatarImage string `json:"avatar_image"`
	ActorID     string `json:"actor_id"`
	TenantID    string `json:"tenant_id"`
}

func (q *Queries) UpsertAgentAvatarImage(ctx context.Context, arg UpsertAgentAvatarImageParams) error {
	_, err := q.db.Exec(ctx, upsertAgentAvatarImage, arg.AvatarImage, arg.ActorID, arg.TenantID)
	return err
}