synabun 2.4.3 → 2.4.5

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 (177) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/README.md +1 -1
  3. package/docs/browser-extension-bridge.md +66 -36
  4. package/docs/whatsapp.md +3 -3
  5. package/mcp-server/dist/http.d.ts.map +1 -1
  6. package/mcp-server/dist/http.js +8 -1
  7. package/mcp-server/dist/http.js.map +1 -1
  8. package/mcp-server/dist/services/identity.d.ts +2 -0
  9. package/mcp-server/dist/services/identity.d.ts.map +1 -1
  10. package/mcp-server/dist/services/identity.js +4 -0
  11. package/mcp-server/dist/services/identity.js.map +1 -1
  12. package/mcp-server/dist/services/memory-client.d.ts +5 -0
  13. package/mcp-server/dist/services/memory-client.d.ts.map +1 -1
  14. package/mcp-server/dist/services/memory-client.js +21 -2
  15. package/mcp-server/dist/services/memory-client.js.map +1 -1
  16. package/mcp-server/dist/services/memory-writer.d.ts +3 -0
  17. package/mcp-server/dist/services/memory-writer.d.ts.map +1 -1
  18. package/mcp-server/dist/services/memory-writer.js +7 -1
  19. package/mcp-server/dist/services/memory-writer.js.map +1 -1
  20. package/mcp-server/dist/services/neural-interface.d.ts +12 -1
  21. package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
  22. package/mcp-server/dist/services/neural-interface.js +68 -17
  23. package/mcp-server/dist/services/neural-interface.js.map +1 -1
  24. package/mcp-server/dist/services/typesafe-config.d.ts +38 -2
  25. package/mcp-server/dist/services/typesafe-config.d.ts.map +1 -1
  26. package/mcp-server/dist/services/typesafe-config.js +260 -8
  27. package/mcp-server/dist/services/typesafe-config.js.map +1 -1
  28. package/mcp-server/dist/tools/agent-definition.d.ts +2 -2
  29. package/mcp-server/dist/tools/agents.d.ts +19 -4
  30. package/mcp-server/dist/tools/agents.d.ts.map +1 -1
  31. package/mcp-server/dist/tools/agents.js +85 -17
  32. package/mcp-server/dist/tools/agents.js.map +1 -1
  33. package/mcp-server/dist/tools/browser-observe.d.ts +11 -0
  34. package/mcp-server/dist/tools/browser-observe.d.ts.map +1 -1
  35. package/mcp-server/dist/tools/browser-observe.js +113 -27
  36. package/mcp-server/dist/tools/browser-observe.js.map +1 -1
  37. package/mcp-server/dist/tools/browser-readers.d.ts +6 -0
  38. package/mcp-server/dist/tools/browser-readers.d.ts.map +1 -0
  39. package/mcp-server/dist/tools/browser-readers.js +17 -0
  40. package/mcp-server/dist/tools/browser-readers.js.map +1 -0
  41. package/mcp-server/dist/tools/remember.d.ts.map +1 -1
  42. package/mcp-server/dist/tools/remember.js +6 -2
  43. package/mcp-server/dist/tools/remember.js.map +1 -1
  44. package/mcp-server/dist/tools/youtube/analytics.d.ts +4 -0
  45. package/mcp-server/dist/tools/youtube/analytics.d.ts.map +1 -1
  46. package/mcp-server/dist/tools/youtube/analytics.js +25 -20
  47. package/mcp-server/dist/tools/youtube/analytics.js.map +1 -1
  48. package/mcp-server/dist/tools/youtube/helpers.d.ts +5 -1
  49. package/mcp-server/dist/tools/youtube/helpers.d.ts.map +1 -1
  50. package/mcp-server/dist/tools/youtube/helpers.js +7 -3
  51. package/mcp-server/dist/tools/youtube/helpers.js.map +1 -1
  52. package/mcp-server/dist/tools/youtube/navigate.d.ts +2 -0
  53. package/mcp-server/dist/tools/youtube/navigate.d.ts.map +1 -1
  54. package/mcp-server/dist/tools/youtube/navigate.js +5 -3
  55. package/mcp-server/dist/tools/youtube/navigate.js.map +1 -1
  56. package/mcp-server/dist/tools/youtube/playlist.js +2 -2
  57. package/mcp-server/dist/tools/youtube/playlist.js.map +1 -1
  58. package/mcp-server/dist/tools/youtube/readers.d.ts +4 -0
  59. package/mcp-server/dist/tools/youtube/readers.d.ts.map +1 -0
  60. package/mcp-server/dist/tools/youtube/readers.js +15 -0
  61. package/mcp-server/dist/tools/youtube/readers.js.map +1 -0
  62. package/mcp-server/package-lock.json +2 -2
  63. package/mcp-server/package.json +1 -1
  64. package/mcp-server/src/http.ts +8 -1
  65. package/mcp-server/src/services/identity.ts +5 -0
  66. package/mcp-server/src/services/memory-client.ts +32 -12
  67. package/mcp-server/src/services/memory-writer.ts +5 -2
  68. package/mcp-server/src/services/neural-interface.ts +67 -19
  69. package/mcp-server/src/services/typesafe-config.ts +268 -7
  70. package/mcp-server/src/tools/agents.ts +79 -17
  71. package/mcp-server/src/tools/browser-observe.ts +117 -28
  72. package/mcp-server/src/tools/browser-readers.ts +19 -0
  73. package/mcp-server/src/tools/remember.ts +6 -1
  74. package/mcp-server/src/tools/youtube/analytics.ts +26 -28
  75. package/mcp-server/src/tools/youtube/helpers.ts +8 -2
  76. package/mcp-server/src/tools/youtube/navigate.ts +6 -7
  77. package/mcp-server/src/tools/youtube/playlist.ts +2 -2
  78. package/mcp-server/src/tools/youtube/readers.ts +15 -0
  79. package/neural-interface/i18n/en.json +487 -8
  80. package/neural-interface/i18n/pt-BR.json +487 -8
  81. package/neural-interface/lib/agents-studio-api.js +7 -2
  82. package/neural-interface/lib/antigravity/home.js +43 -8
  83. package/neural-interface/lib/antigravity/tool-call.js +14 -0
  84. package/neural-interface/lib/assistant-api.js +90 -0
  85. package/neural-interface/lib/assistant-brains/antigravity.js +4 -2
  86. package/neural-interface/lib/assistant-brains/claude.js +10 -0
  87. package/neural-interface/lib/assistant-dispatch.js +276 -42
  88. package/neural-interface/lib/assistant-memory.js +3 -1
  89. package/neural-interface/lib/assistant-persona.js +14 -3
  90. package/neural-interface/lib/assistant-route-gate.js +11 -2
  91. package/neural-interface/lib/assistant-router.js +18 -8
  92. package/neural-interface/lib/assistant-runtime.js +103 -6
  93. package/neural-interface/lib/assistant-spilled-output.js +53 -0
  94. package/neural-interface/lib/assistant-task-prompt.js +15 -2
  95. package/neural-interface/lib/browser-connection-state.js +20 -0
  96. package/neural-interface/lib/browser-default.js +22 -2
  97. package/neural-interface/lib/browser-extension-adapter.js +221 -15
  98. package/neural-interface/lib/browser-extension-bridge.js +89 -9
  99. package/neural-interface/lib/browser-extension-folder.js +50 -11
  100. package/neural-interface/lib/browser-extension-package.js +6 -5
  101. package/neural-interface/lib/browser-extension-pin.json +15 -13
  102. package/neural-interface/lib/browser-extension-protocol.js +141 -14
  103. package/neural-interface/lib/browser-extension-setup.js +210 -40
  104. package/neural-interface/lib/browser-extension-update.js +104 -0
  105. package/neural-interface/lib/browser-extraction.js +38 -14
  106. package/neural-interface/lib/claude-bg-tasks.js +183 -0
  107. package/neural-interface/lib/claude-history.js +12 -1
  108. package/neural-interface/lib/confined-fs.js +25 -0
  109. package/neural-interface/lib/coordination/operations.js +2 -0
  110. package/neural-interface/lib/db.js +39 -16
  111. package/neural-interface/lib/editor-completion-opencode.js +2 -2
  112. package/neural-interface/lib/git-bash/manager.js +28 -3
  113. package/neural-interface/lib/git-status-runner.js +31 -3
  114. package/neural-interface/lib/loop-inventory.js +162 -0
  115. package/neural-interface/lib/loop-stall.js +74 -4
  116. package/neural-interface/lib/memory-session-capture.js +157 -66
  117. package/neural-interface/lib/native-loop-providers.js +73 -13
  118. package/neural-interface/lib/native-loop-runtime.js +3 -0
  119. package/neural-interface/lib/opencode-protocol.js +4 -2
  120. package/neural-interface/lib/peer-identity.js +62 -16
  121. package/neural-interface/lib/remote-policy.js +24 -7
  122. package/neural-interface/lib/session-cache-builder.js +66 -18
  123. package/neural-interface/lib/session-capture-gate.js +42 -0
  124. package/neural-interface/lib/session-indexer.js +28 -20
  125. package/neural-interface/lib/teams/README.md +22 -1
  126. package/neural-interface/lib/teams/api.js +79 -6
  127. package/neural-interface/lib/teams/index.js +2 -0
  128. package/neural-interface/lib/teams/recovery.js +68 -0
  129. package/neural-interface/lib/teams/scheduler.js +352 -31
  130. package/neural-interface/lib/teams/worktrees.js +123 -30
  131. package/neural-interface/lib/ui-blob-api.js +14 -5
  132. package/neural-interface/lib/ui-blob-store.js +302 -39
  133. package/neural-interface/package-lock.json +2 -2
  134. package/neural-interface/package.json +1 -1
  135. package/neural-interface/public/extension-setup.html +7 -2
  136. package/neural-interface/public/shared/agents/studio/ax-api.js +16 -0
  137. package/neural-interface/public/shared/agents/studio/ax-teams-view.js +318 -13
  138. package/neural-interface/public/shared/agents/studio/ax-teams.js +141 -9
  139. package/neural-interface/public/shared/assistant/asst-agents-dock.js +4 -0
  140. package/neural-interface/public/shared/assistant/asst-api.js +42 -0
  141. package/neural-interface/public/shared/assistant/asst-composer.js +85 -12
  142. package/neural-interface/public/shared/assistant/asst-panel.js +285 -10
  143. package/neural-interface/public/shared/assistant/asst-render.js +205 -4
  144. package/neural-interface/public/shared/assistant/asst-scenes.js +12 -0
  145. package/neural-interface/public/shared/assistant/asst-sidepanel.js +18 -1
  146. package/neural-interface/public/shared/assistant/asst-state.js +241 -2
  147. package/neural-interface/public/shared/assistant/asst-steer.js +294 -0
  148. package/neural-interface/public/shared/assistant/asst-styles.js +20 -0
  149. package/neural-interface/public/shared/bg-tasks/bg-tasks-claude.js +147 -0
  150. package/neural-interface/public/shared/bg-tasks/bg-tasks-model.js +527 -0
  151. package/neural-interface/public/shared/bg-tasks/bg-tasks-panel.js +161 -0
  152. package/neural-interface/public/shared/bg-tasks/bg-tasks-view.js +508 -0
  153. package/neural-interface/public/shared/browser-extension-updates.js +90 -0
  154. package/neural-interface/public/shared/cp/cp-bg-tasks.js +130 -0
  155. package/neural-interface/public/shared/extension-setup/es-page.js +41 -15
  156. package/neural-interface/public/shared/extension-setup/es-view.js +51 -11
  157. package/neural-interface/public/shared/extension-update-view.js +34 -0
  158. package/neural-interface/public/shared/ocp-v2/ocp-v2-shell-logic.js +8 -4
  159. package/neural-interface/public/shared/settings/settings-ai-browser.js +23 -3
  160. package/neural-interface/public/shared/settings/settings-browser-extension.js +581 -197
  161. package/neural-interface/public/shared/settings/settings-extension-diagrams.js +116 -0
  162. package/neural-interface/public/shared/settings/settings-extension-guide.js +222 -0
  163. package/neural-interface/public/shared/settings/settings-extension-update.js +114 -0
  164. package/neural-interface/public/shared/settings/settings-ia.js +2 -2
  165. package/neural-interface/public/shared/settings/settings-shell.js +5 -0
  166. package/neural-interface/public/shared/styles.css +200 -13
  167. package/neural-interface/public/shared/ui-claude-panel.js +110 -1
  168. package/neural-interface/public/shared/ui-notifications.js +23 -4
  169. package/neural-interface/public/shared/ui-settings-entry.js +6 -0
  170. package/neural-interface/public/shared/ui-settings.js +48 -11
  171. package/neural-interface/public/shared/ui-tray-columns.js +9 -2
  172. package/neural-interface/public/shared/worker-end.js +18 -0
  173. package/neural-interface/scripts/patch-node-pty.mjs +151 -0
  174. package/neural-interface/scripts/rebuild-pty.js +10 -0
  175. package/neural-interface/server.js +503 -281
  176. package/npm-shrinkwrap.json +2 -2
  177. 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
 
