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.

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

package store

import (
	"context"

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

const countProactiveRemindedEvents = `-- name: CountProactiveRemindedEvents :one
SELECT count(*)::bigint FROM proactive_potential_items
WHERE tenant_id=$1::text AND owner_actor_id=$2::text
  AND source='event' AND reminded
`

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

// Events that woke AnotherMe today; the day's records are emptied each night.
func (q *Queries) CountProactiveRemindedEvents(ctx context.Context, arg CountProactiveRemindedEventsParams) (int64, error) {
	row := q.db.QueryRow(ctx, countProactiveRemindedEvents, arg.TenantID, arg.OwnerActorID)
	var column_1 int64
	err := row.Scan(&column_1)
	return column_1, err
}

const createProactiveOutput = `-- name: CreateProactiveOutput :exec
INSERT INTO proactive_outputs(message_id,tenant_id,owner_actor_id,room_id,source,local_run_id)
VALUES ($1::text,$2::text,$3::text,
        $4::text,$5::text,$6::text)
ON CONFLICT DO NOTHING
`

type CreateProactiveOutputParams struct {
	MessageID    string `json:"message_id"`
	TenantID     string `json:"tenant_id"`
	OwnerActorID string `json:"owner_actor_id"`
	RoomID       string `json:"room_id"`
	Source       string `json:"source"`
	LocalRunID   string `json:"local_run_id"`
}

// Only the first Message of a wake Run is its output.
func (q *Queries) CreateProactiveOutput(ctx context.Context, arg CreateProactiveOutputParams) error {
	_, err := q.db.Exec(ctx, createProactiveOutput,
		arg.MessageID,
		arg.TenantID,
		arg.OwnerActorID,
		arg.RoomID,
		arg.Source,
		arg.LocalRunID,
	)
	return err
}

const getAnotherMeHuman = `-- name: GetAnotherMeHuman :one
SELECT represented_human_actor_id::text
FROM agent_registrations
WHERE actor_id=$1::text AND tenant_id=$2::text AND agent_type='anotherme'
`

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

func (q *Queries) GetAnotherMeHuman(ctx context.Context, arg GetAnotherMeHumanParams) (string, error) {
	row := q.db.QueryRow(ctx, getAnotherMeHuman, arg.AgentActorID, arg.TenantID)
	var represented_human_actor_id string
	err := row.Scan(&represented_human_actor_id)
	return represented_human_actor_id, err
}

const getExternalConnectionIdentityLabel = `-- name: GetExternalConnectionIdentityLabel :one
SELECT coalesce(identity_label,'')::text FROM external_connections WHERE id=$1::text
`

// The account label a proactive event names for its granted connection.
func (q *Queries) GetExternalConnectionIdentityLabel(ctx context.Context, id string) (string, error) {
	row := q.db.QueryRow(ctx, getExternalConnectionIdentityLabel, id)
	var column_1 string
	err := row.Scan(&column_1)
	return column_1, err
}

const getLatestProactiveGuideline = `-- name: GetLatestProactiveGuideline :one
SELECT version,specific FROM proactive_guidelines
WHERE tenant_id=$1::text AND owner_actor_id=$2::text
ORDER BY version DESC
LIMIT 1
`

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

type GetLatestProactiveGuidelineRow struct {
	Version  int32  `json:"version"`
	Specific []byte `json:"specific"`
}

func (q *Queries) GetLatestProactiveGuideline(ctx context.Context, arg GetLatestProactiveGuidelineParams) (GetLatestProactiveGuidelineRow, error) {
	row := q.db.QueryRow(ctx, getLatestProactiveGuideline, arg.TenantID, arg.OwnerActorID)
	var i GetLatestProactiveGuidelineRow
	err := row.Scan(&i.Version, &i.Specific)
	return i, err
}

const getRunProactiveWakeSource = `-- name: GetRunProactiveWakeSource :one
SELECT wake.source 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=$1::text 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=$2::text AND relation.relation='initial'
  AND wake.delivered_at IS NOT NULL
  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=wake.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=relation.run_id
      AND human_message.message_kind='conversation' AND human_author.kind='human'
  )
ORDER BY wake.delivered_at, wake.id
LIMIT 1
`

type GetRunProactiveWakeSourceParams struct {
	RoomID string `json:"room_id"`
	RunID  string `json:"run_id"`
}

// The source of the delivered proactive wake that started this Run in this
// Room, if one did. A Room notification input names the Messages it carries
// in payload invocationMessageIds. A wake steered into a Run already answering
// the Human does not make that Run proactive. Mixed initial inputs and any
// Human input already attached when this Message is sent keep it ordinary.
func (q *Queries) GetRunProactiveWakeSource(ctx context.Context, arg GetRunProactiveWakeSourceParams) (string, error) {
	row := q.db.QueryRow(ctx, getRunProactiveWakeSource, arg.RoomID, arg.RunID)
	var source string
	err := row.Scan(&source)
	return source, err
}

const hasProactiveSignalForSource = `-- name: HasProactiveSignalForSource :one
SELECT EXISTS(
  SELECT 1 FROM proactive_potential_items
  WHERE tenant_id=$1::text AND owner_actor_id=$2::text
    AND source=$3::text AND source_key=$4::text
)::boolean
`

type HasProactiveSignalForSourceParams struct {
	TenantID     string `json:"tenant_id"`
	OwnerActorID string `json:"owner_actor_id"`
	Source       string `json:"source"`
	SourceKey    string `json:"source_key"`
}

// Whether this source item was already judged today: a candidate is judged
// once a day.
func (q *Queries) HasProactiveSignalForSource(ctx context.Context, arg HasProactiveSignalForSourceParams) (bool, error) {
	row := q.db.QueryRow(ctx, hasProactiveSignalForSource,
		arg.TenantID,
		arg.OwnerActorID,
		arg.Source,
		arg.SourceKey,
	)
	var column_1 bool
	err := row.Scan(&column_1)
	return column_1, err
}

const listAnotherMeConnectionsWithoutListener = `-- name: ListAnotherMeConnectionsWithoutListener :many
SELECT registration.tenant_id, registration.represented_human_actor_id::text AS represented_human_actor_id,
       registration.actor_id AS agent_actor_id, room.id AS room_id,
       c.id AS connection_id, c.provider, c.identity_label
FROM agent_registrations registration
JOIN rooms room ON room.tenant_id=registration.tenant_id
  AND room.direct_human_actor_id=registration.represented_human_actor_id
  AND room.direct_agent_actor_id=registration.actor_id
  AND room.deletion_started_at IS NULL
JOIN external_connection_agent_grants d ON d.agent_actor_id=registration.actor_id AND d.tenant_id=registration.tenant_id
  AND d.represented_human_actor_id=registration.represented_human_actor_id AND d.status='active'
JOIN external_connections c ON c.id=d.connection_id AND c.status='active'
  AND c.provider=ANY($1::text[]) AND c.auto_reminders
  AND ($2::text IS NULL OR c.id=$2::text)
WHERE registration.agent_type='anotherme' AND registration.status='active'
  AND NOT EXISTS (
    SELECT 1 FROM room_reminders r
    WHERE r.template_agent_actor_id=registration.actor_id
      AND r.template_routine_key=$3::text || c.id
  )
ORDER BY registration.tenant_id, registration.represented_human_actor_id, c.created_at, c.id
LIMIT 200
`

type ListAnotherMeConnectionsWithoutListenerParams struct {
	Providers        []string    `json:"providers"`
	ConnectionID     pgtype.Text `json:"connection_id"`
	RoutineKeyPrefix string      `json:"routine_key_prefix"`
}

type ListAnotherMeConnectionsWithoutListenerRow struct {
	TenantID                string      `json:"tenant_id"`
	RepresentedHumanActorID string      `json:"represented_human_actor_id"`
	AgentActorID            string      `json:"agent_actor_id"`
	RoomID                  string      `json:"room_id"`
	ConnectionID            string      `json:"connection_id"`
	Provider                string      `json:"provider"`
	IdentityLabel           pgtype.Text `json:"identity_label"`
}

// The Human's own active connections of a listenable provider with auto
// reminders on, granted to their active AnotherMe, with no listener Routine
// for that connection yet. A connection ID narrows it to that connection.
func (q *Queries) ListAnotherMeConnectionsWithoutListener(ctx context.Context, arg ListAnotherMeConnectionsWithoutListenerParams) ([]ListAnotherMeConnectionsWithoutListenerRow, error) {
	rows, err := q.db.Query(ctx, listAnotherMeConnectionsWithoutListener, arg.Providers, arg.ConnectionID, arg.RoutineKeyPrefix)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []ListAnotherMeConnectionsWithoutListenerRow{}
	for rows.Next() {
		var i ListAnotherMeConnectionsWithoutListenerRow
		if err := rows.Scan(
			&i.TenantID,
			&i.RepresentedHumanActorID,
			&i.AgentActorID,
			&i.RoomID,
			&i.ConnectionID,
			&i.Provider,
			&i.IdentityLabel,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listProactiveTrackingItems = `-- name: ListProactiveTrackingItems :many
SELECT id,kind,content,due_at FROM memory_index.tracking_items
WHERE tenant_id=$1::text AND owner_actor_id=$2::text AND status='open'
  AND coalesce(due_at>=now(),created_at>=now()-interval '3 months')
ORDER BY due_at NULLS LAST,created_at
LIMIT 100
`

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

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

// The Human's current Tracking Items, by Memory's rule: current until due, or
// for three months when undated.
func (q *Queries) ListProactiveTrackingItems(ctx context.Context, arg ListProactiveTrackingItemsParams) ([]ListProactiveTrackingItemsRow, error) {
	rows, err := q.db.Query(ctx, listProactiveTrackingItems, arg.TenantID, arg.OwnerActorID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []ListProactiveTrackingItemsRow{}
	for rows.Next() {
		var i ListProactiveTrackingItemsRow
		if err := rows.Scan(
			&i.ID,
			&i.Kind,
			&i.Content,
			&i.DueAt,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const lockConnectionAutoReminders = `-- name: LockConnectionAutoReminders :one
SELECT auto_reminders FROM external_connections WHERE id=$1::text FOR SHARE
`

// Share-locks a connection against its auto reminders switch and reads the
// switch, for the listener sweep's install.
func (q *Queries) LockConnectionAutoReminders(ctx context.Context, id string) (bool, error) {
	row := q.db.QueryRow(ctx, lockConnectionAutoReminders, id)
	var auto_reminders bool
	err := row.Scan(&auto_reminders)
	return auto_reminders, err
}

const upsertProactivePotentialItem = `-- name: UpsertProactivePotentialItem :execrows
INSERT INTO proactive_potential_items(id,tenant_id,owner_actor_id,content,source,source_key,reminded)
VALUES ($1::text,$2::text,$3::text,
        $4::text,$5::text,$6::text,$7::boolean)
ON CONFLICT (tenant_id,owner_actor_id,source,source_key) DO NOTHING
`

type UpsertProactivePotentialItemParams struct {
	ID           string `json:"id"`
	TenantID     string `json:"tenant_id"`
	OwnerActorID string `json:"owner_actor_id"`
	Content      string `json:"content"`
	Source       string `json:"source"`
	SourceKey    string `json:"source_key"`
	Reminded     bool   `json:"reminded"`
}

// A source item enters once a day, tracked or reminded; a repeat judgment is
// ignored.
func (q *Queries) UpsertProactivePotentialItem(ctx context.Context, arg UpsertProactivePotentialItemParams) (int64, error) {
	result, err := q.db.Exec(ctx, upsertProactivePotentialItem,
		arg.ID,
		arg.TenantID,
		arg.OwnerActorID,
		arg.Content,
		arg.Source,
		arg.SourceKey,
		arg.Reminded,
	)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected(), nil
}