62 lines
2.0 KiB
JavaScript
62 lines
2.0 KiB
JavaScript
import { pool } from '../pool.js';
|
|
import { recordAudit } from './audit_stub.js';
|
|
|
|
export async function create({ title, agent_id, participants, metadata }, actor) {
|
|
const { rows: [r] } = await pool.query(
|
|
`INSERT INTO conversations(title, agent_id, participants, metadata)
|
|
VALUES($1,$2,$3,$4) RETURNING *`,
|
|
[title || null, agent_id || null, participants || [], metadata || {}]
|
|
);
|
|
await recordAudit(actor, 'create', 'conversation', r.id, null, r);
|
|
return r;
|
|
}
|
|
|
|
export async function getById(id) {
|
|
const { rows: [r] } = await pool.query(`SELECT * FROM conversations WHERE id=$1`, [id]);
|
|
return r;
|
|
}
|
|
|
|
export async function list({ limit = 50, offset = 0 } = {}) {
|
|
const { rows } = await pool.query(
|
|
`SELECT * FROM conversations ORDER BY started_at DESC LIMIT $1 OFFSET $2`,
|
|
[limit, offset]
|
|
);
|
|
return rows;
|
|
}
|
|
|
|
export async function setStatus(id, status, actor) {
|
|
const before = await getById(id);
|
|
const { rows: [r] } = await pool.query(
|
|
`UPDATE conversations SET status=$1, ended_at = CASE WHEN $1='archived' THEN now() ELSE ended_at END
|
|
WHERE id=$2 RETURNING *`,
|
|
[status, id]
|
|
);
|
|
await recordAudit(actor, 'update', 'conversation', id, before, r);
|
|
return r;
|
|
}
|
|
|
|
export async function setSummary(id, summary) {
|
|
const { rows: [r] } = await pool.query(
|
|
`UPDATE conversations SET summary=$1, status='summarized' WHERE id=$2 RETURNING *`,
|
|
[summary, id]
|
|
);
|
|
return r;
|
|
}
|
|
|
|
export async function findOrCreateForSpace(space_id, agent_id, actor) {
|
|
const { rows: [existing] } = await pool.query(
|
|
`SELECT * FROM conversations
|
|
WHERE space_id=$1 AND agent_id=$2 AND status='open'
|
|
ORDER BY started_at DESC LIMIT 1`,
|
|
[space_id, agent_id]
|
|
);
|
|
if (existing) return existing;
|
|
const { rows: [r] } = await pool.query(
|
|
`INSERT INTO conversations(title, space_id, agent_id, metadata)
|
|
VALUES($1,$2,$3,$4) RETURNING *`,
|
|
['Companion', space_id, agent_id, {}]
|
|
);
|
|
await recordAudit(actor, 'create', 'conversation', r.id, null, r);
|
|
return r;
|
|
}
|