@@ -41,6 +41,12 @@ export const RUN_EVENT_KINDS = [
41
41
  /** One title limit for agent_route planned_split.slices and agent_team slices[].title (= TEAM_LIMITS.title in neural-interface/lib/teams/schema.js). */
42
42
  export const SLICE_TITLE_MAX = 80;
43
43
 
44
+ /** agent_list's page: newest first, AGENT_LIST_DEFAULT runs unless the brain asks for more. */
45
+ export const AGENT_LIST_DEFAULT = 20;
46
+ export const AGENT_LIST_MAX = 100;
47
+ /** How much of a run's result summary a roster row or a dispatch answer keeps (agent_read has the whole result). */
48
+ const RUN_SUMMARY_CHARS = 400;
49
+
44
50
  const runIdField = (purpose: string) => z.string().min(1).max(200).describe(purpose);
45
51
  const optionalId = (purpose: string) => z.string().min(1).max(200).optional().describe(purpose);
46
52
 
@@ -111,6 +117,9 @@ export const agentListSchema = {
111
117
  ),
112
118
  assistant_session_id: optionalId('Restrict to runs dispatched by this assistant session (your ASSISTANT_SESSION_ID).'),
113
119
  workflow_id: optionalId('Restrict to one workflow (the workflow_id passed to agent_dispatch).'),
120
+ limit: z.number().int().min(1).max(AGENT_LIST_MAX).optional().describe(
121
+ `How many runs, newest first (default ${AGENT_LIST_DEFAULT}, at most ${AGENT_LIST_MAX}).`
122
+ ),
114
123
  };
