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.

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

package store

import (
	"context"

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

const advanceConversationWindowProgress = `-- name: AdvanceConversationWindowProgress :execrows
UPDATE proactive_conversation_windows SET judged_count=$1, updated_at=now()
WHERE room_id=$2::text AND judged_count=$3
`

type AdvanceConversationWindowProgressParams struct {
	JudgedCount         int64  `json:"judged_count"`
	RoomID              string `json:"room_id"`
	ExpectedJudgedCount int64  `json:"expected_judged_count"`
}

func (q *Queries) AdvanceConversationWindowProgress(ctx context.Context, arg AdvanceConversationWindowProgressParams) (int64, error) {
	result, err := q.db.Exec(ctx, advanceConversationWindowProgress, arg.JudgedCount, arg.RoomID, arg.ExpectedJudgedCount)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected(), nil
}

const countRoomConversationMessages = `-- name: CountRoomConversationMessages :one
SELECT count(*)::bigint FROM messages
WHERE room_id=$1::text AND message_kind='conversation'
`

func (q *Queries) CountRoomConversationMessages(ctx context.Context, roomID string) (int64, error) {
	row := q.db.QueryRow(ctx, countRoomConversationMessages, roomID)
	var column_1 int64
	err := row.Scan(&column_1)
	return column_1, err
}

const deleteOldDeliveredWakes = `-- name: DeleteOldDeliveredWakes :exec
DELETE FROM proactive_pending_wakes
WHERE room_id=$1::text AND delivered_at < now() - interval '1 day'
`

// Keep recent wake provenance for reply attribution; older replies are already quiet.
func (q *Queries) DeleteOldDeliveredWakes(ctx context.Context, roomID string) error {
	_, err := q.db.Exec(ctx, deleteOldDeliveredWakes, roomID)
	return err
}

const deletePendingWake = `-- name: DeletePendingWake :exec
DELETE FROM proactive_pending_wakes WHERE id=$1::text AND delivered_at IS NULL
`

func (q *Queries) DeletePendingWake(ctx context.Context, id string) error {
	_, err := q.db.Exec(ctx, deletePendingWake, id)
	return err
}

const getAnotherMeDirectRoomAgent = `-- name: GetAnotherMeDirectRoomAgent :one
SELECT direct.direct_agent_actor_id::text AS agent_actor_id, direct.direct_human_actor_id::text AS human_actor_id
FROM rooms direct
JOIN agent_registrations registration
  ON registration.actor_id=direct.direct_agent_actor_id AND registration.represented_human_actor_id=direct.direct_human_actor_id
WHERE direct.id=$1::text AND registration.tenant_id=$2::text
  AND registration.agent_type='anotherme' AND registration.status<>'revoked'
`

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

type GetAnotherMeDirectRoomAgentRow struct {
	AgentActorID string `json:"agent_actor_id"`
	HumanActorID string `json:"human_actor_id"`
}

// The AnotherMe of a direct Room, when the Room is a Human's AnotherMe Room.
func (q *Queries) GetAnotherMeDirectRoomAgent(ctx context.Context, arg GetAnotherMeDirectRoomAgentParams) (GetAnotherMeDirectRoomAgentRow, error) {
	row := q.db.QueryRow(ctx, getAnotherMeDirectRoomAgent, arg.RoomID, arg.TenantID)
	var i GetAnotherMeDirectRoomAgentRow
	err := row.Scan(&i.AgentActorID, &i.HumanActorID)
	return i, err
}

const getAnotherMeRoomForAgent = `-- name: GetAnotherMeRoomForAgent :one
SELECT direct.id AS room_id, direct.direct_agent_actor_id::text AS agent_actor_id,
       direct.direct_human_actor_id::text AS human_actor_id, registration.tenant_id
FROM agent_registrations registration
JOIN rooms direct
  ON direct.direct_agent_actor_id=registration.actor_id AND direct.direct_human_actor_id=registration.represented_human_actor_id
WHERE registration.agent_management_id=$1::text AND direct.id=$2::text
  AND registration.agent_type='anotherme' AND registration.status='active'
`

type GetAnotherMeRoomForAgentParams struct {
	AgentManagementID string `json:"agent_management_id"`
	RoomID            string `json:"room_id"`
}

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

// The AnotherMe direct Room of an active AnotherMe, addressed by Agent Service.
func (q *Queries) GetAnotherMeRoomForAgent(ctx context.Context, arg GetAnotherMeRoomForAgentParams) (GetAnotherMeRoomForAgentRow, error) {
	row := q.db.QueryRow(ctx, getAnotherMeRoomForAgent, arg.AgentManagementID, arg.RoomID)
	var i GetAnotherMeRoomForAgentRow
	err := row.Scan(
		&i.RoomID,
		&i.AgentActorID,
		&i.HumanActorID,
		&i.TenantID,
	)
	return i, err
}

const getConversationWindowProgress = `-- name: GetConversationWindowProgress :one
SELECT judged_count FROM proactive_conversation_windows WHERE room_id=$1::text
`

func (q *Queries) GetConversationWindowProgress(ctx context.Context, roomID string) (int64, error) {
	row := q.db.QueryRow(ctx, getConversationWindowProgress, roomID)
	var judged_count int64
	err := row.Scan(&judged_count)
	return judged_count, err
}

const getPendingWakeRoom = `-- name: GetPendingWakeRoom :one
SELECT room_id, delivered_at FROM proactive_pending_wakes WHERE id=$1::text
`

type GetPendingWakeRoomRow struct {
	RoomID      string             `json:"room_id"`
	DeliveredAt pgtype.Timestamptz `json:"delivered_at"`
}

func (q *Queries) GetPendingWakeRoom(ctx context.Context, id string) (GetPendingWakeRoomRow, error) {
	row := q.db.QueryRow(ctx, getPendingWakeRoom, id)
	var i GetPendingWakeRoomRow
	err := row.Scan(&i.RoomID, &i.DeliveredAt)
	return i, err
}

const getRoomLastConversationAt = `-- name: GetRoomLastConversationAt :one
SELECT coalesce(max(m.created_at), '-infinity'::timestamptz)::timestamptz
FROM messages m
JOIN actors author ON author.id=m.author_actor_id
WHERE m.room_id=$1::text AND m.message_kind='conversation'
  AND (author.kind='human' OR NOT EXISTS (
    SELECT 1 FROM agent_local_run_inputs relation
    JOIN agent_runtime_inputs input
      ON input.context_key=relation.context_key AND input.input_id=relation.input_id
    JOIN proactive_pending_wakes wake
      ON wake.room_id=m.room_id AND wake.agent_actor_id=m.author_actor_id
     AND wake.delivered_at IS NOT NULL AND wake.message_id IS NOT NULL
     AND (input.source_message_id=wake.message_id
          OR jsonb_typeof(input.payload->'invocationMessageIds')='array'
             AND input.payload->'invocationMessageIds' @> to_jsonb(wake.message_id))
    WHERE relation.run_id=m.local_run_id AND relation.relation='initial'
      AND NOT EXISTS (
        SELECT 1 FROM agent_local_run_inputs human_relation
        JOIN agent_runtime_inputs human_input
          ON human_input.context_key=human_relation.context_key
         AND human_input.input_id=human_relation.input_id
        JOIN messages human_message ON human_message.room_id=m.room_id
         AND (human_input.source_message_id=human_message.id
              OR jsonb_typeof(human_input.payload->'invocationMessageIds')='array'
                 AND human_input.payload->'invocationMessageIds' @> to_jsonb(human_message.id))
        JOIN actors human_author ON human_author.id=human_message.author_actor_id
        WHERE human_relation.run_id=m.local_run_id
          AND human_relation.created_at <= m.created_at
          AND human_message.message_kind='conversation' AND human_author.kind='human'
      )
  ))
`

// Only answers from a Run started by a delivered wake are excluded. Ordinary
// replies, including late results and Runs merely steered by a wake, reset quiet.
func (q *Queries) GetRoomLastConversationAt(ctx context.Context, roomID string) (pgtype.Timestamptz, error) {
	row := q.db.QueryRow(ctx, getRoomLastConversationAt, roomID)
	var column_1 pgtype.Timestamptz
	err := row.Scan(&column_1)
	return column_1, err
}

const insertPendingWake = `-- name: InsertPendingWake :exec
INSERT INTO proactive_pending_wakes (id, tenant_id, room_id, author_actor_id, agent_actor_id, body, tracking_item_id, source, connection_grant,
                                     fired_routine_id, fired_routine_instruction)
VALUES ($1, $2, $3, $4,
        $5, $6, $7, $8, $9,
        $10, $11)
`

type InsertPendingWakeParams struct {
	ID                      string      `json:"id"`
	TenantID                string      `json:"tenant_id"`
	RoomID                  string      `json:"room_id"`
	AuthorActorID           string      `json:"author_actor_id"`
	AgentActorID            string      `json:"agent_actor_id"`
	Body                    string      `json:"body"`
	TrackingItemID          pgtype.Text `json:"tracking_item_id"`
	Source                  string      `json:"source"`
	ConnectionGrant         []byte      `json:"connection_grant"`
	FiredRoutineID          pgtype.Text `json:"fired_routine_id"`
	FiredRoutineInstruction pgtype.Text `json:"fired_routine_instruction"`
}

func (q *Queries) InsertPendingWake(ctx context.Context, arg InsertPendingWakeParams) error {
	_, err := q.db.Exec(ctx, insertPendingWake,
		arg.ID,
		arg.TenantID,
		arg.RoomID,
		arg.AuthorActorID,
		arg.AgentActorID,
		arg.Body,
		arg.TrackingItemID,
		arg.Source,
		arg.ConnectionGrant,
		arg.FiredRoutineID,
		arg.FiredRoutineInstruction,
	)
	return err
}

const listOpenTrackingItemsByID = `-- name: ListOpenTrackingItemsByID :many
SELECT id, kind, content, due_at, due_text
FROM memory_index.tracking_items
WHERE tenant_id=$1::text AND owner_actor_id=$2::text
  AND id = ANY($3::text[]) AND status='open'
ORDER BY due_at NULLS LAST, id
`

type ListOpenTrackingItemsByIDParams struct {
	TenantID     string   `json:"tenant_id"`
	OwnerActorID string   `json:"owner_actor_id"`
	Ids          []string `json:"ids"`
}

type ListOpenTrackingItemsByIDRow struct {
	ID      string             `json:"id"`
	Kind    string             `json:"kind"`
	Content string             `json:"content"`
	DueAt   pgtype.Timestamptz `json:"due_at"`
	DueText pgtype.Text        `json:"due_text"`
}

func (q *Queries) ListOpenTrackingItemsByID(ctx context.Context, arg ListOpenTrackingItemsByIDParams) ([]ListOpenTrackingItemsByIDRow, error) {
	rows, err := q.db.Query(ctx, listOpenTrackingItemsByID, arg.TenantID, arg.OwnerActorID, arg.Ids)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []ListOpenTrackingItemsByIDRow{}
	for rows.Next() {
		var i ListOpenTrackingItemsByIDRow
		if err := rows.Scan(
			&i.ID,
			&i.Kind,
			&i.Content,
			&i.DueAt,
			&i.DueText,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listRoomConversationWindow = `-- name: ListRoomConversationWindow :many
SELECT m.id, m.body, m.created_at, author.kind AS author_kind
FROM messages m
JOIN actors author ON author.id=m.author_actor_id
WHERE m.room_id=$1::text AND m.message_kind='conversation'
ORDER BY m.created_at, m.id
OFFSET $2::bigint LIMIT $3::bigint
`

type ListRoomConversationWindowParams struct {
	RoomID string `json:"room_id"`
	Skip   int64  `json:"skip"`
	Take   int64  `json:"take"`
}

type ListRoomConversationWindowRow struct {
	ID         string             `json:"id"`
	Body       string             `json:"body"`
	CreatedAt  pgtype.Timestamptz `json:"created_at"`
	AuthorKind string             `json:"author_kind"`
}

// One window of ordinary conversation, oldest first, after the judged ones.
func (q *Queries) ListRoomConversationWindow(ctx context.Context, arg ListRoomConversationWindowParams) ([]ListRoomConversationWindowRow, error) {
	rows, err := q.db.Query(ctx, listRoomConversationWindow, arg.RoomID, arg.Skip, arg.Take)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []ListRoomConversationWindowRow{}
	for rows.Next() {
		var i ListRoomConversationWindowRow
		if err := rows.Scan(
			&i.ID,
			&i.Body,
			&i.CreatedAt,
			&i.AuthorKind,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listUndeliveredWakes = `-- name: ListUndeliveredWakes :many
SELECT id, tenant_id, room_id, author_actor_id, agent_actor_id, body, tracking_item_id, created_at, delivered_at, source, message_id, connection_grant, fired_routine_id, fired_routine_instruction FROM proactive_pending_wakes
WHERE room_id=$1::text AND delivered_at IS NULL
ORDER BY created_at, id
`

func (q *Queries) ListUndeliveredWakes(ctx context.Context, roomID string) ([]ProactivePendingWake, error) {
	rows, err := q.db.Query(ctx, listUndeliveredWakes, roomID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []ProactivePendingWake{}
	for rows.Next() {
		var i ProactivePendingWake
		if err := rows.Scan(
			&i.ID,
			&i.TenantID,
			&i.RoomID,
			&i.AuthorActorID,
			&i.AgentActorID,
			&i.Body,
			&i.TrackingItemID,
			&i.CreatedAt,
			&i.DeliveredAt,
			&i.Source,
			&i.MessageID,
			&i.ConnectionGrant,
			&i.FiredRoutineID,
			&i.FiredRoutineInstruction,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const lockRoomPendingWakes = `-- name: LockRoomPendingWakes :exec
SELECT pg_advisory_xact_lock(hashtextextended('proactive_pending_wakes:' || $1::text, 0))
`

// Serializes delivery for one Room so wakes go out once and in order.
func (q *Queries) LockRoomPendingWakes(ctx context.Context, roomID string) error {
	_, err := q.db.Exec(ctx, lockRoomPendingWakes, roomID)
	return err
}

const markWakeDelivered = `-- name: MarkWakeDelivered :exec
UPDATE proactive_pending_wakes SET delivered_at=clock_timestamp(), message_id=$1::text
WHERE id=$2::text
`

type MarkWakeDeliveredParams struct {
	MessageID string `json:"message_id"`
	ID        string `json:"id"`
}

func (q *Queries) MarkWakeDelivered(ctx context.Context, arg MarkWakeDeliveredParams) error {
	_, err := q.db.Exec(ctx, markWakeDelivered, arg.MessageID, arg.ID)
	return err
}

const startConversationWindowProgress = `-- name: StartConversationWindowProgress :exec
INSERT INTO proactive_conversation_windows (room_id, tenant_id, judged_count)
VALUES ($1, $2, $3)
ON CONFLICT (room_id) DO NOTHING
`

type StartConversationWindowProgressParams struct {
	RoomID      string `json:"room_id"`
	TenantID    string `json:"tenant_id"`
	JudgedCount int64  `json:"judged_count"`
}

func (q *Queries) StartConversationWindowProgress(ctx context.Context, arg StartConversationWindowProgressParams) error {
	_, err := q.db.Exec(ctx, startConversationWindowProgress, arg.RoomID, arg.TenantID, arg.JudgedCount)
	return err
}