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.

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

package store

import (
	"context"

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

const getDecisionAuthority = `-- name: GetDecisionAuthority :one
SELECT decision.message_id,decision.decider_actor_id,caller.id AS caller_actor_id,card.version AS card_version,
       decision.kind,decision.tenant_id,decision.room_id,decision.requested_by_actor_id,
       coalesce(decision.alter_ego_task_id,'')::text AS alter_ego_task_id,decision.request,decision.view,decision.status,
       ((decision.status='pending' OR decision.kind='connection_auth' AND decision.status='authorizing')
         AND (decision.expires_at IS NULL OR decision.expires_at>clock_timestamp()))::boolean AS open,
       coalesce(registration.visibility_scope,'')::text AS requester_visibility_scope
FROM decisions decision
JOIN message_cards card ON card.message_id=decision.message_id
LEFT JOIN agent_registrations registration
  ON registration.actor_id=decision.requested_by_actor_id AND registration.tenant_id=decision.tenant_id
JOIN actors caller
  ON caller.tenant_id=decision.tenant_id
 AND caller.account_id=$1::text
 AND caller.kind='human'
JOIN active_room_members membership
  ON membership.room_id=collaboration_membership_room_id(decision.room_id)
 AND membership.actor_id=caller.id
WHERE decision.id=$2::text
FOR UPDATE OF decision, card
`

type GetDecisionAuthorityParams struct {
	AccountID  string `json:"account_id"`
	DecisionID string `json:"decision_id"`
}

type GetDecisionAuthorityRow struct {
	MessageID                string `json:"message_id"`
	DeciderActorID           string `json:"decider_actor_id"`
	CallerActorID            string `json:"caller_actor_id"`
	CardVersion              int64  `json:"card_version"`
	Kind                     string `json:"kind"`
	TenantID                 string `json:"tenant_id"`
	RoomID                   string `json:"room_id"`
	RequestedByActorID       string `json:"requested_by_actor_id"`
	AlterEgoTaskID           string `json:"alter_ego_task_id"`
	Request                  []byte `json:"request"`
	View                     []byte `json:"view"`
	Status                   string `json:"status"`
	Open                     bool   `json:"open"`
	RequesterVisibilityScope string `json:"requester_visibility_scope"`
}

// Any member of the card's Room sees the decision; the caller row names the
// member deciding it. requester_visibility_scope is the requesting Agent's.
// A connection authorization stays open while authorizing, so the Human can
// still cancel the OAuth they started.
func (q *Queries) GetDecisionAuthority(ctx context.Context, arg GetDecisionAuthorityParams) (GetDecisionAuthorityRow, error) {
	row := q.db.QueryRow(ctx, getDecisionAuthority, arg.AccountID, arg.DecisionID)
	var i GetDecisionAuthorityRow
	err := row.Scan(
		&i.MessageID,
		&i.DeciderActorID,
		&i.CallerActorID,
		&i.CardVersion,
		&i.Kind,
		&i.TenantID,
		&i.RoomID,
		&i.RequestedByActorID,
		&i.AlterEgoTaskID,
		&i.Request,
		&i.View,
		&i.Status,
		&i.Open,
		&i.RequesterVisibilityScope,
	)
	return i, err
}

const getHumanRoomMemberActor = `-- name: GetHumanRoomMemberActor :one
SELECT actor.id, actor.tenant_id, actor.kind, actor.display_name, actor.account_id, actor.handle, actor.created_at
FROM actors actor
JOIN active_room_members membership
  ON membership.actor_id=actor.id
 AND membership.tenant_id=actor.tenant_id
 AND membership.room_id=collaboration_membership_room_id($1::text)
WHERE actor.id=$2::text
  AND actor.tenant_id=$3::text
  AND actor.kind=$4::text
`

type GetHumanRoomMemberActorParams struct {
	RoomID   string `json:"room_id"`
	ActorID  string `json:"actor_id"`
	TenantID string `json:"tenant_id"`
	Kind     string `json:"kind"`
}

func (q *Queries) GetHumanRoomMemberActor(ctx context.Context, arg GetHumanRoomMemberActorParams) (Actor, error) {
	row := q.db.QueryRow(ctx, getHumanRoomMemberActor,
		arg.RoomID,
		arg.ActorID,
		arg.TenantID,
		arg.Kind,
	)
	var i Actor
	err := row.Scan(
		&i.ID,
		&i.TenantID,
		&i.Kind,
		&i.DisplayName,
		&i.AccountID,
		&i.Handle,
		&i.CreatedAt,
	)
	return i, err
}

const getPendingProfileSetupCard = `-- name: GetPendingProfileSetupCard :one
SELECT message_id FROM decisions
WHERE requested_by_actor_id=$1::text AND status='pending'
  AND room_id=$2::text AND kind IN ('profile_setup_apps','profile_setup_sources')
ORDER BY created_at DESC,id DESC
LIMIT 1
`

type GetPendingProfileSetupCardParams struct {
	AgentActorID string `json:"agent_actor_id"`
	RoomID       string `json:"room_id"`
}

// The AnotherMe setup card still open in its Direct Room. The pending
// requester index keeps this cheap on the Human's message path.
func (q *Queries) GetPendingProfileSetupCard(ctx context.Context, arg GetPendingProfileSetupCardParams) (string, error) {
	row := q.db.QueryRow(ctx, getPendingProfileSetupCard, arg.AgentActorID, arg.RoomID)
	var message_id string
	err := row.Scan(&message_id)
	return message_id, err
}

const getRoomCreationSubmissionReplay = `-- name: GetRoomCreationSubmissionReplay :one
SELECT decision.id,decision.message_id,idempotency.request_hash,
       idempotency.response_status,idempotency.response_body
FROM decisions decision
JOIN command_replays idempotency
  ON idempotency.scope='agent:'||decision.requested_by_actor_id
 AND idempotency.resource_id=decision.message_id
WHERE decision.kind='room_creation'
  AND decision.requested_by_actor_id=$1::text
  AND decision.request->>'submission_id'=$2::text
  AND idempotency.operation=$3::text
  AND idempotency.key=$2::text
`

type GetRoomCreationSubmissionReplayParams struct {
	AgentActorID string `json:"agent_actor_id"`
	SubmissionID string `json:"submission_id"`
	Operation    string `json:"operation"`
}

type GetRoomCreationSubmissionReplayRow struct {
	ID             string      `json:"id"`
	MessageID      string      `json:"message_id"`
	RequestHash    []byte      `json:"request_hash"`
	ResponseStatus pgtype.Int4 `json:"response_status"`
	ResponseBody   []byte      `json:"response_body"`
}

func (q *Queries) GetRoomCreationSubmissionReplay(ctx context.Context, arg GetRoomCreationSubmissionReplayParams) (GetRoomCreationSubmissionReplayRow, error) {
	row := q.db.QueryRow(ctx, getRoomCreationSubmissionReplay, arg.AgentActorID, arg.SubmissionID, arg.Operation)
	var i GetRoomCreationSubmissionReplayRow
	err := row.Scan(
		&i.ID,
		&i.MessageID,
		&i.RequestHash,
		&i.ResponseStatus,
		&i.ResponseBody,
	)
	return i, err
}

const getTaskOriginRoomID = `-- name: GetTaskOriginRoomID :one
SELECT room_id FROM work_item_room_links
WHERE work_item_id=$1::text AND tenant_id=$2::text AND link_type='origin'
`

type GetTaskOriginRoomIDParams struct {
	WorkItemID string `json:"work_item_id"`
	TenantID   string `json:"tenant_id"`
}

func (q *Queries) GetTaskOriginRoomID(ctx context.Context, arg GetTaskOriginRoomIDParams) (string, error) {
	row := q.db.QueryRow(ctx, getTaskOriginRoomID, arg.WorkItemID, arg.TenantID)
	var room_id string
	err := row.Scan(&room_id)
	return room_id, err
}

const humanAndAgentShareRoom = `-- name: HumanAndAgentShareRoom :one
SELECT (
  EXISTS(
    SELECT 1 FROM active_room_members member
    JOIN actors actor ON actor.id=member.actor_id AND actor.tenant_id=member.tenant_id AND actor.kind='human'
    WHERE member.room_id=$1::text AND member.tenant_id=$2::text
      AND member.actor_id=$3::text
  )
  AND EXISTS(
    SELECT 1 FROM active_room_members member
    WHERE member.room_id=$1::text AND member.tenant_id=$2::text
      AND member.actor_id=$4::text
  )
)::boolean
`

type HumanAndAgentShareRoomParams struct {
	RoomID       string `json:"room_id"`
	TenantID     string `json:"tenant_id"`
	HumanActorID string `json:"human_actor_id"`
	AgentActorID string `json:"agent_actor_id"`
}

func (q *Queries) HumanAndAgentShareRoom(ctx context.Context, arg HumanAndAgentShareRoomParams) (bool, error) {
	row := q.db.QueryRow(ctx, humanAndAgentShareRoom,
		arg.RoomID,
		arg.TenantID,
		arg.HumanActorID,
		arg.AgentActorID,
	)
	var column_1 bool
	err := row.Scan(&column_1)
	return column_1, err
}

const humanWroteInRoom = `-- name: HumanWroteInRoom :one
SELECT EXISTS(
  SELECT 1 FROM messages
  WHERE room_id=$1::text AND author_actor_id=$2::text
    AND message_kind='conversation' AND room_seq IS NOT NULL AND card_context_message_id IS NULL
)::boolean
`

type HumanWroteInRoomParams struct {
	RoomID       string `json:"room_id"`
	HumanActorID string `json:"human_actor_id"`
}

// Whether the Human has written in the Room themselves: published
// conversation Messages that are not a card's recorded result.
func (q *Queries) HumanWroteInRoom(ctx context.Context, arg HumanWroteInRoomParams) (bool, error) {
	row := q.db.QueryRow(ctx, humanWroteInRoom, arg.RoomID, arg.HumanActorID)
	var column_1 bool
	err := row.Scan(&column_1)
	return column_1, err
}

const insertDecision = `-- name: InsertDecision :one
INSERT INTO decisions (id,tenant_id,room_id,message_id,kind,requested_by_actor_id,decider_actor_id,
    alter_ego_task_id,request,view,expires_at,screenshot,screenshot_media_type)
VALUES ($1::text,$2::text,$3::text,$4::text,
    $5::text,$6::text,$7::text,
    $8::text,$9::jsonb,$10::jsonb,
    CASE WHEN $11::float8>0
      THEN clock_timestamp()+make_interval(secs => $11::float8) END,
    $12::bytea,$13::text)
RETURNING expires_at
`

type InsertDecisionParams struct {
	ID                  string      `json:"id"`
	TenantID            string      `json:"tenant_id"`
	RoomID              string      `json:"room_id"`
	MessageID           string      `json:"message_id"`
	Kind                string      `json:"kind"`
	RequestedByActorID  string      `json:"requested_by_actor_id"`
	DeciderActorID      string      `json:"decider_actor_id"`
	AlterEgoTaskID      pgtype.Text `json:"alter_ego_task_id"`
	Request             []byte      `json:"request"`
	View                []byte      `json:"view"`
	LifetimeSeconds     float64     `json:"lifetime_seconds"`
	Screenshot          []byte      `json:"screenshot"`
	ScreenshotMediaType pgtype.Text `json:"screenshot_media_type"`
}

// A lifetime of zero seconds makes a card that waits until it is answered.
func (q *Queries) InsertDecision(ctx context.Context, arg InsertDecisionParams) (pgtype.Timestamptz, error) {
	row := q.db.QueryRow(ctx, insertDecision,
		arg.ID,
		arg.TenantID,
		arg.RoomID,
		arg.MessageID,
		arg.Kind,
		arg.RequestedByActorID,
		arg.DeciderActorID,
		arg.AlterEgoTaskID,
		arg.Request,
		arg.View,
		arg.LifetimeSeconds,
		arg.Screenshot,
		arg.ScreenshotMediaType,
	)
	var expires_at pgtype.Timestamptz
	err := row.Scan(&expires_at)
	return expires_at, err
}

const listDecisionsByMessages = `-- name: ListDecisionsByMessages :many
SELECT id,tenant_id,room_id,message_id,kind,requested_by_actor_id,decider_actor_id,alter_ego_task_id,status,
       request,view,answer,result,expires_at,decided_at,decided_by_actor_id,finished_at,created_at,
       (screenshot IS NOT NULL)::boolean AS has_screenshot
FROM decisions
WHERE message_id=ANY($1::text[])
`

type ListDecisionsByMessagesRow struct {
	ID                 string             `json:"id"`
	TenantID           string             `json:"tenant_id"`
	RoomID             string             `json:"room_id"`
	MessageID          string             `json:"message_id"`
	Kind               string             `json:"kind"`
	RequestedByActorID string             `json:"requested_by_actor_id"`
	DeciderActorID     string             `json:"decider_actor_id"`
	AlterEgoTaskID     pgtype.Text        `json:"alter_ego_task_id"`
	Status             string             `json:"status"`
	Request            []byte             `json:"request"`
	View               []byte             `json:"view"`
	Answer             []byte             `json:"answer"`
	Result             []byte             `json:"result"`
	ExpiresAt          pgtype.Timestamptz `json:"expires_at"`
	DecidedAt          pgtype.Timestamptz `json:"decided_at"`
	DecidedByActorID   pgtype.Text        `json:"decided_by_actor_id"`
	FinishedAt         pgtype.Timestamptz `json:"finished_at"`
	CreatedAt          pgtype.Timestamptz `json:"created_at"`
	HasScreenshot      bool               `json:"has_screenshot"`
}

// A card page never reads a permission card's screenshot.
func (q *Queries) ListDecisionsByMessages(ctx context.Context, messageIds []string) ([]ListDecisionsByMessagesRow, error) {
	rows, err := q.db.Query(ctx, listDecisionsByMessages, messageIds)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []ListDecisionsByMessagesRow{}
	for rows.Next() {
		var i ListDecisionsByMessagesRow
		if err := rows.Scan(
			&i.ID,
			&i.TenantID,
			&i.RoomID,
			&i.MessageID,
			&i.Kind,
			&i.RequestedByActorID,
			&i.DeciderActorID,
			&i.AlterEgoTaskID,
			&i.Status,
			&i.Request,
			&i.View,
			&i.Answer,
			&i.Result,
			&i.ExpiresAt,
			&i.DecidedAt,
			&i.DecidedByActorID,
			&i.FinishedAt,
			&i.CreatedAt,
			&i.HasScreenshot,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listProfileSetupReminderCards = `-- name: ListProfileSetupReminderCards :many
SELECT decision.id AS decision_id,decision.room_id
FROM external_connection_agent_grants grant_row
JOIN external_connections connection
  ON connection.id=grant_row.connection_id AND connection.status='active'
JOIN decisions decision
  ON decision.requested_by_actor_id=grant_row.agent_actor_id AND decision.tenant_id=grant_row.tenant_id
 AND decision.decider_actor_id=grant_row.represented_human_actor_id
 AND decision.kind IN ('profile_setup_apps','profile_setup_sources') AND decision.status='pending'
WHERE grant_row.connection_id=$1::text AND grant_row.status='active'
ORDER BY decision.id
`

type ListProfileSetupReminderCardsRow struct {
	DecisionID string `json:"decision_id"`
	RoomID     string `json:"room_id"`
}

// The open AnotherMe setup cards whose AnotherMe holds an active grant to the
// active Connection for the card's Human: the setups a reminder may concern.
func (q *Queries) ListProfileSetupReminderCards(ctx context.Context, connectionID string) ([]ListProfileSetupReminderCardsRow, error) {
	rows, err := q.db.Query(ctx, listProfileSetupReminderCards, connectionID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []ListProfileSetupReminderCardsRow{}
	for rows.Next() {
		var i ListProfileSetupReminderCardsRow
		if err := rows.Scan(&i.DecisionID, &i.RoomID); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const locateDecision = `-- name: LocateDecision :one
SELECT tenant_id,room_id FROM decisions WHERE id=$1
`

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

func (q *Queries) LocateDecision(ctx context.Context, id string) (LocateDecisionRow, error) {
	row := q.db.QueryRow(ctx, locateDecision, id)
	var i LocateDecisionRow
	err := row.Scan(&i.TenantID, &i.RoomID)
	return i, err
}

const lockPendingProfileSetupCard = `-- name: LockPendingProfileSetupCard :one
SELECT decision.message_id,decision.tenant_id,decision.decider_actor_id,decision.requested_by_actor_id
FROM decisions decision
WHERE decision.id=$1::text AND decision.status='pending'
  AND decision.kind IN ('profile_setup_apps','profile_setup_sources')
FOR UPDATE
`

type LockPendingProfileSetupCardRow struct {
	MessageID          string `json:"message_id"`
	TenantID           string `json:"tenant_id"`
	DeciderActorID     string `json:"decider_actor_id"`
	RequestedByActorID string `json:"requested_by_actor_id"`
}

// Locks one AnotherMe setup card while it is still open, after the Room
// membership lock, as a decision answer does.
func (q *Queries) LockPendingProfileSetupCard(ctx context.Context, decisionID string) (LockPendingProfileSetupCardRow, error) {
	row := q.db.QueryRow(ctx, lockPendingProfileSetupCard, decisionID)
	var i LockPendingProfileSetupCardRow
	err := row.Scan(
		&i.MessageID,
		&i.TenantID,
		&i.DeciderActorID,
		&i.RequestedByActorID,
	)
	return i, err
}

const personalProfileNotStarted = `-- name: PersonalProfileNotStarted :one
SELECT (
  NOT EXISTS(SELECT 1 FROM personal_profile_currents
    WHERE tenant_id=$1::text AND owner_actor_id=$2::text)
  AND NOT EXISTS(SELECT 1 FROM personal_profile_builds
    WHERE tenant_id=$1::text AND owner_actor_id=$2::text
      AND expires_at>clock_timestamp())
  AND NOT EXISTS(SELECT 1 FROM personal_profile_generations
    WHERE tenant_id=$1::text AND owner_actor_id=$2::text
      AND status IN ('queued','running'))
)::boolean
`

type PersonalProfileNotStartedParams struct {
	TenantID     string `json:"tenant_id"`
	OwnerActorID string `json:"owner_actor_id"`
}

// Whether the Human has no Personal Profile and none is being written.
func (q *Queries) PersonalProfileNotStarted(ctx context.Context, arg PersonalProfileNotStartedParams) (bool, error) {
	row := q.db.QueryRow(ctx, personalProfileNotStarted, arg.TenantID, arg.OwnerActorID)
	var column_1 bool
	err := row.Scan(&column_1)
	return column_1, err
}

const profileOfferedInRoom = `-- name: ProfileOfferedInRoom :one
SELECT EXISTS(
  SELECT 1 FROM messages message
  JOIN decisions decision
    ON decision.message_id=message.card_context_message_id AND decision.room_id=message.room_id
   AND decision.kind IN ('profile_setup_apps','profile_setup_sources')
  WHERE message.room_id=$1::text AND message.author_actor_id=$2::text
    AND message.message_kind='agent_runtime'
    AND EXISTS(SELECT 1 FROM external_connection_agent_grants grant_row
      WHERE grant_row.agent_actor_id=$3::text AND grant_row.tenant_id=decision.tenant_id
        AND grant_row.created_at<=message.created_at
        AND (grant_row.revoked_at IS NULL OR grant_row.revoked_at>message.created_at))
)::boolean
`

type ProfileOfferedInRoomParams struct {
	RoomID       string `json:"room_id"`
	HumanActorID string `json:"human_actor_id"`
	AgentActorID string `json:"agent_actor_id"`
}

// Whether a setup status AnotherMe read already offered the Profile: one
// written while the Human had an app granted to AnotherMe. A status written
// with no app granted only told AnotherMe to wait. Links and files arrive only
// with the status that finishes setup, after which no card is left to check.
func (q *Queries) ProfileOfferedInRoom(ctx context.Context, arg ProfileOfferedInRoomParams) (bool, error) {
	row := q.db.QueryRow(ctx, profileOfferedInRoom, arg.RoomID, arg.HumanActorID, arg.AgentActorID)
	var column_1 bool
	err := row.Scan(&column_1)
	return column_1, err
}