115
124
 
116
125
  export const agentDispatchSchema = {
@@ -162,10 +171,10 @@ export const agentDispatchSchema = {
162
171
  '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
172
  ),
164
173
  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).'
174
+ '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
175
  ),
167
176
  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.'
177
+ '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
178
  ),
170
179
  focus: z.boolean().optional().describe(
171
180
  'true to bring the worker\'s sidepanel tab to the front on attach. Default false: runs attach without stealing focus.'
@@ -225,6 +234,9 @@ export const agentSendSchema = {
225
234
  queue: z.boolean().optional().describe(
226
235
  '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
236
  ),
237
+ steer: z.boolean().optional().describe(
238
+ '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.'
239
+ ),
228
240
  };
229
241
 
230
242
  export const agentWaitSchema = {
@@ -279,22 +291,22 @@ export const agentClarifyDescription =
279
291
  'Ask the user 1-3 targeted questions BEFORE routing a new request that is materially ambiguous: two plausible readings with different results, an unclear target (project, feature, files, audience), destructive or irreversible scope, spend, or memories that conflict with it. Not for clear requests, details a sensible default covers, anything the request, memory or the project answers, or the model (agent_route asks that). Each question gets 2-4 options (recommended first; the user can always type their own); add constraints (what the request fixes) and assumptions (what you will assume for the rest). The card waits briefly. Follow the returned status and next: answered → route, then agent_dispatch with the brief_id (SynaBun adds the user\'s original words, their answers, the constraints and assumptions to the worker\'s context); declined → proceed on your assumptions; pending → end your turn, the answers arrive as a [SynaBun Mailbox] clarify_answered event or as the user\'s next message, and dependent routes and dispatches wait until then. Returns JSON.';
280
292
 
281
293
  export const agentListDescription =
282
- 'List dispatched worker runs with status, state, provider/model, the agent a run runs as (agentRef, agentRevision; absent for a plain worker), title, elapsed time, work time left (workLeftMs), cost and resumes (how often a server restart cut the run off and it was resumed). Use it before dispatching more work, to recover run ids, or after a mailbox event. Filter with active_only, assistant_session_id (your own session) or workflow_id. Returns JSON.';
294
+ 'List dispatched worker runs with status, state, provider/model, the agent a run runs as (agentRef, agentRevision; absent for a plain worker), title, elapsed time, work time left (workLeftMs), cost and resumes (how often a server restart cut the run off and it was resumed). Use it before dispatching more work, to recover run ids, or after a mailbox event. Filter with active_only, assistant_session_id (your own session) or workflow_id; limit sets how many (newest first, default 20). Each run is compact: the task, context and turn texts are counted, not repeated (agent_read and agent_status have them). Returns JSON.';
283
295
 
284
296
  export const agentDispatchDescription =
285
297
  'Dispatch a task to a worker agent (Claude Code, Codex or OpenCode). Route it first with agent_route and pass the approved route_id (the server applies that provider/model/effort); without one, the dispatch may be held until the user picks a model (awaitingRoute:true — do not dispatch it again; if the user picks "here" instead, the run never starts and a route_decided mailbox event asks you to do the task yourself). A route_id the user decided to keep here is refused (ROUTE_IS_DIRECT): do that task yourself. After agent_clarify, pass its brief_id: the worker gets the user\'s own words and answers; while its questions are open a dependent dispatch is refused (CLARIFICATION_PENDING). The run attaches as a live automation tab in the matching sidepanel without stealing focus. Write a self-contained task that ends with a ## Result block, pass the absolute cwd and your assistant_session_id. Defaults: permission_policy "auto", capability "full", 45 minutes of work time (max_minutes, at least 20), no per-run dollar ceiling (with a budget the run draws from its provider\'s share; a provider whose share is used up and cannot get more is refused with BUDGET_SHARE_EXHAUSTED: route again). Use "ask" only for sensitive scopes (Codex cannot ask: use "restricted"). uses_computer:true for desktop work (one at a time, vision model). uses_browser:true with morelogin_profile (a profile id or name) opens the worker\'s browser tab in that MoreLogin profile for this run only, next to runs in the default or other profiles (only a profile the owner allowed agents to choose; MORELOGIN_PROFILE_NOT_ALLOWED otherwise: tell the user to switch it on in Settings). An image_gen / video_gen run makes the asset with its model\'s own generation tool; SynaBun collects the files into the run\'s result (media: path + url); with no model that generates the medium an un-routed dispatch is refused (NO_CAPABLE_MODEL), and a route_id approved for other work is refused for image_gen / video_gen / design (and the other way round: ROUTE_CLASS_MISMATCH; route the task again with its own class). A design run gets SynaBun\'s design rules and the project\'s style guide, defaults to capability "workspace", uses_browser true, browser, styleguide and image groups, and 60 minutes of work time (explicit values win), runs only on a model confirmed to see (MODEL_CANNOT_SEE otherwise), and its screenshots land in the result\'s media. The class agent applies automatically; agent_ref "none" opts out. An explicit agent_ref runs the worker as one of the owner\'s approved agents (agent_catalog agents): its definition fills what you leave out and its instructions become the worker\'s role, the run carries agentRef and agentRevision, and corrections list what the definition was held to. Group fan-outs with workflow_id, chain with parent_run_id, retry safely with idempotency_key. Over-limit dispatches are queued (queued:true, position). After dispatching, block with agent_wait rather than polling. Returns JSON.';
286
298
 
287
299
  export const agentStatusDescription =
288
- 'Get one run\'s current descriptor: status (queued, starting, running, completed, failed, stopped, interrupted), state (the detail: also idle, awaiting_permission, and suspended / resuming while a SynaBun server restart cuts a Claude Code worker off and the next start resumes it as the same run, its Claude session and its tab; resumes counts that, at most 3; a run that could not be resumed ends interrupted, with why in notes), turnState (running, idle, awaiting_permission), provider/model/account, the agent it runs as (agentRef, agentRevision, agentPin with what its definition was held to; absent for a plain worker), elapsed time (elapsedMs, wall clock), work time used and left of max_minutes (workMs, workLeftMs), cost, the last parsed result summary and any pending permission or question requests. Cheap; use it between agent_wait calls or before agent_send / agent_stop. Returns JSON.';
300
+ 'Get one run\'s current descriptor: status (queued, starting, running, completed, failed, stopped, interrupted), state (the detail: also idle, awaiting_permission, and suspended / resuming while a SynaBun server restart cuts a Claude Code worker off and the next start resumes it as the same run, its Claude session and its tab; resumes counts that, at most 3; a run that could not be resumed ends interrupted, with why in notes), turnState (running, idle, awaiting_permission), provider/model/account, the agent it runs as (agentRef, agentRevision, agentPin with what its definition was held to; absent for a plain worker), elapsed time (elapsedMs, wall clock), work time used and left of max_minutes (workMs, workLeftMs), cost, the last parsed result summary and any pending permission or question requests. The task, context and turn texts are counted, not repeated (agent_read has the texts). Cheap; use it between agent_wait calls or before agent_send / agent_stop. Returns JSON.';
289
301
 
290
302
  export const agentReadDescription =
291
303
  '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
304
 
293
305
  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.';
306
+ '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
307
 
296
308
  export const agentWaitDescription =
297
- '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.';
309
+ '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 compact run descriptors (task, context and turn texts counted, not repeated; questions, permission requests and events whole) and whether the wait timed out; call again to keep waiting. Prefer this over polling agent_status. Returns JSON.';
298
310
 
299
311
  export const agentStopDescription =
300
312
  'Stop work. run_id stops one run; all:true with your assistant_session_id stops every run of this assistant session, workflow_id every run of a workflow (kill-all). Use when the user cancels, a worker misbehaves, or a time/budget rail is at risk. Returns JSON.';
@@ -341,6 +353,7 @@ export const agentTeamSchema = {
341
353
  effort: z.string().max(40).optional().describe('start: reasoning effort for the workers.'),
342
354
  account_id: z.string().max(200).optional().describe('start: account profile id, or "auto".'),
343
355
  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.'),
356
+ 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
357
  max_minutes: z.number().int().min(1).max(1440).optional().describe('start: work time per worker, in minutes.'),
345
358
  permission_policy: z.enum(['auto', 'ask', 'restricted']).optional().describe('start: as for agent_dispatch (default auto).'),
346
359
  context: z.string().max(8000).optional().describe('start: background every worker of the team gets (decisions already taken, conventions).'),
@@ -431,12 +444,58 @@ export function handleAgentClarify(args: AgentClarifyArgs): Promise<ToolResult>
431
444
  })));
