synabun 2.4.3 → 2.4.4

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.
Files changed (153) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +1 -1
  3. package/docs/browser-extension-bridge.md +61 -32
  4. package/mcp-server/dist/http.d.ts.map +1 -1
  5. package/mcp-server/dist/http.js +8 -1
  6. package/mcp-server/dist/http.js.map +1 -1
  7. package/mcp-server/dist/services/identity.d.ts +2 -0
  8. package/mcp-server/dist/services/identity.d.ts.map +1 -1
  9. package/mcp-server/dist/services/identity.js +4 -0
  10. package/mcp-server/dist/services/identity.js.map +1 -1
  11. package/mcp-server/dist/services/memory-client.d.ts +5 -0
  12. package/mcp-server/dist/services/memory-client.d.ts.map +1 -1
  13. package/mcp-server/dist/services/memory-client.js +21 -2
  14. package/mcp-server/dist/services/memory-client.js.map +1 -1
  15. package/mcp-server/dist/services/memory-writer.d.ts +3 -0
  16. package/mcp-server/dist/services/memory-writer.d.ts.map +1 -1
  17. package/mcp-server/dist/services/memory-writer.js +7 -1
  18. package/mcp-server/dist/services/memory-writer.js.map +1 -1
  19. package/mcp-server/dist/services/neural-interface.d.ts +11 -1
  20. package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
  21. package/mcp-server/dist/services/neural-interface.js +67 -17
  22. package/mcp-server/dist/services/neural-interface.js.map +1 -1
  23. package/mcp-server/dist/services/typesafe-config.d.ts +38 -2
  24. package/mcp-server/dist/services/typesafe-config.d.ts.map +1 -1
  25. package/mcp-server/dist/services/typesafe-config.js +260 -8
  26. package/mcp-server/dist/services/typesafe-config.js.map +1 -1
  27. package/mcp-server/dist/tools/agent-definition.d.ts +2 -2
  28. package/mcp-server/dist/tools/agents.d.ts +3 -1
  29. package/mcp-server/dist/tools/agents.d.ts.map +1 -1
  30. package/mcp-server/dist/tools/agents.js +11 -6
  31. package/mcp-server/dist/tools/agents.js.map +1 -1
  32. package/mcp-server/dist/tools/browser-observe.d.ts +11 -0
  33. package/mcp-server/dist/tools/browser-observe.d.ts.map +1 -1
  34. package/mcp-server/dist/tools/browser-observe.js +113 -27
  35. package/mcp-server/dist/tools/browser-observe.js.map +1 -1
  36. package/mcp-server/dist/tools/browser-readers.d.ts +6 -0
  37. package/mcp-server/dist/tools/browser-readers.d.ts.map +1 -0
  38. package/mcp-server/dist/tools/browser-readers.js +17 -0
  39. package/mcp-server/dist/tools/browser-readers.js.map +1 -0
  40. package/mcp-server/dist/tools/remember.d.ts.map +1 -1
  41. package/mcp-server/dist/tools/remember.js +6 -2
  42. package/mcp-server/dist/tools/remember.js.map +1 -1
  43. package/mcp-server/dist/tools/youtube/analytics.d.ts +4 -0
  44. package/mcp-server/dist/tools/youtube/analytics.d.ts.map +1 -1
  45. package/mcp-server/dist/tools/youtube/analytics.js +25 -20
  46. package/mcp-server/dist/tools/youtube/analytics.js.map +1 -1
  47. package/mcp-server/dist/tools/youtube/helpers.d.ts +5 -1
  48. package/mcp-server/dist/tools/youtube/helpers.d.ts.map +1 -1
  49. package/mcp-server/dist/tools/youtube/helpers.js +7 -3
  50. package/mcp-server/dist/tools/youtube/helpers.js.map +1 -1
  51. package/mcp-server/dist/tools/youtube/navigate.d.ts +2 -0
  52. package/mcp-server/dist/tools/youtube/navigate.d.ts.map +1 -1
  53. package/mcp-server/dist/tools/youtube/navigate.js +5 -3
  54. package/mcp-server/dist/tools/youtube/navigate.js.map +1 -1
  55. package/mcp-server/dist/tools/youtube/playlist.js +2 -2
  56. package/mcp-server/dist/tools/youtube/playlist.js.map +1 -1
  57. package/mcp-server/dist/tools/youtube/readers.d.ts +4 -0
  58. package/mcp-server/dist/tools/youtube/readers.d.ts.map +1 -0
  59. package/mcp-server/dist/tools/youtube/readers.js +15 -0
  60. package/mcp-server/dist/tools/youtube/readers.js.map +1 -0
  61. package/mcp-server/package-lock.json +2 -2
  62. package/mcp-server/package.json +1 -1
  63. package/mcp-server/src/http.ts +8 -1
  64. package/mcp-server/src/services/identity.ts +5 -0
  65. package/mcp-server/src/services/memory-client.ts +32 -12
  66. package/mcp-server/src/services/memory-writer.ts +5 -2
  67. package/mcp-server/src/services/neural-interface.ts +65 -18
  68. package/mcp-server/src/services/typesafe-config.ts +268 -7
  69. package/mcp-server/src/tools/agents.ts +12 -6
  70. package/mcp-server/src/tools/browser-observe.ts +117 -28
  71. package/mcp-server/src/tools/browser-readers.ts +19 -0
  72. package/mcp-server/src/tools/remember.ts +6 -1
  73. package/mcp-server/src/tools/youtube/analytics.ts +26 -28
  74. package/mcp-server/src/tools/youtube/helpers.ts +8 -2
  75. package/mcp-server/src/tools/youtube/navigate.ts +6 -7
  76. package/mcp-server/src/tools/youtube/playlist.ts +2 -2
  77. package/mcp-server/src/tools/youtube/readers.ts +15 -0
  78. package/neural-interface/i18n/en.json +139 -0
  79. package/neural-interface/i18n/pt-BR.json +139 -0
  80. package/neural-interface/lib/assistant-api.js +90 -0
  81. package/neural-interface/lib/assistant-brains/claude.js +10 -0
  82. package/neural-interface/lib/assistant-dispatch.js +276 -42
  83. package/neural-interface/lib/assistant-memory.js +3 -1
  84. package/neural-interface/lib/assistant-persona.js +6 -0
  85. package/neural-interface/lib/assistant-router.js +18 -8
  86. package/neural-interface/lib/assistant-runtime.js +87 -1
  87. package/neural-interface/lib/assistant-task-prompt.js +15 -2
  88. package/neural-interface/lib/browser-connection-state.js +20 -0
  89. package/neural-interface/lib/browser-extension-adapter.js +221 -15
  90. package/neural-interface/lib/browser-extension-bridge.js +40 -7
  91. package/neural-interface/lib/browser-extension-folder.js +50 -11
  92. package/neural-interface/lib/browser-extension-package.js +6 -5
  93. package/neural-interface/lib/browser-extension-pin.json +15 -13
  94. package/neural-interface/lib/browser-extension-protocol.js +111 -13
  95. package/neural-interface/lib/browser-extension-setup.js +7 -5
  96. package/neural-interface/lib/browser-extension-update.js +104 -0
  97. package/neural-interface/lib/browser-extraction.js +38 -14
  98. package/neural-interface/lib/claude-bg-tasks.js +183 -0
  99. package/neural-interface/lib/claude-history.js +12 -1
  100. package/neural-interface/lib/confined-fs.js +25 -0
  101. package/neural-interface/lib/coordination/operations.js +2 -0
  102. package/neural-interface/lib/db.js +39 -16
  103. package/neural-interface/lib/editor-completion-opencode.js +2 -2
  104. package/neural-interface/lib/git-bash/manager.js +28 -3
  105. package/neural-interface/lib/git-status-runner.js +31 -3
  106. package/neural-interface/lib/loop-inventory.js +162 -0
  107. package/neural-interface/lib/loop-stall.js +74 -4
  108. package/neural-interface/lib/memory-session-capture.js +157 -66
  109. package/neural-interface/lib/native-loop-providers.js +73 -13
  110. package/neural-interface/lib/native-loop-runtime.js +3 -0
  111. package/neural-interface/lib/opencode-protocol.js +4 -2
  112. package/neural-interface/lib/peer-identity.js +62 -16
  113. package/neural-interface/lib/session-cache-builder.js +66 -18
  114. package/neural-interface/lib/session-capture-gate.js +42 -0
  115. package/neural-interface/lib/session-indexer.js +28 -20
  116. package/neural-interface/lib/teams/scheduler.js +3 -2
  117. package/neural-interface/lib/ui-blob-api.js +14 -5
  118. package/neural-interface/lib/ui-blob-store.js +302 -39
  119. package/neural-interface/package-lock.json +2 -2
  120. package/neural-interface/package.json +1 -1
  121. package/neural-interface/public/extension-setup.html +1 -0
  122. package/neural-interface/public/shared/assistant/asst-agents-dock.js +4 -0
  123. package/neural-interface/public/shared/assistant/asst-api.js +42 -0
  124. package/neural-interface/public/shared/assistant/asst-composer.js +85 -12
  125. package/neural-interface/public/shared/assistant/asst-panel.js +285 -10
  126. package/neural-interface/public/shared/assistant/asst-render.js +205 -4
  127. package/neural-interface/public/shared/assistant/asst-scenes.js +12 -0
  128. package/neural-interface/public/shared/assistant/asst-sidepanel.js +18 -1
  129. package/neural-interface/public/shared/assistant/asst-state.js +241 -2
  130. package/neural-interface/public/shared/assistant/asst-steer.js +294 -0
  131. package/neural-interface/public/shared/assistant/asst-styles.js +20 -0
  132. package/neural-interface/public/shared/bg-tasks/bg-tasks-claude.js +147 -0
  133. package/neural-interface/public/shared/bg-tasks/bg-tasks-model.js +527 -0
  134. package/neural-interface/public/shared/bg-tasks/bg-tasks-panel.js +161 -0
  135. package/neural-interface/public/shared/bg-tasks/bg-tasks-view.js +508 -0
  136. package/neural-interface/public/shared/browser-extension-updates.js +88 -0
  137. package/neural-interface/public/shared/cp/cp-bg-tasks.js +130 -0
  138. package/neural-interface/public/shared/extension-setup/es-page.js +18 -11
  139. package/neural-interface/public/shared/extension-update-view.js +34 -0
  140. package/neural-interface/public/shared/ocp-v2/ocp-v2-shell-logic.js +8 -4
  141. package/neural-interface/public/shared/settings/settings-browser-extension.js +10 -4
  142. package/neural-interface/public/shared/settings/settings-extension-update.js +114 -0
  143. package/neural-interface/public/shared/styles.css +4 -0
  144. package/neural-interface/public/shared/ui-claude-panel.js +110 -1
  145. package/neural-interface/public/shared/ui-notifications.js +23 -4
  146. package/neural-interface/public/shared/ui-settings-entry.js +6 -0
  147. package/neural-interface/public/shared/ui-tray-columns.js +9 -2
  148. package/neural-interface/public/shared/worker-end.js +18 -0
  149. package/neural-interface/scripts/patch-node-pty.mjs +151 -0
  150. package/neural-interface/scripts/rebuild-pty.js +10 -0
  151. package/neural-interface/server.js +483 -280
  152. package/npm-shrinkwrap.json +2 -2
  153. package/package.json +1 -1
