Skip to content
Source
Sign inSign up
samwillis/neon-glow-demo
Open History to see the last commit

conversation.ts

63 lines5.0 KB

1import type { PoolClient } from 'pg';
2import type { z } from 'zod';
3import { ApiError, type GlowApp, type Run, type answerQuestionSchema, type progressSchema, type questionSchema } from '@glow/contracts';
4import { appendMessage, fingerprint, now } from './store.ts';
5import { checkOwner } from './scheduler.ts';
6import { config } from './config.ts';
7import type { Grant } from './tokens.ts';
8​
9async function lockWorker(client: PoolClient, grant: Grant) {
10 const app = await client.query('SELECT data FROM glow_apps WHERE id=$1 FOR UPDATE', [grant.appId]);
11 if (!app.rows[0] || app.rows[0].data.generation !== grant.generation || app.rows[0].data.disabled) throw new ApiError(409, 'This change was replaced');
12 return checkOwner(grant, client, true);
14​
15export async function recordProgress(client: PoolClient, grant: Grant, input: z.infer<typeof progressSchema>) {
16 await lockWorker(client, grant);
17 const previous = await client.query('SELECT data FROM glow_messages WHERE id=$1', [input.eventId]);
18 if (previous.rows[0]) {
19 const message = previous.rows[0].data;
20 if (message.appId !== grant.appId || message.runId !== grant.runId || message.kind !== 'progress' || message.content !== input.content) throw new ApiError(409, 'Progress ID already used');
21 return { ok: true };
22 }
23 const existing = await client.query(`SELECT count(*)::int AS count FROM glow_messages WHERE app_id=$1 AND data->>'runId'=$2 AND data->>'kind'='progress'`, [grant.appId, grant.runId]);
24 if (existing.rows[0].count >= 40) return { ok: true };
25 await appendMessage(client, grant.appId, 'assistant', input.content, grant.runId!, input.eventId, { kind: 'progress' });
26 const phase = { thinking: 'Thinking', working: 'Making changes', checking: 'Checking the app' }[input.stage];
27 await client.query(`UPDATE glow_runs SET data=data || jsonb_build_object('phase',$2::text,'updatedAt',$3::text) WHERE id=$1`, [grant.runId, phase, now()]);
28 return { ok: true };
30​
31export async function waitForAnswer(client: PoolClient, grant: Grant, input: z.infer<typeof questionSchema>, checkpointKey: string) {
32 const row = await lockWorker(client, grant);
33 const existing = await client.query('SELECT id FROM glow_messages WHERE id=$1', [input.questionId]);
34 if (existing.rowCount) throw new ApiError(409, 'Question ID already used');
35 await appendMessage(client, grant.appId, 'assistant', input.content, grant.runId!, input.questionId, { kind: 'question', options: input.options });
36 const run: Run = { ...row.data, status: 'waiting', phase: 'Waiting for your answer', questionId: input.questionId, fence: row.data.fence + 1, updatedAt: now() };
37 await client.query('UPDATE glow_runs SET data=$2,checkpoint_key=$3,owner_id=NULL,activation_hash=NULL,dispatch_id=NULL,lease_until=NULL WHERE id=$1', [grant.runId, JSON.stringify(run), checkpointKey]);
38 return run;
40​
41export async function answerQuestion(client: PoolClient, app: GlowApp, questionId: string, input: z.infer<typeof answerQuestionSchema>) {
42 const digest = fingerprint({ appId: app.id, questionId, answer: input.answer });
43 const receipt = await client.query('SELECT * FROM glow_operations WHERE id=$1', [input.operationId]);
44 if (receipt.rows[0]) {
45 const previous = receipt.rows[0];
46 if (previous.owner_id !== app.ownerId || previous.kind !== 'answer' || previous.result.fingerprint !== digest) throw new ApiError(409, 'Answer request ID already used');
47 const saved = await client.query('SELECT data FROM glow_runs WHERE id=$1 AND app_id=$2', [previous.result.runId, app.id]);
48 return saved.rows[0].data as Run;
49 }
50 const question = await client.query(`SELECT data FROM glow_messages WHERE id=$1 AND app_id=$2 AND data->>'kind'='question' FOR UPDATE`, [questionId, app.id]);
51 const message = question.rows[0]?.data;
52 if (!message) throw new ApiError(404, 'Question not found');
53 const result = await client.query('SELECT * FROM glow_runs WHERE id=$1 AND app_id=$2 FOR UPDATE', [message.runId, app.id]);
54 const row = result.rows[0];
55 if (!row || row.data.status !== 'waiting' || row.data.questionId !== questionId || row.data.generation !== app.generation || message.answeredBy) throw new ApiError(409, 'This question is no longer waiting for an answer');
56 const replyMessageId = input.operationId;
57 await appendMessage(client, app.id, 'user', input.answer, row.id, replyMessageId, { answerTo: questionId });
58 await client.query(`UPDATE glow_messages SET data=data || jsonb_build_object('answeredBy',$2::text) WHERE id=$1`, [questionId, replyMessageId]);
59 const run = { ...row.data, status: 'queued', phase: 'Queued', replyMessageId, fence: row.data.fence + 1, attempt: 0, error: null, agentVersion: config().agentVersion, updatedAt: now() };
60 await client.query('UPDATE glow_runs SET data=$2,model_calls=0,owner_id=NULL,activation_hash=NULL,dispatch_id=NULL,lease_until=NULL WHERE id=$1', [row.id, JSON.stringify(run)]);
61 await client.query('INSERT INTO glow_operations(id,owner_id,kind,result) VALUES($1,$2,$3,$4)', [input.operationId, app.ownerId, 'answer', JSON.stringify({ fingerprint: digest, runId: row.id })]);
62 return run as Run;