432
445
  }
433
446
 
447
+ /**
448
+ * A run as a roster row or a dispatch answer shows it. The server's view carries the whole run: the task and context
449
+ * the brain wrote itself, the last text and up to 50 turns (each up to 20 KB of text, and its parsed result with the
450
+ * worker's whole final message as `raw`). Those are what agent_read serves; here they are counted, not repeated, so an
451
+ * answer stays small enough for every host (Antigravity spills an output above about 10 KB into a file).
452
+ */
453
+ export function compactRunView(run: unknown, { keepResult = false }: { keepResult?: boolean } = {}): unknown {
454
+ if (!run || typeof run !== 'object' || Array.isArray(run)) return run;
455
+ const { task, context, lastText, turns, lastResult, ...rest } = run as Record<string, unknown>;
456
+ const out: Record<string, unknown> = { ...rest };
457
+ if (typeof task === 'string') out.taskChars = task.length;
458
+ if (typeof context === 'string' && context) out.contextChars = context.length;
459
+ if (typeof lastText === 'string' && lastText) out.lastTextChars = lastText.length;
460
+ if (Array.isArray(turns) && typeof out.turnCount !== 'number') out.turnCount = turns.length;
461
+ if (keepResult && lastResult && typeof lastResult === 'object') {
462
+ // agent_status / agent_wait: the parsed result whole (changes, files, follow-ups, media, question), the
463
+ // worker's whole final message (`raw`) aside.
464
+ const { raw: _raw, ...result } = lastResult as Record<string, unknown>;
465
+ out.lastResult = result;
466
+ } else if (lastResult && typeof lastResult === 'object') {
467
+ const result = lastResult as Record<string, unknown>;
468
+ const summary = typeof result.summary === 'string' ? result.summary : '';
469
+ out.lastResult = {
470
+ status: result.status ?? null,
471
+ summary: summary.length > RUN_SUMMARY_CHARS ? `${summary.slice(0, RUN_SUMMARY_CHARS)}…` : summary,
472
+ ...(typeof result.question === 'string' && result.question ? { question: result.question } : {}),
473
+ };
474
+ } else if (lastResult !== undefined) out.lastResult = lastResult;
475
+ return out;
476
+ }
477
+
478
+ /**
479
+ * An answer whose runs are compacted (compactRunView): `run`, `runs`, and agent_wait's `done` / `pending`.
480
+ * Everything else as it came: a wait's `needsInput`, `permissions` and `events` (the questions and permission
481
+ * requests to answer) and a run's own `pending` requests stay whole.
482
+ */
483
+ function withCompactRuns(answer: unknown, options: { keepResult?: boolean } = {}): unknown {
484
+ if (!answer || typeof answer !== 'object' || Array.isArray(answer)) return answer;
485
+ const out: Record<string, unknown> = { ...(answer as Record<string, unknown>) };
486
+ const compact = (run: unknown) => compactRunView(run, options);
487
+ for (const key of ['runs', 'done', 'pending']) if (Array.isArray(out[key])) out[key] = (out[key] as unknown[]).map(compact);
488
+ if (out.run && typeof out.run === 'object') out.run = compact(out.run);
489
+ return out;
490
+ }
491
+
434
492
  export function handleAgentList(args: AgentListArgs): Promise<ToolResult> {
435
- return guarded(async () => json(await ni.assistantListRuns({
493
+ return guarded(async () => json(withCompactRuns(await ni.assistantListRuns({
436
494
  activeOnly: args.active_only === true,
437
495
  assistantSessionId: args.assistant_session_id,
438
496
  workflowId: args.workflow_id,
439
- })));
497
+ limit: args.limit ?? AGENT_LIST_DEFAULT,
498
+ }))));
440
499
  }
