@schlessera/brain-ui-server 0.33.1 → 0.34.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -38,6 +38,7 @@ import {
38
38
  resolveStandalonePricingConfig,
39
39
  } from "../config/env.js";
40
40
  import { createModelPricing, type PricingRates } from "../pricing/model-pricing.js";
41
+ import { ACTIVITY_SQL } from "./sql.js";
41
42
 
42
43
  export const SPAN_OUTCOMES = [
43
44
  "success",
@@ -327,15 +328,13 @@ export function createActivityStore(
327
328
 
328
329
  function nextSeq(runId: string): number {
329
330
  const row = db
330
- .query("SELECT COALESCE(MAX(seq), 0) AS hi FROM activity_changes WHERE run_id = ?")
331
+ .query(ACTIVITY_SQL.nextSeq)
331
332
  .get(runId) as { hi: number };
332
333
  return row.hi + 1;
333
334
  }
334
335
 
335
336
  function logChange(runId: string, seq: number, spanId: string, eventIndex?: number) {
336
- db.query(
337
- "INSERT INTO activity_changes (run_id, seq, span_id, event_index) VALUES (?, ?, ?, ?)"
338
- ).run(runId, seq, spanId, eventIndex ?? null);
337
+ db.query(ACTIVITY_SQL.insertChange).run(runId, seq, spanId, eventIndex ?? null);
339
338
  }
340
339
 
341
340
  function rowToSpan(r: any): SpanRow {
@@ -380,20 +379,20 @@ export function createActivityStore(
380
379
  }
381
380
 
382
381
  function getSpanRaw(spanId: string): SpanRow | null {
383
- const r = db.query("SELECT * FROM activity_spans WHERE span_id = ?").get(spanId);
382
+ const r = db.query(ACTIVITY_SQL.spanById).get(spanId);
384
383
  return r ? rowToSpan(r) : null;
385
384
  }
386
385
 
387
386
  function runHighWaterSeqRaw(runId: string): number {
388
387
  const row = db
389
- .query("SELECT COALESCE(MAX(seq), 0) AS hi FROM activity_changes WHERE run_id = ?")
388
+ .query(ACTIVITY_SQL.nextSeq)
390
389
  .get(runId) as { hi: number };
391
390
  return row.hi;
392
391
  }
393
392
 
394
393
  function endSpanInTx(spanId: string, input: EndSpanInput): boolean {
395
394
  const existing = db
396
- .query("SELECT run_id, outcome, attrs FROM activity_spans WHERE span_id = ?")
395
+ .query(ACTIVITY_SQL.spanStateById)
397
396
  .get(spanId) as { run_id: string; outcome: string | null; attrs: string | null } | null;
398
397
  if (!existing || existing.outcome !== null) return false;
399
398
 
@@ -402,16 +401,7 @@ export function createActivityStore(
402
401
  ? JSON.stringify({ ...(safeParse(existing.attrs) ?? {}), ...input.attrs })
403
402
  : existing.attrs;
404
403
  const u = input.usage ?? {};
405
- db.query(
406
- `UPDATE activity_spans SET outcome = ?, outcome_reason = ?, ended_at = ?, attrs = ?,
407
- input_tokens = COALESCE(?, input_tokens),
408
- output_tokens = COALESCE(?, output_tokens),
409
- cache_read_tokens = COALESCE(?, cache_read_tokens),
410
- cache_creation_tokens = COALESCE(?, cache_creation_tokens),
411
- cost_usd = COALESCE(?, cost_usd),
412
- model = COALESCE(?, model)
413
- WHERE span_id = ?`
414
- ).run(
404
+ db.query(ACTIVITY_SQL.endSpan).run(
415
405
  input.outcome,
416
406
  input.reason ?? null,
417
407
  endedAt,
@@ -431,9 +421,7 @@ export function createActivityStore(
431
421
  /** Close every open span of the run (children first) and roll it up. */
432
422
  function closeRunInTx(runId: string, outcome: SpanOutcome, reason: string): number {
433
423
  const open = db
434
- .query(
435
- "SELECT span_id FROM activity_spans WHERE run_id = ? AND outcome IS NULL ORDER BY started_at DESC"
436
- )
424
+ .query(ACTIVITY_SQL.openSpansByRun)
437
425
  .all(runId) as Array<{ span_id: string }>;
438
426
  let closed = 0;
439
427
  for (const { span_id } of open) {
@@ -445,7 +433,7 @@ export function createActivityStore(
445
433
 
446
434
  function rollupRunInTx(runId: string) {
447
435
  const spans = db
448
- .query("SELECT * FROM activity_spans WHERE run_id = ? ORDER BY started_at")
436
+ .query(ACTIVITY_SQL.spansByRun)
449
437
  .all(runId)
450
438
  .map(rowToSpan);
451
439
  if (spans.length === 0) return;
@@ -506,37 +494,7 @@ export function createActivityStore(
506
494
  const costUsd = root.usage.costUsd ?? priced?.costUsd ?? null;
507
495
 
508
496
  db.query(
509
- `INSERT INTO activity_run_rollups
510
- (run_id, origin, name, session_id, job_name, started_at, ended_at, outcome,
511
- duration_ms, span_count, input_tokens, output_tokens, cache_read_tokens,
512
- cache_creation_tokens, cost_usd, effective_cost_usd, billing_mode,
513
- pricing_estimate, failure_reason, detail_pruned)
514
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0)
515
- ON CONFLICT(run_id) DO UPDATE SET
516
- ended_at = excluded.ended_at, outcome = excluded.outcome,
517
- duration_ms = excluded.duration_ms, span_count = excluded.span_count,
518
- input_tokens = excluded.input_tokens, output_tokens = excluded.output_tokens,
519
- cache_read_tokens = excluded.cache_read_tokens,
520
- cache_creation_tokens = excluded.cache_creation_tokens,
521
- cost_usd = COALESCE(activity_run_rollups.cost_usd, excluded.cost_usd),
522
- effective_cost_usd = CASE
523
- WHEN activity_run_rollups.effective_cost_usd IS NOT NULL
524
- THEN activity_run_rollups.effective_cost_usd
525
- WHEN activity_run_rollups.billing_mode IS NULL
526
- OR activity_run_rollups.billing_mode = excluded.billing_mode
527
- THEN excluded.effective_cost_usd
528
- ELSE NULL
529
- END,
530
- billing_mode = COALESCE(activity_run_rollups.billing_mode, excluded.billing_mode),
531
- pricing_estimate = CASE
532
- WHEN activity_run_rollups.pricing_estimate IS NOT NULL
533
- THEN activity_run_rollups.pricing_estimate
534
- WHEN activity_run_rollups.billing_mode IS NULL
535
- OR activity_run_rollups.billing_mode = excluded.billing_mode
536
- THEN excluded.pricing_estimate
537
- ELSE NULL
538
- END,
539
- failure_reason = excluded.failure_reason`
497
+ ACTIVITY_SQL.upsertRollup
540
498
  // Every cost column is FROZEN at first non-NULL write (AE5): a re-rollup
541
499
  // after a pricing refresh must not silently reprice history — only a
542
500
  // still-NULL slot may be filled by a later computation. cost_usd gets
@@ -576,12 +534,7 @@ export function createActivityStore(
576
534
  startSpan(input) {
577
535
  return inWrite(() => {
578
536
  const startedAt = input.startedAt ?? Date.now();
579
- db.query(
580
- `INSERT INTO activity_spans
581
- (span_id, run_id, parent_span_id, name, kind, origin, session_id, job_name,
582
- attrs, started_at, writer, last_heartbeat_at)
583
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
584
- ).run(
537
+ db.query(ACTIVITY_SQL.insertSpan).run(
585
538
  input.spanId,
586
539
  input.runId,
587
540
  input.parentSpanId ?? null,
@@ -607,23 +560,14 @@ export function createActivityStore(
607
560
  patchSpan(spanId, patch) {
608
561
  return inWrite(() => {
609
562
  const existing = db
610
- .query("SELECT run_id, outcome, attrs FROM activity_spans WHERE span_id = ?")
563
+ .query(ACTIVITY_SQL.spanStateById)
611
564
  .get(spanId) as { run_id: string; outcome: string | null; attrs: string | null } | null;
612
565
  if (!existing || existing.outcome !== null) return false;
613
566
  const attrs = patch.attrs
614
567
  ? JSON.stringify({ ...(safeParse(existing.attrs) ?? {}), ...patch.attrs })
615
568
  : existing.attrs;
616
569
  const u = patch.usage ?? {};
617
- db.query(
618
- `UPDATE activity_spans SET attrs = ?, wait_until = COALESCE(?, wait_until),
619
- input_tokens = COALESCE(?, input_tokens),
620
- output_tokens = COALESCE(?, output_tokens),
621
- cache_read_tokens = COALESCE(?, cache_read_tokens),
622
- cache_creation_tokens = COALESCE(?, cache_creation_tokens),
623
- cost_usd = COALESCE(?, cost_usd),
624
- model = COALESCE(?, model)
625
- WHERE span_id = ?`
626
- ).run(
570
+ db.query(ACTIVITY_SQL.patchSpan).run(
627
571
  attrs,
628
572
  patch.waitUntil ?? null,
629
573
  u.inputTokens ?? null,
@@ -642,19 +586,21 @@ export function createActivityStore(
642
586
  appendEvent(spanId, eventType, payload, ts, cap) {
643
587
  return inWrite(() => {
644
588
  const span = db
645
- .query("SELECT run_id FROM activity_spans WHERE span_id = ?")
589
+ .query(ACTIVITY_SQL.spanRunById)
646
590
  .get(spanId) as { run_id: string } | null;
647
591
  if (!span) return null;
648
592
  const next = db
649
- .query(
650
- "SELECT COALESCE(MAX(event_index), -1) + 1 AS idx FROM activity_events WHERE span_id = ?"
651
- )
593
+ .query(ACTIVITY_SQL.nextEventIndex)
652
594
  .get(spanId) as { idx: number };
653
595
  const stored = capPayload(payload, cap);
654
596
  const at = ts ?? Date.now();
655
- db.query(
656
- "INSERT INTO activity_events (span_id, event_index, ts, event_type, payload) VALUES (?, ?, ?, ?, ?)"
657
- ).run(spanId, next.idx, at, eventType, JSON.stringify(stored));
597
+ db.query(ACTIVITY_SQL.insertEvent).run(
598
+ spanId,
599
+ next.idx,
600
+ at,
601
+ eventType,
602
+ JSON.stringify(stored)
603
+ );
658
604
  logChange(span.run_id, nextSeq(span.run_id), spanId, next.idx);
659
605
  // Built from the values just written — no read-back needed.
660
606
  return {
@@ -672,9 +618,7 @@ export function createActivityStore(
672
618
  inWrite(() => {
673
619
  // Deliberately NOT change-logged: a heartbeat is liveness metadata,
674
620
  // not activity the client needs a delta for.
675
- db.query(
676
- "UPDATE activity_spans SET last_heartbeat_at = ? WHERE span_id = ? AND outcome IS NULL"
677
- ).run(at ?? Date.now(), spanId);
621
+ db.query(ACTIVITY_SQL.heartbeat).run(at ?? Date.now(), spanId);
678
622
  });
679
623
  },
680
624
 
@@ -697,9 +641,7 @@ export function createActivityStore(
697
641
  // loop re-checks open-ness inside the transaction (endSpanInTx is
698
642
  // write-once), so a race just skips.
699
643
  const open = db
700
- .query(
701
- "SELECT DISTINCT run_id FROM activity_spans WHERE outcome IS NULL AND origin = 'session'"
702
- )
644
+ .query(ACTIVITY_SQL.openSessionRuns)
703
645
  .all() as Array<{ run_id: string }>;
704
646
  if (open.length === 0) return 0;
705
647
  getPricing(); // construct outside the write lock; rollup reuses it
@@ -718,11 +660,7 @@ export function createActivityStore(
718
660
  // legitimately long, quiet run with a live writer is never killed.
719
661
  // Candidate read outside the write transaction, same as sweepOwnOrphans.
720
662
  const staleRoots = db
721
- .query(
722
- `SELECT span_id, run_id FROM activity_spans
723
- WHERE outcome IS NULL AND parent_span_id IS NULL
724
- AND writer != ? AND COALESCE(last_heartbeat_at, started_at) < ?`
725
- )
663
+ .query(ACTIVITY_SQL.staleRoots)
726
664
  .all(writer, cutoff) as Array<{ span_id: string; run_id: string }>;
727
665
  if (staleRoots.length === 0) return 0;
728
666
  getPricing(); // construct outside the write lock; rollup reuses it
@@ -739,9 +677,7 @@ export function createActivityStore(
739
677
  const cutoff = (now ?? Date.now()) - thresholdMs;
740
678
  return (
741
679
  db
742
- .query(
743
- "SELECT * FROM activity_spans WHERE outcome IS NULL AND parent_span_id IS NULL AND started_at < ?"
744
- )
680
+ .query(ACTIVITY_SQL.stuckRoots)
745
681
  .all(cutoff) as any[]
746
682
  ).map(rowToSpan);
747
683
  },
@@ -751,23 +687,10 @@ export function createActivityStore(
751
687
  // change whose span/event row was pruned drops out via the join, same
752
688
  // as the old per-row miss.
753
689
  const spanRows = db
754
- .query(
755
- `SELECT c.change_id, c.run_id, c.seq, s.*
756
- FROM activity_changes c
757
- JOIN activity_spans s ON s.span_id = c.span_id
758
- WHERE c.change_id > ? AND c.event_index IS NULL
759
- ORDER BY c.change_id LIMIT ?`
760
- )
690
+ .query(ACTIVITY_SQL.spanChanges)
761
691
  .all(changeCursor, limit) as any[];
762
692
  const eventRows = db
763
- .query(
764
- `SELECT c.change_id, c.run_id, c.seq, e.*
765
- FROM activity_changes c
766
- JOIN activity_events e
767
- ON e.span_id = c.span_id AND e.event_index = c.event_index
768
- WHERE c.change_id > ? AND c.event_index IS NOT NULL
769
- ORDER BY c.change_id LIMIT ?`
770
- )
693
+ .query(ACTIVITY_SQL.eventChanges)
771
694
  .all(changeCursor, limit) as any[];
772
695
  const changes: ActivityChange[] = [
773
696
  ...spanRows.map(
@@ -795,22 +718,14 @@ export function createActivityStore(
795
718
 
796
719
  terminalRootChangesSince(changeCursor, limit = 500) {
797
720
  const rows = db
798
- .query(
799
- `SELECT MAX(c.change_id) AS change_id, s.*
800
- FROM activity_changes c
801
- JOIN activity_spans s ON s.span_id = c.span_id
802
- WHERE c.change_id > ? AND c.event_index IS NULL
803
- AND s.parent_span_id IS NULL AND s.outcome IS NOT NULL
804
- GROUP BY s.span_id
805
- ORDER BY change_id LIMIT ?`
806
- )
721
+ .query(ACTIVITY_SQL.terminalRootChanges)
807
722
  .all(changeCursor, limit) as any[];
808
723
  return rows.map((r) => ({ changeId: r.change_id, span: rowToSpan(r) }));
809
724
  },
810
725
 
811
726
  latestChangeCursor() {
812
727
  const row = db
813
- .query("SELECT COALESCE(MAX(change_id), 0) AS hi FROM activity_changes")
728
+ .query(ACTIVITY_SQL.latestChangeCursor)
814
729
  .get() as { hi: number };
815
730
  return row.hi;
816
731
  },
@@ -822,21 +737,17 @@ export function createActivityStore(
822
737
  return db.transaction(() => {
823
738
  const spans = (
824
739
  db
825
- .query("SELECT * FROM activity_spans WHERE run_id = ? ORDER BY started_at")
740
+ .query(ACTIVITY_SQL.spansByRun)
826
741
  .all(runId) as any[]
827
742
  ).map(rowToSpan);
828
743
  if (spans.length === 0) return null;
829
744
  const events = (
830
745
  db
831
- .query(
832
- `SELECT e.* FROM activity_events e
833
- JOIN activity_spans s ON s.span_id = e.span_id
834
- WHERE s.run_id = ? ORDER BY e.ts, e.event_index`
835
- )
746
+ .query(ACTIVITY_SQL.eventsByRun)
836
747
  .all(runId) as any[]
837
748
  ).map(rowToEvent);
838
749
  const cursor = db
839
- .query("SELECT COALESCE(MAX(change_id), 0) AS hi FROM activity_changes")
750
+ .query(ACTIVITY_SQL.latestChangeCursor)
840
751
  .get() as { hi: number };
841
752
  return {
842
753
  runId,
@@ -855,9 +766,7 @@ export function createActivityStore(
855
766
  openRootSpans() {
856
767
  return (
857
768
  db
858
- .query(
859
- "SELECT * FROM activity_spans WHERE outcome IS NULL AND parent_span_id IS NULL ORDER BY started_at DESC"
860
- )
769
+ .query(ACTIVITY_SQL.openRootSpans)
861
770
  .all() as any[]
862
771
  ).map(rowToSpan);
863
772
  },
@@ -887,46 +796,24 @@ export function createActivityStore(
887
796
  // run — that terminal write is what made the run prunable), guarded
888
797
  // against any run that still has an open span.
889
798
  const candidates = db
890
- .query(
891
- `SELECT run_id, ended_at AS ended FROM activity_run_rollups r
892
- WHERE detail_pruned = 0 AND ended_at IS NOT NULL
893
- AND ((ended_at < ? AND ended_at < ?) OR ended_at < ?)
894
- AND NOT EXISTS (
895
- SELECT 1 FROM activity_spans s
896
- WHERE s.run_id = r.run_id AND s.outcome IS NULL
897
- )
898
- LIMIT ?`
899
- )
799
+ .query(ACTIVITY_SQL.pruneCandidates)
900
800
  .all(floor, retentionCutoff, ceiling, batch) as Array<{ run_id: string; ended: number }>;
901
801
  let spansDeleted = 0;
902
802
  for (const { run_id, ended } of candidates) {
903
- db.query(
904
- "UPDATE activity_run_rollups SET detail_pruned = 1 WHERE run_id = ?"
905
- ).run(run_id);
803
+ db.query(ACTIVITY_SQL.markDetailPruned).run(run_id);
906
804
  if (ended >= floor) {
907
805
  // Pruned by the hard ceiling alone — the digest never covered
908
806
  // this run; make the coverage gap visible on the rollup.
909
- db.query(
910
- "UPDATE activity_run_rollups SET failure_reason = COALESCE(failure_reason, 'digest coverage gap') WHERE run_id = ?"
911
- ).run(run_id);
807
+ db.query(ACTIVITY_SQL.markDigestCoverageGap).run(run_id);
912
808
  }
913
- db.query(
914
- `DELETE FROM activity_events WHERE span_id IN
915
- (SELECT span_id FROM activity_spans WHERE run_id = ?)`
916
- ).run(run_id);
917
- const res = db.query("DELETE FROM activity_spans WHERE run_id = ?").run(run_id);
809
+ db.query(ACTIVITY_SQL.deleteEventsByRun).run(run_id);
810
+ const res = db.query(ACTIVITY_SQL.deleteSpansByRun).run(run_id);
918
811
  spansDeleted += res.changes;
919
- db.query("DELETE FROM activity_changes WHERE run_id = ?").run(run_id);
812
+ db.query(ACTIVITY_SQL.deleteChangesByRun).run(run_id);
920
813
  }
921
814
  // The change log only serves live polling; rows this deep in the past
922
815
  // are unreachable by any live cursor. Keep runs with open spans.
923
- db.query(
924
- `DELETE FROM activity_changes WHERE change_id < (
925
- SELECT COALESCE(MAX(change_id), 0) FROM activity_changes
926
- ) - 100000 AND run_id NOT IN (
927
- SELECT DISTINCT run_id FROM activity_spans WHERE outcome IS NULL
928
- )`
929
- ).run();
816
+ db.query(ACTIVITY_SQL.compactChanges).run();
930
817
  return { runsPruned: candidates.length, spansDeleted };
931
818
  });
932
819
  },