Open History to see the last commit
1import { randomUUID, timingSafeEqual } from 'node:crypto';
2import { Hono } from 'hono';
3import { cors } from 'hono/cors';
4import { bodyLimit } from 'hono/body-limit';
5import { z } from 'zod';
6import { createRealtime, rawSql } from '@neon/realtime/server';
7import { parseTriggerDelivery } from '@neon/functions/triggers';
8import { compileCreation } from '@glow/creation-runtime';
9import { ApiError, agentCaptureSchema, candidateSchema, checkpointSchema, createAppSchema, forkSchema, id, maxRequestBytes, restoreSchema, sendMessageSchema, shareSchema, stateMutationSchema, stateReadSchema, progressSchema, askQuestionSchema, answerQuestionSchema, updateAppSchema, type GlowApp, type Run, type User, type VersionMedia } from '@glow/contracts';
10import { auth } from './auth.ts';
11import { config, required } from './config.ts';
12import { database, transaction } from './database.ts';
13import { activate, checkOwner, dispatchOne, finishFailed, maxSlices, type Artifact } from './scheduler.ts';
14import { appById, appendMessage, createApp, deleteApp, now, ownedApp, snapshot, acceptMessage } from './store.ts';
15import { signGrant, verifyGrant, type Grant } from './tokens.ts';
16import { getMedia, getObject, mediaResponse, putObject, type MediaExtension } from './objects.ts';
17import { applyMedia, captureForAgent, claimJob, completeJob, failJob, heartbeat, storeMedia } from './capture.ts';
18import { withCaptureRuntime } from '@glow/creation-runtime/capture';
19import { discover, feed, feedItem, inbox, lineage, markInboxSeen, myProfile, profile, recordPlay, replies, resolveUser, setFollow, setLike, updateProfile } from './social.ts';
20import { mutateState, readState, stateSubscription } from './state.ts';
21import { addComment, listComments, listRemixes, removeComment, sharedApp } from './community.ts';
22import { commentSchema } from '@glow/contracts';
23import { answerQuestion, recordProgress, waitForAnswer } from './conversation.ts';
24
25type Variables = { user: User; grant: Grant; viewer: User | null };
26const publicPrefixes = ['/v1/play/', '/v1/state/', '/v1/feed', '/v1/discover', '/v1/users/', '/v1/media/'];
27const coverOf = (versionId: string, media?: VersionMedia) => media ? { versionId, poster: media.poster, clip: media.clip, color: media.color } : undefined;
28const bearer = (request: Request) => request.headers.get('authorization')?.replace(/^Bearer /, '') ?? '';
29export function createApi(background: (promise: Promise<unknown>) => void = promise => { void promise.catch(() => console.error('Background dispatch failed')); }) {
30 const api = new Hono<{ Variables: Variables }>();
31 api.use('*', cors({ origin: config().webOrigins, credentials: true, allowHeaders: ['Content-Type', 'Authorization', 'Cookie', 'expo-origin', 'x-glow-user'], exposeHeaders: ['set-cookie'] }));
32 api.use('*', bodyLimit({ maxSize: maxRequestBytes, onError: c => c.json({ error: 'Request too large' }, 413) }));
33 api.use('*', async (c, next) => {
34 // Content-addressed media is public and immutable; everything else stays out of shared caches.
35 if (!c.req.path.startsWith('/v1/media/')) c.header('Cache-Control', 'private, no-store');
36 c.header('X-Content-Type-Options', 'nosniff'); await next();
37 });
38 api.onError((error, c) => {
39 if (error instanceof ApiError) return c.json({ error: error.message, details: error.details }, error.status as 400);
40 if (error instanceof z.ZodError) return c.json({ error: 'Please check the request.', details: error.flatten() }, 400);
41 console.error('API request failed:', error.name);
42 return c.json({ error: 'Something went wrong. Your last working creation is safe.' }, 500);
43 });
44 api.get('/health', c => c.json({ ok: true, version: config().agentVersion }));
45 api.on(['GET', 'POST'], '/api/auth/*', c => auth().handler(c.req.raw));
46 api.use('/v1/*', async (c, next) => {
47 if (c.req.path === '/v1/visitor' || c.req.path.startsWith('/v1/state/') || c.req.path.startsWith('/v1/media/')) return next();
48 if (publicPrefixes.some(prefix => c.req.path.startsWith(prefix))) {
49 // Discovery works signed out; a session only personalizes likes and follows.
50 const session = await auth().api.getSession({ headers: c.req.raw.headers }).catch(() => null);
51 c.set('viewer', session?.user ?? null); return next();
52 }
53 const session = await auth().api.getSession({ headers: c.req.raw.headers });
54 if (!session) throw new ApiError(401, 'Sign in to make or remix something.');
55 if (c.req.header('x-glow-user') && c.req.header('x-glow-user') !== session.user.id) throw new ApiError(401, 'Your account changed. Reload this view.');
56 c.set('user', session.user); await next();
57 });
58 api.get('/v1/me', c => c.json(c.get('user')));
59 const signedIn = (c: { get(key: 'viewer'): User | null }) => { const viewer = c.get('viewer'); if (!viewer) throw new ApiError(401, 'Sign in to do that.'); return viewer; };
60 api.get('/v1/feed', async c => c.json(await feed(database(), c.get('viewer')?.id ?? null, z.enum(['foryou', 'following', 'new']).catch('foryou').parse(c.req.query('tab')), c.req.query('cursor'))));
61 api.get('/v1/discover', async c => c.json(await discover(database(), c.get('viewer')?.id ?? null)));
62 api.get('/v1/users/:id', async c => c.json(await profile(database(), c.get('viewer')?.id ?? null, z.string().min(1).max(100).parse(c.req.param('id')))));
63 api.get('/v1/users/:id/replies', async c => c.json(await replies(database(), z.string().min(1).max(100).parse(c.req.param('id')))));
64 api.post('/v1/users/:id/follow', async c => {
65 const viewer = signedIn(c), input = z.object({ following: z.boolean() }).parse(await c.req.json());
66 return c.json(await setFollow(database(), viewer.id, await resolveUser(database(), z.string().min(1).max(100).parse(c.req.param('id'))), input.following));
67 });
68 api.get('/v1/play/:id/social', async c => {
69 const appId = id.parse(c.req.param('id'));
70 const [item, chain] = await Promise.all([feedItem(database(), c.get('viewer')?.id ?? null, appId), lineage(database(), appId)]);
71 return c.json({ item, lineage: chain });
72 });
73 api.get('/v1/media/:file', async c => {
74 const match = /^([a-f0-9]{64})\.(jpg|webm|mp4)$/.exec(c.req.param('file'));
75 if (!match) throw new ApiError(404, 'Media not found');
76 let bytes: Buffer;
77 try { bytes = await getMedia(`media/${match[1]}.${match[2]}`); } catch { throw new ApiError(404, 'Media not found'); }
78 return mediaResponse(bytes, match[2] as MediaExtension, c.req.header('range'));
79 });
80 api.post('/v1/apps/:id/like', async c => {
81 const input = z.object({ liked: z.boolean() }).parse(await c.req.json());
82 return c.json(await setLike(database(), id.parse(c.req.param('id')), c.get('user').id, input.liked));
83 });
84 // The creator's browser captures covers and clips of its own preview and uploads them.
85 api.post('/v1/apps/:id/versions/:versionId/media', async c => {
86 const app = await ownedApp(id.parse(c.req.param('id')), c.get('user').id), versionId = id.parse(c.req.param('versionId'));
87 const media = await storeMedia(await c.req.json());
88 await applyMedia(app.id, versionId, media);
89 return c.json(media);
90 });
91 // An open builder tab serves its own app's agent visual checks (rendered in a hidden frame).
92 const builderWorker = (appId: string, userId: string) => `builder:${appId}:${userId}`.slice(0, 80);
93 api.post('/v1/apps/:id/capture/next', async c => {
94 const app = await ownedApp(id.parse(c.req.param('id')), c.get('user').id);
95 const job = await claimJob(builderWorker(app.id, c.get('user').id), 20_000, app.id);
96 return job ? c.json(job) : c.body(null, 204);
97 });
98 api.post('/v1/apps/:id/capture/:jobId/complete', async c => {
99 const app = await ownedApp(id.parse(c.req.param('id')), c.get('user').id);
100 await completeJob(id.parse(c.req.param('jobId')), builderWorker(app.id, c.get('user').id), await c.req.json()); return c.json({ ok: true });
101 });
102 api.post('/v1/apps/:id/capture/:jobId/fail', async c => {
103 const app = await ownedApp(id.parse(c.req.param('id')), c.get('user').id), input = z.object({ error: z.string().max(1000) }).parse(await c.req.json());
104 await failJob(id.parse(c.req.param('jobId')), builderWorker(app.id, c.get('user').id), input.error); return c.json({ ok: true });
105 });
106 api.get('/v1/me/profile', async c => c.json(await myProfile(database(), c.get('user').id)));
107 api.post('/v1/me/profile', async c => c.json(await updateProfile(database(), c.get('user').id, await c.req.json())));
108 api.get('/v1/inbox', async c => c.json(await inbox(database(), c.get('user').id)));
109 api.post('/v1/inbox/seen', async c => { await markInboxSeen(database(), c.get('user').id); return c.json({ ok: true }); });
110 api.post('/v1/apps/:id/details', async c => {
111 const input = updateAppSchema.parse(await c.req.json());
112 const result = await transaction(async client => {
113 const app = await ownedApp(id.parse(c.req.param('id')), c.get('user').id, client, true);
114 if (input.title) { app.title = input.title; app.titleSource = 'user'; }
115 if (input.tagline !== undefined) app.tagline = input.tagline || undefined;
116 if (input.caption !== undefined) app.caption = input.caption || undefined;
117 if (input.visibility === 'private') app.visibility = 'private';
118 else if (input.visibility && app.visibility !== 'private') app.visibility = input.visibility;
119 else if (input.visibility) throw new ApiError(409, 'Post the app before choosing who can see it.');
120 app.updatedAt = now();
121 await client.query('UPDATE glow_apps SET data=$2 WHERE id=$1', [app.id, JSON.stringify(app)]);
122 return app;
123 });
124 return c.json(result.data);
125 });
126 api.get('/v1/play/:id/comments', async c => c.json(await listComments(database(), id.parse(c.req.param('id')), c.req.query('before'))));
127 api.get('/v1/play/:id/remixes', async c => c.json(await listRemixes(database(), id.parse(c.req.param('id')), c.req.query('before'))));
128 api.post('/v1/apps/:id/comments', async c => {
129 const input = commentSchema.parse(await c.req.json());
130 const result = await transaction(client => addComment(client, id.parse(c.req.param('id')), c.get('user').id, input));
131 return c.json(result.data, 201);
132 });
133 api.delete('/v1/apps/:id/comments/:commentId', async c => {
134 const result = await transaction(client => removeComment(client, id.parse(c.req.param('id')), id.parse(c.req.param('commentId')), c.get('user').id));
135 return c.json(result.data);
136 });
137 api.get('/v1/play/:id/live/:kind', async c => {
138 const appId = id.parse(c.req.param('id')), kind = z.enum(['comments', 'remixes']).parse(c.req.param('kind'));
139 await sharedApp(database(), appId);
140 if (!process.env.NEON_REALTIME_SECRET || !process.env.NEON_REALTIME_URL) return c.json({ available: false });
141 const visible = `a.data->>'visibility' IN ('public','unlisted') AND a.data->>'status'='ready' AND a.data->>'headVersionId' IS NOT NULL AND NOT coalesce((a.data->>'disabled')::boolean,false)`;
142 const query = kind === 'comments'
143 ? rawSql(`SELECT c.id,c.created_at,c.deleted_at FROM glow_comments c JOIN glow_apps a ON a.id=c.app_id WHERE c.app_id=$1 AND ${visible} ORDER BY coalesce(c.deleted_at,c.created_at) DESC,c.id DESC LIMIT 1`, [appId])
144 : rawSql(`SELECT r.id,r.data->>'updatedAt' AS updated FROM glow_apps r JOIN glow_apps a ON r.data->>'parentAppId'=a.id::text WHERE a.id=$1 AND ${visible} AND r.data->>'visibility' IN ('public','unlisted') AND r.data->>'status'='ready' AND r.data->>'headVersionId' IS NOT NULL AND NOT coalesce((r.data->>'disabled')::boolean,false) ORDER BY r.data->>'updatedAt' DESC,r.id DESC LIMIT 20`, [appId]);
145 const realtime = createRealtime({ secret: process.env.NEON_REALTIME_SECRET, db: new URL(config().databaseUrl).pathname.slice(1) });
146 return c.json({ available: true, url: process.env.NEON_REALTIME_URL, query: await realtime.seal({ query }) });
147 });
148 api.get('/v1/apps', async c => {
149 const { rows } = await database().query(`SELECT data FROM glow_apps WHERE owner_id=$1 AND NOT coalesce((data->>'deleted')::boolean,false) ORDER BY data->>'updatedAt' DESC LIMIT 50`, [c.get('user').id]);
150 return c.json(rows.map(row => row.data));
151 });
152 api.get('/v1/responses', async c => {
153 const { rows } = await database().query(`SELECT child.data FROM glow_apps child JOIN glow_apps parent ON child.data->>'parentAppId'=parent.id::text WHERE parent.owner_id=$1 AND child.owner_id<>$1 AND child.data->>'visibility'<>'private' ORDER BY child.data->>'updatedAt' DESC LIMIT 20`, [c.get('user').id]);
154 return c.json(rows.map(row => row.data));
155 });
156 api.post('/v1/apps', async c => {
157 const input = createAppSchema.parse(await c.req.json());
158 const result = await createApp(c.get('user').id, input.prompt, input.operationId);
159 background(dispatchOne()); return c.json(result, 201);
160 });
161 api.delete('/v1/apps/:id', async c => c.json((await deleteApp(id.parse(c.req.param('id')), c.get('user').id)).data));
162 api.get('/v1/apps/:id', async c => c.json(await snapshot(id.parse(c.req.param('id')), c.get('user').id)));
163 api.post('/v1/apps/:id/messages', async c => {
164 const input = sendMessageSchema.parse(await c.req.json());
165 const result = await transaction(async client => {
166 const app = await ownedApp(id.parse(c.req.param('id')), c.get('user').id, client, true);
167 const waiting = await client.query(`SELECT id FROM glow_runs WHERE app_id=$1 AND data->>'status'='waiting'`, [app.id]);
168 if (waiting.rowCount) throw new ApiError(409, 'Answer the question below to continue this change.');
169 return acceptMessage(client, app, input.prompt, input.operationId);
170 });
171 background(dispatchOne()); return c.json(result, 202);
172 });
173 api.post('/v1/apps/:id/questions/:questionId/answer', async c => {
174 const input = answerQuestionSchema.parse(await c.req.json());
175 const result = await transaction(async client => {
176 const app = await ownedApp(id.parse(c.req.param('id')), c.get('user').id, client, true);
177 return answerQuestion(client, app, id.parse(c.req.param('questionId')), input);
178 });
179 background(dispatchOne()); return c.json(result, 202);
180 });
181 api.post('/v1/apps/:id/runs/:runId/:action', async c => {
182 const appId = id.parse(c.req.param('id')), runId = id.parse(c.req.param('runId'));
183 const action = z.enum(['stop', 'remove', 'retry']).parse(c.req.param('action'));
184 const result = await transaction(async client => {
185 await ownedApp(appId, c.get('user').id, client, true);
186 const { rows } = await client.query('SELECT * FROM glow_runs WHERE id=$1 AND app_id=$2 FOR UPDATE', [runId, appId]);
187 const run = rows[0]?.data as (Run & { agentVersion?: string }) | undefined;
188 if (!run) throw new ApiError(404, 'Change not found');
189 if (action === 'retry') {
190 if (!['failed', 'stopped'].includes(run.status)) throw new ApiError(409, 'This change is not ready to retry');
191 const active = await client.query(`SELECT 1 FROM glow_runs WHERE app_id=$1 AND data->>'status' IN ('queued','running','stopping','waiting')`, [appId]);
192 if (active.rowCount) throw new ApiError(409, 'Let the current changes finish first');
193 run.status = 'queued'; run.error = null; run.phase = 'Queued'; run.attempt = 0; run.continuation = false; run.slices = 0;
194 run.agentVersion = config().agentVersion;
195 await client.query('UPDATE glow_runs SET model_calls=0 WHERE id=$1', [runId]);
196 } else {
197 if ((action === 'remove' && run.status !== 'queued') || (action === 'stop' && !['queued', 'running', 'waiting'].includes(run.status))) throw new ApiError(409, 'This change already moved on. Refresh to see its current state.');
198 run.status = 'stopped'; run.phase = 'Stopped';
199 }
200 run.fence++; run.updatedAt = now();
201 await client.query('UPDATE glow_runs SET data=$2,owner_id=NULL,activation_hash=NULL,lease_until=NULL,dispatch_id=NULL WHERE id=$1', [runId, JSON.stringify(run)]);
202 return run;
203 });
204 background(dispatchOne()); return c.json(result);
205 });
206 api.post('/v1/apps/:id/share', async c => {
207 const input = shareSchema.parse(await c.req.json());
208 const result = await transaction(async client => {
209 const app = await ownedApp(id.parse(c.req.param('id')), c.get('user').id, client, true);
210 if (app.draftVersionId !== input.expectedVersion) throw new ApiError(409, 'The creation changed. Review its latest result before sharing.');
211 if (app.visibility === 'private' && !app.postedAt) app.postedAt = now();
212 app.headVersionId = app.draftVersionId; app.visibility = input.visibility; app.updatedAt = now();
213 if (input.title) { app.title = input.title; app.titleSource = 'user'; }
214 if (input.caption !== undefined) app.caption = input.caption || undefined;
215 const draft = await client.query('SELECT data FROM glow_versions WHERE id=$1', [app.draftVersionId]);
216 const media = draft.rows[0]?.data.media as VersionMedia | undefined;
217 if (media && input.coverFrame !== undefined && media.frames?.[input.coverFrame]) {
218 media.poster = media.frames[input.coverFrame];
219 await client.query(`UPDATE glow_versions SET data=data || jsonb_build_object('media',$2::jsonb) WHERE id=$1`, [app.draftVersionId, JSON.stringify(media)]);
220 }
221 if (media) { app.cover = coverOf(app.draftVersionId!, media); app.publicCover = app.cover; }
222 await client.query('UPDATE glow_apps SET data=$2 WHERE id=$1', [app.id, JSON.stringify(app)]);
223 await client.query(`UPDATE glow_versions SET data=data || '{"published":true}'::jsonb WHERE id=$1`, [app.headVersionId]);
224 return { app, url: `${config().webUrl}/a/${app.id}` };
225 }); return c.json(result);
226 });
227 api.post('/v1/apps/:id/restore', async c => {
228 const input = restoreSchema.parse(await c.req.json());
229 const result = await transaction(async client => {
230 const app = await ownedApp(id.parse(c.req.param('id')), c.get('user').id, client, true);
231 if (app.generation !== input.expectedGeneration) throw new ApiError(409, 'Another device changed this app. Review its latest history.');
232 const version = await client.query('SELECT data FROM glow_versions WHERE id=$1 AND app_id=$2', [input.versionId, app.id]);
233 if (!version.rows[0]) throw new ApiError(404, 'Version not found');
234 app.generation++; app.draftVersionId = input.versionId; app.updatedAt = now();
235 app.cover = coverOf(input.versionId, version.rows[0].data.media);
236 if (app.visibility !== 'private') { app.headVersionId = input.versionId; app.publicCover = app.cover; }
237 await client.query('UPDATE glow_apps SET data=$2 WHERE id=$1', [app.id, JSON.stringify(app)]);
238 await client.query(`UPDATE glow_runs SET data=data || jsonb_build_object('status','superseded','fence',(data->>'fence')::int+1,'updatedAt',$2::text),owner_id=NULL,lease_until=NULL WHERE app_id=$1 AND data->>'status' IN ('queued','running','stopping','waiting')`, [app.id, now()]);
239 await appendMessage(client, app.id, 'system', `Restored: ${version.rows[0].data.summary}`);
240 return app;
241 }); return c.json(result);
242 });
243 api.post('/v1/apps/:id/remix', async c => {
244 const input = forkSchema.parse(await c.req.json()), sourceApp = await appById(id.parse(c.req.param('id')));
245 if (sourceApp.visibility === 'private' && sourceApp.ownerId !== c.get('user').id) throw new ApiError(404, 'Creation not found');
246 const result = await database().query(`SELECT data,object_key FROM glow_versions WHERE id=$1 AND app_id=$2 AND ((data->>'published')::boolean=true OR $3=true)`, [input.versionId, sourceApp.id, sourceApp.ownerId === c.get('user').id]);
247 if (!result.rows[0]) throw new ApiError(404, 'The shared version was not found');
248 const original = await getObject<Artifact>(result.rows[0].object_key);
249 const objectKey = await putObject({ source: original.source, html: original.html, session: null });
250 const created = await createApp(c.get('user').id, '', input.operationId, { app: sourceApp, version: result.rows[0].data, objectKey });
251 background(dispatchOne()); return c.json(created, 201);
252 });
253 api.post('/v1/apps/:id/report', async c => {
254 const app = await appById(id.parse(c.req.param('id'))), input = z.object({ reason: z.string().trim().min(1).max(1000) }).parse(await c.req.json());
255 await database().query('INSERT INTO glow_reports(id,app_id,reporter_id,reason) VALUES($1,$2,$3,$4)', [randomUUID(), app.id, c.get('user').id, input.reason]);
256 return c.json({ ok: true });
257 });
258 api.post('/v1/apps/:id/disable', async c => {
259 const app = await ownedApp(id.parse(c.req.param('id')), c.get('user').id);
260 await database().query(`UPDATE glow_apps SET data=data || '{"disabled":true,"visibility":"private"}'::jsonb WHERE id=$1`, [app.id]);
261 return c.json({ ok: true });
262 });
263 api.get('/v1/live/:kind', async c => {
264 if (!process.env.NEON_REALTIME_SECRET || !process.env.NEON_REALTIME_URL) return c.json({ available: false });
265 const kind = z.enum(['apps', 'messages', 'runs']).parse(c.req.param('kind')), ownerId = c.get('user').id;
266 let query;
267 if (kind === 'apps') query = rawSql(`SELECT id,data FROM glow_apps WHERE owner_id=$1 AND NOT coalesce((data->>'deleted')::boolean,false) ORDER BY data->>'updatedAt' DESC LIMIT 50`, [ownerId]);
268 else {
269 const appId = id.parse(c.req.query('appId'));
270 await ownedApp(appId, ownerId);
271 query = kind === 'messages'
272 ? rawSql('SELECT m.id,m.data || jsonb_build_object(\'sequence\',m.sequence) AS data FROM glow_messages m JOIN glow_apps a ON a.id=m.app_id WHERE m.app_id=$1 AND a.owner_id=$2 ORDER BY m.sequence DESC LIMIT 100', [appId, ownerId])
273 : rawSql('SELECT r.id,r.data FROM glow_runs r JOIN glow_apps a ON a.id=r.app_id WHERE r.app_id=$1 AND a.owner_id=$2 ORDER BY r.data->>\'createdAt\' DESC LIMIT 30', [appId, ownerId]);
274 }
275 const realtime = createRealtime({ secret: process.env.NEON_REALTIME_SECRET, db: new URL(config().databaseUrl).pathname.slice(1) });
276 return c.json({ available: true, url: process.env.NEON_REALTIME_URL, query: await realtime.seal({ query }) });
277 });
278 api.post('/v1/visitor', async c => c.json({ token: await signGrant('visitor', { playerId: randomUUID() }, 60 * 60 * 24 * 365) }));
279 async function play(appId: string, versionId: string, playerId: string, preview: boolean) {
280 const version = await database().query('SELECT object_key FROM glow_versions WHERE id=$1 AND app_id=$2', [versionId, appId]);
281 if (!version.rows[0]) throw new ApiError(404, 'No playable version yet');
282 const artifact = await getObject<Artifact>(version.rows[0].object_key);
283 // Private previews include the capture runtime so the creator's browser can make covers and clips.
284 return { html: preview && artifact.html ? withCaptureRuntime(artifact.html) : artifact.html, versionId, token: await signGrant('play', { appId, versionId, playerId, preview, jti: randomUUID() }, 900) };
285 }
286 api.get('/v1/apps/:id/preview', async c => {
287 const app = await ownedApp(id.parse(c.req.param('id')), c.get('user').id);
288 if (!app.draftVersionId) throw new ApiError(404, 'The first version is still being made');
289 return c.json(await play(app.id, app.draftVersionId, c.get('user').id, true));
290 });
291 api.get('/v1/play/:id', async c => {
292 const app = await appById(id.parse(c.req.param('id')));
293 if (app.visibility === 'private' || !app.headVersionId) throw new ApiError(404, 'This creation is private');
294 let visitor: Grant;
295 try { visitor = await verifyGrant(bearer(c.req.raw), 'visitor'); }
296 catch { throw new ApiError(401, 'A player session is needed'); }
297 const owner = await database().query(`SELECT coalesce(p.display_name,u.name) AS name FROM "user" u LEFT JOIN glow_profiles p ON p.user_id=u.id WHERE u.id=$1`, [app.ownerId]);
298 const session = await auth().api.getSession({ headers: c.req.raw.headers });
299 const playerId = session?.user.id ?? visitor.playerId!;
300 await recordPlay(database(), app, playerId).catch(() => {});
301 return c.json({ app, creator: owner.rows[0]?.name ?? 'Someone', ...await play(app.id, app.headVersionId, playerId, false) });
302 });
303 api.use('/v1/state/*', async (c, next) => {
304 try { c.set('grant', await verifyGrant(bearer(c.req.raw), 'play')); } catch { throw new ApiError(401, 'Reopen the creation to continue playing'); }
305 await next();
306 });
307 api.get('/v1/state/read', async c => {
308 const { scope, key } = stateReadSchema.parse(c.req.query());
309 return c.json(await readState(c.get('grant'), scope, key));
310 });
311 api.post('/v1/state/patch', async c => c.json(await mutateState(c.get('grant'), stateMutationSchema.parse(await c.req.json()))));
312 api.get('/v1/state/live', async c => {
313 const { scope, key } = stateReadSchema.parse(c.req.query());
314 return c.json(await stateSubscription(c.get('grant'), scope, key));
315 });
316
317 api.post('/internal/activate', async c => {
318 let grant: Grant;
319 try { grant = await verifyGrant(bearer(c.req.raw), 'dispatch'); } catch { throw new ApiError(401, 'Invalid dispatch'); }
320 const input = z.object({ invocationId: id, activationKey: z.string().min(32).max(100) }).parse(await c.req.json());
321 return c.json(await activate(grant, input.invocationId, input.activationKey));
322 });
323 api.use('/internal/run/*', async (c, next) => {
324 try { c.set('grant', await verifyGrant(bearer(c.req.raw), 'execution')); } catch { throw new ApiError(401, 'Invalid worker capability'); }
325 await checkOwner(c.get('grant')); await next();
326 });
327 api.post('/internal/run/heartbeat', async c => {
328 const grant = c.get('grant');
329 const result = await database().query(`UPDATE glow_runs SET lease_until=now()+interval '90 seconds' WHERE id=$1 AND owner_id=$2 AND (data->>'fence')::int=$3 AND data->>'status'='running' AND lease_until>now()`, [grant.runId, grant.invocationId, grant.fence]);
330 if (!result.rowCount) throw new ApiError(409, 'This worker lease expired');
331 return c.json({ ok: true });
332 });
333 api.get('/internal/run/live', async c => {
334 if (!process.env.NEON_REALTIME_SECRET || !process.env.NEON_REALTIME_URL) return c.json({ available: false });
335 const grant = c.get('grant');
336 const query = rawSql('SELECT id,data->>\'status\' AS status,(data->>\'fence\')::int AS fence FROM glow_runs WHERE id=$1 AND owner_id=$2', [grant.runId!, grant.invocationId!]);
337 const realtime = createRealtime({ secret: process.env.NEON_REALTIME_SECRET, db: new URL(config().databaseUrl).pathname.slice(1) });
338 return c.json({ available: true, url: process.env.NEON_REALTIME_URL, origin: config().webUrl, query: await realtime.seal({ query }) });
339 });
340 async function release(grant: Grant) {
341 const result = await database().query(`SELECT r.object_key,r.digest,r.version FROM glow_agent_releases r JOIN glow_runs j ON j.data->>'agentVersion'=r.version WHERE j.id=$1`, [grant.runId]);
342 if (!result.rows[0]) throw new ApiError(503, 'The pinned agent release is unavailable');
343 return result.rows[0] as { object_key: string; digest: string; version: string };
344 }
345 api.get('/internal/run/package', async c => {
346 const row = await release(c.get('grant'));
347 return c.json({ signature: await signGrant('agent-release', { digest: row.digest, version: row.version }, 120) });
348 });
349 api.get('/internal/run/package/archive', async c => {
350 const row = await release(c.get('grant')), object = await getObject<{ archive: string }>(row.object_key);
351 return new Response(Buffer.from(object.archive, 'base64'), { headers: { 'Content-Type': 'application/zip', 'Cache-Control': 'no-store' } });
352 });
353 api.post('/internal/run/checkpoint', async c => {
354 const input = checkpointSchema.parse(await c.req.json()), grant = c.get('grant');
355 const key = await putObject({ source: input.source, session: input.session, complete: input.phase === 'Checking the finished creation' });
356 const saved = await database().query(`UPDATE glow_runs SET checkpoint_key=$2,data=data || jsonb_build_object('phase',$3::text,'updatedAt',$4::text) WHERE id=$1 AND owner_id=$5 AND (data->>'fence')::int=$6 AND data->>'status'='running' AND lease_until>now() RETURNING id`, [grant.runId, key, input.phase, now(), grant.invocationId, grant.fence]);
357 if (!saved.rowCount) throw new ApiError(409, 'Change no longer current');
358 return c.json({ ok: true });
359 });
360 // The worker reached its slice limit mid-change: save its work and queue the next slice.
361 api.post('/internal/run/continue', async c => {
362 const input = checkpointSchema.parse(await c.req.json()), grant = c.get('grant');
363 const key = await putObject({ source: input.source, session: input.session, complete: false });
364 const saved = await database().query(`UPDATE glow_runs SET checkpoint_key=$2,owner_id=NULL,activation_hash=NULL,lease_until=NULL,dispatch_id=NULL,
365 data=data || jsonb_build_object('status','queued','phase','Still working','continuation',true,'slices',coalesce((data->>'slices')::int,0)+1,'fence',(data->>'fence')::int+1,'updatedAt',$3::text)
366 WHERE id=$1 AND owner_id=$4 AND (data->>'fence')::int=$5 AND data->>'status'='running' AND coalesce((data->>'slices')::int,0)<$6 RETURNING id`, [grant.runId, key, now(), grant.invocationId, grant.fence, maxSlices - 1]);
367 if (!saved.rowCount) throw new ApiError(409, 'This change cannot continue');
368 background(dispatchOne()); return c.json({ ok: true });
369 });
370 api.post('/internal/run/progress', async c => {
371 const input = progressSchema.parse(await c.req.json());
372 return c.json((await transaction(client => recordProgress(client, c.get('grant'), input))).data);
373 });
374 api.post('/internal/run/question', async c => {
375 const input = askQuestionSchema.parse(await c.req.json());
376 const key = await putObject({ source: input.source, session: input.session, complete: false });
377 return c.json((await transaction(client => waitForAnswer(client, c.get('grant'), input, key))).data);
378 });
379 api.post('/internal/run/candidate', async c => {
380 const input = candidateSchema.parse(await c.req.json()), grant = c.get('grant');
381 const html = await compileCreation(input.source);
382 const objectKey = await putObject({ source: input.source, session: input.session, html });
383 const result = await transaction(async client => {
384 const appResult = await client.query('SELECT data FROM glow_apps WHERE id=$1 FOR UPDATE', [grant.appId]);
385 const app = appResult.rows[0]?.data;
386 const job = await client.query('SELECT * FROM glow_runs WHERE id=$1 FOR UPDATE', [grant.runId]);
387 if (!app || app.generation !== grant.generation || job.rows[0]?.data.fence !== grant.fence || job.rows[0]?.owner_id !== grant.invocationId || job.rows[0]?.data.status !== 'running' || new Date(job.rows[0].lease_until).getTime() <= Date.now()) throw new ApiError(409, 'A newer change replaced this result');
388 const version = { id: randomUUID(), appId: app.id, parentId: app.draftVersionId, summary: input.summary, createdAt: now(), published: app.visibility !== 'private', demo: input.details?.demo, runId: grant.runId };
389 if (input.details) {
390 if (app.titleSource !== 'user') { app.title = input.details.title; app.titleSource = 'agent'; }
391 app.tagline = input.details.tagline; app.emoji = input.details.emoji; app.color = input.details.color;
392 }
393 await client.query('INSERT INTO glow_versions(id,app_id,data,object_key) VALUES($1,$2,$3,$4)', [version.id, app.id, JSON.stringify(version), objectKey]);
394 app.draftVersionId = version.id; app.updatedAt = now();
395 if (app.visibility !== 'private') app.headVersionId = version.id;
396 await client.query('UPDATE glow_apps SET data=$2 WHERE id=$1', [app.id, JSON.stringify(app)]);
397 await client.query(`UPDATE glow_runs SET data=data || $2::jsonb,lease_until=NULL WHERE id=$1`, [grant.runId, JSON.stringify({ status: 'ready', phase: 'Ready to play', error: null, updatedAt: now() })]);
398 await appendMessage(client, app.id, 'assistant', input.summary, grant.runId!);
399 return version;
400 });
401 return c.json(result);
402 });
403 api.post('/internal/run/capture', async c => {
404 const input = agentCaptureSchema.parse(await c.req.json());
405 let html: string;
406 try { html = await compileCreation(input.source); }
407 catch (error) { return c.json({ available: false, reason: `The app does not compile yet: ${String(error).slice(0, 1500)}` }); }
408 return c.json(await captureForAgent(c.get('grant').appId, html, { steps: input.steps, posterDelayMs: input.posterDelayMs }));
409 });
410 api.use('/internal/capture/*', async (c, next) => {
411 try { c.set('grant', await verifyGrant(bearer(c.req.raw), 'capture-worker')); } catch { throw new ApiError(401, 'Invalid capture worker'); }
412 await next();
413 });
414 const workerId = (grant: Grant) => z.string().min(1).max(80).parse((grant as Grant & { workerId?: string }).workerId);
415 api.post('/internal/capture/next', async c => {
416 const job = await claimJob(workerId(c.get('grant')), 20_000);
417 return job ? c.json(job) : c.body(null, 204);
418 });
419 api.post('/internal/capture/heartbeat', async c => { await heartbeat(workerId(c.get('grant')), await c.req.json().catch(() => ({}))); return c.json({ ok: true }); });
420 api.post('/internal/capture/:jobId/complete', async c => {
421 await completeJob(id.parse(c.req.param('jobId')), workerId(c.get('grant')), await c.req.json()); return c.json({ ok: true });
422 });
423 api.post('/internal/capture/:jobId/fail', async c => {
424 const input = z.object({ error: z.string().max(1000) }).parse(await c.req.json());
425 await failJob(id.parse(c.req.param('jobId')), workerId(c.get('grant')), input.error); return c.json({ ok: true });
426 });
427 api.post('/internal/run/fail', async c => {
428 const input = z.object({ error: z.string().max(1000) }).parse(await c.req.json());
429 await finishFailed(c.get('grant'), input.error); return c.json({ ok: true });
430 });
431 api.post('/internal/run/model/v1/chat/completions', async c => {
432 const grant = c.get('grant'), input = await c.req.json();
433 const admission = await database().query(`UPDATE glow_runs SET model_calls=model_calls+1,model_calls_total=model_calls_total+1 WHERE id=$1 AND owner_id=$2 AND model_calls<150 AND (data->>'fence')::int=$3 AND data->>'status'='running' AND lease_until>now() RETURNING id`, [grant.runId, grant.invocationId, grant.fence]);
434 if (!admission.rowCount) throw new ApiError(429, 'This change reached its model budget');
435 delete input.store;
436 input.model = config().model; input.max_tokens = Math.min(Number(input.max_tokens ?? 8192), 8192);
437 const response = await fetch(`${required('NEON_AI_GATEWAY_BASE_URL').replace(/\/$/, '')}/v1/chat/completions`, {
438 method: 'POST', headers: { Authorization: `Bearer ${required('NEON_AI_GATEWAY_TOKEN')}`, 'Content-Type': 'application/json' },
439 body: JSON.stringify(input), signal: AbortSignal.timeout(180_000), redirect: 'error',
440 });
441 return new Response(response.body, { status: response.status, headers: { 'Content-Type': response.headers.get('Content-Type') ?? 'application/json', 'Cache-Control': 'no-store' } });
442 });
443 api.post('/internal/sweep', async c => {
444 const expected = Buffer.from(required('GLOW_SWEEP_SECRET')), provided = Buffer.from(bearer(c.req.raw));
445 if (expected.length !== provided.length || !timingSafeEqual(expected, provided)) throw new ApiError(401, 'Unauthorized');
446 background(dispatchOne()); return c.json({ ok: true });
447 });
448 api.post('/internal/recovery', async c => {
449 const delivery = await parseTriggerDelivery(c.req.raw);
450 if (!delivery.ok || delivery.invocation.trigger.type !== 'schedule' || delivery.invocation.trigger.name !== 'glow-recovery') throw new ApiError(401, 'Invalid recovery trigger');
451 background(dispatchOne()); return c.json({ ok: true });
452 });
453 return api;
454}