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.

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

package store

import (
	"context"

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

const attachVoiceLiveHandoverToInput = `-- name: AttachVoiceLiveHandoverToInput :exec
UPDATE agent_runtime_inputs SET payload=$1::jsonb,payload_hash=$2::bytea,updated_at=clock_timestamp()
WHERE context_key=$3::text AND input_id=$4::text
`

type AttachVoiceLiveHandoverToInputParams struct {
	Payload     []byte `json:"payload"`
	PayloadHash []byte `json:"payload_hash"`
	ContextKey  string `json:"context_key"`
	InputID     string `json:"input_id"`
}

func (q *Queries) AttachVoiceLiveHandoverToInput(ctx context.Context, arg AttachVoiceLiveHandoverToInputParams) error {
	_, err := q.db.Exec(ctx, attachVoiceLiveHandoverToInput,
		arg.Payload,
		arg.PayloadHash,
		arg.ContextKey,
		arg.InputID,
	)
	return err
}

const cancelVoiceLiveMessageForRoomAgents = `-- name: CancelVoiceLiveMessageForRoomAgents :exec
INSERT INTO room_agent_message_cancellations(tenant_id,room_id,agent_actor_id,message_id)
SELECT message.tenant_id,message.room_id,membership.actor_id,message.id
FROM messages message
JOIN active_room_members membership
  ON membership.room_id=coalesce((SELECT parent_room_id FROM rooms WHERE id=message.room_id),message.room_id)
JOIN actors agent ON agent.id=membership.actor_id AND agent.tenant_id=message.tenant_id AND agent.kind='agent'
WHERE message.id=$1::text
ON CONFLICT DO NOTHING
`

// A live turn is answered by the live model; reuse Stop's cancellation fact so
// no Room Agent accepts it while it stays in ordinary Room history.
func (q *Queries) CancelVoiceLiveMessageForRoomAgents(ctx context.Context, messageID string) error {
	_, err := q.db.Exec(ctx, cancelVoiceLiveMessageForRoomAgents, messageID)
	return err
}

const claimVoiceLiveToolCall = `-- name: ClaimVoiceLiveToolCall :execrows
INSERT INTO voice_live_tool_calls(voice_session_id,call_id,turn_id,name,arguments,request_hash)
SELECT voice.id,$1::text,$2::text,$3::text,
 $4::text,$5::text
FROM voice_sessions voice
WHERE voice.id=$6::text AND voice.purpose='chat_live'
 AND voice.status IN ('provisioning','connected','reconnecting')
 AND voice.live_lease_until>clock_timestamp()
ON CONFLICT DO NOTHING
`

type ClaimVoiceLiveToolCallParams struct {
	CallID         string `json:"call_id"`
	TurnID         string `json:"turn_id"`
	Name           string `json:"name"`
	Arguments      string `json:"arguments"`
	RequestHash    string `json:"request_hash"`
	VoiceSessionID string `json:"voice_session_id"`
}

// Admission commits before external effects. Retries never execute a sent call twice.
func (q *Queries) ClaimVoiceLiveToolCall(ctx context.Context, arg ClaimVoiceLiveToolCallParams) (int64, error) {
	result, err := q.db.Exec(ctx, claimVoiceLiveToolCall,
		arg.CallID,
		arg.TurnID,
		arg.Name,
		arg.Arguments,
		arg.RequestHash,
		arg.VoiceSessionID,
	)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected(), nil
}

const completeVoiceLiveToolCall = `-- name: CompleteVoiceLiveToolCall :exec
UPDATE voice_live_tool_calls SET output=$1::text,state=$2::text
WHERE voice_session_id=$3::text AND call_id=$4::text
`

type CompleteVoiceLiveToolCallParams struct {
	Output         string `json:"output"`
	State          string `json:"state"`
	VoiceSessionID string `json:"voice_session_id"`
	CallID         string `json:"call_id"`
}

func (q *Queries) CompleteVoiceLiveToolCall(ctx context.Context, arg CompleteVoiceLiveToolCallParams) error {
	_, err := q.db.Exec(ctx, completeVoiceLiveToolCall,
		arg.Output,
		arg.State,
		arg.VoiceSessionID,
		arg.CallID,
	)
	return err
}

const countVoiceLiveTurnCanvasChanges = `-- name: CountVoiceLiveTurnCanvasChanges :one
SELECT count(*)::bigint FROM voice_live_tool_calls
WHERE voice_session_id=$1::text
  AND turn_id=$2::text
  AND name IN ('open_email_canvas','edit_email_canvas','attach_email_file')
`

type CountVoiceLiveTurnCanvasChangesParams struct {
	VoiceSessionID string `json:"voice_session_id"`
	TurnID         string `json:"turn_id"`
}

// Whether a live turn wrote or changed a Gmail canvas: a send in that turn
// would go out before the user saw the change.
func (q *Queries) CountVoiceLiveTurnCanvasChanges(ctx context.Context, arg CountVoiceLiveTurnCanvasChangesParams) (int64, error) {
	row := q.db.QueryRow(ctx, countVoiceLiveTurnCanvasChanges, arg.VoiceSessionID, arg.TurnID)
	var column_1 int64
	err := row.Scan(&column_1)
	return column_1, err
}

const countVoiceLiveTurnToolCalls = `-- name: CountVoiceLiveTurnToolCalls :one
SELECT count(*)::bigint FROM voice_live_tool_calls
WHERE voice_session_id=$1::text
  AND turn_id=$2::text AND name=$3::text
`

type CountVoiceLiveTurnToolCallsParams struct {
	VoiceSessionID string `json:"voice_session_id"`
	TurnID         string `json:"turn_id"`
	Name           string `json:"name"`
}

// How many calls of one tool a live turn already made.
func (q *Queries) CountVoiceLiveTurnToolCalls(ctx context.Context, arg CountVoiceLiveTurnToolCallsParams) (int64, error) {
	row := q.db.QueryRow(ctx, countVoiceLiveTurnToolCalls, arg.VoiceSessionID, arg.TurnID, arg.Name)
	var column_1 int64
	err := row.Scan(&column_1)
	return column_1, err
}

const createVoiceLiveReply = `-- name: CreateVoiceLiveReply :exec
INSERT INTO voice_live_replies(voice_session_id,event_id,turn_id,message_id)
VALUES ($1::text,$2::text,$3::text,$4::text)
`

type CreateVoiceLiveReplyParams struct {
	VoiceSessionID string `json:"voice_session_id"`
	EventID        string `json:"event_id"`
	TurnID         string `json:"turn_id"`
	MessageID      string `json:"message_id"`
}

func (q *Queries) CreateVoiceLiveReply(ctx context.Context, arg CreateVoiceLiveReplyParams) error {
	_, err := q.db.Exec(ctx, createVoiceLiveReply,
		arg.VoiceSessionID,
		arg.EventID,
		arg.TurnID,
		arg.MessageID,
	)
	return err
}

const createVoiceLiveReportDelivery = `-- name: CreateVoiceLiveReportDelivery :exec
INSERT INTO voice_live_report_deliveries(report_id,voice_session_id,message_id)
VALUES($1::text,$2::text,$3::text)
ON CONFLICT (report_id) DO NOTHING
`

type CreateVoiceLiveReportDeliveryParams struct {
	ReportID       string `json:"report_id"`
	VoiceSessionID string `json:"voice_session_id"`
	MessageID      string `json:"message_id"`
}

// A report is delivered once; a later card with the same files keeps the first.
func (q *Queries) CreateVoiceLiveReportDelivery(ctx context.Context, arg CreateVoiceLiveReportDeliveryParams) error {
	_, err := q.db.Exec(ctx, createVoiceLiveReportDelivery, arg.ReportID, arg.VoiceSessionID, arg.MessageID)
	return err
}

const createVoiceLiveTurn = `-- name: CreateVoiceLiveTurn :execrows
INSERT INTO voice_live_turns(voice_session_id,turn_id,human_message_id)
VALUES ($1::text,$2::text,$3::text)
ON CONFLICT DO NOTHING
`

type CreateVoiceLiveTurnParams struct {
	VoiceSessionID string `json:"voice_session_id"`
	TurnID         string `json:"turn_id"`
	HumanMessageID string `json:"human_message_id"`
}

func (q *Queries) CreateVoiceLiveTurn(ctx context.Context, arg CreateVoiceLiveTurnParams) (int64, error) {
	result, err := q.db.Exec(ctx, createVoiceLiveTurn, arg.VoiceSessionID, arg.TurnID, arg.HumanMessageID)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected(), nil
}

const findVoiceLiveRoomsForAccount = `-- name: FindVoiceLiveRoomsForAccount :many
SELECT room.id,
  coalesce(nullif(coalesce(direct_peer.display_name,''),''),room.name)::text AS name
FROM rooms room
JOIN actors caller ON caller.tenant_id=room.tenant_id AND caller.id=$1::text AND caller.kind='human'
JOIN active_room_members membership ON membership.room_id=room.id AND membership.actor_id=caller.id
LEFT JOIN room_member_states participation
  ON participation.room_id=room.id AND participation.actor_id=caller.id
 AND participation.participation_epoch_id=membership.membership_epoch_id
LEFT JOIN rooms direct ON direct.id=room.id
LEFT JOIN actors direct_peer ON direct_peer.id=direct.direct_agent_actor_id AND direct_peer.tenant_id=direct.tenant_id
WHERE room.deleted_at IS NULL AND room.deletion_started_at IS NULL
  AND participation.left_at IS NULL
  AND NOT EXISTS (SELECT 1 FROM rooms thread WHERE thread.id=room.id AND thread.parent_room_id IS NOT NULL)
  -- Task Work Rooms are never listed, as in the Room list.
  AND NOT EXISTS (SELECT 1 FROM work_item_room_links work WHERE work.room_id=room.id AND work.link_type='work')
  AND strpos(lower(coalesce(direct_peer.display_name,'') || ' ' || room.name),
    lower($2::text))>0
ORDER BY room.updated_at DESC,room.id
LIMIT 10
`

type FindVoiceLiveRoomsForAccountParams struct {
	HumanActorID string `json:"human_actor_id"`
	Query        string `json:"query"`
}

type FindVoiceLiveRoomsForAccountRow struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

// Rooms the Human can post in, matched by Room name or direct peer name.
func (q *Queries) FindVoiceLiveRoomsForAccount(ctx context.Context, arg FindVoiceLiveRoomsForAccountParams) ([]FindVoiceLiveRoomsForAccountRow, error) {
	rows, err := q.db.Query(ctx, findVoiceLiveRoomsForAccount, arg.HumanActorID, arg.Query)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []FindVoiceLiveRoomsForAccountRow{}
	for rows.Next() {
		var i FindVoiceLiveRoomsForAccountRow
		if err := rows.Scan(&i.ID, &i.Name); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const getLatestVoiceLiveToolOutput = `-- name: GetLatestVoiceLiveToolOutput :one
SELECT output FROM voice_live_tool_calls
WHERE voice_session_id=$1::text AND name=$2::text
 AND call_id<>$3::text
ORDER BY created_at DESC LIMIT 1
`

type GetLatestVoiceLiveToolOutputParams struct {
	VoiceSessionID string `json:"voice_session_id"`
	Name           string `json:"name"`
	CallID         string `json:"call_id"`
}

// The newest output this session returned for the tool before the call that
// asks, such as the page the browser showed last. The asking call is already
// claimed with no output, so it is left out.
func (q *Queries) GetLatestVoiceLiveToolOutput(ctx context.Context, arg GetLatestVoiceLiveToolOutputParams) (string, error) {
	row := q.db.QueryRow(ctx, getLatestVoiceLiveToolOutput, arg.VoiceSessionID, arg.Name, arg.CallID)
	var output string
	err := row.Scan(&output)
	return output, err
}

const getVoiceLiveComputerTarget = `-- name: GetVoiceLiveComputerTarget :one
SELECT registration.agent_management_id::text AS agent_management_id,
       registration.computer_id::text AS computer_id
FROM agent_registrations registration
JOIN local_computers computer ON computer.computer_id=registration.computer_id
WHERE registration.actor_id=$1::text
 AND registration.tenant_id=$2::text
 AND registration.created_by_actor_id=$3::text
 AND registration.status='active' AND computer.status='online'
`

type GetVoiceLiveComputerTargetParams struct {
	AgentActorID string `json:"agent_actor_id"`
	TenantID     string `json:"tenant_id"`
	HumanActorID string `json:"human_actor_id"`
}

type GetVoiceLiveComputerTargetRow struct {
	AgentManagementID string `json:"agent_management_id"`
	ComputerID        string `json:"computer_id"`
}

func (q *Queries) GetVoiceLiveComputerTarget(ctx context.Context, arg GetVoiceLiveComputerTargetParams) (GetVoiceLiveComputerTargetRow, error) {
	row := q.db.QueryRow(ctx, getVoiceLiveComputerTarget, arg.AgentActorID, arg.TenantID, arg.HumanActorID)
	var i GetVoiceLiveComputerTargetRow
	err := row.Scan(&i.AgentManagementID, &i.ComputerID)
	return i, err
}

const getVoiceLiveDocumentBodyState = `-- name: GetVoiceLiveDocumentBodyState :one
SELECT body.seq, encode(sha256(body.state),'hex')::text AS fingerprint
FROM document_bodies body
JOIN documents document ON document.id=body.document_id
WHERE body.document_id=$1::text AND document.tenant_id=$2::text
`

type GetVoiceLiveDocumentBodyStateParams struct {
	DocumentID string `json:"document_id"`
	TenantID   string `json:"tenant_id"`
}

type GetVoiceLiveDocumentBodyStateRow struct {
	Seq         int64  `json:"seq"`
	Fingerprint string `json:"fingerprint"`
}

// The persisted sequence and full-state fingerprint a comment anchor attaches against.
func (q *Queries) GetVoiceLiveDocumentBodyState(ctx context.Context, arg GetVoiceLiveDocumentBodyStateParams) (GetVoiceLiveDocumentBodyStateRow, error) {
	row := q.db.QueryRow(ctx, getVoiceLiveDocumentBodyState, arg.DocumentID, arg.TenantID)
	var i GetVoiceLiveDocumentBodyStateRow
	err := row.Scan(&i.Seq, &i.Fingerprint)
	return i, err
}

const getVoiceLiveDocumentTitle = `-- name: GetVoiceLiveDocumentTitle :one
SELECT title FROM documents WHERE id=$1::text AND tenant_id=$2::text
`

type GetVoiceLiveDocumentTitleParams struct {
	DocumentID string `json:"document_id"`
	TenantID   string `json:"tenant_id"`
}

// The title a file the live voice sends is named after; its download
// already checked the Agent reads it.
func (q *Queries) GetVoiceLiveDocumentTitle(ctx context.Context, arg GetVoiceLiveDocumentTitleParams) (string, error) {
	row := q.db.QueryRow(ctx, getVoiceLiveDocumentTitle, arg.DocumentID, arg.TenantID)
	var title string
	err := row.Scan(&title)
	return title, err
}

const getVoiceLiveHandoverForContext = `-- name: GetVoiceLiveHandoverForContext :one
SELECT voice.id,voice.room_id,voice.created_by_actor_id,voice.live_agent_actor_id
FROM agent_execution_contexts context JOIN voice_sessions voice
 ON voice.tenant_id=context.tenant_id AND voice.live_agent_actor_id=context.agent_actor_id
WHERE context.context_key=$1::text AND context.context_kind='meta'
 AND voice.purpose='chat_live' AND (voice.status IN ('closing','closed') OR voice.live_lease_until<=now())
 AND (voice.room_id=context.room_id OR EXISTS(SELECT 1 FROM voice_live_tasks task
  WHERE task.room_id=voice.room_id AND task.owner_actor_id=voice.created_by_actor_id AND task.home_room_id=context.room_id))
 AND EXISTS(SELECT 1 FROM active_room_members member WHERE member.room_id=voice.room_id AND member.actor_id=context.agent_actor_id)
 AND NOT EXISTS(SELECT 1 FROM agent_live_handover_receipts receipt
  JOIN agent_runtime_inputs input ON input.context_key=receipt.context_key AND input.input_id=receipt.input_id
  WHERE receipt.context_key=context.context_key AND receipt.voice_session_id=voice.id
   AND (input.status='steering' OR EXISTS(SELECT 1 FROM agent_local_run_inputs link
    JOIN agent_local_runs run ON run.run_id=link.run_id
    WHERE link.context_key=receipt.context_key AND link.input_id=receipt.input_id
     AND run.status IN ('queued','running','succeeded'))))
ORDER BY voice.created_at DESC,voice.id DESC LIMIT 1
`

type GetVoiceLiveHandoverForContextRow struct {
	ID               string      `json:"id"`
	RoomID           string      `json:"room_id"`
	CreatedByActorID string      `json:"created_by_actor_id"`
	LiveAgentActorID pgtype.Text `json:"live_agent_actor_id"`
}

func (q *Queries) GetVoiceLiveHandoverForContext(ctx context.Context, contextKey string) (GetVoiceLiveHandoverForContextRow, error) {
	row := q.db.QueryRow(ctx, getVoiceLiveHandoverForContext, contextKey)
	var i GetVoiceLiveHandoverForContextRow
	err := row.Scan(
		&i.ID,
		&i.RoomID,
		&i.CreatedByActorID,
		&i.LiveAgentActorID,
	)
	return i, err
}

const getVoiceLiveReply = `-- name: GetVoiceLiveReply :one
SELECT message_id FROM voice_live_replies
WHERE voice_session_id=$1::text AND event_id=$2::text
`

type GetVoiceLiveReplyParams struct {
	VoiceSessionID string `json:"voice_session_id"`
	EventID        string `json:"event_id"`
}

func (q *Queries) GetVoiceLiveReply(ctx context.Context, arg GetVoiceLiveReplyParams) (string, error) {
	row := q.db.QueryRow(ctx, getVoiceLiveReply, arg.VoiceSessionID, arg.EventID)
	var message_id string
	err := row.Scan(&message_id)
	return message_id, err
}

const getVoiceLiveReplyAgent = `-- name: GetVoiceLiveReplyAgent :one
SELECT agent.id,agent.tenant_id,agent.kind,agent.display_name,agent.account_id,agent.handle,agent.created_at
FROM actors agent
JOIN agent_registrations registration
  ON registration.actor_id=agent.id AND registration.tenant_id=agent.tenant_id AND registration.status='active'
JOIN active_room_members membership
  ON membership.room_id=$1::text AND membership.actor_id=agent.id
WHERE agent.kind='agent'
  AND agent.id=coalesce(
    (SELECT direct.direct_agent_actor_id FROM rooms direct
     WHERE direct.id=$1::text AND direct.direct_human_actor_id=$2::text),
    (SELECT another_me.actor_id FROM agent_registrations another_me
     WHERE another_me.represented_human_actor_id=$2::text
       AND another_me.agent_type='anotherme' AND another_me.status='active'
     ORDER BY another_me.actor_id LIMIT 1)
  )
`

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

// The live reply speaks as the Agent of an Agent direct Room, otherwise as the
// Human's own AnotherMe when it is an active member of the Room.
func (q *Queries) GetVoiceLiveReplyAgent(ctx context.Context, arg GetVoiceLiveReplyAgentParams) (Actor, error) {
	row := q.db.QueryRow(ctx, getVoiceLiveReplyAgent, arg.RoomID, arg.HumanActorID)
	var i Actor
	err := row.Scan(
		&i.ID,
		&i.TenantID,
		&i.Kind,
		&i.DisplayName,
		&i.AccountID,
		&i.Handle,
		&i.CreatedAt,
	)
	return i, err
}

const getVoiceLiveReplySessionContext = `-- name: GetVoiceLiveReplySessionContext :one
SELECT voice.id, voice.tenant_id, voice.room_id, voice.created_by_actor_id, voice.status, voice.provider_room_name, voice.participant_identity, voice.credential_generation, voice.last_failure_code, voice.created_at, voice.updated_at, voice.closed_at, voice.latest_partial_text, voice.latest_partial_start_offset_ms, voice.latest_partial_end_offset_ms, voice.latest_partial_updated_at, voice.last_input_started_ms, voice.last_input_ended_ms, voice.purpose, voice.auth_session_id, voice.live_agent_actor_id, voice.live_lease_until, voice.next_media_epoch,actor.account_id
FROM voice_sessions voice
JOIN actors actor
  ON actor.id=voice.created_by_actor_id AND actor.tenant_id=voice.tenant_id AND actor.kind='human'
JOIN active_room_members member ON member.room_id=voice.room_id AND member.actor_id=actor.id
JOIN rooms room ON room.id=voice.room_id AND room.deleted_at IS NULL
WHERE voice.id=$1::text AND voice.purpose='chat_live'
  AND (voice.status IN ('provisioning','connected','reconnecting','closing')
    OR (voice.status='closed' AND voice.closed_at > now() - interval '60 seconds'))
`

type GetVoiceLiveReplySessionContextRow struct {
	ID                         string             `json:"id"`
	TenantID                   string             `json:"tenant_id"`
	RoomID                     string             `json:"room_id"`
	CreatedByActorID           string             `json:"created_by_actor_id"`
	Status                     string             `json:"status"`
	ProviderRoomName           string             `json:"provider_room_name"`
	ParticipantIdentity        string             `json:"participant_identity"`
	CredentialGeneration       int64              `json:"credential_generation"`
	LastFailureCode            pgtype.Text        `json:"last_failure_code"`
	CreatedAt                  pgtype.Timestamptz `json:"created_at"`
	UpdatedAt                  pgtype.Timestamptz `json:"updated_at"`
	ClosedAt                   pgtype.Timestamptz `json:"closed_at"`
	LatestPartialText          pgtype.Text        `json:"latest_partial_text"`
	LatestPartialStartOffsetMs pgtype.Int8        `json:"latest_partial_start_offset_ms"`
	LatestPartialEndOffsetMs   pgtype.Int8        `json:"latest_partial_end_offset_ms"`
	LatestPartialUpdatedAt     pgtype.Timestamptz `json:"latest_partial_updated_at"`
	LastInputStartedMs         pgtype.Int8        `json:"last_input_started_ms"`
	LastInputEndedMs           pgtype.Int8        `json:"last_input_ended_ms"`
	Purpose                    string             `json:"purpose"`
	AuthSessionID              pgtype.Text        `json:"auth_session_id"`
	LiveAgentActorID           pgtype.Text        `json:"live_agent_actor_id"`
	LiveLeaseUntil             pgtype.Timestamptz `json:"live_lease_until"`
	NextMediaEpoch             int32              `json:"next_media_epoch"`
	AccountID                  pgtype.Text        `json:"account_id"`
}

// A reply may still be saved shortly after its session closed: the Human can
// exit Voice Mode while the last answer plays. Membership is still required.
func (q *Queries) GetVoiceLiveReplySessionContext(ctx context.Context, voiceSessionID string) (GetVoiceLiveReplySessionContextRow, error) {
	row := q.db.QueryRow(ctx, getVoiceLiveReplySessionContext, voiceSessionID)
	var i GetVoiceLiveReplySessionContextRow
	err := row.Scan(
		&i.ID,
		&i.TenantID,
		&i.RoomID,
		&i.CreatedByActorID,
		&i.Status,
		&i.ProviderRoomName,
		&i.ParticipantIdentity,
		&i.CredentialGeneration,
		&i.LastFailureCode,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.ClosedAt,
		&i.LatestPartialText,
		&i.LatestPartialStartOffsetMs,
		&i.LatestPartialEndOffsetMs,
		&i.LatestPartialUpdatedAt,
		&i.LastInputStartedMs,
		&i.LastInputEndedMs,
		&i.Purpose,
		&i.AuthSessionID,
		&i.LiveAgentActorID,
		&i.LiveLeaseUntil,
		&i.NextMediaEpoch,
		&i.AccountID,
	)
	return i, err
}

const getVoiceLiveRoomLabel = `-- name: GetVoiceLiveRoomLabel :one
SELECT coalesce(agent_peer.display_name,room.name)::text AS label
FROM rooms room
LEFT JOIN rooms direct ON direct.id=room.id
LEFT JOIN actors agent_peer ON agent_peer.id=direct.direct_agent_actor_id AND agent_peer.tenant_id=direct.tenant_id
WHERE room.id=$1::text
`

// The name the Human sees for a Room: the other side of a direct Room, else its name.
func (q *Queries) GetVoiceLiveRoomLabel(ctx context.Context, roomID string) (string, error) {
	row := q.db.QueryRow(ctx, getVoiceLiveRoomLabel, roomID)
	var label string
	err := row.Scan(&label)
	return label, err
}

const getVoiceLiveSessionForTurn = `-- name: GetVoiceLiveSessionForTurn :one
SELECT voice.id
FROM voice_sessions voice
WHERE voice.id=$1::text
  AND voice.created_by_actor_id=$2::text
  AND voice.room_id=$3::text
  AND voice.purpose='chat_live'
  AND voice.status IN ('provisioning','connected','reconnecting') AND voice.live_lease_until>clock_timestamp()
`

type GetVoiceLiveSessionForTurnParams struct {
	VoiceSessionID string `json:"voice_session_id"`
	ActorID        string `json:"actor_id"`
	RoomID         string `json:"room_id"`
}

func (q *Queries) GetVoiceLiveSessionForTurn(ctx context.Context, arg GetVoiceLiveSessionForTurnParams) (string, error) {
	row := q.db.QueryRow(ctx, getVoiceLiveSessionForTurn, arg.VoiceSessionID, arg.ActorID, arg.RoomID)
	var id string
	err := row.Scan(&id)
	return id, err
}

const getVoiceLiveSlackUser = `-- name: GetVoiceLiveSlackUser :one
SELECT coalesce(remote_user_id,'')::text FROM external_connections
WHERE id=$1::text AND provider='slack'
`

// The Slack user a connection was identified as, so the live voice need not
// ask Slack who the user is on every call.
func (q *Queries) GetVoiceLiveSlackUser(ctx context.Context, connectionID string) (string, error) {
	row := q.db.QueryRow(ctx, getVoiceLiveSlackUser, connectionID)
	var column_1 string
	err := row.Scan(&column_1)
	return column_1, err
}

const getVoiceLiveTaskLatestReport = `-- name: GetVoiceLiveTaskLatestReport :one
SELECT message.id FROM task_meta_callback_messages message
JOIN work_items item ON item.id=message.task_id AND item.task_execution_generation=message.generation
JOIN task_meta_callbacks callback ON callback.task_id=message.task_id AND callback.generation=message.generation
WHERE message.task_id=$1::text
  AND callback.coordinator_actor_id=$2::text AND callback.tenant_id=$3::text
ORDER BY message.meta_seq DESC LIMIT 1
`

type GetVoiceLiveTaskLatestReportParams struct {
	TaskID             string `json:"task_id"`
	CoordinatorActorID string `json:"coordinator_actor_id"`
	TenantID           string `json:"tenant_id"`
}

// The report the Task's coordinator got when its latest turn ended.
func (q *Queries) GetVoiceLiveTaskLatestReport(ctx context.Context, arg GetVoiceLiveTaskLatestReportParams) (string, error) {
	row := q.db.QueryRow(ctx, getVoiceLiveTaskLatestReport, arg.TaskID, arg.CoordinatorActorID, arg.TenantID)
	var id string
	err := row.Scan(&id)
	return id, err
}

const getVoiceLiveToolCall = `-- name: GetVoiceLiveToolCall :one
SELECT output,request_hash,state,name FROM voice_live_tool_calls
WHERE voice_session_id=$1::text AND call_id=$2::text
`

type GetVoiceLiveToolCallParams struct {
	VoiceSessionID string `json:"voice_session_id"`
	CallID         string `json:"call_id"`
}

type GetVoiceLiveToolCallRow struct {
	Output      string `json:"output"`
	RequestHash string `json:"request_hash"`
	State       string `json:"state"`
	Name        string `json:"name"`
}

func (q *Queries) GetVoiceLiveToolCall(ctx context.Context, arg GetVoiceLiveToolCallParams) (GetVoiceLiveToolCallRow, error) {
	row := q.db.QueryRow(ctx, getVoiceLiveToolCall, arg.VoiceSessionID, arg.CallID)
	var i GetVoiceLiveToolCallRow
	err := row.Scan(
		&i.Output,
		&i.RequestHash,
		&i.State,
		&i.Name,
	)
	return i, err
}

const getVoiceLiveUserMemory = `-- name: GetVoiceLiveUserMemory :one
SELECT actor.display_name,
  coalesce(memory.markdown,'')::text AS markdown
FROM actors actor
LEFT JOIN LATERAL (
  SELECT revision.markdown FROM user_memory_revisions revision
  WHERE revision.tenant_id=actor.tenant_id AND revision.owner_actor_id=actor.id
  ORDER BY revision.version DESC LIMIT 1
) memory ON true
WHERE actor.id=$1::text AND actor.tenant_id=$2::text
`

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

type GetVoiceLiveUserMemoryRow struct {
	DisplayName string `json:"display_name"`
	Markdown    string `json:"markdown"`
}

// The user's name and latest memory.md, for the live voice to know who it
// talks to without a lookup.
func (q *Queries) GetVoiceLiveUserMemory(ctx context.Context, arg GetVoiceLiveUserMemoryParams) (GetVoiceLiveUserMemoryRow, error) {
	row := q.db.QueryRow(ctx, getVoiceLiveUserMemory, arg.ActorID, arg.TenantID)
	var i GetVoiceLiveUserMemoryRow
	err := row.Scan(&i.DisplayName, &i.Markdown)
	return i, err
}

const isVoiceLiveTaskWorkRoom = `-- name: IsVoiceLiveTaskWorkRoom :one
SELECT EXISTS(
  SELECT 1 FROM work_item_room_links
  WHERE room_id=$1::text AND link_type='work'
)
`

// A Task's own working Room: its results go back to the Room it came from,
// so the live voice neither offers nor opens it unasked.
func (q *Queries) IsVoiceLiveTaskWorkRoom(ctx context.Context, roomID string) (bool, error) {
	row := q.db.QueryRow(ctx, isVoiceLiveTaskWorkRoom, roomID)
	var exists bool
	err := row.Scan(&exists)
	return exists, err
}

const listVoiceLiveDocumentImages = `-- name: ListVoiceLiveDocumentImages :many
SELECT asset.filename
FROM document_bodies body
JOIN document_assets asset
  ON asset.id=ANY(body.asset_ids) AND asset.document_id=body.document_id
 AND asset.media_type LIKE 'image/%'
WHERE body.document_id=$1::text
ORDER BY asset.id
LIMIT 20
`

// Images the Document's body references, in Asset ID order. The caller has
// already checked the Human can read the Document.
func (q *Queries) ListVoiceLiveDocumentImages(ctx context.Context, documentID string) ([]string, error) {
	rows, err := q.db.Query(ctx, listVoiceLiveDocumentImages, documentID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []string{}
	for rows.Next() {
		var filename string
		if err := rows.Scan(&filename); err != nil {
			return nil, err
		}
		items = append(items, filename)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listVoiceLiveDocumentTitles = `-- name: ListVoiceLiveDocumentTitles :many
SELECT id::text AS document_id, title FROM documents
WHERE id=ANY($1::text[]) AND tenant_id=$2::text AND status='active'
`

type ListVoiceLiveDocumentTitlesParams struct {
	DocumentIds []string `json:"document_ids"`
	TenantID    string   `json:"tenant_id"`
}

type ListVoiceLiveDocumentTitlesRow struct {
	DocumentID string `json:"document_id"`
	Title      string `json:"title"`
}

func (q *Queries) ListVoiceLiveDocumentTitles(ctx context.Context, arg ListVoiceLiveDocumentTitlesParams) ([]ListVoiceLiveDocumentTitlesRow, error) {
	rows, err := q.db.Query(ctx, listVoiceLiveDocumentTitles, arg.DocumentIds, arg.TenantID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []ListVoiceLiveDocumentTitlesRow{}
	for rows.Next() {
		var i ListVoiceLiveDocumentTitlesRow
		if err := rows.Scan(&i.DocumentID, &i.Title); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listVoiceLiveHandoverMessages = `-- name: ListVoiceLiveHandoverMessages :many
SELECT message.id,message.author_actor_id,author.display_name AS author,author.kind AS author_kind,message.created_at,
 left(message.body,1500)::text AS body,(char_length(message.body)>1500)::boolean AS truncated,
 ARRAY(SELECT DISTINCT reference->>'document_id' FROM agent_history_messages history
  CROSS JOIN LATERAL jsonb_array_elements(history.resource_references) reference
  WHERE history.message_id=message.id AND history.tenant_id=message.tenant_id
  ORDER BY reference->>'document_id')::text[] AS document_ids,
 -- A recording's meeting summary is a card whose text lives on its Capture;
 -- the live voice reads it here instead of only the card's label.
 coalesce((SELECT capture.quick_notes FROM jsonb_array_elements(message.segments) segment
  JOIN capture_sessions capture ON capture.id=segment->>'capture_id' AND capture.tenant_id=message.tenant_id
  WHERE segment->>'type'='meeting_notes' AND capture.quick_notes_state='ready' LIMIT 1),'null'::jsonb)::jsonb AS meeting_summary
FROM messages message JOIN actors author ON author.id=message.author_actor_id
WHERE message.room_id=$1::text AND message.message_kind='conversation'
ORDER BY message.created_at DESC,message.id DESC LIMIT 20
`

type ListVoiceLiveHandoverMessagesRow struct {
	ID             string             `json:"id"`
	AuthorActorID  string             `json:"author_actor_id"`
	Author         string             `json:"author"`
	AuthorKind     string             `json:"author_kind"`
	CreatedAt      pgtype.Timestamptz `json:"created_at"`
	Body           string             `json:"body"`
	Truncated      bool               `json:"truncated"`
	DocumentIds    []string           `json:"document_ids"`
	MeetingSummary []byte             `json:"meeting_summary"`
}

func (q *Queries) ListVoiceLiveHandoverMessages(ctx context.Context, roomID string) ([]ListVoiceLiveHandoverMessagesRow, error) {
	rows, err := q.db.Query(ctx, listVoiceLiveHandoverMessages, roomID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []ListVoiceLiveHandoverMessagesRow{}
	for rows.Next() {
		var i ListVoiceLiveHandoverMessagesRow
		if err := rows.Scan(
			&i.ID,
			&i.AuthorActorID,
			&i.Author,
			&i.AuthorKind,
			&i.CreatedAt,
			&i.Body,
			&i.Truncated,
			&i.DocumentIds,
			&i.MeetingSummary,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listVoiceLiveHandoverTasks = `-- name: ListVoiceLiveHandoverTasks :many
SELECT task.work_item_id,task.ordinal,task.goal,task.home_room_id,
 coalesce(item.task_execution_status,'')::text AS state
FROM voice_live_tasks task JOIN work_items item ON item.id=task.work_item_id
WHERE task.room_id=$1::text AND task.owner_actor_id=$2::text
 AND task.canceled_at IS NULL AND item.archived_at IS NULL
ORDER BY task.ordinal DESC LIMIT 20
`

type ListVoiceLiveHandoverTasksParams struct {
	RoomID       string `json:"room_id"`
	OwnerActorID string `json:"owner_actor_id"`
}

type ListVoiceLiveHandoverTasksRow struct {
	WorkItemID string `json:"work_item_id"`
	Ordinal    int32  `json:"ordinal"`
	Goal       string `json:"goal"`
	HomeRoomID string `json:"home_room_id"`
	State      string `json:"state"`
}

// The call's Tasks the Meta keeps coordinating. Their reports are the live
// voice's to tell, so the Meta is not handed them.
func (q *Queries) ListVoiceLiveHandoverTasks(ctx context.Context, arg ListVoiceLiveHandoverTasksParams) ([]ListVoiceLiveHandoverTasksRow, error) {
	rows, err := q.db.Query(ctx, listVoiceLiveHandoverTasks, arg.RoomID, arg.OwnerActorID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []ListVoiceLiveHandoverTasksRow{}
	for rows.Next() {
		var i ListVoiceLiveHandoverTasksRow
		if err := rows.Scan(
			&i.WorkItemID,
			&i.Ordinal,
			&i.Goal,
			&i.HomeRoomID,
			&i.State,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listVoiceLiveRecentToolCalls = `-- name: ListVoiceLiveRecentToolCalls :many
SELECT name, arguments, output FROM voice_live_tool_calls
WHERE voice_session_id=$1::text
ORDER BY created_at DESC LIMIT 200
`

type ListVoiceLiveRecentToolCallsRow struct {
	Name      string `json:"name"`
	Arguments string `json:"arguments"`
	Output    string `json:"output"`
}

// This call's latest tool calls, newest first, for the Documents they named.
func (q *Queries) ListVoiceLiveRecentToolCalls(ctx context.Context, voiceSessionID string) ([]ListVoiceLiveRecentToolCallsRow, error) {
	rows, err := q.db.Query(ctx, listVoiceLiveRecentToolCalls, voiceSessionID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []ListVoiceLiveRecentToolCallsRow{}
	for rows.Next() {
		var i ListVoiceLiveRecentToolCallsRow
		if err := rows.Scan(&i.Name, &i.Arguments, &i.Output); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listVoiceLiveRoomDocuments = `-- name: ListVoiceLiveRoomDocuments :many
SELECT DISTINCT ON (document.id) document.id::text AS document_id,document.title,
  coalesce(search.search_text,'')::text AS body_text,greatest(document.updated_at,(SELECT body.updated_at FROM document_bodies body WHERE body.document_id=document.id))::timestamptz AS updated_at,message.created_at AS shared_at
FROM messages message
CROSS JOIN LATERAL jsonb_array_elements(CASE WHEN jsonb_typeof(message.segments)='array' THEN message.segments ELSE '[]'::jsonb END) segment
JOIN documents document ON document.id=segment.value->>'document_id' AND document.tenant_id=message.tenant_id
  AND document.status='active'
LEFT JOIN document_texts search ON search.document_id=document.id AND search.status='ready'
WHERE message.room_id=$1::text
  AND message.tenant_id=$2::text
  AND segment.value->>'type' IN ('document','file')
ORDER BY document.id,message.created_at DESC
LIMIT 50
`

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

type ListVoiceLiveRoomDocumentsRow struct {
	DocumentID string             `json:"document_id"`
	Title      string             `json:"title"`
	BodyText   string             `json:"body_text"`
	UpdatedAt  pgtype.Timestamptz `json:"updated_at"`
	SharedAt   pgtype.Timestamptz `json:"shared_at"`
}

// Documents and files shared in a Room's Messages, newest first, with their
// indexed text. Being shown in the Room is what lets its members read them.
func (q *Queries) ListVoiceLiveRoomDocuments(ctx context.Context, arg ListVoiceLiveRoomDocumentsParams) ([]ListVoiceLiveRoomDocumentsRow, error) {
	rows, err := q.db.Query(ctx, listVoiceLiveRoomDocuments, arg.RoomID, arg.TenantID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []ListVoiceLiveRoomDocumentsRow{}
	for rows.Next() {
		var i ListVoiceLiveRoomDocumentsRow
		if err := rows.Scan(
			&i.DocumentID,
			&i.Title,
			&i.BodyText,
			&i.UpdatedAt,
			&i.SharedAt,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listVoiceLiveRoomRuns = `-- name: ListVoiceLiveRoomRuns :many
SELECT run.run_id,run.status,run.created_at,run.finished_at,actor.display_name
FROM agent_local_runs run
JOIN agent_execution_contexts context ON context.context_key=run.context_key
JOIN actors actor ON actor.id=context.agent_actor_id AND actor.tenant_id=context.tenant_id
WHERE context.tenant_id=$1::text
  AND context.room_id=$2::text
  AND context.context_kind='meta'
  AND (run.created_at >= $3::timestamptz OR run.status IN ('queued','running'))
ORDER BY run.created_at DESC,run.run_id DESC
LIMIT 50
`

type ListVoiceLiveRoomRunsParams struct {
	TenantID string             `json:"tenant_id"`
	RoomID   string             `json:"room_id"`
	Since    pgtype.Timestamptz `json:"since"`
}

type ListVoiceLiveRoomRunsRow struct {
	RunID       string             `json:"run_id"`
	Status      string             `json:"status"`
	CreatedAt   pgtype.Timestamptz `json:"created_at"`
	FinishedAt  pgtype.Timestamptz `json:"finished_at"`
	DisplayName string             `json:"display_name"`
}

// Room Agent Runs of this Room that are unfinished or started since the given time.
func (q *Queries) ListVoiceLiveRoomRuns(ctx context.Context, arg ListVoiceLiveRoomRunsParams) ([]ListVoiceLiveRoomRunsRow, error) {
	rows, err := q.db.Query(ctx, listVoiceLiveRoomRuns, arg.TenantID, arg.RoomID, arg.Since)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []ListVoiceLiveRoomRunsRow{}
	for rows.Next() {
		var i ListVoiceLiveRoomRunsRow
		if err := rows.Scan(
			&i.RunID,
			&i.Status,
			&i.CreatedAt,
			&i.FinishedAt,
			&i.DisplayName,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listVoiceLiveTodayMessages = `-- name: ListVoiceLiveTodayMessages :many
SELECT message.body,message.created_at,author.display_name AS author,room.name AS room_name,
       coalesce(direct_peer.display_name,'')::text AS direct_peer
FROM messages message
JOIN rooms room ON room.id=message.room_id AND room.tenant_id=message.tenant_id
LEFT JOIN rooms thread ON thread.id=room.id
JOIN rooms access_room
  ON access_room.id=coalesce(thread.parent_room_id,room.id)
 AND access_room.deleted_at IS NULL AND access_room.deletion_started_at IS NULL
JOIN active_room_members membership
  ON membership.room_id=access_room.id AND membership.actor_id=$1::text
JOIN actors author ON author.id=message.author_actor_id AND author.tenant_id=message.tenant_id
LEFT JOIN rooms direct ON direct.id=access_room.id
LEFT JOIN actors direct_peer ON direct_peer.id=direct.direct_agent_actor_id AND direct_peer.tenant_id=direct.tenant_id
WHERE message.tenant_id=$2::text
  AND message.created_at >= $3::timestamptz
  AND message.message_kind='conversation'
  AND btrim(message.body)<>''
  AND NOT EXISTS (SELECT 1 FROM work_item_room_links work WHERE work.room_id=access_room.id AND work.link_type='work')
ORDER BY message.created_at DESC,message.id DESC
LIMIT 15
`

type ListVoiceLiveTodayMessagesParams struct {
	HumanActorID string             `json:"human_actor_id"`
	TenantID     string             `json:"tenant_id"`
	Since        pgtype.Timestamptz `json:"since"`
}

type ListVoiceLiveTodayMessagesRow struct {
	Body       string             `json:"body"`
	CreatedAt  pgtype.Timestamptz `json:"created_at"`
	Author     string             `json:"author"`
	RoomName   string             `json:"room_name"`
	DirectPeer string             `json:"direct_peer"`
}

// Conversation Messages since the given time in Rooms the Human is an active
// member of (threads through their parent Room), newest first: what Memory has
// not indexed yet when the Human asks about today.
func (q *Queries) ListVoiceLiveTodayMessages(ctx context.Context, arg ListVoiceLiveTodayMessagesParams) ([]ListVoiceLiveTodayMessagesRow, error) {
	rows, err := q.db.Query(ctx, listVoiceLiveTodayMessages, arg.HumanActorID, arg.TenantID, arg.Since)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []ListVoiceLiveTodayMessagesRow{}
	for rows.Next() {
		var i ListVoiceLiveTodayMessagesRow
		if err := rows.Scan(
			&i.Body,
			&i.CreatedAt,
			&i.Author,
			&i.RoomName,
			&i.DirectPeer,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listVoiceLiveUncertainOperations = `-- name: ListVoiceLiveUncertainOperations :many
SELECT call_id,name,arguments,state,created_at FROM voice_live_tool_calls
WHERE voice_session_id=$1::text AND state<>'completed'
ORDER BY created_at,call_id LIMIT 20
`

type ListVoiceLiveUncertainOperationsRow struct {
	CallID    string             `json:"call_id"`
	Name      string             `json:"name"`
	Arguments string             `json:"arguments"`
	State     string             `json:"state"`
	CreatedAt pgtype.Timestamptz `json:"created_at"`
}

func (q *Queries) ListVoiceLiveUncertainOperations(ctx context.Context, voiceSessionID string) ([]ListVoiceLiveUncertainOperationsRow, error) {
	rows, err := q.db.Query(ctx, listVoiceLiveUncertainOperations, voiceSessionID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []ListVoiceLiveUncertainOperationsRow{}
	for rows.Next() {
		var i ListVoiceLiveUncertainOperationsRow
		if err := rows.Scan(
			&i.CallID,
			&i.Name,
			&i.Arguments,
			&i.State,
			&i.CreatedAt,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const lockVoiceLiveSessionCurrent = `-- name: LockVoiceLiveSessionCurrent :one
SELECT (status IN ('provisioning','connected','reconnecting') AND live_lease_until>clock_timestamp())::boolean
FROM voice_sessions WHERE id=$1::text FOR UPDATE
`

// Locks the VoiceSession so close and lease loss serialize against a
// publication, and reports whether it still holds the live lease.
func (q *Queries) LockVoiceLiveSessionCurrent(ctx context.Context, id string) (bool, error) {
	row := q.db.QueryRow(ctx, lockVoiceLiveSessionCurrent, id)
	var column_1 bool
	err := row.Scan(&column_1)
	return column_1, err
}

const lockVoiceLiveTurn = `-- name: LockVoiceLiveTurn :one
SELECT voice_session_id, turn_id, human_message_id, created_at FROM voice_live_turns
WHERE voice_session_id=$1::text AND turn_id=$2::text
FOR UPDATE
`

type LockVoiceLiveTurnParams struct {
	VoiceSessionID string `json:"voice_session_id"`
	TurnID         string `json:"turn_id"`
}

func (q *Queries) LockVoiceLiveTurn(ctx context.Context, arg LockVoiceLiveTurnParams) (VoiceLiveTurn, error) {
	row := q.db.QueryRow(ctx, lockVoiceLiveTurn, arg.VoiceSessionID, arg.TurnID)
	var i VoiceLiveTurn
	err := row.Scan(
		&i.VoiceSessionID,
		&i.TurnID,
		&i.HumanMessageID,
		&i.CreatedAt,
	)
	return i, err
}

const recordVoiceLiveHandoverReceipt = `-- name: RecordVoiceLiveHandoverReceipt :exec
INSERT INTO agent_live_handover_receipts(context_key,voice_session_id,input_id)
VALUES($1::text,$2::text,$3::text)
ON CONFLICT(context_key,voice_session_id) DO UPDATE SET input_id=excluded.input_id,created_at=clock_timestamp()
`

type RecordVoiceLiveHandoverReceiptParams struct {
	ContextKey     string `json:"context_key"`
	VoiceSessionID string `json:"voice_session_id"`
	InputID        string `json:"input_id"`
}

func (q *Queries) RecordVoiceLiveHandoverReceipt(ctx context.Context, arg RecordVoiceLiveHandoverReceiptParams) error {
	_, err := q.db.Exec(ctx, recordVoiceLiveHandoverReceipt, arg.ContextKey, arg.VoiceSessionID, arg.InputID)
	return err
}

const renewVoiceLiveLease = `-- name: RenewVoiceLiveLease :execrows
UPDATE voice_sessions SET live_lease_until=clock_timestamp()+interval '45 seconds'
WHERE id=$1::text AND purpose='chat_live'
 AND status IN ('provisioning','connected','reconnecting') AND live_lease_until>clock_timestamp()
`

func (q *Queries) RenewVoiceLiveLease(ctx context.Context, voiceSessionID string) (int64, error) {
	result, err := q.db.Exec(ctx, renewVoiceLiveLease, voiceSessionID)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected(), nil
}

const searchVoiceLiveMessagesForAccount = `-- name: SearchVoiceLiveMessagesForAccount :many
WITH page AS (
  SELECT m.id, m.created_at
  FROM messages m
  JOIN rooms r ON r.id=m.room_id
  JOIN actors caller ON caller.tenant_id=r.tenant_id AND caller.account_id=$1::text AND caller.kind='human'
  JOIN rooms access_room
    ON access_room.id=COALESCE(r.parent_room_id, r.id)
   AND access_room.deleted_at IS NULL
   AND access_room.deletion_started_at IS NULL
  JOIN active_room_members membership
    ON membership.room_id=access_room.id AND membership.actor_id=caller.id
  -- Leaving is recorded on the Room that grants membership, while the frozen
  -- position is each Room's own: a thread numbers its Messages separately.
  -- Joining both per Room keeps the check off every matching Message.
  LEFT JOIN room_member_states departure
    ON departure.room_id=access_room.id AND departure.actor_id=caller.id
   AND departure.participation_epoch_id=membership.membership_epoch_id
   AND departure.left_at IS NOT NULL
  LEFT JOIN room_member_states frozen
    ON frozen.room_id=r.id AND frozen.actor_id=caller.id
   AND frozen.participation_epoch_id=membership.membership_epoch_id
   AND frozen.left_at IS NOT NULL
  WHERE r.tenant_id=$2::text
    AND r.deleted_at IS NULL
    AND r.deletion_started_at IS NULL
    AND ($3::text='' OR m.room_id=$3::text)
    AND m.message_kind='conversation'
    AND m.card_context_message_id IS NULL
    AND (departure.room_id IS NULL OR EXISTS (
      SELECT 1 FROM room_events saved
      WHERE saved.tenant_id=r.tenant_id AND saved.room_id=r.id AND saved.resource_id=m.id
        AND saved.event_type='message.created' AND saved.room_seq<=frozen.left_room_seq
    ))
    AND NOT EXISTS (
      SELECT 1 FROM work_item_room_links work_room
      WHERE work_room.tenant_id=r.tenant_id AND work_room.room_id=r.id AND work_room.link_type='work'
    )
    AND strpos(lower(m.body),lower($4::text))>0
    AND ($5::text='' OR (m.created_at,m.id) < (
      SELECT created_at,id FROM messages WHERE id=$5::text
    ))
  ORDER BY m.created_at DESC, m.id DESC
  LIMIT $6::int
)
SELECT m.id, m.tenant_id, m.room_id, m.author_actor_id, m.body, m.segments, m.message_kind,
       m.card_context_message_id, m.card_title, m.card_kind, m.created_at,
       m.reply_to_message_id,
       author.kind AS author_kind, author.display_name AS author_display_name,
       author.account_id AS author_account_id, author.handle AS author_handle,
       author.created_at AS author_created_at,
       r.name AS room_name,
       (r.direct_agent_actor_id IS NOT NULL)::boolean AS is_direct,
       coalesce(direct_peer.display_name,'')::text AS direct_peer_display_name,
       (r.parent_room_id IS NOT NULL)::boolean AS is_thread,
       coalesce(r.parent_room_id,'')::text AS parent_room_id,
       coalesce(r.root_message_id,'')::text AS root_message_id
FROM page
JOIN messages m ON m.id=page.id
JOIN rooms r ON r.id=m.room_id
JOIN actors author ON author.id=m.author_actor_id AND author.tenant_id=m.tenant_id
LEFT JOIN actors direct_peer
  ON direct_peer.id=r.direct_agent_actor_id AND direct_peer.tenant_id=r.tenant_id
ORDER BY page.created_at DESC, page.id DESC
`

type SearchVoiceLiveMessagesForAccountParams struct {
	AccountID string `json:"account_id"`
	TenantID  string `json:"tenant_id"`
	RoomID    string `json:"room_id"`
	Query     string `json:"query"`
	Cursor    string `json:"cursor"`
	PageLimit int32  `json:"page_limit"`
}

type SearchVoiceLiveMessagesForAccountRow struct {
	ID                    string             `json:"id"`
	TenantID              string             `json:"tenant_id"`
	RoomID                string             `json:"room_id"`
	AuthorActorID         string             `json:"author_actor_id"`
	Body                  string             `json:"body"`
	Segments              []byte             `json:"segments"`
	MessageKind           string             `json:"message_kind"`
	CardContextMessageID  pgtype.Text        `json:"card_context_message_id"`
	CardTitle             pgtype.Text        `json:"card_title"`
	CardKind              pgtype.Text        `json:"card_kind"`
	CreatedAt             pgtype.Timestamptz `json:"created_at"`
	ReplyToMessageID      pgtype.Text        `json:"reply_to_message_id"`
	AuthorKind            string             `json:"author_kind"`
	AuthorDisplayName     string             `json:"author_display_name"`
	AuthorAccountID       pgtype.Text        `json:"author_account_id"`
	AuthorHandle          pgtype.Text        `json:"author_handle"`
	AuthorCreatedAt       pgtype.Timestamptz `json:"author_created_at"`
	RoomName              string             `json:"room_name"`
	IsDirect              bool               `json:"is_direct"`
	DirectPeerDisplayName string             `json:"direct_peer_display_name"`
	IsThread              bool               `json:"is_thread"`
	ParentRoomID          string             `json:"parent_room_id"`
	RootMessageID         string             `json:"root_message_id"`
}

// Keyword search over conversation Messages the caller can read across one
// Tenant. Visibility is the Message list's: membership through the parent Room
// for threads, and after leaving, only Messages up to each Room's own frozen
// left_room_seq. The Room list exclusions also apply, so every hit opens
// through an existing route. The query is one substring; both sides are
// lower-cased here. The page is chosen from narrow rows first and only its
// hits are joined to authors and Rooms, so a word found in every Message sorts
// ids instead of whole rows.
func (q *Queries) SearchVoiceLiveMessagesForAccount(ctx context.Context, arg SearchVoiceLiveMessagesForAccountParams) ([]SearchVoiceLiveMessagesForAccountRow, error) {
	rows, err := q.db.Query(ctx, searchVoiceLiveMessagesForAccount,
		arg.AccountID,
		arg.TenantID,
		arg.RoomID,
		arg.Query,
		arg.Cursor,
		arg.PageLimit,
	)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []SearchVoiceLiveMessagesForAccountRow{}
	for rows.Next() {
		var i SearchVoiceLiveMessagesForAccountRow
		if err := rows.Scan(
			&i.ID,
			&i.TenantID,
			&i.RoomID,
			&i.AuthorActorID,
			&i.Body,
			&i.Segments,
			&i.MessageKind,
			&i.CardContextMessageID,
			&i.CardTitle,
			&i.CardKind,
			&i.CreatedAt,
			&i.ReplyToMessageID,
			&i.AuthorKind,
			&i.AuthorDisplayName,
			&i.AuthorAccountID,
			&i.AuthorHandle,
			&i.AuthorCreatedAt,
			&i.RoomName,
			&i.IsDirect,
			&i.DirectPeerDisplayName,
			&i.IsThread,
			&i.ParentRoomID,
			&i.RootMessageID,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const snapshotVoiceLiveCanvasRevision = `-- name: SnapshotVoiceLiveCanvasRevision :one
SELECT snapshot_document_body(body.document_id)::text FROM document_bodies body
JOIN documents document ON document.id=body.document_id
WHERE body.document_id=$1::text AND document.tenant_id=$2::text
`

type SnapshotVoiceLiveCanvasRevisionParams struct {
	DocumentID string `json:"document_id"`
	TenantID   string `json:"tenant_id"`
}

func (q *Queries) SnapshotVoiceLiveCanvasRevision(ctx context.Context, arg SnapshotVoiceLiveCanvasRevisionParams) (string, error) {
	row := q.db.QueryRow(ctx, snapshotVoiceLiveCanvasRevision, arg.DocumentID, arg.TenantID)
	var column_1 string
	err := row.Scan(&column_1)
	return column_1, err
}

const voiceLiveForegroundSwitching = `-- name: VoiceLiveForegroundSwitching :one
SELECT EXISTS(
  SELECT 1 FROM agent_local_runs run
  JOIN agent_execution_contexts context ON context.context_key=run.context_key
  WHERE run.status='running' AND context.context_kind='meta'
    AND context.agent_actor_id=$1::text AND context.tenant_id=$2::text
    AND voice_live_owns_context(context.context_key)
)::boolean
`

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

// A running Meta Run of a Context the live voice owns means the previous
// foreground is still stopping.
func (q *Queries) VoiceLiveForegroundSwitching(ctx context.Context, arg VoiceLiveForegroundSwitchingParams) (bool, error) {
	row := q.db.QueryRow(ctx, voiceLiveForegroundSwitching, arg.AgentActorID, arg.TenantID)
	var column_1 bool
	err := row.Scan(&column_1)
	return column_1, err
}

const voiceLiveOwnsContext = `-- name: VoiceLiveOwnsContext :one
SELECT voice_live_owns_context($1::text)::boolean
`

func (q *Queries) VoiceLiveOwnsContext(ctx context.Context, contextKey string) (bool, error) {
	row := q.db.QueryRow(ctx, voiceLiveOwnsContext, contextKey)
	var column_1 bool
	err := row.Scan(&column_1)
	return column_1, err
}

const voiceLiveTaskCoordinatedBy = `-- name: VoiceLiveTaskCoordinatedBy :one
SELECT EXISTS(
  SELECT 1 FROM task_meta_callbacks callback
  JOIN work_items item ON item.id=callback.task_id AND item.task_execution_generation=callback.generation
  WHERE callback.task_id=$1::text AND callback.tenant_id=$2::text
    AND callback.coordinator_actor_id=$3::text AND item.archived_at IS NULL
)::boolean
`

type VoiceLiveTaskCoordinatedByParams struct {
	TaskID             string `json:"task_id"`
	TenantID           string `json:"tenant_id"`
	CoordinatorActorID string `json:"coordinator_actor_id"`
}

func (q *Queries) VoiceLiveTaskCoordinatedBy(ctx context.Context, arg VoiceLiveTaskCoordinatedByParams) (bool, error) {
	row := q.db.QueryRow(ctx, voiceLiveTaskCoordinatedBy, arg.TaskID, arg.TenantID, arg.CoordinatorActorID)
	var column_1 bool
	err := row.Scan(&column_1)
	return column_1, err
}