441
500
 
442
501
  export function handleAgentDispatch(args: AgentDispatchArgs): Promise<ToolResult> {
@@ -447,7 +506,8 @@ export function handleAgentDispatch(args: AgentDispatchArgs): Promise<ToolResult
447
506
  if (!args.provider && !args.route_id && !args.task_class && (!args.agent_ref || args.agent_ref === 'none')) return invalid('Provide provider, task_class, the route_id of an approved agent_route, or a named agent_ref.');
448
507
  const selection = resolveToolList(args.tools, { source: 'dispatch', provider: args.provider, usesBrowser: args.uses_browser, taskClass: args.task_class });
449
508
  if (!selection.ok) return { ...json(selection), isError: true };
450
- return json(await ni.assistantDispatch({
509
+ // The answer's run is compacted (compactRunView): the brain wrote the task and context it would echo.
510
+ return json(withCompactRuns(await ni.assistantDispatch({
451
511
  provider: args.provider,
452
512
  task: args.task,
453
513
  cwd: args.cwd,
@@ -484,12 +544,12 @@ export function handleAgentDispatch(args: AgentDispatchArgs): Promise<ToolResult
484
544
  idempotencyKey: args.idempotency_key,
485
545
  briefId: args.brief_id,
486
546
  independent: args.independent,
487
- }));
547
+ })));
488
548
  });