@@ -15,7 +15,7 @@
15
15
  * never break `judge()`.
16
16
  */
17
17
 
18
- import { getDb } from './sqlite.js';
18
+ import { getDb, onDatabaseClose } from './sqlite.js';
19
19
  import { withMemoryWrite, writeNowOrSoon } from './sqlite-write.js';
20
20
  import { autoHealGate, readTargetBench, DEFAULT_BROWSER_ASSIST, BROWSER_TARGET_DEFAULTS, type BrowserAssistConfig } from './browser-assist-gate.js';
21
21
  export type { BrowserAssistConfig, BrowserTargetBench } from './browser-assist-gate.js';
@@ -439,6 +439,7 @@ let cachedAt = 0;
439
439
 
440
440
  function readStored(): Partial<TypeSafeConfig> | null {
441
441
  try {
442
+ ensureCloseHook();
442
443
  const row = getDb().prepare('SELECT value FROM kv_config WHERE key=?').get(CONFIG_KEY) as { value?: string } | undefined;
443
444
  if (!row?.value) return null;
444
445
  const parsed = JSON.parse(String(row.value)) as unknown;
@@ -528,8 +529,27 @@ export interface TypeSafeLogRow {
528
529
 
529
530
  /** Rows kept. ~1 KB each; 2,000 covered two minutes of a backfill, 20,000 covers a few hours. */
530
531
  export const LOG_KEEP = 20000;
531
- const PRUNE_EVERY = 25;
532
+ export const LOG_PRUNE_EVERY = 25;
533
+ export const LOG_PRUNE_BATCH_SIZE = 100;
534
+ export const LOG_PRUNE_TICK_MS = 10;
535
+ interface PruneCycle {
536
+ generation: number;
537
+ targetKeep: number;
538
+ batchSize: number;
539
+ tickMs: number;
540
+ maxSparseChunk: number | undefined;
541
+ timer: ReturnType<typeof setTimeout> | null;
542
+ running: boolean;
543
+ recomputeRequested: boolean;
544
+ cachedPlan: { db: ReturnType<typeof getDb>; keep: number; cutoff: number; partial: boolean } | null;
545
+ deleted: number;
546
+ promise: Promise<number>;
547
+ resolve: (deleted: number) => void;
548
+ settled: boolean;
549
+ }
532
550
  let insertsSincePrune = 0;
551
+ let pruneGeneration = 0;
552
+ let activePrune: PruneCycle | null = null;
533
553
  const OUTCOME_MAX_CHARS = 4096;
534
554
  const SESSION_ID_RE = /^[A-Za-z0-9_.:-]{1,128}$/;
535
555
 
@@ -549,7 +569,232 @@ export function logSessionFromRef(ref: unknown): string | null {
549
569
  return cleanSessionId(compaction ? compaction[1] : ref);
550
570
  }
551
571
 
572
+ /**
573
+ * Compute the highest `id` to delete so at most `keep` newest rows remain.
574
+ * Work is strictly bounded by the retention window (never a full-table COUNT(*)):
575
+ * 1. MIN(id) / MAX(id) rowid edge seeks (O(log N)): if `maxId - minId + 1 <= keep`, nothing to delete.
576
+ * 2. Bounded reverse rowid seek (`ORDER BY id DESC LIMIT 1 OFFSET keep`): traverses at most
577
+ * `keep + 1` rows regardless of total table size, returning the exact cutoff for dense and sparse
578
+ * tables alike. Scheduled prune ticks run this OUTSIDE the writer transaction so WAL writers never wait.
579
+ * 3. Optional `maxSparseChunk` caps a single plan to at most that many oldest excess rows (`partial: true`).
580
+ */
581
+ export function computeTypeSafeLogCutoff(
582
+ d: ReturnType<typeof getDb>,
583
+ keep = LOG_KEEP,
584
+ options?: { maxSparseChunk?: number },
585
+ ): { cutoff: number; partial: boolean } | null {
586
+ const limit = Number.isFinite(Number(keep)) ? Math.max(0, Math.floor(Number(keep))) : LOG_KEEP;
587
+ // Separate ASC/DESC LIMIT 1 subqueries hit the rowid B-tree edge directly (O(log N));
588
+ // a single SELECT MIN(id), MAX(id) falls back to scanning an index in SQLite.
589
+ const bounds = d.prepare(
590
+ 'SELECT (SELECT id FROM typesafe_log ORDER BY id ASC LIMIT 1) AS minId, (SELECT id FROM typesafe_log ORDER BY id DESC LIMIT 1) AS maxId',
591
+ ).get() as { minId: number | null; maxId: number | null } | undefined;
592
+ if (bounds?.minId == null || bounds?.maxId == null) return null;
593
+ const minId = Number(bounds.minId);
594
+ const maxId = Number(bounds.maxId);
595
+ if (limit === 0) return { cutoff: maxId, partial: false };
596
+ const span = maxId - minId + 1;
597
+ if (span <= limit) return null;
598
+ const row = d.prepare('SELECT id FROM typesafe_log ORDER BY id DESC LIMIT 1 OFFSET ?').get(limit) as { id?: number } | undefined;
599
+ if (row?.id == null) return null;
600
+ const exactCutoff = Number(row.id);
601
+ const maxChunk = options?.maxSparseChunk != null && Number.isFinite(Number(options.maxSparseChunk))
602
+ ? Math.max(1, Math.floor(Number(options.maxSparseChunk)))
603
+ : null;
604
+ if (maxChunk != null) {
605
+ const chunkRow = d.prepare('SELECT id FROM typesafe_log WHERE id <= ? ORDER BY id ASC LIMIT 1 OFFSET ?').get(exactCutoff, maxChunk - 1) as { id?: number } | undefined;
606
+ if (chunkRow?.id != null && Number(chunkRow.id) < exactCutoff) {
607
+ return { cutoff: Number(chunkRow.id), partial: true };
608
+ }
609
+ }
610
+ return { cutoff: exactCutoff, partial: false };
611
+ }
612
+
613
+ function deleteTypeSafeLogBatch(d: ReturnType<typeof getDb>, cutoff: number, batchSize = LOG_PRUNE_BATCH_SIZE): number {
614
+ const limit = Math.max(1, Math.floor(batchSize));
615
+ const result = d.prepare('DELETE FROM typesafe_log WHERE id IN (SELECT id FROM typesafe_log WHERE id <= ? ORDER BY id ASC LIMIT ?)').run(cutoff, limit);
616
+ return Number(result.changes);
617
+ }
618
+
619
+ function finishPruneCycle(cycle: PruneCycle): void {
620
+ if (cycle.timer) { clearTimeout(cycle.timer); cycle.timer = null; }
621
+ cycle.cachedPlan = null;
622
+ cycle.recomputeRequested = false;
623
+ if (activePrune === cycle) activePrune = null;
624
+ if (!cycle.settled) {
625
+ cycle.settled = true;
626
+ cycle.resolve(cycle.deleted);
627
+ }
628
+ }
629
+
630
+ /**
631
+ * Cancel any pending background prune timer and drop the cached cutoff.
632
+ * Called on real DB close/reopen/teardown — decoupled from config cache invalidation.
633
+ */
634
+ export function resetTypeSafeLogPrune(): void {
635
+ pruneGeneration++;
636
+ insertsSincePrune = 0;
637
+ const prev = activePrune;
638
+ activePrune = null;
639
+ if (prev) {
640
+ if (prev.timer) { clearTimeout(prev.timer); prev.timer = null; }
641
+ prev.cachedPlan = null;
642
+ prev.recomputeRequested = false;
643
+ if (!prev.settled) {
644
+ prev.settled = true;
645
+ prev.resolve(prev.deleted);
646
+ }
647
+ }
648
+ }
649
+
650
+ function armPruneTimer(cycle: PruneCycle, delayMs: number): void {
651
+ if (cycle !== activePrune || cycle.timer) return;
652
+ cycle.timer = setTimeout(() => {
653
+ cycle.timer = null;
654
+ void runScheduledPruneTick(cycle);
655
+ }, Math.max(0, delayMs));
656
+ cycle.timer.unref?.();
657
+ }
658
+
659
+ async function runScheduledPruneTick(cycle: PruneCycle): Promise<void> {
660
+ if (cycle !== activePrune || cycle.running) return;
661
+ cycle.running = true;
662
+ const gen = cycle.generation;
663
+ let scheduleNext = false;
664
+ try {
665
+ const d = getDb();
666
+ const keep = cycle.targetKeep;
667
+ const batch = cycle.batchSize;
668
+ const maxSparseChunk = cycle.maxSparseChunk;
669
+ // Compute the cutoff OUTSIDE the writer transaction so SQLite WAL writers are never blocked.
670
+ let plan = cycle.cachedPlan && cycle.cachedPlan.db === d && cycle.cachedPlan.keep === keep ? cycle.cachedPlan : null;
671
+ if (!plan) {
672
+ // Any recompute request queued before this fresh cutoff computation is covered by it.
673
+ cycle.recomputeRequested = false;
674
+ const computed = computeTypeSafeLogCutoff(d, keep, maxSparseChunk != null ? { maxSparseChunk } : undefined);
675
+ if (!computed) {
676
+ // The cutoff read is synchronous. No rows remain for this cycle to delete.
677
+ finishPruneCycle(cycle);
678
+ return;
679
+ }
680
+ plan = { db: d, keep, cutoff: computed.cutoff, partial: computed.partial };
681
+ cycle.cachedPlan = plan;
682
+ }
683
+ const activePlan = plan;
684
+ const deleted = await withMemoryWrite(d, () => {
685
+ // A retention change while queued for the writer invalidates the old cutoff.
686
+ if (cycle !== activePrune || cycle.generation !== gen || cycle.cachedPlan !== activePlan || cycle.targetKeep !== activePlan.keep) return 0;
687
+ return deleteTypeSafeLogBatch(d, activePlan.cutoff, batch);
688
+ });
689
+ if (cycle !== activePrune || cycle.generation !== gen) return;
690
+ cycle.deleted += deleted;
691
+ const drained = deleted < batch;
692
+ if (drained) cycle.cachedPlan = null;
693
+ if (!drained) {
694
+ scheduleNext = true;
695
+ } else if (activePlan.partial) {
696
+ // Recompute the cutoff after every drained partial plan (including a 0-delete final batch).
697
+ scheduleNext = true;
698
+ } else if (cycle.recomputeRequested) {
699
+ cycle.recomputeRequested = false;
700
+ scheduleNext = true;
701
+ }
702
+ } catch {
703
+ // Database closed or unavailable during shutdown: stop quietly without throwing.
704
+ if (cycle === activePrune && cycle.generation === gen) {
705
+ cycle.cachedPlan = null;
706
+ scheduleNext = false;
707
+ }
708
+ } finally {
709
+ cycle.running = false;
710
+ }
711
+ if (cycle !== activePrune || cycle.generation !== gen) return;
712
+ if (scheduleNext) {
713
+ armPruneTimer(cycle, cycle.tickMs);
714
+ } else {
715
+ finishPruneCycle(cycle);
716
+ }
717
+ }
718
+
719
+ /**
720
+ * Schedule retention pruning off the write path in small bounded batches spread across ticks.
721
+ * Coalesces repeated triggers per generation and returns a promise resolving to rows deleted when the cycle finishes.
722
+ */
723
+ export function scheduleTypeSafeLogPrune(
724
+ keep = LOG_KEEP,
725
+ options: { batchSize?: number; tickMs?: number; delayMs?: number; maxSparseChunk?: number } = {},
726
+ ): Promise<number> {
727
+ const target = Number.isFinite(Number(keep)) ? Math.max(0, Math.floor(Number(keep))) : LOG_KEEP;
728
+ const batch = options.batchSize != null && Number.isFinite(Number(options.batchSize)) ? Math.max(1, Math.floor(Number(options.batchSize))) : LOG_PRUNE_BATCH_SIZE;
729
+ const tickMs = options.tickMs != null && Number.isFinite(Number(options.tickMs)) ? Math.max(0, Math.floor(Number(options.tickMs))) : LOG_PRUNE_TICK_MS;
730
+ const delayMs = options.delayMs != null && Number.isFinite(Number(options.delayMs)) ? Math.max(0, Math.floor(Number(options.delayMs))) : tickMs;
731
+ const maxSparseChunk = options.maxSparseChunk != null && Number.isFinite(Number(options.maxSparseChunk))
732
+ ? Math.max(1, Math.floor(Number(options.maxSparseChunk)))
733
+ : undefined;
734
+
735
+ if (activePrune) {
736
+ if (target !== activePrune.targetKeep || maxSparseChunk !== activePrune.maxSparseChunk) {
737
+ activePrune.cachedPlan = null;
738
+ }
739
+ activePrune.targetKeep = target;
740
+ activePrune.batchSize = batch;
741
+ activePrune.tickMs = tickMs;
742
+ if (maxSparseChunk !== undefined) activePrune.maxSparseChunk = maxSparseChunk;
743
+ // Mark pending recompute whether a tick is currently running OR the timer is currently armed.
744
+ activePrune.recomputeRequested = true;
745
+ if (!activePrune.running && !activePrune.timer) {
746
+ armPruneTimer(activePrune, delayMs);
747
+ }
748
+ return activePrune.promise;
749
+ }
750
+
751
+ let resolve!: (deleted: number) => void;
752
+ const promise = new Promise<number>((res) => { resolve = res; });
753
+ const cycle: PruneCycle = {
754
+ generation: pruneGeneration,
755
+ targetKeep: target,
756
+ batchSize: batch,
757
+ tickMs,
758
+ maxSparseChunk,
759
+ timer: null,
760
+ running: false,
761
+ recomputeRequested: false,
762
+ cachedPlan: null,
763
+ deleted: 0,
764
+ promise,
765
+ resolve,
766
+ settled: false,
767
+ };
768
+ ensureCloseHook();
769
+ activePrune = cycle;
770
+ armPruneTimer(cycle, delayMs);
771
+ return cycle.promise;
772
+ }
773
+
774
+ /** Await any scheduled/in-flight background retention prune (returns 0 if none is pending). */
775
+ export function flushTypeSafeLogPrune(): Promise<number> {
776
+ return activePrune?.promise ?? Promise.resolve(0);
777
+ }
778
+
779
+ // Register the DB close/teardown hook lazily on first use (keeps partial sqlite mocks in unit tests working).
780
+ let closeHookRegistered = false;
781
+ function ensureCloseHook(): void {
782
+ if (closeHookRegistered) return;
783
+ closeHookRegistered = true;
784
+ try {
785
+ if (typeof onDatabaseClose === 'function') {
786
+ onDatabaseClose(() => {
787
+ cached = null;
788
+ cachedAt = 0;
789
+ statsCache = null;
790
+ resetTypeSafeLogPrune();
791
+ });
792
+ }
793
+ } catch { /* partial sqlite mock in isolated unit tests */ }
794
+ }
795
+
552
796
  function insertTypeSafeLog(d: ReturnType<typeof getDb>, row: TypeSafeLogRow): number {
797
+ ensureCloseHook();
553
798
  const result = d.prepare(`INSERT INTO typesafe_log(created_at,surface,origin,entity_id,model,question_count,state_preview,answers,latency_ms,input_tokens,output_tokens,cached,error,session_id,project,surfaces)
554
799
  VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`).run(
555
800
  row.created_at ?? new Date().toISOString(), row.surface, row.origin, row.entity_id, row.model, row.question_count,
@@ -558,7 +803,10 @@ function insertTypeSafeLog(d: ReturnType<typeof getDb>, row: TypeSafeLogRow): nu
558
803
  cleanSessionId(row.session_id), typeof row.project === 'string' && row.project ? row.project.slice(0, 200) : null,
559
804
  row.surfaces?.length ? JSON.stringify(row.surfaces) : null,
560
805
  );
561
- if (++insertsSincePrune >= PRUNE_EVERY) { insertsSincePrune = 0; pruneTypeSafeLog(); }
806
+ if (++insertsSincePrune >= LOG_PRUNE_EVERY) {
807
+ insertsSincePrune = 0;
808
+ scheduleTypeSafeLogPrune(LOG_KEEP);
809
+ }
562
810
  return Number(result.lastInsertRowid);
563
811
  }
564
812
 
@@ -600,11 +848,24 @@ export function relinkTypeSafeLog(fromEntity: string, toEntity: string): void {
600
848
  try { const d = getDb(); writeNowOrSoon(d, () => d.prepare('UPDATE typesafe_log SET entity_id=? WHERE entity_id=?').run(toEntity, fromEntity)); } catch { /* diagnostics */ }
601
849
  }
602
850
 
603
- /** Keep only the newest `keep` rows. Returns the number deleted. */
604
- export function pruneTypeSafeLog(keep = LOG_KEEP): number {
851
+ /** Keep only the newest `keep` rows synchronously in bounded batches. Returns the number deleted. */
852
+ export function pruneTypeSafeLog(keep = LOG_KEEP, batchSize = LOG_PRUNE_BATCH_SIZE): number {
605
853
  try {
606
- const result = getDb().prepare('DELETE FROM typesafe_log WHERE id <= (SELECT id FROM typesafe_log ORDER BY id DESC LIMIT 1 OFFSET ?)').run(keep);
607
- return Number(result.changes);
854
+ const d = getDb();
855
+ let total = 0;
856
+ for (;;) {
857
+ const plan = computeTypeSafeLogCutoff(d, keep);
858
+ if (!plan) break;
859
+ let drained = false;
860
+ while (!drained) {
861
+ const deleted = deleteTypeSafeLogBatch(d, plan.cutoff, batchSize);
862
+ total += deleted;
863
+ if (deleted < Math.max(1, Math.floor(batchSize))) drained = true;
864
+ }
865
+ if (!plan.partial) break;
866
+ }
867
+ if (total > 0 && activePrune) activePrune.cachedPlan = null;
868
+ return total;
608
869
  } catch { return 0; }
609
870
  }
610
871
 
@@ -162,10 +162,10 @@ export const agentDispatchSchema = {
162
162
  'Optional ceiling in USD for this one run (0.01-1000), inside its provider\'s share of the session budget. Omit it: the run may use what its provider\'s share has left (nothing is reserved; idle runs hold no money). Every provider is held to it: Claude between model calls, OpenCode per step, Codex per rollout record or turn (at list price). Ignored, with a correction, when the user chose No limit.'
163
163
  ),
164
164
  uses_browser: z.boolean().optional().describe(
165
- 'true when the worker drives the SynaBun browser: it gets a loop browser tab and the browser enforcement block; page content is treated as untrusted data. Design runs default to true; false keeps one off the browser (no tab, no automatic browser group).'
165
+ 'Pass true to require a SynaBun browser tab before the worker starts. Browser tools inherited from an agent open a tab on first use. Page content is untrusted. Design runs default to true; false keeps one off the browser (no tab, no automatic browser group).'
166
166
  ),
167
167
  morelogin_profile: z.string().max(200).optional().describe(
168
- 'With uses_browser: the MoreLogin profile (its id or its name, as the morelogin tool\'s "list" shows it) the worker\'s browser tab opens in, for this run only. Omit it for the default AI browser (Settings → Connected tools → MoreLogin). Workers on different profiles run side by side; two on the same profile share its browser, each in its own tab. Only a profile the owner allowed agents to choose (the morelogin tool\'s "list" and "status" say which; none until the owner switches one on in SynaBun\'s Settings → Connected tools → MoreLogin): any other is refused with MORELOGIN_PROFILE_NOT_ALLOWED and nothing starts; tell the user which profile to switch on and where, and never dispatch into another profile instead. Only a Chrome-type profile; one that is unknown, Firefox-type or cannot start fails the dispatch by name (never another profile or browser). Use it when the user names a profile or an account for the task: never change the default AI browser for one run.'
168
+ 'When the worker uses the browser, open its tab in this MoreLogin profile before startup, including when browser access is inherited. Choose the profile for this run only by its id or name from the morelogin tool\'s "list". Omit it for the default AI browser (Settings → Connected tools → MoreLogin). Workers on different profiles run side by side; two on the same profile share its browser, each in its own tab. Only a profile the owner allowed agents to choose (the morelogin tool\'s "list" and "status" say which; none until the owner switches one on in SynaBun\'s Settings → Connected tools → MoreLogin): any other is refused with MORELOGIN_PROFILE_NOT_ALLOWED and nothing starts; tell the user which profile to switch on and where, and never dispatch into another profile instead. Only a Chrome-type profile; one that is unknown, Firefox-type or cannot start fails the dispatch by name (never another profile or browser). Use it when the user names a profile or an account for the task: never change the default AI browser for one run.'
169
169
  ),
170
170
  focus: z.boolean().optional().describe(
171
171
  'true to bring the worker\'s sidepanel tab to the front on attach. Default false: runs attach without stealing focus.'
@@ -225,6 +225,9 @@ export const agentSendSchema = {
225
225
  queue: z.boolean().optional().describe(
226
226
  'true to enqueue text while the worker is still running (delivered at its next idle point, in the order sent; it survives a server restart). At most 20 may wait for one run: more is refused with FOLLOW_UP_QUEUE_FULL. Default: send only when idle.'
227
227
  ),
228
+ steer: z.boolean().optional().describe(
229
+ 'true to STEER the run with text: the user changed what this worker is doing mid-run. Its current turn is interrupted (the run, its session and its context stay; tool calls already done stay done; a pending permission or question is cancelled) and text follows at once as the next turn, marked as a steer. An idle run gets it as a plain follow-up. queue is ignored. Refused with RUN_NOT_ACTIVE for a run that ended.'
230
+ ),
228
231
  };
229
232
 
230
233
  export const agentWaitSchema = {
@@ -291,7 +294,7 @@ export const agentReadDescription =
291
294
  'Read a run\'s output. format "result" (default) returns the parsed ## Result contract (status, summary, changes, follow_ups, question, json, and media: the images / videos an image_gen or video_gen run generated or a design run captured, each { kind, path, url, mime, bytes } — show one with ![](url) plus its path); "tail" returns the last transcript events (also after the run ended or the server restarted); "text" the worker\'s assistant text; "files" the files it reported. Call after agent_wait reports idle or terminal; keep max_chars small. A text longer than max_chars is read in pages: the answer carries totalChars, offset and nextOffset; pass offset (0 for the start, then each nextOffset) to read the rest. Returns JSON.';
292
295
 
293
296
  export const agentSendDescription =
294
- 'Continue a worker\'s conversation. text sends a follow-up turn (queue:true enqueues it while the worker is still running, or while it is suspended / resuming after a server restart: it goes to the worker once resumed; queued follow-ups keep their order, survive a restart, and at most 20 wait per run). reply answers a pending permission or question request: decision allow/deny for tools, answer (with answers) for questions, note as an optional message. Obtain request ids from agent_status or agent_wait until="event". A follow-up to a run whose work time (max_minutes) is used up is refused with TIME_CAP: dispatch a new run with its result as context. Returns JSON.';
297
+ 'Continue a worker\'s conversation. text sends a follow-up turn (queue:true enqueues it while the worker is still running, or while it is suspended / resuming after a server restart: it goes to the worker once resumed; queued follow-ups keep their order, survive a restart, and at most 20 wait per run). reply answers a pending permission or question request: decision allow/deny for tools, answer (with answers) for questions, note as an optional message. Obtain request ids from agent_status or agent_wait until="event". A follow-up to a run whose work time (max_minutes) is used up is refused with TIME_CAP: dispatch a new run with its result as context. steer:true with text redirects a run that is still working: its current turn is cut, its context kept, and the change follows at once (use it on the one run the user\'s change concerns, never to stop other runs). Returns JSON.';
295
298
 
296
299
  export const agentWaitDescription =
297
300
  'Blocking barrier for orchestration. Waits up to timeout_seconds (max 120) for one run (run_id), several runs (run_ids with mode all/any) or a whole workflow to reach until="idle" (turn finished; default), "terminal" (completed, failed, stopped, interrupted) or "event" (typed events: by default a result, a question, a permission request, a failure, a stall, a stop; narrow with kinds). An "event" answer lists the events with their seq and a cursor: pass it back as after_seq to go on from there. A workflow wait follows runs added to the workflow while it waits. A run suspended or resuming after a SynaBun server restart is still working: keep waiting (a wait cut off by the restart is simply called again, with the same after_seq). Returns the run descriptors and whether the wait timed out; call again to keep waiting. Prefer this over polling agent_status. Returns JSON.';
@@ -341,6 +344,7 @@ export const agentTeamSchema = {
341
344
  effort: z.string().max(40).optional().describe('start: reasoning effort for the workers.'),
342
345
  account_id: z.string().max(200).optional().describe('start: account profile id, or "auto".'),
343
346
  tools: z.array(z.string().min(1).max(72)).max(32).optional().describe('start: SynaBun tool groups for the workers, as for agent_dispatch. The team tool is added by itself.'),
347
+ uses_browser: z.boolean().optional().describe('start: require a SynaBun browser tab for each slice before it starts. An inherited browser is opened on first use.'),
344
348
  max_minutes: z.number().int().min(1).max(1440).optional().describe('start: work time per worker, in minutes.'),
345
349
  permission_policy: z.enum(['auto', 'ask', 'restricted']).optional().describe('start: as for agent_dispatch (default auto).'),
346
350
  context: z.string().max(8000).optional().describe('start: background every worker of the team gets (decisions already taken, conventions).'),
@@ -514,7 +518,9 @@ export function handleAgentSend(args: AgentSendArgs): Promise<ToolResult> {
514
518
  message: args.reply.note,
515
519
  });
516
520
  }
517
- if (args.text) {
521
+ if (args.text && args.steer) {
522
+ out.send = await ni.assistantSteer(args.run_id, { text: args.text });
523
+ } else if (args.text) {
518
524
  out.send = await ni.assistantSend(args.run_id, { text: args.text, queue: args.queue });
519
525
  }
520
526
  return json(args.reply && args.text ? out : (out.reply ?? out.send));
@@ -681,13 +687,13 @@ export function handleAgentTeam(args: AgentTeamArgs): Promise<ToolResult> {
681
687
  if (!args.slices?.length) return invalid(`${args.action} needs slices: the parts of the task, each with the files it owns.`);
682
688
  if (args.action === 'plan') return json(await ni.assistantTeamPlan(teamPlanBody(args)));
683
689
  if (args.tools) {
684
- const selection = resolveToolList(args.tools, { source: 'dispatch', provider: args.provider, taskClass: args.task_class });
690
+ const selection = resolveToolList(args.tools, { source: 'dispatch', provider: args.provider, usesBrowser: args.uses_browser, taskClass: args.task_class });
685
691
  if (!selection.ok) return { ...json(selection), isError: true };
686
692
  }
687
693
  return json(await ni.assistantTeamStart({
688
694
  ...teamPlanBody(args),
689
695
  testCommand: args.test_command, routeId: args.route_id, taskClass: args.task_class,
690
- provider: args.provider, model: args.model, effort: args.effort, accountId: args.account_id, tools: args.tools,
696
+ provider: args.provider, model: args.model, effort: args.effort, accountId: args.account_id, tools: args.tools, usesBrowser: args.uses_browser,
691
697
  maxMinutes: args.max_minutes, permissionPolicy: args.permission_policy, context: args.context, tags: args.tags, briefId: args.brief_id,
692
698
  }));
693
699
  }