@spencerboucher/switchyard 0.10.0 → 0.11.0

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 (119) hide show
  1. package/README.md +1 -1
  2. package/dist/bridge/pi-model.js +12 -0
  3. package/dist/bridge/switchyard-terminal.js +66 -1
  4. package/dist/switchyard.mjs +394 -51
  5. package/dist/terminal/holder.js +47 -1
  6. package/package.json +1 -1
  7. package/web-dist/assets/AutomationView-CrKqim2i.js +2 -0
  8. package/web-dist/assets/{AutomationView-BsTwLnMp.js.map → AutomationView-CrKqim2i.js.map} +1 -1
  9. package/web-dist/assets/{Card-CAFxHoHd.js → Card-XMb6DfZU.js} +2 -2
  10. package/web-dist/assets/{Card-CAFxHoHd.js.map → Card-XMb6DfZU.js.map} +1 -1
  11. package/web-dist/assets/{Checkbox-rDvnQnxc.js → Checkbox-CeUPbVi7.js} +2 -2
  12. package/web-dist/assets/{Checkbox-rDvnQnxc.js.map → Checkbox-CeUPbVi7.js.map} +1 -1
  13. package/web-dist/assets/{Copy-D8xhl7eJ.js → Copy-CGnl0Vga.js} +2 -2
  14. package/web-dist/assets/{Copy-D8xhl7eJ.js.map → Copy-CGnl0Vga.js.map} +1 -1
  15. package/web-dist/assets/Field-DVurWE-E.js +2 -0
  16. package/web-dist/assets/Field-DVurWE-E.js.map +1 -0
  17. package/web-dist/assets/{InteractionCard-Yu5wgLC3.js → InteractionCard-1ePc4XOF.js} +4 -4
  18. package/web-dist/assets/{InteractionCard-Yu5wgLC3.js.map → InteractionCard-1ePc4XOF.js.map} +1 -1
  19. package/web-dist/assets/{Menu-euseM8yR.js → Menu-CYZQ97c0.js} +2 -2
  20. package/web-dist/assets/{Menu-euseM8yR.js.map → Menu-CYZQ97c0.js.map} +1 -1
  21. package/web-dist/assets/Overlay-DlLhg1cK.js +2 -0
  22. package/web-dist/assets/Overlay-DlLhg1cK.js.map +1 -0
  23. package/web-dist/assets/Priority-BCHLJqWN.js +2 -0
  24. package/web-dist/assets/{Priority-Ca1B2yFr.js.map → Priority-BCHLJqWN.js.map} +1 -1
  25. package/web-dist/assets/{SegmentedControl-D2d-NEr-.js → SegmentedControl-CSO0EMTX.js} +2 -2
  26. package/web-dist/assets/{SegmentedControl-D2d-NEr-.js.map → SegmentedControl-CSO0EMTX.js.map} +1 -1
  27. package/web-dist/assets/{Select-C9L1HKMm.js → Select-Dgmnmpz3.js} +2 -2
  28. package/web-dist/assets/{Select-C9L1HKMm.js.map → Select-Dgmnmpz3.js.map} +1 -1
  29. package/web-dist/assets/{Switch-DAcUcSbH.js → Switch-DS4NRENd.js} +2 -2
  30. package/web-dist/assets/{Switch-DAcUcSbH.js.map → Switch-DS4NRENd.js.map} +1 -1
  31. package/web-dist/assets/{Tabs-xtagjtA5.js → Tabs-9xp-tGja.js} +4 -4
  32. package/web-dist/assets/{Tabs-xtagjtA5.js.map → Tabs-9xp-tGja.js.map} +1 -1
  33. package/web-dist/assets/{TextArea-CKGHwURx.js → TextArea-PfVKaz29.js} +2 -2
  34. package/web-dist/assets/{TextArea-CKGHwURx.js.map → TextArea-PfVKaz29.js.map} +1 -1
  35. package/web-dist/assets/{TextLink-Bub7sMxr.js → TextLink-CYqiAUlK.js} +2 -2
  36. package/web-dist/assets/{TextLink-Bub7sMxr.js.map → TextLink-CYqiAUlK.js.map} +1 -1
  37. package/web-dist/assets/attention-CTkX5JXq.js +2 -0
  38. package/web-dist/assets/attention-CTkX5JXq.js.map +1 -0
  39. package/web-dist/assets/automations-CsdtA3xp.js +2 -0
  40. package/web-dist/assets/{automations-BzpsJoa3.js.map → automations-CsdtA3xp.js.map} +1 -1
  41. package/web-dist/assets/board-CJL75uGb.js +10 -0
  42. package/web-dist/assets/{board-CeJxBVHC.js.map → board-CJL75uGb.js.map} +1 -1
  43. package/web-dist/assets/code-B1njb2Cr.css +1 -0
  44. package/web-dist/assets/code-CEYPZt-J.js +21 -0
  45. package/web-dist/assets/code-CEYPZt-J.js.map +1 -0
  46. package/web-dist/assets/describe-DjRsBpcB.js +5 -0
  47. package/web-dist/assets/{describe-CVXeUClF.js.map → describe-DjRsBpcB.js.map} +1 -1
  48. package/web-dist/assets/enroll-DcEYGgoX.js +2 -0
  49. package/web-dist/assets/{enroll-jnKygG4L.js.map → enroll-DcEYGgoX.js.map} +1 -1
  50. package/web-dist/assets/index-BeJqGnFE.css +2 -0
  51. package/web-dist/assets/index-DSJZdQ79.js +11 -0
  52. package/web-dist/assets/index-DSJZdQ79.js.map +1 -0
  53. package/web-dist/assets/more-BQSa_-H6.js +2 -0
  54. package/web-dist/assets/{more-DvKHMdBk.js.map → more-BQSa_-H6.js.map} +1 -1
  55. package/web-dist/assets/plus-BLP-wIYD.js +2 -0
  56. package/web-dist/assets/plus-BLP-wIYD.js.map +1 -0
  57. package/web-dist/assets/preload-helper-Huh16h6r.js +13 -0
  58. package/web-dist/assets/preload-helper-Huh16h6r.js.map +1 -0
  59. package/web-dist/assets/queue-CCjBjQhT.js +2 -0
  60. package/web-dist/assets/{queue-B2Vl0uSh.js.map → queue-CCjBjQhT.js.map} +1 -1
  61. package/web-dist/assets/repo-pkFfpra6.js +2 -0
  62. package/web-dist/assets/repo-pkFfpra6.js.map +1 -0
  63. package/web-dist/assets/settings-vrxspmWN.js +7 -0
  64. package/web-dist/assets/settings-vrxspmWN.js.map +1 -0
  65. package/web-dist/assets/shared-Bm6Rhfqw.js +3 -0
  66. package/web-dist/assets/shared-Bm6Rhfqw.js.map +1 -0
  67. package/web-dist/assets/states-BQxrRFdh.js +56 -0
  68. package/web-dist/assets/states-BQxrRFdh.js.map +1 -0
  69. package/web-dist/assets/{terminal-login-BK5UjUir.js → terminal-login-D9enO0EH.js} +2 -2
  70. package/web-dist/assets/{terminal-login-BK5UjUir.js.map → terminal-login-D9enO0EH.js.map} +1 -1
  71. package/web-dist/assets/timer-BCIucSXh.js +2 -0
  72. package/web-dist/assets/timer-BCIucSXh.js.map +1 -0
  73. package/web-dist/assets/useBreakpoint-LY_qlpRG.js +2 -0
  74. package/web-dist/assets/useBreakpoint-LY_qlpRG.js.map +1 -0
  75. package/web-dist/assets/useNow-BUvGqrfn.js +2 -0
  76. package/web-dist/assets/{useNow-Cm-tdyod.js.map → useNow-BUvGqrfn.js.map} +1 -1
  77. package/web-dist/assets/{useResource-BBqCoY2q.js → useResource-Dul6MTDM.js} +2 -2
  78. package/web-dist/assets/{useResource-BBqCoY2q.js.map → useResource-Dul6MTDM.js.map} +1 -1
  79. package/web-dist/index.html +10 -7
  80. package/web-dist/sw.js +1 -1
  81. package/web-dist/sw.js.map +1 -1
  82. package/web-dist/assets/AutomationView-BsTwLnMp.js +0 -2
  83. package/web-dist/assets/Field-Dbg_8KTt.js +0 -2
  84. package/web-dist/assets/Field-Dbg_8KTt.js.map +0 -1
  85. package/web-dist/assets/Overlay-BNPvMjLX.js +0 -2
  86. package/web-dist/assets/Overlay-BNPvMjLX.js.map +0 -1
  87. package/web-dist/assets/Priority-Ca1B2yFr.js +0 -2
  88. package/web-dist/assets/StatusChip-BYuVxYS7.js +0 -2
  89. package/web-dist/assets/StatusChip-BYuVxYS7.js.map +0 -1
  90. package/web-dist/assets/attention-CI4dHY81.js +0 -2
  91. package/web-dist/assets/attention-CI4dHY81.js.map +0 -1
  92. package/web-dist/assets/auth-308hUVgi.js +0 -2
  93. package/web-dist/assets/auth-308hUVgi.js.map +0 -1
  94. package/web-dist/assets/automations-BzpsJoa3.js +0 -2
  95. package/web-dist/assets/bell-DSwa2PAb.js +0 -2
  96. package/web-dist/assets/bell-DSwa2PAb.js.map +0 -1
  97. package/web-dist/assets/board-CeJxBVHC.js +0 -10
  98. package/web-dist/assets/code-DkNQvMI9.js +0 -12
  99. package/web-dist/assets/code-DkNQvMI9.js.map +0 -1
  100. package/web-dist/assets/describe-CVXeUClF.js +0 -5
  101. package/web-dist/assets/enroll-jnKygG4L.js +0 -2
  102. package/web-dist/assets/index-BHGZTS2e.js +0 -16
  103. package/web-dist/assets/index-BHGZTS2e.js.map +0 -1
  104. package/web-dist/assets/index-D2ml031z.css +0 -2
  105. package/web-dist/assets/more-DvKHMdBk.js +0 -2
  106. package/web-dist/assets/queue-B2Vl0uSh.js +0 -2
  107. package/web-dist/assets/repo-BDS8RBxq.js +0 -2
  108. package/web-dist/assets/repo-BDS8RBxq.js.map +0 -1
  109. package/web-dist/assets/server-BqZ-w6M8.js +0 -2
  110. package/web-dist/assets/server-BqZ-w6M8.js.map +0 -1
  111. package/web-dist/assets/settings-CLt7x9u8.js +0 -8
  112. package/web-dist/assets/settings-CLt7x9u8.js.map +0 -1
  113. package/web-dist/assets/states-C773NlHo.js +0 -56
  114. package/web-dist/assets/states-C773NlHo.js.map +0 -1
  115. package/web-dist/assets/useBackTo-BIrCq3W2.js +0 -2
  116. package/web-dist/assets/useBackTo-BIrCq3W2.js.map +0 -1
  117. package/web-dist/assets/useBreakpoint-BphHBrzF.js +0 -2
  118. package/web-dist/assets/useBreakpoint-BphHBrzF.js.map +0 -1
  119. package/web-dist/assets/useNow-Cm-tdyod.js +0 -2