489
549
  }
490
550
 
491
551
  export function handleAgentStatus(args: AgentStatusArgs): Promise<ToolResult> {
492
- return guarded(async () => json(await ni.assistantRun(args.run_id)));
552
+ return guarded(async () => json(withCompactRuns(await ni.assistantRun(args.run_id), { keepResult: true })));
493
553
  }
494
554
 
495
555
  export function handleAgentRead(args: AgentReadArgs): Promise<ToolResult> {
@@ -514,7 +574,9 @@ export function handleAgentSend(args: AgentSendArgs): Promise<ToolResult> {
514
574
  message: args.reply.note,
515
575
  });
516
576
  }
517
- if (args.text) {
577
+ if (args.text && args.steer) {
578
+ out.send = await ni.assistantSteer(args.run_id, { text: args.text });
579
+ } else if (args.text) {
518
580
  out.send = await ni.assistantSend(args.run_id, { text: args.text, queue: args.queue });
519
581
  }
520
582
  return json(args.reply && args.text ? out : (out.reply ?? out.send));
@@ -530,10 +592,10 @@ export function handleAgentWait(args: AgentWaitArgs): Promise<ToolResult> {
530
592
  const multi = runIds.length > 0 || !!args.workflow_id;
531
593
  if (!multi) {
532
594
  if (!args.run_id) return invalid('Provide run_id, run_ids or workflow_id.');
533
- return json(await ni.assistantWaitRun(args.run_id, { until, timeoutMs, afterSeq: args.after_seq, kinds: args.kinds }));
595
+ return json(withCompactRuns(await ni.assistantWaitRun(args.run_id, { until, timeoutMs, afterSeq: args.after_seq, kinds: args.kinds }), { keepResult: true }));
534
596
  }
535
597
  if (args.run_id && !runIds.includes(args.run_id)) runIds.unshift(args.run_id);
536
- return json(await ni.assistantWaitMany({
598
+ return json(withCompactRuns(await ni.assistantWaitMany({
537
599
  runIds: runIds.length ? runIds : undefined,
538
600
  workflowId: args.workflow_id,
539
601
  mode: args.mode || (until === 'event' ? 'any' : 'all'),
@@ -541,7 +603,7 @@ export function handleAgentWait(args: AgentWaitArgs): Promise<ToolResult> {
541
603
  timeoutMs,
542
604
  afterSeq: args.after_seq,
543
605
  kinds: args.kinds,
544
- }));
606
+ }), { keepResult: true }));
545
607
  });
546
608
  }
547
609
 
@@ -681,13 +743,13 @@ export function handleAgentTeam(args: AgentTeamArgs): Promise<ToolResult> {
681
743
  if (!args.slices?.length) return invalid(`${args.action} needs slices: the parts of the task, each with the files it owns.`);
682
744
  if (args.action === 'plan') return json(await ni.assistantTeamPlan(teamPlanBody(args)));
683
745
  if (args.tools) {
684
- const selection = resolveToolList(args.tools, { source: 'dispatch', provider: args.provider, taskClass: args.task_class });
746
+ const selection = resolveToolList(args.tools, { source: 'dispatch', provider: args.provider, usesBrowser: args.uses_browser, taskClass: args.task_class });
685
747
  if (!selection.ok) return { ...json(selection), isError: true };
686
748
  }
687
749
  return json(await ni.assistantTeamStart({
688
750
  ...teamPlanBody(args),
689
751
  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,
752
+ provider: args.provider, model: args.model, effort: args.effort, accountId: args.account_id, tools: args.tools, usesBrowser: args.uses_browser,
691
753
  maxMinutes: args.max_minutes, permissionPolicy: args.permission_policy, context: args.context, tags: args.tags, briefId: args.brief_id,
692
754
  }));
693
755
  }