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.9 KB
Raw Blame
// Code generated by sqlc. DO NOT EDIT.
// versions:
//   sqlc v1.29.0
// source: task_delegation.sql

package store

import (
	"context"

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

const getAgentLocalRunFinalResponse = `-- name: GetAgentLocalRunFinalResponse :one
SELECT COALESCE(terminal->>'finalResponse','')::text AS final_response
FROM agent_local_runs
WHERE run_id=$1::text
  AND context_key=$2::text
`

type GetAgentLocalRunFinalResponseParams struct {
	RunID      string `json:"run_id"`
	ContextKey string `json:"context_key"`
}

func (q *Queries) GetAgentLocalRunFinalResponse(ctx context.Context, arg GetAgentLocalRunFinalResponseParams) (string, error) {
	row := q.db.QueryRow(ctx, getAgentLocalRunFinalResponse, arg.RunID, arg.ContextKey)
	var final_response string
	err := row.Scan(&final_response)
	return final_response, err
}

const getDelegatedTaskForAlterEgo = `-- name: GetDelegatedTaskForAlterEgo :one
SELECT item.id AS task_id,item.tenant_id,generation.result_agent_actor_id
FROM work_items item
JOIN task_execution_generations generation
  ON generation.task_id=item.id AND generation.tenant_id=item.tenant_id
 AND generation.generation=item.task_execution_generation
JOIN task_execution_participants participant
  ON participant.task_id=item.id AND participant.tenant_id=item.tenant_id
 AND participant.generation=item.task_execution_generation
 AND participant.agent_management_id=$1::text
WHERE item.id=$2::text
  AND item.kind='task'
  AND item.archived_at IS NULL
`

type GetDelegatedTaskForAlterEgoParams struct {
	AgentManagementID string `json:"agent_management_id"`
	TaskID            string `json:"task_id"`
}

type GetDelegatedTaskForAlterEgoRow struct {
	TaskID             string `json:"task_id"`
	TenantID           string `json:"tenant_id"`
	ResultAgentActorID string `json:"result_agent_actor_id"`
}

// The Task an AlterEgo Context belongs to, for routing an approval result
// back into that Task's input.
func (q *Queries) GetDelegatedTaskForAlterEgo(ctx context.Context, arg GetDelegatedTaskForAlterEgoParams) (GetDelegatedTaskForAlterEgoRow, error) {
	row := q.db.QueryRow(ctx, getDelegatedTaskForAlterEgo, arg.AgentManagementID, arg.TaskID)
	var i GetDelegatedTaskForAlterEgoRow
	err := row.Scan(&i.TaskID, &i.TenantID, &i.ResultAgentActorID)
	return i, err
}

const getDelegatedTaskForCoordinator = `-- name: GetDelegatedTaskForCoordinator :one
SELECT item.id AS task_id,item.tenant_id,item.title,item.created_at,
       item.task_execution_generation::bigint AS generation,
       $1::text AS origin_room_id,
       COALESCE(work_room.room_id,'')::text AS work_room_id
FROM work_items item
JOIN task_execution_generations generation
  ON generation.task_id=item.id AND generation.tenant_id=item.tenant_id
 AND generation.generation=item.task_execution_generation
 AND generation.result_agent_actor_id=$2::text

LEFT JOIN work_item_room_links work_room
  ON work_room.work_item_id=item.id AND work_room.tenant_id=item.tenant_id
 AND work_room.link_type='work'
WHERE item.id=$3::text
  AND item.tenant_id=$4::text
  AND item.kind='task'
  AND item.archived_at IS NULL
  AND (EXISTS (SELECT 1 FROM work_item_room_links origin WHERE origin.work_item_id=item.id AND origin.link_type='origin' AND origin.room_id=$1::text)
   OR EXISTS (SELECT 1 FROM voice_live_tasks voice WHERE voice.work_item_id=item.id AND voice.home_room_id=$1::text))
`

type GetDelegatedTaskForCoordinatorParams struct {
	OriginRoomID string `json:"origin_room_id"`
	AgentActorID string `json:"agent_actor_id"`
	TaskID       string `json:"task_id"`
	TenantID     string `json:"tenant_id"`
}

type GetDelegatedTaskForCoordinatorRow struct {
	TaskID       string             `json:"task_id"`
	TenantID     string             `json:"tenant_id"`
	Title        string             `json:"title"`
	CreatedAt    pgtype.Timestamptz `json:"created_at"`
	Generation   int64              `json:"generation"`
	OriginRoomID string             `json:"origin_room_id"`
	WorkRoomID   string             `json:"work_room_id"`
}

// Only the Meta of the Task's origin Room sees and manages it, so
// a Task is addressed by its Agent and its origin Room together.
func (q *Queries) GetDelegatedTaskForCoordinator(ctx context.Context, arg GetDelegatedTaskForCoordinatorParams) (GetDelegatedTaskForCoordinatorRow, error) {
	row := q.db.QueryRow(ctx, getDelegatedTaskForCoordinator,
		arg.OriginRoomID,
		arg.AgentActorID,
		arg.TaskID,
		arg.TenantID,
	)
	var i GetDelegatedTaskForCoordinatorRow
	err := row.Scan(
		&i.TaskID,
		&i.TenantID,
		&i.Title,
		&i.CreatedAt,
		&i.Generation,
		&i.OriginRoomID,
		&i.WorkRoomID,
	)
	return i, err
}

const getLatestTaskMetaCallbackMessage = `-- name: GetLatestTaskMetaCallbackMessage :one
SELECT body,created_at
FROM task_meta_callback_messages
WHERE task_id=$1::text
  AND tenant_id=$2::text
ORDER BY meta_seq DESC
LIMIT 1
`

type GetLatestTaskMetaCallbackMessageParams struct {
	TaskID   string `json:"task_id"`
	TenantID string `json:"tenant_id"`
}

type GetLatestTaskMetaCallbackMessageRow struct {
	Body      string             `json:"body"`
	CreatedAt pgtype.Timestamptz `json:"created_at"`
}

func (q *Queries) GetLatestTaskMetaCallbackMessage(ctx context.Context, arg GetLatestTaskMetaCallbackMessageParams) (GetLatestTaskMetaCallbackMessageRow, error) {
	row := q.db.QueryRow(ctx, getLatestTaskMetaCallbackMessage, arg.TaskID, arg.TenantID)
	var i GetLatestTaskMetaCallbackMessageRow
	err := row.Scan(&i.Body, &i.CreatedAt)
	return i, err
}

const listDelegatedTaskPendingApprovals = `-- name: ListDelegatedTaskPendingApprovals :many
SELECT CASE WHEN decision.kind='runtime_permission' THEN 'permission' ELSE 'connector' END::text AS kind,
       decision.id,
       COALESCE(decision.view->>'title','')::text AS title,
       decision.created_at,decision.expires_at
FROM decisions decision
WHERE decision.tenant_id=$1::text
  AND decision.alter_ego_task_id=$2::text
  AND decision.status='pending'
  AND decision.kind NOT IN ('connection_auth','provider_key','browser_connection','computer_permission','document_access','search_key')
  AND (decision.kind<>'runtime_permission' OR decision.request->>'context_key'=$3::text)
ORDER BY decision.created_at,decision.id
`

type ListDelegatedTaskPendingApprovalsParams struct {
	TenantID   string `json:"tenant_id"`
	TaskID     string `json:"task_id"`
	ContextKey string `json:"context_key"`
}

type ListDelegatedTaskPendingApprovalsRow struct {
	Kind      string             `json:"kind"`
	ID        string             `json:"id"`
	Title     string             `json:"title"`
	CreatedAt pgtype.Timestamptz `json:"created_at"`
	ExpiresAt pgtype.Timestamptz `json:"expires_at"`
}

// Approvals the Task's AlterEgo is waiting on: Runtime permission cards of
// its Context and the other approvals it asked for. Connection, computer
// permission, web search key and Document access cards are not approvals.
func (q *Queries) ListDelegatedTaskPendingApprovals(ctx context.Context, arg ListDelegatedTaskPendingApprovalsParams) ([]ListDelegatedTaskPendingApprovalsRow, error) {
	rows, err := q.db.Query(ctx, listDelegatedTaskPendingApprovals, arg.TenantID, arg.TaskID, arg.ContextKey)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []ListDelegatedTaskPendingApprovalsRow{}
	for rows.Next() {
		var i ListDelegatedTaskPendingApprovalsRow
		if err := rows.Scan(
			&i.Kind,
			&i.ID,
			&i.Title,
			&i.CreatedAt,
			&i.ExpiresAt,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listDelegatedTasksForCoordinator = `-- name: ListDelegatedTasksForCoordinator :many
SELECT item.id AS task_id,item.title,item.created_at,
       COALESCE(item.task_execution_status,'')::text AS status,
       COALESCE(item.task_execution_reason_code,'')::text AS reason_code,
       item.task_execution_updated_at::timestamptz AS updated_at
FROM work_items item
JOIN task_execution_generations generation
  ON generation.task_id=item.id AND generation.tenant_id=item.tenant_id
 AND generation.generation=item.task_execution_generation
 AND generation.result_agent_actor_id=$1::text

WHERE item.tenant_id=$2::text
  AND item.kind='task'
  AND item.archived_at IS NULL
  AND (EXISTS (SELECT 1 FROM work_item_room_links origin WHERE origin.work_item_id=item.id AND origin.link_type='origin' AND origin.room_id=$3::text)
   OR EXISTS (SELECT 1 FROM voice_live_tasks voice WHERE voice.work_item_id=item.id AND voice.home_room_id=$3::text))
ORDER BY item.created_at DESC,item.id DESC
LIMIT 50
`

type ListDelegatedTasksForCoordinatorParams struct {
	AgentActorID string `json:"agent_actor_id"`
	TenantID     string `json:"tenant_id"`
	OriginRoomID string `json:"origin_room_id"`
}

type ListDelegatedTasksForCoordinatorRow struct {
	TaskID     string             `json:"task_id"`
	Title      string             `json:"title"`
	CreatedAt  pgtype.Timestamptz `json:"created_at"`
	Status     string             `json:"status"`
	ReasonCode string             `json:"reason_code"`
	UpdatedAt  pgtype.Timestamptz `json:"updated_at"`
}

func (q *Queries) ListDelegatedTasksForCoordinator(ctx context.Context, arg ListDelegatedTasksForCoordinatorParams) ([]ListDelegatedTasksForCoordinatorRow, error) {
	rows, err := q.db.Query(ctx, listDelegatedTasksForCoordinator, arg.AgentActorID, arg.TenantID, arg.OriginRoomID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []ListDelegatedTasksForCoordinatorRow{}
	for rows.Next() {
		var i ListDelegatedTasksForCoordinatorRow
		if err := rows.Scan(
			&i.TaskID,
			&i.Title,
			&i.CreatedAt,
			&i.Status,
			&i.ReasonCode,
			&i.UpdatedAt,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listRoomBackgroundTasks = `-- name: ListRoomBackgroundTasks :many
SELECT item.id, item.title, item.description, item.created_at, item.task_execution_status
FROM work_item_room_links origin
JOIN work_items item ON item.id=origin.work_item_id AND item.tenant_id=origin.tenant_id
WHERE origin.room_id=$1::text AND origin.tenant_id=$2::text
  AND origin.link_type='origin' AND item.kind='task' AND item.archived_at IS NULL
  AND item.task_execution_status IN ('running','waiting_for_approval')
ORDER BY item.created_at, item.id
LIMIT 50
`

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

type ListRoomBackgroundTasksRow struct {
	ID                  string             `json:"id"`
	Title               string             `json:"title"`
	Description         string             `json:"description"`
	CreatedAt           pgtype.Timestamptz `json:"created_at"`
	TaskExecutionStatus pgtype.Text        `json:"task_execution_status"`
}

// The background Tasks this Room's Meta delegated that are still running,
// oldest first. Waiting for an approval counts as running.
func (q *Queries) ListRoomBackgroundTasks(ctx context.Context, arg ListRoomBackgroundTasksParams) ([]ListRoomBackgroundTasksRow, error) {
	rows, err := q.db.Query(ctx, listRoomBackgroundTasks, arg.RoomID, arg.TenantID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []ListRoomBackgroundTasksRow{}
	for rows.Next() {
		var i ListRoomBackgroundTasksRow
		if err := rows.Scan(
			&i.ID,
			&i.Title,
			&i.Description,
			&i.CreatedAt,
			&i.TaskExecutionStatus,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listRoomRunningTasks = `-- name: ListRoomRunningTasks :many
SELECT item.id, item.title, item.description, item.created_at, item.quiet,
       EXISTS (SELECT 1 FROM voice_live_tasks voice WHERE voice.work_item_id=item.id)::boolean AS live
FROM work_items item
WHERE item.id IN (
    SELECT origin.work_item_id FROM work_item_room_links origin
    WHERE origin.room_id=$1::text AND origin.tenant_id=$2::text AND origin.link_type='origin'
    UNION
    SELECT live.work_item_id FROM voice_live_tasks live WHERE live.home_room_id=$1::text
  )
  AND item.tenant_id=$2::text AND item.kind='task' AND item.archived_at IS NULL
  AND item.task_execution_status IN ('running','waiting_for_approval')
ORDER BY item.created_at, item.id
LIMIT 50
`

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

type ListRoomRunningTasksRow struct {
	ID          string             `json:"id"`
	Title       string             `json:"title"`
	Description string             `json:"description"`
	CreatedAt   pgtype.Timestamptz `json:"created_at"`
	Quiet       bool               `json:"quiet"`
	Live        bool               `json:"live"`
}

// The Tasks running for this Room, oldest first: the background Tasks its Meta
// delegated and the tasks Live started with it as their home Room; live
// marks the latter, which have no Meta. quiet marks a Task started during a
// proactive wake or a Routine that serves a Tracking Item.
func (q *Queries) ListRoomRunningTasks(ctx context.Context, arg ListRoomRunningTasksParams) ([]ListRoomRunningTasksRow, error) {
	rows, err := q.db.Query(ctx, listRoomRunningTasks, arg.RoomID, arg.TenantID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []ListRoomRunningTasksRow{}
	for rows.Next() {
		var i ListRoomRunningTasksRow
		if err := rows.Scan(
			&i.ID,
			&i.Title,
			&i.Description,
			&i.CreatedAt,
			&i.Quiet,
			&i.Live,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const setDelegatedTaskStatus = `-- name: SetDelegatedTaskStatus :execrows
UPDATE work_items
SET task_execution_status=$1::text,
    task_execution_reason_code=$2::text,
    task_execution_revision=task_execution_revision+1,
    task_execution_updated_at=clock_timestamp(),
    task_next_reconcile_at=clock_timestamp(),
    task_worker_id=NULL,
    task_lease_token_hash=NULL,
    task_lease_expires_at=NULL
WHERE id=$3::text
  AND tenant_id=$4::text
  AND task_execution_generation=$5::bigint
  AND task_execution_revision=$6::bigint
  AND task_execution_status=$7::text
`

type SetDelegatedTaskStatusParams struct {
	NextStatus                string      `json:"next_status"`
	ReasonCode                pgtype.Text `json:"reason_code"`
	TaskID                    string      `json:"task_id"`
	TenantID                  string      `json:"tenant_id"`
	Generation                int64       `json:"generation"`
	ExpectedExecutionRevision int64       `json:"expected_execution_revision"`
	ExpectedStatus            string      `json:"expected_status"`
}

// A Meta input or stop changes a Task outside the Worker lease, so it
// releases any lease and makes the Task due at once.
func (q *Queries) SetDelegatedTaskStatus(ctx context.Context, arg SetDelegatedTaskStatusParams) (int64, error) {
	result, err := q.db.Exec(ctx, setDelegatedTaskStatus,
		arg.NextStatus,
		arg.ReasonCode,
		arg.TaskID,
		arg.TenantID,
		arg.Generation,
		arg.ExpectedExecutionRevision,
		arg.ExpectedStatus,
	)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected(), nil
}