@@ -293,6 +293,8 @@ var RuntimeCapabilities = CoreCapabilities.extend({
293
293
  terminal: z3.boolean().optional(),
294
294
  /** The host answers session.models, session.commands, session.setModel, session.setThinking and session.compact. */
295
295
  sessionControls: z3.boolean().optional(),
296
+ /** The host answers session.navigate for terminal sessions. */
297
+ treeNavigation: z3.boolean().optional(),
296
298
  unsupported: z3.array(z3.object({ capability: z3.string(), reason: z3.string() }))
297
299
  });
298
300
  var ProjectScan = z3.object({
@@ -397,7 +399,9 @@ var SessionModel = z3.object({
397
399
  /** In Pi's scoped (favorite) model list; set only when Pi has one. */
398
400
  scoped: z3.boolean().optional(),
399
401
  /** Effort levels this model accepts, in Pi's order; ["off"] without reasoning. */
400
- thinkingLevels: z3.array(ThinkingLevel)
402
+ thinkingLevels: z3.array(ThinkingLevel),
403
+ /** Prompt-cache lifetimes in seconds from Pi's model metadata. */
404
+ promptCache: z3.object({ short: z3.number().optional(), long: z3.number().optional() }).nullable().optional()
401
405
  });
402
406
  var SlashCommand = z3.object({
403
407
  name: z3.string().min(1),
@@ -458,6 +462,14 @@ var SessionStats = z3.object({
458
462
  costUsd: z3.number().nullable(),
459
463
  context: ContextUsage.nullable().optional()
460
464
  });
465
+ var PromptCacheInfo = z3.object({
466
+ at: Iso,
467
+ provider: z3.string(),
468
+ model: z3.string(),
469
+ cacheRead: z3.number(),
470
+ cacheWrite: z3.number(),
471
+ cacheWrite1h: z3.number()
472
+ });
461
473
  var Session = z3.object({
462
474
  id: Id,
463
475
  title: z3.string(),
@@ -490,7 +502,13 @@ var Session = z3.object({
490
502
  /** A live terminal session: `switchyard tui` can attach to its Pi terminal. */
491
503
  terminal: z3.boolean().optional(),
492
504
  /** Set when the session finished or failed with nobody viewing it; cleared when viewed (coordinator-owned). */
493
- unreadSince: Iso.nullable().optional()
505
+ unreadSince: Iso.nullable().optional(),
506
+ /** Bumped when the transcript is rebuilt (rewind); clients drop cached copies (coordinator-owned). */
507
+ transcriptEpoch: z3.number().int().min(0).optional(),
508
+ /** Last assistant message's cache usage (host-owned). */
509
+ promptCache: PromptCacheInfo.nullable().optional(),
510
+ /** Warn before the prompt cache expires; non-null means on (coordinator-owned). */
511
+ cacheAlert: z3.object({ ttlSec: z3.number().int().min(60).max(86400).nullable(), warnedFor: Iso.nullable() }).nullable().optional()
494
512
  });
495
513
  var ContinuationPolicy = z3.discriminatedUnion("enabled", [
496
514
  z3.object({ enabled: z3.literal(false) }),
@@ -693,7 +711,8 @@ var AttentionReason = z3.enum([
693
711
  "failed",
694
712
  "ready_for_review",
695
713
  "unsupported_interaction",
696
- "host_unreachable"
714
+ "host_unreachable",
715
+ "cache_expiring"
697
716
  ]);
698
717
  var AttentionItem = z3.object({
699
718
  id: Id,
@@ -742,7 +761,12 @@ var TranscriptItem = z3.discriminatedUnion("kind", [
742
761
  order: z3.number().int(),
743
762
  at: Iso,
744
763
  kind: z3.literal("user"),
745
- data: z3.object({ text: z3.string(), images: z3.number().int().optional() })
764
+ data: z3.object({
765
+ text: z3.string(),
766
+ images: z3.number().int().optional(),
767
+ /** Pi session entry id, for rewind and fork from this message. */
768
+ entryId: z3.string().optional()
769
+ })
746
770
  }),
747
771
  z3.object({
748
772
  id: Id,
@@ -864,6 +888,7 @@ var EventDataSchemas = {
864
888
  "view.deleted": z4.object({ id: z4.string() }),
865
889
  "session.updated": Session,
866
890
  "transcript.item": TranscriptItem,
891
+ "transcript.reset": z4.object({ sessionId: z4.string(), epoch: z4.number().int() }),
867
892
  "interaction.updated": Interaction,
868
893
  "panel.updated": Panel,
869
894
  "adapters.updated": z4.object({ hostId: z4.string(), adapters: z4.array(AdapterInfo) }),
@@ -931,14 +956,23 @@ var Cols = z5.number().int().min(10).max(1e3);
931
956
  var Rows = z5.number().int().min(5).max(500);
932
957
  var TermViewerToServer = z5.discriminatedUnion("t", [
933
958
  z5.object({ t: z5.literal("in"), d: z5.string() }),
934
- z5.object({ t: z5.literal("resize"), cols: Cols, rows: Rows })
959
+ z5.object({ t: z5.literal("resize"), cols: Cols, rows: Rows }),
960
+ z5.object({ t: z5.literal("claim") })
935
961
  ]);
936
962
  var TermServerToViewer = z5.discriminatedUnion("t", [
937
963
  z5.object({ t: z5.literal("out"), d: z5.string() }),
938
- z5.object({ t: z5.literal("closed"), reason: z5.string() })
964
+ z5.object({ t: z5.literal("closed"), reason: z5.string() }),
965
+ z5.object({ t: z5.literal("size"), cols: Cols, rows: Rows, owner: z5.boolean() })
939
966
  ]);
940
967
  var TermCoordinatorMsg = z5.discriminatedUnion("t", [
941
- z5.object({ t: z5.literal("open"), sessionId: z5.string(), cols: Cols, rows: Rows }),
968
+ z5.object({
969
+ t: z5.literal("open"),
970
+ sessionId: z5.string(),
971
+ cols: Cols,
972
+ rows: Rows,
973
+ passive: z5.boolean().optional()
974
+ }),
975
+ z5.object({ t: z5.literal("claim") }),
942
976
  z5.object({ t: z5.literal("in"), d: z5.string() }),
943
977
  z5.object({ t: z5.literal("resize"), cols: Cols, rows: Rows }),
944
978
  z5.object({ t: z5.literal("close") })
@@ -1012,6 +1046,13 @@ var HostCommand = z6.discriminatedUnion("type", [
1012
1046
  entryId: z6.string().nullable(),
1013
1047
  fork: z6.boolean()
1014
1048
  }),
1049
+ z6.object({
1050
+ type: z6.literal("session.navigate"),
1051
+ sessionId: z6.string(),
1052
+ entryId: z6.string(),
1053
+ summarize: z6.boolean(),
1054
+ instructions: z6.string().max(2e3).nullable()
1055
+ }),
1015
1056
  z6.object({ type: z6.literal("session.reload"), sessionId: z6.string() }),
1016
1057
  z6.object({ type: z6.literal("session.export"), sessionId: z6.string() }),
1017
1058
  z6.object({
@@ -1324,6 +1365,10 @@ var PromptRequest = z7.object({
1324
1365
  images: z7.array(z7.object({ mimeType: z7.string(), data: z7.string() })).default([]),
1325
1366
  clientMessageId: z7.string().optional()
1326
1367
  });
1368
+ var CacheAlertRequest = z7.object({
1369
+ enabled: z7.boolean(),
1370
+ ttlSec: z7.number().int().min(60).max(86400).nullable().default(null)
1371
+ });
1327
1372
  var RenameRequest = z7.object({ title: z7.string().min(1).max(200) });
1328
1373
  var SetModelRequest = z7.object({
1329
1374
  provider: z7.string().min(1),
@@ -1363,6 +1408,27 @@ var HostBranchResult = z7.object({
1363
1408
  sessionFile: z7.string().nullable(),
1364
1409
  prefill: z7.string().nullable()
1365
1410
  });
1411
+ var TranscriptPage = z7.object({
1412
+ items: z7.array(TranscriptItem),
1413
+ hasMore: z7.boolean(),
1414
+ epoch: z7.number().int().optional(),
1415
+ rev: z7.number().int().optional(),
1416
+ delta: z7.boolean().optional(),
1417
+ reset: z7.boolean().optional()
1418
+ });
1419
+ var NavigateRequest = z7.object({
1420
+ entryId: z7.string().min(1),
1421
+ summarize: z7.boolean().default(false),
1422
+ instructions: z7.string().max(2e3).nullable().default(null)
1423
+ });
1424
+ var HostNavigateResult = z7.object({
1425
+ items: z7.array(TranscriptItem),
1426
+ prefill: z7.string().nullable()
1427
+ });
1428
+ var NavigateResult = z7.object({
1429
+ prefill: z7.string().nullable(),
1430
+ epoch: z7.number().int()
1431
+ });
1366
1432
  var BranchResult = z7.object({
1367
1433
  session: Session.nullable(),
1368
1434
  prefill: z7.string().nullable()
@@ -2327,7 +2393,7 @@ function runRawTerminal(opts) {
2327
2393
  return;
2328
2394
  if (msg.data.t === "out")
2329
2395
  stdout.write(Buffer.from(msg.data.d, "base64"));
2330
- else
2396
+ else if (msg.data.t === "closed")
2331
2397
  finish({ reason: "closed", message: msg.data.reason });
2332
2398
  });
2333
2399
  ws.on("unexpected-response", (_req, res) => {
@@ -2547,7 +2613,8 @@ var REASON_LABEL = {
2547
2613
  unsupported_interaction: "Needs input",
2548
2614
  failed: "Failed",
2549
2615
  ready_for_review: "Ready for review",
2550
- host_unreachable: "Host unreachable"
2616
+ host_unreachable: "Host unreachable",
2617
+ cache_expiring: "Prompt cache expiring"
2551
2618
  };
2552
2619
  function inQuietHours(quiet, at) {
2553
2620
  if (!quiet)
@@ -2704,7 +2771,8 @@ var DEFAULT_SEVERITY = {
2704
2771
  failed: "critical",
2705
2772
  ready_for_review: "info",
2706
2773
  unsupported_interaction: "warning",
2707
- host_unreachable: "critical"
2774
+ host_unreachable: "critical",
2775
+ cache_expiring: "warning"
2708
2776
  };
2709
2777
  function deepLinkFor(i) {
2710
2778
  if (i.reason === "needs_input" && i.sessionId && i.interactionId) {
@@ -4179,6 +4247,84 @@ function occurrenceLabel(o) {
4179
4247
  }
4180
4248
  }
4181
4249
 
4250
+ // packages/coordinator/dist/cache-alerts.js
4251
+ function cacheTtlSec(s) {
4252
+ if (s.cacheAlert?.ttlSec)
4253
+ return s.cacheAlert.ttlSec;
4254
+ const pc = s.promptCache;
4255
+ if (!pc)
4256
+ return null;
4257
+ const long = pc.cacheWrite1h > 0;
4258
+ const meta = s.model?.promptCache;
4259
+ if (s.model && s.model.provider === pc.provider && s.model.id === pc.model && meta) {
4260
+ const v = long ? meta.long : meta.short;
4261
+ if (typeof v === "number")
4262
+ return v;
4263
+ }
4264
+ if (pc.provider === "anthropic")
4265
+ return long ? 3600 : 300;
4266
+ return null;
4267
+ }
4268
+ function cacheWarning(s, _now) {
4269
+ const pc = s.promptCache;
4270
+ if (!s.cacheAlert || !pc || s.archivedAt)
4271
+ return null;
4272
+ if (s.runtime !== "idle")
4273
+ return null;
4274
+ if (pc.cacheRead + pc.cacheWrite <= 0)
4275
+ return null;
4276
+ const ttl = cacheTtlSec(s);
4277
+ if (!ttl)
4278
+ return null;
4279
+ const expiresAt = Date.parse(pc.at) + ttl * 1e3;
4280
+ const warnAt = expiresAt - Math.min(300, ttl / 2) * 1e3;
4281
+ return { expiresAt, warnAt };
4282
+ }
4283
+ var CacheAlertService = class {
4284
+ ctx;
4285
+ opts;
4286
+ timer = null;
4287
+ constructor(ctx, opts) {
4288
+ this.ctx = ctx;
4289
+ this.opts = opts;
4290
+ }
4291
+ start() {
4292
+ if (this.opts.tickMs <= 0)
4293
+ return;
4294
+ this.timer = setInterval(() => this.tick(), this.opts.tickMs);
4295
+ this.timer.unref();
4296
+ }
4297
+ stop() {
4298
+ if (this.timer)
4299
+ clearInterval(this.timer);
4300
+ this.timer = null;
4301
+ }
4302
+ tick(now = Date.now()) {
4303
+ const { store, attention } = this.ctx;
4304
+ for (const s of store.sessions.list("archived_at IS NULL", [])) {
4305
+ if (!s.cacheAlert)
4306
+ continue;
4307
+ const w = cacheWarning(s, now);
4308
+ const pc = s.promptCache;
4309
+ if (w && pc && now >= w.warnAt && now < w.expiresAt && s.cacheAlert.warnedFor !== pc.at) {
4310
+ store.tx(() => {
4311
+ attention.raise({
4312
+ reason: "cache_expiring",
4313
+ sessionId: s.id,
4314
+ projectId: s.projectId,
4315
+ summary: `Prompt cache expires in ${Math.max(1, Math.ceil((w.expiresAt - now) / 6e4))} min. Send a message to keep it warm.`
4316
+ });
4317
+ store.putSession({ ...s, cacheAlert: { ...s.cacheAlert, warnedFor: pc.at } });
4318
+ });
4319
+ continue;
4320
+ }
4321
+ if (!w || now >= w.expiresAt || s.cacheAlert.warnedFor !== pc?.at) {
4322
+ attention.resolve({ sessionId: s.id, reason: "cache_expiring" });
4323
+ }
4324
+ }
4325
+ }
4326
+ };
4327
+
4182
4328
  // packages/coordinator/dist/workspaces.js
4183
4329
  import { z as z10 } from "zod";
4184
4330
  function worktreeDirOf(project) {
@@ -4326,6 +4472,16 @@ function appendNotice(ctx, session, level, text) {
4326
4472
  return item;
4327
4473
  });
4328
4474
  }
4475
+ function resetTranscript(ctx, sessionId, items) {
4476
+ return ctx.store.tx(() => {
4477
+ ctx.store.replaceItems(sessionId, items);
4478
+ const cur = ctx.store.sessions.require(sessionId);
4479
+ const epoch = (cur.transcriptEpoch ?? 0) + 1;
4480
+ ctx.store.putSession({ ...cur, transcriptEpoch: epoch });
4481
+ ctx.store.appendEvent("transcript.reset", { sessionId, hostId: cur.hostId, projectId: cur.projectId ?? void 0 }, { sessionId, epoch });
4482
+ return epoch;
4483
+ });
4484
+ }
4329
4485
  function failSession(ctx, sessionId, message) {
4330
4486
  ctx.store.tx(() => {
4331
4487
  const s = ctx.store.sessions.get(sessionId);
@@ -6936,7 +7092,9 @@ function installBuiltins(app, ctx, opts = {}) {
6936
7092
  const projectFolders = new ProjectFolderService(ctx, {
6937
7093
  intervalMs: opts.projectScanIntervalMs ?? PROJECT_SCAN_INTERVAL_MS
6938
7094
  });
7095
+ const cacheAlerts = new CacheAlertService(ctx, { tickMs: opts.cacheAlertTickMs ?? 15e3 });
6939
7096
  const services = {
7097
+ cacheAlerts,
6940
7098
  dispatcher,
6941
7099
  runs,
6942
7100
  automations,
@@ -6960,8 +7118,10 @@ function installBuiltins(app, ctx, opts = {}) {
6960
7118
  dispatcher.start();
6961
7119
  scheduler.start();
6962
7120
  projectFolders.start();
7121
+ cacheAlerts.start();
6963
7122
  },
6964
7123
  stop() {
7124
+ cacheAlerts.stop();
6965
7125
  projectFolders.stop();
6966
7126
  scheduler.stop();
6967
7127
  dispatcher.stop();
@@ -7474,6 +7634,12 @@ CREATE TABLE views (
7474
7634
  CREATE UNIQUE INDEX views_name ON views(name COLLATE NOCASE);
7475
7635
  `;
7476
7636
 
7637
+ // packages/coordinator/dist/db/migrations/008_item_rev.js
7638
+ var sql8 = `
7639
+ ALTER TABLE session_items ADD COLUMN rev INTEGER NOT NULL DEFAULT 0;
7640
+ CREATE INDEX session_items_rev ON session_items(session_id, rev);
7641
+ `;
7642
+
7477
7643
  // packages/coordinator/dist/db/index.js
7478
7644
  var MIGRATIONS = [
7479
7645
  { version: 1, name: "001_init", sql },
@@ -7482,7 +7648,8 @@ var MIGRATIONS = [
7482
7648
  { version: 4, name: "004_interaction_canceled", sql: sql4 },
7483
7649
  { version: 5, name: "005_workspace_deleted_event", sql: sql5 },
7484
7650
  { version: 6, name: "006_unique_native_session", sql: sql6 },
7485
- { version: 7, name: "007_views", sql: sql7 }
7651
+ { version: 7, name: "007_views", sql: sql7 },
7652
+ { version: 8, name: "008_item_rev", sql: sql8 }
7486
7653
  ];
7487
7654
  var LATEST_MIGRATION = MIGRATIONS[MIGRATIONS.length - 1].version;
7488
7655
  function openDb(path) {
@@ -7651,6 +7818,7 @@ var HOST_SESSION_FIELDS = [
7651
7818
  "model",
7652
7819
  "thinking",
7653
7820
  "compacting",
7821
+ "promptCache",
7654
7822
  "lastAssistantText",
7655
7823
  "lastActivityAt",
7656
7824
  "terminal"
@@ -9640,7 +9808,9 @@ var ListQuery5 = z17.object({
9640
9808
  });
9641
9809
  var TranscriptQuery = z17.object({
9642
9810
  before: z17.coerce.number().int().optional(),
9643
- limit: z17.coerce.number().int().min(1).max(1e3).default(200)
9811
+ limit: z17.coerce.number().int().min(1).max(1e3).default(200),
9812
+ afterRev: z17.coerce.number().int().min(0).optional(),
9813
+ epoch: z17.coerce.number().int().min(0).optional()
9644
9814
  });
9645
9815
  var AbortRequest = z17.object({ clearQueue: z17.boolean().default(false) });
9646
9816
  var ImportableQuery = z17.object({ hostId: z17.string() });
@@ -9783,7 +9953,17 @@ function registerSessionRoutes(app, ctx) {
9783
9953
  const q = parse(TranscriptQuery, req.query, "query");
9784
9954
  if (q.before === void 0)
9785
9955
  await refreshSubagentTranscript(ctx, s);
9786
- return ctx.store.listItems(s.id, { before: q.before, limit: q.limit });
9956
+ const epoch = s.transcriptEpoch ?? 0;
9957
+ const rev = ctx.store.maxItemRev(s.id);
9958
+ if (q.afterRev !== void 0 && q.before === void 0) {
9959
+ if (q.epoch === epoch) {
9960
+ const d = ctx.store.listItemsAfterRev(s.id, q.afterRev, 1e3);
9961
+ if (!d.more)
9962
+ return { items: d.items, hasMore: false, epoch, rev, delta: true };
9963
+ }
9964
+ return { ...ctx.store.listItems(s.id, { limit: q.limit }), epoch, rev, reset: true };
9965
+ }
9966
+ return { ...ctx.store.listItems(s.id, { before: q.before, limit: q.limit }), epoch, rev };
9787
9967
  });
9788
9968
  app.get("/api/sessions/:id/snapshot", async (req) => {
9789
9969
  const s = get(idOf(req));
@@ -9869,6 +10049,28 @@ function registerSessionRoutes(app, ctx) {
9869
10049
  }, s.hostId, s.projectId, native.items ?? []);
9870
10050
  return reply.code(201).send({ session, prefill: r.prefill });
9871
10051
  });
10052
+ app.post("/api/sessions/:id/navigate", async (req) => {
10053
+ const s = get(idOf(req));
10054
+ const body = parse(NavigateRequest, req.body);
10055
+ requireSessionControls(ctx, s);
10056
+ if (s.terminal !== true || ctx.store.hosts.get(s.hostId)?.capabilities?.treeNavigation !== true) {
10057
+ throw new SwitchyardError("invalid_request", "Rewind needs a terminal session on an updated host");
10058
+ }
10059
+ if (s.runtime !== "idle") {
10060
+ throw new SwitchyardError("conflict", "Wait for the reply to finish before rewinding");
10061
+ }
10062
+ if (s.compacting)
10063
+ throw new SwitchyardError("conflict", "Wait for compaction to finish");
10064
+ const r = HostNavigateResult.parse(await ctx.hostHub.request(s.hostId, {
10065
+ type: "session.navigate",
10066
+ sessionId: s.id,
10067
+ entryId: body.entryId,
10068
+ summarize: body.summarize,
10069
+ instructions: body.instructions
10070
+ }, { timeoutMs: body.summarize ? 10 * 6e4 : 3e4 }));
10071
+ const epoch = resetTranscript(ctx, s.id, r.items);
10072
+ return NavigateResult.parse({ prefill: r.prefill, epoch });
10073
+ });
9872
10074
  app.post("/api/sessions/:id/reload", async (req) => {
9873
10075
  const s = get(idOf(req));
9874
10076
  requireSessionControls(ctx, s);
@@ -9974,6 +10176,19 @@ function registerSessionRoutes(app, ctx) {
9974
10176
  await resumeSession(s);
9975
10177
  return get(s.id);
9976
10178
  });
10179
+ app.post("/api/sessions/:id/cache-alert", async (req) => {
10180
+ const s = get(idOf(req));
10181
+ const body = parse(CacheAlertRequest, req.body);
10182
+ return ctx.store.tx(() => {
10183
+ const cur = ctx.store.sessions.require(s.id);
10184
+ if (!body.enabled)
10185
+ ctx.attention.resolve({ sessionId: s.id, reason: "cache_expiring" });
10186
+ return ctx.store.putSession({
10187
+ ...cur,
10188
+ cacheAlert: body.enabled ? { ttlSec: body.ttlSec, warnedFor: cur.cacheAlert?.warnedFor ?? null } : null
10189
+ });
10190
+ });
10191
+ });
9977
10192
  app.post("/api/sessions/:id/rename", async (req) => {
9978
10193
  const s = get(idOf(req));
9979
10194
  const body = parse(RenameRequest, req.body);
@@ -10224,11 +10439,11 @@ var Statements = class {
10224
10439
  constructor(db) {
10225
10440
  this.db = db;
10226
10441
  }
10227
- get(sql8) {
10228
- let s = this.cache.get(sql8);
10442
+ get(sql9) {
10443
+ let s = this.cache.get(sql9);
10229
10444
  if (!s) {
10230
- s = this.db.prepare(sql8);
10231
- this.cache.set(sql8, s);
10445
+ s = this.db.prepare(sql9);
10446
+ this.cache.set(sql9, s);
10232
10447
  }
10233
10448
  return s;
10234
10449
  }
@@ -10259,12 +10474,12 @@ var JsonRepo = class {
10259
10474
  }
10260
10475
  /** List with an optional SQL `WHERE` fragment over the indexed columns. */
10261
10476
  list(where, params = [], orderBy = "rowid") {
10262
- const sql8 = `SELECT json FROM ${this.table}${where ? ` WHERE ${where}` : ""} ORDER BY ${orderBy}`;
10263
- return this.st.get(sql8).all(...params).map((r) => JSON.parse(r.json));
10477
+ const sql9 = `SELECT json FROM ${this.table}${where ? ` WHERE ${where}` : ""} ORDER BY ${orderBy}`;
10478
+ return this.st.get(sql9).all(...params).map((r) => JSON.parse(r.json));
10264
10479
  }
10265
10480
  count(where, params = []) {
10266
- const sql8 = `SELECT COUNT(*) AS n FROM ${this.table}${where ? ` WHERE ${where}` : ""}`;
10267
- return this.st.get(sql8).get(...params).n;
10481
+ const sql9 = `SELECT COUNT(*) AS n FROM ${this.table}${where ? ` WHERE ${where}` : ""}`;
10482
+ return this.st.get(sql9).get(...params).n;
10268
10483
  }
10269
10484
  /**
10270
10485
  * Update by id, or insert when missing. `extra` columns are written in both cases when given
@@ -10705,13 +10920,30 @@ var Store2 = class {
10705
10920
  }
10706
10921
  // ---- transcript items ------------------------------------------------------------------
10707
10922
  upsertItem(item) {
10708
- this.st.get("INSERT INTO session_items (session_id, item_id, ord, json) VALUES (?, ?, ?, ?) ON CONFLICT(session_id, item_id) DO UPDATE SET ord = excluded.ord, json = excluded.json").run(item.sessionId, item.id, item.order, JSON.stringify(item));
10923
+ this.insertItem(item, this.maxItemRev(item.sessionId) + 1);
10924
+ }
10925
+ insertItem(item, rev) {
10926
+ this.st.get("INSERT INTO session_items (session_id, item_id, ord, json, rev) VALUES (?, ?, ?, ?, ?) ON CONFLICT(session_id, item_id) DO UPDATE SET ord = excluded.ord, json = excluded.json, rev = excluded.rev").run(item.sessionId, item.id, item.order, JSON.stringify(item), rev);
10927
+ }
10928
+ /** Highest item revision of a session (0 when it has none). */
10929
+ maxItemRev(sessionId) {
10930
+ const r = this.st.get("SELECT COALESCE(MAX(rev), 0) AS m FROM session_items WHERE session_id = ?").get(sessionId);
10931
+ return r.m;
10709
10932
  }
10710
10933
  /** Replace a session's whole transcript (read-only views re-read from the native file). */
10711
10934
  replaceItems(sessionId, items) {
10935
+ let rev = this.maxItemRev(sessionId);
10712
10936
  this.st.get("DELETE FROM session_items WHERE session_id = ?").run(sessionId);
10713
10937
  for (const item of items)
10714
- this.upsertItem(item);
10938
+ this.insertItem(item, ++rev);
10939
+ }
10940
+ /** Items changed after a revision, in order; `more` when there are more than `limit`. */
10941
+ listItemsAfterRev(sessionId, afterRev, limit = 1e3) {
10942
+ const rows = this.st.get("SELECT json FROM session_items WHERE session_id = ? AND rev > ? ORDER BY ord ASC LIMIT ?").all(sessionId, afterRev, limit + 1);
10943
+ return {
10944
+ items: rows.slice(0, limit).map((r) => JSON.parse(r.json)),
10945
+ more: rows.length > limit
10946
+ };
10715
10947
  }
10716
10948
  /** Items in ascending order; `before` pages backwards from an order value. */
10717
10949
  listItems(sessionId, opts = {}) {
@@ -10982,7 +11214,7 @@ var TerminalHub = class {
10982
11214
  this.hostHub = hostHub;
10983
11215
  this.log = log;
10984
11216
  }
10985
- handleSocket(socket, sessionId, cols, rows) {
11217
+ handleSocket(socket, sessionId, cols, rows, passive = false) {
10986
11218
  const refuse = (reason) => {
10987
11219
  this.sendTo(socket, { t: "closed", reason });
10988
11220
  socket.close(1e3, "closed");
@@ -11021,7 +11253,13 @@ var TerminalHub = class {
11021
11253
  this.toHost(streamId, { t: "close" }, host.id);
11022
11254
  });
11023
11255
  socket.on("error", (err) => this.log.debug({ err, streamId }, "terminal socket error"));
11024
- if (!this.hostHub.sendTerm(host.id, streamId, { t: "open", sessionId, cols, rows })) {
11256
+ if (!this.hostHub.sendTerm(host.id, streamId, {
11257
+ t: "open",
11258
+ sessionId,
11259
+ cols,
11260
+ rows,
11261
+ ...passive ? { passive } : {}
11262
+ })) {
11025
11263
  this.streams.delete(streamId);
11026
11264
  refuse(`Host ${host.name} is not connected`);
11027
11265
  }
@@ -11326,7 +11564,7 @@ function createCoordinator(opts) {
11326
11564
  const n = Number.parseInt(v ?? "", 10);
11327
11565
  return Number.isFinite(n) ? Math.min(max, Math.max(min, n)) : dflt;
11328
11566
  };
11329
- terminalHub.handleSocket(socket, sessionId, size(q.cols, 10, 1e3, 80), size(q.rows, 5, 500, 24));
11567
+ terminalHub.handleSocket(socket, sessionId, size(q.cols, 10, 1e3, 80), size(q.rows, 5, 500, 24), q.passive === "1");
11330
11568
  });
11331
11569
  });
11332
11570
  registerOpsRoutes(app, ctx);
@@ -13377,6 +13615,17 @@ function supportedThinkingLevels(model) {
13377
13615
  return true;
13378
13616
  });
13379
13617
  }
13618
+ function promptCacheOf(model) {
13619
+ const pc = model?.promptCache;
13620
+ if (!pc || typeof pc !== "object")
13621
+ return null;
13622
+ const out = {};
13623
+ if (typeof pc.short === "number")
13624
+ out.short = pc.short;
13625
+ if (typeof pc.long === "number")
13626
+ out.long = pc.long;
13627
+ return out.short !== void 0 || out.long !== void 0 ? out : null;
13628
+ }
13380
13629
  function modelInfo(model) {
13381
13630
  if (!model || typeof model.provider !== "string" || typeof model.id !== "string")
13382
13631
  return null;
@@ -13386,7 +13635,8 @@ function modelInfo(model) {
13386
13635
  name: typeof model.name === "string" && model.name ? model.name : null,
13387
13636
  contextWindow: typeof model.contextWindow === "number" ? model.contextWindow : null,
13388
13637
  reasoning: model.reasoning === true,
13389
- thinkingLevels: supportedThinkingLevels(model)
13638
+ thinkingLevels: supportedThinkingLevels(model),
13639
+ promptCache: promptCacheOf(model)
13390
13640
  };
13391
13641
  }
13392
13642
 
@@ -13587,7 +13837,8 @@ function messagesToItems(messages, opts) {
13587
13837
  switch (m.role) {
13588
13838
  case "user": {
13589
13839
  const { text, images } = contentText(m.content);
13590
- push("user", images > 0 ? { text, images } : { text }, at);
13840
+ const entryId = typeof m.entryId === "string" ? { entryId: m.entryId } : {};
13841
+ push("user", images > 0 ? { text, images, ...entryId } : { text, ...entryId }, at);
13591
13842
  break;
13592
13843
  }
13593
13844
  case "assistant": {
@@ -13939,7 +14190,7 @@ function entriesToMessages(entries) {
13939
14190
  switch (e.type) {
13940
14191
  case "message":
13941
14192
  if (e.message)
13942
- messages.push({ timestamp: ts, ...e.message });
14193
+ messages.push({ timestamp: ts, ...e.message, entryId: e.id });
13943
14194
  break;
13944
14195
  case "custom_message":
13945
14196
  messages.push({
@@ -14137,7 +14388,9 @@ function messageText(message) {
14137
14388
  return c.filter((p) => p?.type === "text" && typeof p.text === "string").map((p) => p.text).join(" ");
14138
14389
  }
14139
14390
  var MAX_ROWS = 2e3;
14140
- function treeRows(sm) {
14391
+ function treeRows(sm, liveLeaf = null) {
14392
+ if (liveLeaf && sm.getEntry?.(liveLeaf))
14393
+ sm.branch?.(liveLeaf);
14141
14394
  const active = new Set((sm.getBranch() ?? []).map((e) => e.id));
14142
14395
  const leafId = sm.getLeafId?.() ?? null;
14143
14396
  const rows = [];
@@ -14176,7 +14429,7 @@ function treeRows(sm) {
14176
14429
  }
14177
14430
  return rows;
14178
14431
  }
14179
- async function branchSession(sessionFile, entryId, fork, piBin, load = loadPiSessionManager, checkFile = true) {
14432
+ async function branchSession(sessionFile, entryId, fork, piBin, load = loadPiSessionManager, checkFile = true, liveLeaf = null) {
14180
14433
  const SM = await load(piBin);
14181
14434
  if (!SM) {
14182
14435
  throw new SwitchyardError("invalid_request", "Pi's SessionManager could not be loaded on this host");
@@ -14194,7 +14447,7 @@ async function branchSession(sessionFile, entryId, fork, piBin, load = loadPiSes
14194
14447
  if (!target)
14195
14448
  return { sessionFile: null, prefill };
14196
14449
  } else {
14197
- target = entryId ?? sm.getLeafId();
14450
+ target = entryId ?? liveLeaf ?? sm.getLeafId();
14198
14451
  if (!target) {
14199
14452
  throw new SwitchyardError("invalid_request", "This session has nothing to branch yet");
14200
14453
  }
@@ -14733,7 +14986,7 @@ var PiTerminalProcess = class _PiTerminalProcess extends EventEmitter3 {
14733
14986
  env,
14734
14987
  cols: opts.cols ?? 120,
14735
14988
  rows: opts.rows ?? 40,
14736
- sizing: process.env.SWITCHYARD_TERMINAL_SIZING === "latest" ? "latest" : "smallest"
14989
+ sizing: /* @__PURE__ */ ((v) => v === "latest" || v === "smallest" ? v : "owner")(process.env.SWITCHYARD_TERMINAL_SIZING)
14737
14990
  };
14738
14991
  const logPath = opts.logPath ?? join15(dirname9(socketPath), `${basename3(socketPath, ".sock")}.log`);
14739
14992
  mkdirSync5(dirname9(logPath), { recursive: true, mode: 448 });
@@ -15058,6 +15311,10 @@ var ManagedSession = class _ManagedSession extends EventEmitter4 {
15058
15311
  /** Set by `detach()`: the agent is going away, so a start in flight neither fails nor closes Pi. */
15059
15312
  detachedDuring = false;
15060
15313
  _native;
15314
+ /** Pi's live leaf entry id (pushed by the terminal extension). */
15315
+ _leafId = null;
15316
+ /** The user item just created, waiting for its entry id from `entry_appended`. */
15317
+ pendingUserItemId = null;
15061
15318
  _queue = { steering: [], followUp: [] };
15062
15319
  pending = /* @__PURE__ */ new Map();
15063
15320
  current = null;
@@ -15095,6 +15352,9 @@ var ManagedSession = class _ManagedSession extends EventEmitter4 {
15095
15352
  get nativeHandle() {
15096
15353
  return this._native;
15097
15354
  }
15355
+ get leafId() {
15356
+ return this._leafId;
15357
+ }
15098
15358
  get queue() {
15099
15359
  return { steering: [...this._queue.steering], followUp: [...this._queue.followUp] };
15100
15360
  }
@@ -15370,6 +15630,32 @@ var ManagedSession = class _ManagedSession extends EventEmitter4 {
15370
15630
  }
15371
15631
  return { disposition: data?.disposition ?? "started", view: null };
15372
15632
  }
15633
+ /**
15634
+ * Move Pi's leaf to an earlier entry in place (terminal sessions only), optionally summarizing
15635
+ * the abandoned branch. Resolves with the new active branch's entries.
15636
+ */
15637
+ async navigate(entryId, summarize, instructions) {
15638
+ const proc = this.requireAlive();
15639
+ if (!(proc instanceof PiTerminalProcess)) {
15640
+ throw new SwitchyardError("invalid_request", "Rewind needs a terminal session");
15641
+ }
15642
+ const data = await this.call(proc, {
15643
+ type: "navigate_tree",
15644
+ entryId,
15645
+ summarize,
15646
+ instructions,
15647
+ sessionFile: this._native?.sessionFile ?? null
15648
+ }, 10 * 6e4);
15649
+ return {
15650
+ leafId: typeof data?.leafId === "string" ? data.leafId : null,
15651
+ editorText: typeof data?.editorText === "string" ? data.editorText : null,
15652
+ entries: Array.isArray(data?.entries) ? data.entries : []
15653
+ };
15654
+ }
15655
+ /** Skip `n` transcript orders (a rebuilt transcript used them). */
15656
+ reserveOrders(n) {
15657
+ this.order += n;
15658
+ }
15373
15659
  /** Reload Pi's extensions, skills, prompts and context files (terminal sessions only). */
15374
15660
  async reload() {
15375
15661
  const proc = this.requireAlive();
@@ -15821,6 +16107,21 @@ var ManagedSession = class _ManagedSession extends EventEmitter4 {
15821
16107
  if (ev.message?.role === "assistant")
15822
16108
  this.current = { blocks: /* @__PURE__ */ new Map() };
15823
16109
  break;
16110
+ case "leaf":
16111
+ this._leafId = typeof ev.leafId === "string" ? ev.leafId : null;
16112
+ break;
16113
+ case "entry_appended": {
16114
+ const entry = ev.entry;
16115
+ if (entry?.type === "message" && entry.message?.role === "user" && typeof entry.id === "string" && this.pendingUserItemId) {
16116
+ const item = this.items.get(this.pendingUserItemId);
16117
+ this.pendingUserItemId = null;
16118
+ if (item && item.kind === "user") {
16119
+ item.data.entryId = entry.id;
16120
+ this.emit("item", structuredClone(item));
16121
+ }
16122
+ }
16123
+ break;
16124
+ }
15824
16125
  case "message_update":
15825
16126
  this.onMessageUpdate(ev.assistantMessageEvent);
15826
16127
  break;
@@ -16000,7 +16301,9 @@ var ManagedSession = class _ManagedSession extends EventEmitter4 {
16000
16301
  switch (message.role) {
16001
16302
  case "user": {
16002
16303
  const { text, images } = contentText(message.content);
16003
- this.emitItem(this.newItem("user", images > 0 ? { text, images } : { text }));
16304
+ const item = this.newItem("user", images > 0 ? { text, images } : { text });
16305
+ this.emitItem(item);
16306
+ this.pendingUserItemId = item.id;
16004
16307
  break;
16005
16308
  }
16006
16309
  case "assistant":
@@ -16053,6 +16356,18 @@ ${output}`.trimEnd() }));
16053
16356
  });
16054
16357
  if (texts.length > 0)
16055
16358
  this.runAssistantText = texts.join("\n");
16359
+ const usage = message.usage;
16360
+ if (usage && typeof usage === "object") {
16361
+ const n = (v) => typeof v === "number" ? v : 0;
16362
+ this.emit("prompt_cache", {
16363
+ at: this.now(),
16364
+ provider: String(message.provider ?? this._model?.provider ?? ""),
16365
+ model: String(message.model ?? this._model?.id ?? ""),
16366
+ cacheRead: n(usage.cacheRead),
16367
+ cacheWrite: n(usage.cacheWrite),
16368
+ cacheWrite1h: n(usage.cacheWrite1h)
16369
+ });
16370
+ }
16056
16371
  const failed = message.stopReason === "error" || message.stopReason === "aborted";
16057
16372
  if (failed && message.errorMessage && !this.abortRequested) {
16058
16373
  this.notice("error", String(message.errorMessage));
@@ -16377,6 +16692,8 @@ var CommandRouter = class {
16377
16692
  return sup.tree(c.sessionId);
16378
16693
  case "session.branch":
16379
16694
  return sup.branch(c.sessionId, c.entryId, c.fork);
16695
+ case "session.navigate":
16696
+ return sup.navigate(c.sessionId, c.entryId, c.summarize, c.instructions);
16380
16697
  case "session.reload":
16381
16698
  return sup.reload(c.sessionId);
16382
16699
  case "session.export":
@@ -16814,15 +17131,15 @@ var HostDb = class {
16814
17131
  else
16815
17132
  fn();
16816
17133
  }
16817
- run(sql8, params = []) {
16818
- const r = this.db.prepare(sql8).run(...params);
17134
+ run(sql9, params = []) {
17135
+ const r = this.db.prepare(sql9).run(...params);
16819
17136
  return { changes: Number(r.changes), lastInsertRowid: Number(r.lastInsertRowid) };
16820
17137
  }
16821
- get(sql8, params = []) {
16822
- return this.db.prepare(sql8).get(...params);
17138
+ get(sql9, params = []) {
17139
+ return this.db.prepare(sql9).get(...params);
16823
17140
  }
16824
- all(sql8, params = []) {
16825
- return this.db.prepare(sql8).all(...params);
17141
+ all(sql9, params = []) {
17142
+ return this.db.prepare(sql9).all(...params);
16826
17143
  }
16827
17144
  // ---- meta ----
16828
17145
  getMeta(key) {
@@ -16832,12 +17149,12 @@ var HostDb = class {
16832
17149
  this.run("INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value", [key, value]);
16833
17150
  }
16834
17151
  // ---- JSON row helpers ----
16835
- getJson(sql8, params = []) {
16836
- const r = this.get(sql8, params);
17152
+ getJson(sql9, params = []) {
17153
+ const r = this.get(sql9, params);
16837
17154
  return r ? JSON.parse(r.json) : void 0;
16838
17155
  }
16839
- allJson(sql8, params = []) {
16840
- return this.all(sql8, params).map((r) => JSON.parse(r.json));
17156
+ allJson(sql9, params = []) {
17157
+ return this.all(sql9, params).map((r) => JSON.parse(r.json));
16841
17158
  }
16842
17159
  close() {
16843
17160
  try {
@@ -17390,7 +17707,8 @@ var NOT_LIVE = {
17390
17707
  reload: "resume to reload",
17391
17708
  setModel: "resume to change the model",
17392
17709
  setThinking: "resume to change the thinking level",
17393
- compact: "resume to compact"
17710
+ compact: "resume to compact",
17711
+ navigate: "resume to rewind"
17394
17712
  };
17395
17713
  var SESSION_LIVE_CONFLICT = "Session already live on this host";
17396
17714
  function lostRuntime(rec) {
@@ -17737,6 +18055,7 @@ var SessionSupervisor = class {
17737
18055
  model: rec.model ?? null,
17738
18056
  thinking: rec.thinking ?? null,
17739
18057
  compacting: rec.compacting ?? false,
18058
+ promptCache: rec.promptCache ?? null,
17740
18059
  lastAssistantText: rec.lastAssistantText,
17741
18060
  createdAt: rec.createdAt,
17742
18061
  terminal: rec.terminal != null
@@ -18108,10 +18427,29 @@ var SessionSupervisor = class {
18108
18427
  if (!SM) {
18109
18428
  throw new SwitchyardError("invalid_request", "Pi's SessionManager could not be loaded on this host");
18110
18429
  }
18111
- return { rows: treeRows(SM.open(file, dirname13(file))) };
18430
+ return {
18431
+ rows: treeRows(SM.open(file, dirname13(file)), this.live.get(sessionId)?.ms?.leafId ?? null)
18432
+ };
18112
18433
  }
18113
18434
  async branch(sessionId, entryId, fork) {
18114
- return branchSession(this.piFile(sessionId), entryId, fork, this.opts.piBin);
18435
+ return branchSession(this.piFile(sessionId), entryId, fork, this.opts.piBin, void 0, true, this.live.get(sessionId)?.ms?.leafId ?? null);
18436
+ }
18437
+ /** Move the running Pi's leaf to an earlier message and rebuild the transcript from its branch. */
18438
+ async navigate(sessionId, entryId, summarize, instructions) {
18439
+ const ms = this.requireLive(sessionId, "navigate");
18440
+ const l = this.live.get(sessionId);
18441
+ const r = await ms.navigate(entryId, summarize, instructions);
18442
+ const start = ms.snapshot().nextOrder;
18443
+ const items = messagesToItems(entriesToMessages(r.entries), {
18444
+ sessionId,
18445
+ startOrder: start,
18446
+ fallbackAt: nowIso()
18447
+ });
18448
+ ms.reserveOrders(items.length);
18449
+ l.rec.nextOrder = ms.snapshot().nextOrder;
18450
+ this.db.tx(() => this.saveAndEmit(l.rec));
18451
+ void this.refreshStats(l);
18452
+ return { items, prefill: r.editorText };
18115
18453
  }
18116
18454
  async exportSession(sessionId) {
18117
18455
  const file = this.piFile(sessionId);
@@ -18404,6 +18742,10 @@ var SessionSupervisor = class {
18404
18742
  this.db.tx(() => this.saveAndEmit(rec));
18405
18743
  void this.refreshStats(l);
18406
18744
  });
18745
+ ms.on("prompt_cache", (p) => {
18746
+ rec.promptCache = p;
18747
+ this.db.tx(() => this.saveAndEmit(rec));
18748
+ });
18407
18749
  ms.on("compacting", (c) => {
18408
18750
  rec.compacting = c;
18409
18751
  this.db.tx(() => this.saveAndEmit(rec));
@@ -18926,9 +19268,10 @@ var TerminalRelay = class {
18926
19268
  handle(streamId, msg) {
18927
19269
  switch (msg.t) {
18928
19270
  case "open":
18929
- this.open(streamId, msg.sessionId, msg.cols, msg.rows);
19271
+ this.open(streamId, msg.sessionId, msg.cols, msg.rows, msg.passive === true);
18930
19272
  return;
18931
19273
  case "in":
19274
+ case "claim":
18932
19275
  case "resize": {
18933
19276
  const s = this.streams.get(streamId);
18934
19277
  if (s && !s.socket.destroyed)
@@ -18955,7 +19298,7 @@ var TerminalRelay = class {
18955
19298
  }
18956
19299
  this.streams.clear();
18957
19300
  }
18958
- open(streamId, sessionId, cols, rows) {
19301
+ open(streamId, sessionId, cols, rows, passive) {
18959
19302
  const existing = this.streams.get(streamId);
18960
19303
  if (existing)
18961
19304
  return;
@@ -18991,7 +19334,7 @@ var TerminalRelay = class {
18991
19334
  if (!entry.closed)
18992
19335
  this.opts.send(streamId, parsed.data);
18993
19336
  });
18994
- socket.write(`${JSON.stringify({ role: "viewer", cols, rows })}
19337
+ socket.write(`${JSON.stringify({ role: "viewer", cols, rows, passive })}
18995
19338
  `);
18996
19339
  }
18997
19340
  };
@@ -19262,7 +19605,7 @@ async function runHostAgent(opts = {}) {
19262
19605
  piVersion: pi.version,
19263
19606
  piCompatible: pi.compatible,
19264
19607
  platform: hostPlatform(),
19265
- capabilities: pi.capabilities ? { ...pi.capabilities, terminal: terminalEnabled } : null,
19608
+ capabilities: pi.capabilities ? { ...pi.capabilities, terminal: terminalEnabled, treeNavigation: terminalEnabled } : null,
19266
19609
  protocolVersion: PROTOCOL_VERSION
19267
19610
  }),
19268
19611
  onTerm: (streamId, msg) => relay.handle(streamId, msg),