@spencerboucher/switchyard 0.19.0 → 0.20.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 (162) hide show
  1. package/README.md +8 -5
  2. package/dist/bridge/enroll.js +36 -6
  3. package/dist/bridge/switchyard-terminal.js +2 -1
  4. package/dist/policies/worker.js +47 -12
  5. package/dist/switchyard.mjs +1421 -585
  6. package/package.json +1 -1
  7. package/web-dist/assets/AutomationView-B4O_teaB.js +2 -0
  8. package/web-dist/assets/{AutomationView-X-U6Fpm7.js.map → AutomationView-B4O_teaB.js.map} +1 -1
  9. package/web-dist/assets/Button-C7TQGuSX.js +2 -0
  10. package/web-dist/assets/Button-C7TQGuSX.js.map +1 -0
  11. package/web-dist/assets/{Card-WONLvqGM.js → Card-DzHrwFrv.js} +2 -2
  12. package/web-dist/assets/{Card-WONLvqGM.js.map → Card-DzHrwFrv.js.map} +1 -1
  13. package/web-dist/assets/{Checkbox-BmiLcC-z.js → Checkbox-BnRsg6ki.js} +2 -2
  14. package/web-dist/assets/{Checkbox-BmiLcC-z.js.map → Checkbox-BnRsg6ki.js.map} +1 -1
  15. package/web-dist/assets/{DangerZone-Ch2KNmob.js → DangerZone-BicyqXv8.js} +2 -2
  16. package/web-dist/assets/{DangerZone-Ch2KNmob.js.map → DangerZone-BicyqXv8.js.map} +1 -1
  17. package/web-dist/assets/Field-Cp-08kpe.js +2 -0
  18. package/web-dist/assets/Field-Cp-08kpe.js.map +1 -0
  19. package/web-dist/assets/{Markdown-BKOAPNDn.js → Markdown-BPWc6K6m.js} +2 -2
  20. package/web-dist/assets/{Markdown-BKOAPNDn.js.map → Markdown-BPWc6K6m.js.map} +1 -1
  21. package/web-dist/assets/{Priority-DTBkp1nb.js → Priority-ZGpTH645.js} +2 -2
  22. package/web-dist/assets/{Priority-DTBkp1nb.js.map → Priority-ZGpTH645.js.map} +1 -1
  23. package/web-dist/assets/{SegmentedControl-Ca8Fsw-g.js → SegmentedControl-Cvkz7C_A.js} +2 -2
  24. package/web-dist/assets/{SegmentedControl-Ca8Fsw-g.js.map → SegmentedControl-Cvkz7C_A.js.map} +1 -1
  25. package/web-dist/assets/Select-DHRR7IAK.js +2 -0
  26. package/web-dist/assets/{Select-YFnt2Br2.js.map → Select-DHRR7IAK.js.map} +1 -1
  27. package/web-dist/assets/{Switch-DHX-YYPr.js → Switch-D5pVfZgf.js} +2 -2
  28. package/web-dist/assets/{Switch-DHX-YYPr.js.map → Switch-D5pVfZgf.js.map} +1 -1
  29. package/web-dist/assets/Tabs-2GilVMsH.js +2 -0
  30. package/web-dist/assets/{Tabs-DrFCe494.js.map → Tabs-2GilVMsH.js.map} +1 -1
  31. package/web-dist/assets/{TextLink-CCc3WEdm.js → TextLink-BGtYWCW9.js} +2 -2
  32. package/web-dist/assets/{TextLink-CCc3WEdm.js.map → TextLink-BGtYWCW9.js.map} +1 -1
  33. package/web-dist/assets/{UINodeRenderer-BdvzPTz0.js → UINodeRenderer-BaANWHvJ.js} +3 -3
  34. package/web-dist/assets/{UINodeRenderer-BdvzPTz0.js.map → UINodeRenderer-BaANWHvJ.js.map} +1 -1
  35. package/web-dist/assets/UnfilteredNote-zVO8ajSi.js +2 -0
  36. package/web-dist/assets/{UnfilteredNote-C44Gi9gP.js.map → UnfilteredNote-zVO8ajSi.js.map} +1 -1
  37. package/web-dist/assets/ViewSelect-C9gNftWK.js +2 -0
  38. package/web-dist/assets/ViewSelect-C9gNftWK.js.map +1 -0
  39. package/web-dist/assets/api-DMrk4xwq.js +2 -0
  40. package/web-dist/assets/api-DMrk4xwq.js.map +1 -0
  41. package/web-dist/assets/{arrow-down-YwTzxo-r.js → arrow-down-Dn3KG_JI.js} +2 -2
  42. package/web-dist/assets/{arrow-down-YwTzxo-r.js.map → arrow-down-Dn3KG_JI.js.map} +1 -1
  43. package/web-dist/assets/{arrow-up-Bzh112dp.js → arrow-up-BiPtOqqy.js} +2 -2
  44. package/web-dist/assets/{arrow-up-Bzh112dp.js.map → arrow-up-BiPtOqqy.js.map} +1 -1
  45. package/web-dist/assets/attention-B9uawu1d.js +2 -0
  46. package/web-dist/assets/attention-B9uawu1d.js.map +1 -0
  47. package/web-dist/assets/automations-IX9DQNk8.js +2 -0
  48. package/web-dist/assets/{automations-CkbEL-3K.js.map → automations-IX9DQNk8.js.map} +1 -1
  49. package/web-dist/assets/board-BUAI4L7M.js +6 -0
  50. package/web-dist/assets/{board-DRNTDqMF.js.map → board-BUAI4L7M.js.map} +1 -1
  51. package/web-dist/assets/{calendar-clock-CwOgyN2z.js → calendar-clock-DVlat602.js} +2 -2
  52. package/web-dist/assets/{calendar-clock-CwOgyN2z.js.map → calendar-clock-DVlat602.js.map} +1 -1
  53. package/web-dist/assets/check-CEnbWw4D.js +2 -0
  54. package/web-dist/assets/{check-DTN2VHtE.js.map → check-CEnbWw4D.js.map} +1 -1
  55. package/web-dist/assets/chevron-right-BM1IJI2z.js +2 -0
  56. package/web-dist/assets/{chevron-right-aaHL5Igi.js.map → chevron-right-BM1IJI2z.js.map} +1 -1
  57. package/web-dist/assets/code-Dav4E15n.js +25 -0
  58. package/web-dist/assets/code-Dav4E15n.js.map +1 -0
  59. package/web-dist/assets/{core.esm-C84Qlq9d.js → core.esm-C4dCvG0s.js} +2 -2
  60. package/web-dist/assets/{core.esm-C84Qlq9d.js.map → core.esm-C4dCvG0s.js.map} +1 -1
  61. package/web-dist/assets/describe-B66LJTqU.js +2 -0
  62. package/web-dist/assets/describe-B66LJTqU.js.map +1 -0
  63. package/web-dist/assets/{describe-Bt36Y0d7.js → describe-BeFxHr2Y.js} +3 -3
  64. package/web-dist/assets/{describe-Bt36Y0d7.js.map → describe-BeFxHr2Y.js.map} +1 -1
  65. package/web-dist/assets/enroll-GUEF5Uxu.js +2 -0
  66. package/web-dist/assets/{enroll--c9VSPgK.js.map → enroll-GUEF5Uxu.js.map} +1 -1
  67. package/web-dist/assets/{external-link-CI-Uzhfh.js → external-link-B3hnazCa.js} +2 -2
  68. package/web-dist/assets/{external-link-CI-Uzhfh.js.map → external-link-B3hnazCa.js.map} +1 -1
  69. package/web-dist/assets/{hand-HCdmhGph.js → hand-B6lvj014.js} +2 -2
  70. package/web-dist/assets/{hand-HCdmhGph.js.map → hand-B6lvj014.js.map} +1 -1
  71. package/web-dist/assets/index-BUZpNu-R.js +22 -0
  72. package/web-dist/assets/index-BUZpNu-R.js.map +1 -0
  73. package/web-dist/assets/index-C9iuCGwg.css +2 -0
  74. package/web-dist/assets/{keyboardLayers-DKHA_Gcs.js → keyboardLayers-BZOygMAH.js} +2 -2
  75. package/web-dist/assets/{keyboardLayers-DKHA_Gcs.js.map → keyboardLayers-BZOygMAH.js.map} +1 -1
  76. package/web-dist/assets/{link-2-D6l0YZ-8.js → link-2-CCq9WzMy.js} +2 -2
  77. package/web-dist/assets/{link-2-D6l0YZ-8.js.map → link-2-CCq9WzMy.js.map} +1 -1
  78. package/web-dist/assets/logic-BBQ4d1GC.js +4 -0
  79. package/web-dist/assets/logic-BBQ4d1GC.js.map +1 -0
  80. package/web-dist/assets/{logic-CzU-NdeO.js → logic-BnSIy9_P.js} +2 -2
  81. package/web-dist/assets/{logic-CzU-NdeO.js.map → logic-BnSIy9_P.js.map} +1 -1
  82. package/web-dist/assets/more-C1oPXLVM.js +2 -0
  83. package/web-dist/assets/{more-Dca-1nh1.js.map → more-C1oPXLVM.js.map} +1 -1
  84. package/web-dist/assets/{pencil-BtK08_f_.js → pencil-DeML-0z2.js} +2 -2
  85. package/web-dist/assets/{pencil-BtK08_f_.js.map → pencil-DeML-0z2.js.map} +1 -1
  86. package/web-dist/assets/{play-j138GLHB.js → play-NHO6U6cY.js} +2 -2
  87. package/web-dist/assets/{play-j138GLHB.js.map → play-NHO6U6cY.js.map} +1 -1
  88. package/web-dist/assets/{plus-D935l0Os.js → plus-C83uJhbf.js} +2 -2
  89. package/web-dist/assets/{plus-D935l0Os.js.map → plus-C83uJhbf.js.map} +1 -1
  90. package/web-dist/assets/policyLogic-DqKyFQEW.js +2 -0
  91. package/web-dist/assets/policyLogic-DqKyFQEW.js.map +1 -0
  92. package/web-dist/assets/{queue-CbFYHdtZ.js → queue-DWSd1kia.js} +2 -2
  93. package/web-dist/assets/{queue-CbFYHdtZ.js.map → queue-DWSd1kia.js.map} +1 -1
  94. package/web-dist/assets/repo-DRwGWCut.js +2 -0
  95. package/web-dist/assets/repo-DRwGWCut.js.map +1 -0
  96. package/web-dist/assets/{rotate-ccw-mfO3Crkq.js → rotate-ccw-BRrlVEAQ.js} +2 -2
  97. package/web-dist/assets/{rotate-ccw-mfO3Crkq.js.map → rotate-ccw-BRrlVEAQ.js.map} +1 -1
  98. package/web-dist/assets/{search-DdgUAUi7.js → search-C5H14z0D.js} +2 -2
  99. package/web-dist/assets/{search-DdgUAUi7.js.map → search-C5H14z0D.js.map} +1 -1
  100. package/web-dist/assets/settings-B0IbaTOd.js +12 -0
  101. package/web-dist/assets/settings-B0IbaTOd.js.map +1 -0
  102. package/web-dist/assets/{states-DM6omTC-.js → states-hyf_ATdQ.js} +4 -4
  103. package/web-dist/assets/states-hyf_ATdQ.js.map +1 -0
  104. package/web-dist/assets/{terminal-DKqo1lis.js → terminal-CATQN_17.js} +2 -2
  105. package/web-dist/assets/{terminal-DKqo1lis.js.map → terminal-CATQN_17.js.map} +1 -1
  106. package/web-dist/assets/terminal-login-BdkmJdOO.js +2 -0
  107. package/web-dist/assets/{terminal-login-CK1PXQq9.js.map → terminal-login-BdkmJdOO.js.map} +1 -1
  108. package/web-dist/assets/{timer-CDGYPIoD.js → timer-DFrvOKOy.js} +2 -2
  109. package/web-dist/assets/{timer-CDGYPIoD.js.map → timer-DFrvOKOy.js.map} +1 -1
  110. package/web-dist/assets/{useBreakpoint-kT0J1Dnk.js → useBreakpoint-BYCN9s8X.js} +2 -2
  111. package/web-dist/assets/{useBreakpoint-kT0J1Dnk.js.map → useBreakpoint-BYCN9s8X.js.map} +1 -1
  112. package/web-dist/assets/useNow-DXyC-YfE.js +2 -0
  113. package/web-dist/assets/{useNow-DOQOgv7k.js.map → useNow-DXyC-YfE.js.map} +1 -1
  114. package/web-dist/assets/{useResource-OCKiw9Xe.js → useResource-DYNGG9XS.js} +2 -2
  115. package/web-dist/assets/{useResource-OCKiw9Xe.js.map → useResource-DYNGG9XS.js.map} +1 -1
  116. package/web-dist/assets/workboard-BJCZsLp5.js +3 -0
  117. package/web-dist/assets/workboard-BJCZsLp5.js.map +1 -0
  118. package/web-dist/index.html +7 -8
  119. package/web-dist/sw.js +1 -1
  120. package/web-dist/sw.js.map +1 -1
  121. package/web-dist/assets/AutomationView-X-U6Fpm7.js +0 -2
  122. package/web-dist/assets/Button-BKQW9doW.js +0 -2
  123. package/web-dist/assets/Button-BKQW9doW.js.map +0 -1
  124. package/web-dist/assets/Copy-CdlOSzns.js +0 -2
  125. package/web-dist/assets/Copy-CdlOSzns.js.map +0 -1
  126. package/web-dist/assets/InteractionCard-CMLAH54x.js +0 -4
  127. package/web-dist/assets/InteractionCard-CMLAH54x.js.map +0 -1
  128. package/web-dist/assets/Select-YFnt2Br2.js +0 -2
  129. package/web-dist/assets/Tabs-DrFCe494.js +0 -2
  130. package/web-dist/assets/UnfilteredNote-C44Gi9gP.js +0 -2
  131. package/web-dist/assets/ViewSelect-Dr9Akgak.js +0 -2
  132. package/web-dist/assets/ViewSelect-Dr9Akgak.js.map +0 -1
  133. package/web-dist/assets/api-Dbc6zmlY.js +0 -2
  134. package/web-dist/assets/api-Dbc6zmlY.js.map +0 -1
  135. package/web-dist/assets/attention-BWVl_pfs.js +0 -2
  136. package/web-dist/assets/attention-BWVl_pfs.js.map +0 -1
  137. package/web-dist/assets/automations-CkbEL-3K.js +0 -2
  138. package/web-dist/assets/board-DRNTDqMF.js +0 -6
  139. package/web-dist/assets/check-DTN2VHtE.js +0 -2
  140. package/web-dist/assets/chevron-right-aaHL5Igi.js +0 -2
  141. package/web-dist/assets/code-0I1wn1N7.js +0 -25
  142. package/web-dist/assets/code-0I1wn1N7.js.map +0 -1
  143. package/web-dist/assets/enroll--c9VSPgK.js +0 -2
  144. package/web-dist/assets/index-9TW72kVM.css +0 -2
  145. package/web-dist/assets/index-C6YuwL8H.js +0 -17
  146. package/web-dist/assets/index-C6YuwL8H.js.map +0 -1
  147. package/web-dist/assets/more-Dca-1nh1.js +0 -2
  148. package/web-dist/assets/policyLogic-Bs-3OIqh.js +0 -2
  149. package/web-dist/assets/policyLogic-Bs-3OIqh.js.map +0 -1
  150. package/web-dist/assets/repo-BB50Kdri.js +0 -2
  151. package/web-dist/assets/repo-BB50Kdri.js.map +0 -1
  152. package/web-dist/assets/selection-QGVHfoxz.js +0 -7
  153. package/web-dist/assets/selection-QGVHfoxz.js.map +0 -1
  154. package/web-dist/assets/settings-BvUmCxtY.js +0 -12
  155. package/web-dist/assets/settings-BvUmCxtY.js.map +0 -1
  156. package/web-dist/assets/states-DM6omTC-.js.map +0 -1
  157. package/web-dist/assets/terminal-login-CK1PXQq9.js +0 -2
  158. package/web-dist/assets/trackers-BIhLByAc.js +0 -2
  159. package/web-dist/assets/trackers-BIhLByAc.js.map +0 -1
  160. package/web-dist/assets/useNow-DOQOgv7k.js +0 -2
  161. package/web-dist/assets/workboard-C0XpNo0s.js +0 -3
  162. package/web-dist/assets/workboard-C0XpNo0s.js.map +0 -1
@@ -1165,26 +1165,37 @@ var View = z6.object({
1165
1165
  projectIds: z6.array(z6.string()).nullable(),
1166
1166
  hostIds: z6.array(z6.string()).nullable(),
1167
1167
  sessionIds: z6.array(z6.string()),
1168
- /** Deprecated: always empty; see Surface. */
1168
+ /** Deprecated: always empty; see Terminal. */
1169
1169
  clients: z6.array(ViewClient).default([]),
1170
1170
  /** A tracker keeps this view's projects (see docs/trackers.md). */
1171
1171
  trackerId: z6.string().nullable().optional(),
1172
1172
  createdAt: Iso,
1173
1173
  updatedAt: Iso
1174
1174
  });
1175
- var SurfaceKind = z6.enum(["herdr", "tmux"]);
1176
- var Surface = z6.object({
1175
+ var TerminalKind = z6.enum(["herdr", "tmux"]);
1176
+ var TerminalMirror = z6.enum(["none", "all", "view"]);
1177
+ var Terminal = z6.object({
1177
1178
  /** `${kind}:${name}@${machine}` */
1178
1179
  id: z6.string().min(1).max(200),
1179
- kind: SurfaceKind,
1180
+ kind: TerminalKind,
1180
1181
  name: z6.string().min(1),
1181
1182
  machine: z6.string().min(1),
1182
1183
  deviceId: Id4,
1183
1184
  hostId: Id4.nullable(),
1185
+ /** What it mirrors (coordinator-owned); older records have only `viewId`. */
1186
+ mirror: TerminalMirror.optional(),
1187
+ /** The view it mirrors when `mirror` is "view" (coordinator-owned). */
1184
1188
  viewId: Id4.nullable(),
1189
+ /** When the binding was recorded; null when it never was (a daemon may seed it once). */
1190
+ bindingSetAt: Iso.nullable().optional(),
1191
+ /** Sessions it shows in mirror tabs or windows now (daemon-owned). */
1192
+ shows: z6.array(Id4).max(1e3).optional(),
1185
1193
  lastSeenAt: Iso,
1186
1194
  createdAt: Iso
1187
1195
  });
1196
+ function terminalMirror(t) {
1197
+ return t.mirror ?? (t.viewId ? "view" : "none");
1198
+ }
1188
1199
  var RuntimeState = z6.enum([
1189
1200
  "starting",
1190
1201
  "idle",
@@ -1246,6 +1257,14 @@ var Session = z6.object({
1246
1257
  * in, when known). Switchyard never shows or closes that terminal.
1247
1258
  */
1248
1259
  external: z6.object({ client: z6.string().min(1).max(200).nullable() }).nullable().optional(),
1260
+ /**
1261
+ * Where this Pi last ran by hand (host-owned): the terminal (`herdr:<s>@<m>`, `tmux:<s>@<m>`)
1262
+ * and pane. Kept after it stops; cleared once Switchyard starts it. Older hosts omit it.
1263
+ */
1264
+ place: z6.object({
1265
+ terminalId: z6.string().min(1).max(200),
1266
+ pane: z6.string().min(1).max(200).nullable()
1267
+ }).nullable().optional(),
1249
1268
  /** The session this subagent was started by (coordinator-owned). */
1250
1269
  parentSessionId: Id4.nullable().optional(),
1251
1270
  /** Chosen as its branch's primary session (coordinator-owned); without one the primary is derived. */
@@ -1480,6 +1499,11 @@ var AttentionReason = z6.enum([
1480
1499
  "host_unreachable",
1481
1500
  "cache_expiring"
1482
1501
  ]);
1502
+ var INPUT_ATTENTION_REASONS = [
1503
+ "needs_input",
1504
+ "unsupported_interaction"
1505
+ ];
1506
+ var isInputAttentionReason = (r) => INPUT_ATTENTION_REASONS.includes(r);
1483
1507
  var AttentionItem = z6.object({
1484
1508
  id: Id4,
1485
1509
  sessionId: Id4.nullable(),
@@ -2216,13 +2240,15 @@ var EventDataSchemas = {
2216
2240
  "device.updated": Device,
2217
2241
  "issue.updated": TrackedIssue,
2218
2242
  "issue.deleted": z11.object({ id: z11.string() }),
2219
- "surface.updated": Surface,
2220
- "surface.deleted": z11.object({ id: z11.string() }),
2243
+ "terminal.updated": Terminal,
2244
+ "terminal.deleted": z11.object({ id: z11.string() }),
2221
2245
  "settings.updated": z11.object({ dispatchPaused: z11.boolean() })
2222
2246
  };
2223
2247
  var EVENT_TYPES = Object.keys(EventDataSchemas);
2224
2248
  var LEGACY_EVENT_TYPES = {
2225
- "workspace.removed": "workspace.deleted"
2249
+ "workspace.removed": "workspace.deleted",
2250
+ "surface.updated": "terminal.updated",
2251
+ "surface.deleted": "terminal.deleted"
2226
2252
  };
2227
2253
  function canonicalEventType(type) {
2228
2254
  return LEGACY_EVENT_TYPES[type] ?? type;
@@ -3135,7 +3161,17 @@ var MeResponse = z14.object({
3135
3161
  admin: z14.boolean(),
3136
3162
  publicUrl: z14.string()
3137
3163
  });
3138
- var SurfaceReport = Surface.pick({
3164
+ var TerminalBindingInput = z14.object({ mirror: TerminalMirror, viewId: z14.string().min(1).nullable().optional() }).refine((b) => b.mirror === "view" === !!b.viewId, {
3165
+ message: "viewId is required for mirror=view and only then"
3166
+ });
3167
+ var TerminalReport = Terminal.pick({ kind: true, name: true, machine: true }).extend({
3168
+ hostId: z14.string().nullable().optional(),
3169
+ /** Sessions in its mirror tabs or windows; omitted when unchanged or unknown. */
3170
+ shows: z14.array(z14.string()).max(1e3).optional(),
3171
+ /** The binding this terminal had before bindings were recorded (env file); applied only when none is recorded. */
3172
+ seed: TerminalBindingInput.optional()
3173
+ });
3174
+ var SurfaceReport = Terminal.pick({
3139
3175
  kind: true,
3140
3176
  name: true,
3141
3177
  machine: true,
@@ -3165,7 +3201,7 @@ function reconnectDelay(attempt, steps = RECONNECT_BACKOFF_MS, random = Math.ran
3165
3201
  }
3166
3202
 
3167
3203
  // packages/protocol/dist/views.js
3168
- var SURFACE_OPEN_MS = 10 * 6e4;
3204
+ var TERMINAL_OPEN_MS = 10 * 6e4;
3169
3205
  var LIVE_RUNTIMES = ["starting", "idle", "running", "waiting_input"];
3170
3206
  function isLiveRuntime(r) {
3171
3207
  return LIVE_RUNTIMES.includes(r);
@@ -3224,8 +3260,11 @@ ${ws.branch}`))
3224
3260
  function sessionInView(view, s, workspaces, scope) {
3225
3261
  return sessionViewReason(view, s, workspaces, scope) !== null;
3226
3262
  }
3227
- function openSurfaces(surfaces, viewId, now = Date.now()) {
3228
- return surfaces.filter((c) => c.viewId === viewId && now - Date.parse(c.lastSeenAt) < SURFACE_OPEN_MS).sort((a, b) => a.kind.localeCompare(b.kind) || a.name.localeCompare(b.name));
3263
+ function terminalOpen(t, now = Date.now()) {
3264
+ return now - Date.parse(t.lastSeenAt) < TERMINAL_OPEN_MS;
3265
+ }
3266
+ function openTerminals(terminals, viewId, now = Date.now()) {
3267
+ return terminals.filter((c) => terminalMirror(c) === "view" && c.viewId === viewId && terminalOpen(c, now)).sort((a, b) => a.kind.localeCompare(b.kind) || a.name.localeCompare(b.name));
3229
3268
  }
3230
3269
  function findView(views, ref) {
3231
3270
  const byId3 = views.find((v) => v.id === ref);
@@ -3423,15 +3462,22 @@ var SyncState = z15.object({
3423
3462
  devices: z15.array(Device),
3424
3463
  /** Tracked issues; absent from older coordinators. */
3425
3464
  issues: z15.array(TrackedIssue).default([]),
3426
- /** Terminal surfaces; absent from older coordinators. */
3427
- surfaces: z15.array(Surface).default([]),
3465
+ /** Terminals (herdr and tmux sessions); absent from older coordinators. */
3466
+ terminals: z15.array(Terminal).optional(),
3467
+ /** Deprecated: terminals as older coordinators send them (`terminals` replaces it). */
3468
+ surfaces: z15.array(Terminal).optional(),
3428
3469
  adapters: z15.record(z15.string(), z15.array(AdapterInfo)),
3429
3470
  dispatchPaused: z15.boolean()
3430
3471
  });
3431
3472
  var Presence = z15.object({
3432
3473
  foreground: z15.boolean(),
3433
3474
  interactedAt: z15.string().nullable(),
3434
- viewing: z15.object({ sessionId: z15.string() }).nullable()
3475
+ viewing: z15.object({ sessionId: z15.string() }).nullable(),
3476
+ /**
3477
+ * A herdr or tmux daemon reporting the session focused in its terminal (kept apart from the
3478
+ * device's own presence). Older coordinators ignore it.
3479
+ */
3480
+ terminalId: z15.string().min(1).max(200).optional()
3435
3481
  });
3436
3482
  var CLIENT_CAPABILITIES = ["adapter.slots.v1", "timeline.cards.v1"];
3437
3483
  var ClientToServer = z15.discriminatedUnion("type", [
@@ -3601,7 +3647,7 @@ function emptyState() {
3601
3647
  interactions: {},
3602
3648
  panels: {},
3603
3649
  devices: {},
3604
- surfaces: {},
3650
+ terminals: {},
3605
3651
  issues: {},
3606
3652
  dispatchPaused: false
3607
3653
  };
@@ -3652,7 +3698,7 @@ function applySnapshot(state, seq, snap) {
3652
3698
  interactions: byId(snap.interactions),
3653
3699
  panels,
3654
3700
  devices: byId(snap.devices),
3655
- surfaces: byId(snap.surfaces ?? []),
3701
+ terminals: byId(snap.terminals ?? snap.surfaces ?? []),
3656
3702
  issues: byId(snap.issues ?? []),
3657
3703
  dispatchPaused: snap.dispatchPaused
3658
3704
  };
@@ -3776,13 +3822,13 @@ function reduceEvent(state, type, data) {
3776
3822
  const d = data;
3777
3823
  return { ...state, issues: drop(state.issues, d.id) };
3778
3824
  }
3779
- case "surface.updated": {
3825
+ case "terminal.updated": {
3780
3826
  const d = data;
3781
- return { ...state, surfaces: put(state.surfaces, d.id, d) };
3827
+ return { ...state, terminals: put(state.terminals, d.id, d) };
3782
3828
  }
3783
- case "surface.deleted": {
3829
+ case "terminal.deleted": {
3784
3830
  const d = data;
3785
- return { ...state, surfaces: drop(state.surfaces, d.id) };
3831
+ return { ...state, terminals: drop(state.terminals, d.id) };
3786
3832
  }
3787
3833
  case "settings.updated": {
3788
3834
  const d = data;
@@ -6916,7 +6962,7 @@ function isEnrollMeta(v) {
6916
6962
  if (!v || typeof v !== "object")
6917
6963
  return false;
6918
6964
  const m = v;
6919
- return typeof m.pid === "number" && Number.isInteger(m.pid) && m.pid > 0 && typeof m.cwd === "string" && m.cwd.startsWith("/") && (m.client === null || typeof m.client === "string") && typeof m.sessionId === "string" && m.sessionId.length > 0 && typeof m.sessionFile === "string" && m.sessionFile.length > 0 && typeof m.startedAt === "string";
6965
+ return typeof m.pid === "number" && Number.isInteger(m.pid) && m.pid > 0 && typeof m.cwd === "string" && m.cwd.startsWith("/") && (m.client === null || typeof m.client === "string") && (m.pane === void 0 || m.pane === null || typeof m.pane === "string") && typeof m.sessionId === "string" && m.sessionId.length > 0 && typeof m.sessionFile === "string" && m.sessionFile.length > 0 && typeof m.startedAt === "string";
6920
6966
  }
6921
6967
  function readEnrollMeta(socketPath) {
6922
6968
  try {
@@ -11343,15 +11389,15 @@ var HostDb = class {
11343
11389
  else
11344
11390
  fn();
11345
11391
  }
11346
- run(sql21, params = []) {
11347
- const r = this.db.prepare(sql21).run(...params);
11392
+ run(sql23, params = []) {
11393
+ const r = this.db.prepare(sql23).run(...params);
11348
11394
  return { changes: Number(r.changes), lastInsertRowid: Number(r.lastInsertRowid) };
11349
11395
  }
11350
- get(sql21, params = []) {
11351
- return this.db.prepare(sql21).get(...params);
11396
+ get(sql23, params = []) {
11397
+ return this.db.prepare(sql23).get(...params);
11352
11398
  }
11353
- all(sql21, params = []) {
11354
- return this.db.prepare(sql21).all(...params);
11399
+ all(sql23, params = []) {
11400
+ return this.db.prepare(sql23).all(...params);
11355
11401
  }
11356
11402
  // ---- meta ----
11357
11403
  getMeta(key) {
@@ -11361,12 +11407,12 @@ var HostDb = class {
11361
11407
  this.run("INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value", [key, value]);
11362
11408
  }
11363
11409
  // ---- JSON row helpers ----
11364
- getJson(sql21, params = []) {
11365
- const r = this.get(sql21, params);
11410
+ getJson(sql23, params = []) {
11411
+ const r = this.get(sql23, params);
11366
11412
  return r ? JSON.parse(r.json) : void 0;
11367
11413
  }
11368
- allJson(sql21, params = []) {
11369
- return this.all(sql21, params).map((r) => JSON.parse(r.json));
11414
+ allJson(sql23, params = []) {
11415
+ return this.all(sql23, params).map((r) => JSON.parse(r.json));
11370
11416
  }
11371
11417
  close() {
11372
11418
  try {
@@ -15032,6 +15078,7 @@ var RESTART_TERMINAL_LOST_DETAIL = "Host agent restarted and the terminal sessio
15032
15078
  var terminalLostNotice = (reason3) => `Host agent restarted and the terminal session had ended (${reason3}); resume to continue`;
15033
15079
  var QUEUED_ANSWER_SUMMARY = "Answered from your earlier form";
15034
15080
  var PI_CLOSED_SUMMARY = "Pi closed this question (timeout or abort)";
15081
+ var PI_EXITED_SUMMARY = "Pi exited before this question was answered";
15035
15082
  var UNSUPPORTED_TITLE = "Terminal-only interface requested";
15036
15083
  var UNSUPPORTED_TEXT = "An extension opened a terminal-only dialog. In RPC mode Pi gave it no answer, so the extension continued without one.";
15037
15084
  var PROMPT_NOT_SENT = "The launch prompt was not sent to Pi";
@@ -15241,7 +15288,7 @@ var SessionSupervisor = class {
15241
15288
  rec.queue = { steering: [], followUp: [] };
15242
15289
  rec.terminal = null;
15243
15290
  rec.external = null;
15244
- this.expirePending(rec.id, lost.expireSummary);
15291
+ this.expirePending(rec.id, lost.expireSummary, true);
15245
15292
  if (next === "interrupted") {
15246
15293
  const item = {
15247
15294
  id: newId("itm"),
@@ -15732,6 +15779,7 @@ var SessionSupervisor = class {
15732
15779
  rec.runtimeDetail = "Attaching to your terminal\u2026";
15733
15780
  rec.terminal = { socketPath };
15734
15781
  rec.external = { client: meta.client };
15782
+ rec.place = meta.client ? { terminalId: meta.client, pane: meta.pane ?? null } : null;
15735
15783
  rec.endedAt = null;
15736
15784
  rec.lastActivityAt = now;
15737
15785
  this.records.set(rec.id, rec);
@@ -15780,6 +15828,7 @@ var SessionSupervisor = class {
15780
15828
  createdAt: rec.createdAt,
15781
15829
  terminal: rec.terminal != null && !rec.external,
15782
15830
  external: rec.external ?? null,
15831
+ place: rec.place ?? null,
15783
15832
  ...rec.bridge ? { bridge: rec.bridge } : {},
15784
15833
  ...rec.adapterGeneration ? { adapterGeneration: rec.adapterGeneration } : {}
15785
15834
  };
@@ -16002,6 +16051,7 @@ var SessionSupervisor = class {
16002
16051
  }, "session started");
16003
16052
  const socketPath = ms.terminalSocket;
16004
16053
  rec.terminal = socketPath ? { socketPath } : null;
16054
+ rec.place = null;
16005
16055
  this.db.tx(() => this.saveAndEmit(rec));
16006
16056
  } catch (err) {
16007
16057
  if (ms.process)
@@ -16753,7 +16803,17 @@ var SessionSupervisor = class {
16753
16803
  rec.external = null;
16754
16804
  this.db.tx(() => this.saveAndEmit(rec));
16755
16805
  }
16756
- void l.chain.finally(() => this.teardown(l));
16806
+ void l.chain.finally(() => {
16807
+ if (!this.closing && this.live.get(rec.id) === l) {
16808
+ l.terminalPrompt = null;
16809
+ try {
16810
+ this.db.tx(() => this.expirePending(rec.id, PI_EXITED_SUMMARY, true));
16811
+ } catch (err) {
16812
+ this.opts.log.warn({ sessionId: rec.id, err: errorMessage2(err) }, "could not expire questions after Pi exited");
16813
+ }
16814
+ }
16815
+ this.teardown(l);
16816
+ });
16757
16817
  });
16758
16818
  }
16759
16819
  teardown(l) {
@@ -17104,7 +17164,7 @@ var SessionSupervisor = class {
17104
17164
  state: "expired",
17105
17165
  resolution: {
17106
17166
  by: "pi",
17107
- summary: r.by === "pi" ? PI_CLOSED_SUMMARY : "Pi exited before this question was answered",
17167
+ summary: r.by === "pi" ? PI_CLOSED_SUMMARY : PI_EXITED_SUMMARY,
17108
17168
  at: nowIso()
17109
17169
  }
17110
17170
  });
@@ -17338,8 +17398,13 @@ var SessionSupervisor = class {
17338
17398
  });
17339
17399
  return next;
17340
17400
  }
17341
- expirePending(sessionId, summary) {
17342
- for (const i of this.pendingInteractions(sessionId)) {
17401
+ /**
17402
+ * Expire a session's pending questions. With `pi_gone`, also its unanswered terminal-only
17403
+ * dialogs: nothing can answer them once Pi has exited.
17404
+ */
17405
+ expirePending(sessionId, summary, piGone = false) {
17406
+ const open3 = piGone ? this.db.allJson("SELECT json FROM interactions WHERE session_id = ? AND state IN ('pending', 'unsupported') ORDER BY rowid", [sessionId]).filter((i) => i.state === "pending" || i.resolution === null) : this.pendingInteractions(sessionId);
17407
+ for (const i of open3) {
17343
17408
  this.updateInteraction(i, {
17344
17409
  state: "expired",
17345
17410
  resolution: { by: "host", summary, at: nowIso() }
@@ -18439,14 +18504,53 @@ var AttentionService = class {
18439
18504
  resolve(filter) {
18440
18505
  return this.store.tx(() => {
18441
18506
  const items = this.open(filter).filter((a) => !filter.interactionId || a.interactionId === filter.interactionId);
18442
- const now = this.store.nowIso();
18443
- const out = [];
18444
- for (const a of items) {
18445
- const resolved = this.store.putAttention({ ...a, resolvedAt: now });
18446
- out.push(resolved);
18447
- this.store.afterCommit(() => this.hub.emit("attention.resolved", resolved));
18448
- }
18449
- return out;
18507
+ return items.map((a) => this.resolveItem(a));
18508
+ });
18509
+ }
18510
+ /** Resolve one open item. Call in a transaction. */
18511
+ resolveItem(a, patch = {}) {
18512
+ const resolved = this.store.putAttention({ ...a, ...patch, resolvedAt: this.store.nowIso() });
18513
+ this.store.afterCommit(() => this.hub.emit("attention.resolved", resolved));
18514
+ return resolved;
18515
+ }
18516
+ /**
18517
+ * A session's Pi stopped: nothing it asked can be answered any more, whatever raised it (Pi, an
18518
+ * adapter, a terminal-only dialog). Expire its open interactions and resolve its input attention.
18519
+ * Hosts expire their own copies too, but hosts one release behind do not for every kind, and the
18520
+ * coordinator owns what the web shows. Joins the caller's transaction.
18521
+ */
18522
+ endSessionInput(sessionId, summary = "Pi stopped before this was answered") {
18523
+ return this.store.tx(() => {
18524
+ const session = this.store.sessions.get(sessionId);
18525
+ const scope = {
18526
+ ...session ? { hostId: session.hostId } : {},
18527
+ ...session?.projectId ? { projectId: session.projectId } : {}
18528
+ };
18529
+ const at = this.store.nowIso();
18530
+ const listed = this.store.interactions.list("session_id = ? AND state IN ('pending', 'unsupported')", [sessionId], "created_at").filter((i) => i.state === "pending" || i.resolution === null);
18531
+ const policy = new Set(listed.filter((i) => i.permission?.kind === "policy").map((i) => i.id));
18532
+ const open3 = listed.filter((i) => !policy.has(i.id));
18533
+ for (const i of open3) {
18534
+ this.store.putInteraction({
18535
+ ...i,
18536
+ state: "expired",
18537
+ revision: i.revision + 1,
18538
+ resolution: { by: "coordinator", summary, at }
18539
+ }, scope);
18540
+ }
18541
+ const items = this.open({ sessionId }).filter((a) => INPUT_ATTENTION_REASONS.includes(a.reason) && !(a.interactionId && policy.has(a.interactionId)));
18542
+ for (const a of items)
18543
+ this.resolveItem(a);
18544
+ return { interactions: open3.length, attention: items.length };
18545
+ });
18546
+ }
18547
+ /** Dismiss: resolve one item by hand, so it stops flagging its session or task. */
18548
+ dismiss(id) {
18549
+ return this.store.tx(() => {
18550
+ const a = this.store.attention.require(id);
18551
+ if (a.resolvedAt)
18552
+ return a;
18553
+ return this.resolveItem(a, { acknowledgedAt: a.acknowledgedAt ?? this.store.nowIso() });
18450
18554
  });
18451
18555
  }
18452
18556
  acknowledge(id) {
@@ -18740,9 +18844,6 @@ var Auth = class {
18740
18844
  push: { ...d.push, subscribed: false }
18741
18845
  };
18742
18846
  this.store.deletePushSubscriptionsForDevice(id);
18743
- for (const x of this.store.surfaces.list("device_id = ?", [id])) {
18744
- this.store.deleteSurface(x.id);
18745
- }
18746
18847
  return this.store.putDevice(updated);
18747
18848
  });
18748
18849
  this.hub.emit("device.revoked", { deviceId: id });
@@ -27481,6 +27582,7 @@ var ClientHub = class {
27481
27582
  const p = msg.presence;
27482
27583
  this.store.upsertPresence({
27483
27584
  deviceId: conn.deviceId,
27585
+ terminalId: p.terminalId ?? null,
27484
27586
  foregroundUntil: p.foreground ? new Date(now.getTime() + this.opts.foregroundLeaseMs).toISOString() : null,
27485
27587
  interactedAt: p.interactedAt,
27486
27588
  viewingSessionId: p.viewing?.sessionId ?? null,
@@ -28223,6 +28325,35 @@ UPDATE sessions SET json = json_remove(json, '$.startedIn')
28223
28325
  WHERE json_type(json, '$.startedIn') IS NOT NULL;
28224
28326
  `;
28225
28327
 
28328
+ // packages/coordinator/dist/db/migrations/021_terminals.js
28329
+ var sql21 = `
28330
+ ALTER TABLE surfaces RENAME TO terminals;
28331
+ DROP INDEX surfaces_device;
28332
+ CREATE INDEX terminals_device ON terminals(device_id);
28333
+ UPDATE terminals SET json = json_set(
28334
+ json,
28335
+ '$.mirror', CASE WHEN view_id IS NULL THEN 'none' ELSE 'view' END,
28336
+ '$.bindingSetAt', CASE WHEN view_id IS NULL THEN NULL ELSE last_seen_at END,
28337
+ '$.shows', json('[]')
28338
+ );
28339
+ UPDATE events SET type = 'terminal.updated' WHERE type = 'surface.updated';
28340
+ UPDATE events SET type = 'terminal.deleted' WHERE type = 'surface.deleted';
28341
+ `;
28342
+
28343
+ // packages/coordinator/dist/db/migrations/022_terminal_presence.js
28344
+ var sql22 = `
28345
+ DROP TABLE presence;
28346
+ CREATE TABLE presence (
28347
+ device_id TEXT NOT NULL,
28348
+ terminal_id TEXT NOT NULL DEFAULT '',
28349
+ foreground_until TEXT,
28350
+ interacted_at TEXT,
28351
+ viewing_session_id TEXT,
28352
+ updated_at TEXT NOT NULL,
28353
+ PRIMARY KEY (device_id, terminal_id)
28354
+ );
28355
+ `;
28356
+
28226
28357
  // packages/coordinator/dist/db/index.js
28227
28358
  var MIGRATIONS2 = [
28228
28359
  { version: 1, name: "001_init", sql },
@@ -28244,7 +28375,9 @@ var MIGRATIONS2 = [
28244
28375
  { version: 17, name: "017_surfaces", sql: sql17 },
28245
28376
  { version: 18, name: "018_panel_event_seq", sql: sql18 },
28246
28377
  { version: 19, name: "019_unread_needs_output", sql: sql19 },
28247
- { version: 20, name: "020_drop_view_sources", sql: sql20 }
28378
+ { version: 20, name: "020_drop_view_sources", sql: sql20 },
28379
+ { version: 21, name: "021_terminals", sql: sql21 },
28380
+ { version: 22, name: "022_terminal_presence", sql: sql22 }
28248
28381
  ];
28249
28382
  var LATEST_MIGRATION = MIGRATIONS2[MIGRATIONS2.length - 1].version;
28250
28383
  function openDb(path3) {
@@ -28413,6 +28546,7 @@ async function refreshSubagentTranscript(ctx, session) {
28413
28546
  // packages/coordinator/dist/host-hub.js
28414
28547
  var HOST_SESSION_FIELDS = [
28415
28548
  "external",
28549
+ "place",
28416
28550
  "title",
28417
28551
  "subtitle",
28418
28552
  "cwd",
@@ -29197,11 +29331,15 @@ var HostHub = class {
29197
29331
  this.store.appendEvent("diagnostic", { hostId, sessionId: d.sessionId ?? void 0 }, d);
29198
29332
  const att = raw.attention;
29199
29333
  const sessionId = d.sessionId ?? ev.sessionId ?? null;
29200
- if (att && typeof att === "object" && sessionId && this.ownedSession(hostId, sessionId)) {
29334
+ const owned = att && typeof att === "object" && sessionId ? this.ownedSession(hostId, sessionId) : void 0;
29335
+ if (att && owned && sessionId) {
29201
29336
  const given = att.reason ?? "needs_input";
29202
- const reason3 = AttentionReason.safeParse(given);
29337
+ const parsed = AttentionReason.safeParse(given);
29338
+ const reason3 = parsed.success ? parsed.data : "unsupported_interaction";
29339
+ if (isInputAttentionReason(reason3) && !isLiveRuntime(owned.runtime))
29340
+ return;
29203
29341
  this.attention.raise({
29204
- reason: reason3.success ? reason3.data : "unsupported_interaction",
29342
+ reason: reason3,
29205
29343
  sessionId,
29206
29344
  summary: typeof att.summary === "string" && att.summary.trim() ? att.summary.slice(0, 500) : d.message
29207
29345
  });
@@ -29321,6 +29459,8 @@ var HostHub = class {
29321
29459
  if (existing && JSON.stringify(existing) === JSON.stringify(next))
29322
29460
  return;
29323
29461
  this.store.putSession(next);
29462
+ if (!isLiveRuntime(next.runtime))
29463
+ this.attention.endSessionInput(id);
29324
29464
  if (partial.bridge !== void 0) {
29325
29465
  this.store.afterCommit(() => this.retryDeferred(hostId));
29326
29466
  }
@@ -29355,6 +29495,18 @@ var HostHub = class {
29355
29495
  }
29356
29496
  /** Keep `needs_input` / `unsupported_interaction` attention in line with interaction state. */
29357
29497
  reconcileInputAttention(i) {
29498
+ const session = this.store.sessions.get(i.sessionId);
29499
+ if (session && !isLiveRuntime(session.runtime) && i.permission?.kind !== "policy" && (i.state === "pending" || i.state === "unsupported" && !i.resolution)) {
29500
+ this.attention.endSessionInput(i.sessionId);
29501
+ return;
29502
+ }
29503
+ if (i.state !== "unsupported") {
29504
+ this.attention.resolve({
29505
+ sessionId: i.sessionId,
29506
+ reason: "unsupported_interaction",
29507
+ interactionId: i.id
29508
+ });
29509
+ }
29358
29510
  if (i.state === "pending") {
29359
29511
  this.attention.raise({
29360
29512
  reason: "needs_input",
@@ -30140,6 +30292,7 @@ function registerAttentionRoutes(app, ctx) {
30140
30292
  return ctx.store.attention.list(where.join(" AND ") || void 0, params, `${orderBy} LIMIT ${q.limit}`);
30141
30293
  });
30142
30294
  app.post("/api/attention/:id/acknowledge", async (req) => ctx.attention.acknowledge(req.params.id));
30295
+ app.post("/api/attention/:id/dismiss", async (req) => ctx.attention.dismiss(req.params.id));
30143
30296
  }
30144
30297
 
30145
30298
  // packages/coordinator/dist/routes/auth.js
@@ -30509,14 +30662,13 @@ function archiveEndedSessions(store, days = sessionArchiveDays(store)) {
30509
30662
  const now = store.nowIso();
30510
30663
  const cutoff = new Date(Date.parse(now) - days * 864e5).toISOString();
30511
30664
  const sessions = store.sessions.list("archived_at IS NULL");
30512
- const pinned = new Set(store.views.list().flatMap((v) => v.sessionIds));
30513
- const waiting = new Set(store.interactions.list("state IN ('pending', 'unsupported')").map((i) => i.sessionId));
30665
+ const waiting = new Set(store.interactions.list("state IN ('pending', 'unsupported')").filter((i) => i.state === "pending" || i.resolution === null).map((i) => i.sessionId));
30514
30666
  const { branches } = buildBranches({
30515
30667
  workspaces: store.workspaces.list("archived_at IS NULL"),
30516
30668
  sessions,
30517
30669
  issues: []
30518
30670
  });
30519
- const stale3 = (s) => !isLiveRuntime(s.runtime) && s.lastActivityAt < cutoff && s.taskId === null && !pinned.has(s.id) && !waiting.has(s.id);
30671
+ const stale3 = (s) => !isLiveRuntime(s.runtime) && s.lastActivityAt < cutoff && s.taskId === null && !waiting.has(s.id);
30520
30672
  const archived = /* @__PURE__ */ new Map();
30521
30673
  const archive = (s) => {
30522
30674
  archived.set(s.id, store.putSession({ ...s, archivedAt: now }));
@@ -30528,7 +30680,7 @@ function archiveEndedSessions(store, days = sessionArchiveDays(store)) {
30528
30680
  const known = new Map(sessions.map((s) => [s.id, s]));
30529
30681
  for (const b of branches) {
30530
30682
  for (const s of b.subagents) {
30531
- if (isLiveRuntime(s.runtime) || waiting.has(s.id) || pinned.has(s.id))
30683
+ if (isLiveRuntime(s.runtime) || waiting.has(s.id))
30532
30684
  continue;
30533
30685
  const parentGone = !!s.parentSessionId && (archived.has(s.parentSessionId) || !known.has(s.parentSessionId));
30534
30686
  if (parentGone || stale3(s))
@@ -30541,6 +30693,38 @@ function archiveEndedSessions(store, days = sessionArchiveDays(store)) {
30541
30693
  function sessionArchiveDays(store) {
30542
30694
  return store.getSetting("sessionArchiveDays", DEFAULT_SESSION_ARCHIVE_DAYS);
30543
30695
  }
30696
+ function sweepStaleSessionState(store, attention) {
30697
+ return store.tx(() => {
30698
+ const ids2 = /* @__PURE__ */ new Set();
30699
+ const reasons = INPUT_ATTENTION_REASONS.map(() => "?").join(", ");
30700
+ for (const a of store.attention.list(`resolved_at IS NULL AND session_id IS NOT NULL AND reason IN (${reasons})`, [...INPUT_ATTENTION_REASONS]))
30701
+ ids2.add(a.sessionId);
30702
+ for (const i of store.interactions.list("state IN ('pending', 'unsupported')"))
30703
+ if (i.state === "pending" || i.resolution === null)
30704
+ ids2.add(i.sessionId);
30705
+ let sessions = 0;
30706
+ for (const id of ids2) {
30707
+ const s = store.sessions.get(id);
30708
+ if (s && isLiveRuntime(s.runtime))
30709
+ continue;
30710
+ const r = attention.endSessionInput(id);
30711
+ if (r.interactions + r.attention > 0)
30712
+ sessions++;
30713
+ }
30714
+ let pins = 0;
30715
+ for (const v of store.views.list()) {
30716
+ const kept = v.sessionIds.filter((id) => {
30717
+ const s = store.sessions.get(id);
30718
+ return !!s && s.archivedAt === null;
30719
+ });
30720
+ if (kept.length === v.sessionIds.length)
30721
+ continue;
30722
+ pins += v.sessionIds.length - kept.length;
30723
+ store.putView({ ...v, sessionIds: kept, updatedAt: store.nowIso() });
30724
+ }
30725
+ return { sessions, pins };
30726
+ });
30727
+ }
30544
30728
 
30545
30729
  // packages/coordinator/dist/routes/ops.js
30546
30730
  function registerOpsRoutes(app, ctx) {
@@ -31279,48 +31463,120 @@ function registerSessionRoutes(app, ctx) {
31279
31463
  });
31280
31464
  }
31281
31465
 
31282
- // packages/coordinator/dist/routes/surfaces.js
31283
- var SURFACE_REWRITE_MS = 5 * 6e4;
31284
- function reportSurface(ctx, id, body2, deviceId) {
31466
+ // packages/coordinator/dist/routes/terminals.js
31467
+ var TERMINAL_REWRITE_MS = 5 * 6e4;
31468
+ function parseTerminalId(id) {
31469
+ const m = /^(herdr|tmux):(.+)@([^@]+)$/.exec(id);
31470
+ return m ? { kind: m[1], name: m[2], machine: m[3] } : null;
31471
+ }
31472
+ function sameIds(a, b) {
31473
+ const x = a ?? [];
31474
+ const y = b ?? [];
31475
+ return x.length === y.length && x.every((v, i) => v === y[i]);
31476
+ }
31477
+ function checkedBinding(ctx, b) {
31478
+ if (b.mirror !== "view")
31479
+ return { mirror: b.mirror, viewId: null };
31480
+ ctx.store.views.require(b.viewId);
31481
+ return { mirror: "view", viewId: b.viewId };
31482
+ }
31483
+ function reportTerminal(ctx, id, body2, deviceId) {
31285
31484
  const { store } = ctx;
31286
31485
  if (id !== `${body2.kind}:${body2.name}@${body2.machine}`) {
31287
- throw new SwitchyardError("invalid_request", "Surface id does not match its kind, name and machine");
31486
+ throw new SwitchyardError("invalid_request", "Terminal id does not match its kind, name and machine");
31288
31487
  }
31289
31488
  return store.tx(() => {
31290
- if (body2.viewId !== null)
31291
- store.views.require(body2.viewId);
31292
- const existing = store.surfaces.get(id);
31489
+ const existing = store.terminals.get(id);
31293
31490
  const asked = body2.hostId === void 0 ? existing?.hostId ?? null : body2.hostId;
31294
31491
  const hostId = asked && store.hosts.get(asked) ? asked : null;
31295
31492
  const now = store.now();
31296
- if (existing && now.getTime() - Date.parse(existing.lastSeenAt) < SURFACE_REWRITE_MS && existing.kind === body2.kind && existing.name === body2.name && existing.machine === body2.machine && existing.viewId === body2.viewId && existing.hostId === hostId && existing.deviceId === deviceId) {
31493
+ let mirror = existing ? terminalMirror(existing) : "none";
31494
+ let viewId = existing?.viewId ?? null;
31495
+ let bindingSetAt = existing?.bindingSetAt ?? null;
31496
+ if (!bindingSetAt && body2.seed) {
31497
+ const b = checkedBinding(ctx, body2.seed);
31498
+ mirror = b.mirror;
31499
+ viewId = b.viewId;
31500
+ bindingSetAt = now.toISOString();
31501
+ }
31502
+ const shows = body2.shows ?? existing?.shows ?? [];
31503
+ if (existing && now.getTime() - Date.parse(existing.lastSeenAt) < TERMINAL_REWRITE_MS && existing.kind === body2.kind && existing.name === body2.name && existing.machine === body2.machine && existing.mirror === mirror && existing.viewId === viewId && (existing.bindingSetAt ?? null) === bindingSetAt && sameIds(existing.shows, shows) && existing.hostId === hostId && existing.deviceId === deviceId) {
31297
31504
  return existing;
31298
31505
  }
31299
- return store.putSurface({
31506
+ return store.putTerminal({
31300
31507
  id,
31301
31508
  kind: body2.kind,
31302
31509
  name: body2.name,
31303
31510
  machine: body2.machine,
31304
31511
  deviceId,
31305
31512
  hostId,
31306
- viewId: body2.viewId,
31513
+ mirror,
31514
+ viewId,
31515
+ bindingSetAt,
31516
+ shows,
31307
31517
  lastSeenAt: now.toISOString(),
31308
31518
  createdAt: existing?.createdAt ?? now.toISOString()
31309
31519
  });
31310
31520
  });
31311
31521
  }
31312
- function registerSurfaceRoutes(app, ctx) {
31522
+ function bindTerminal(ctx, id, input, deviceId) {
31523
+ const { store } = ctx;
31524
+ const parts = parseTerminalId(id);
31525
+ if (!parts) {
31526
+ throw new SwitchyardError("invalid_request", "A terminal id is <herdr|tmux>:<name>@<machine>");
31527
+ }
31528
+ return store.tx(() => {
31529
+ const b = checkedBinding(ctx, input);
31530
+ const existing = store.terminals.get(id);
31531
+ const now = store.nowIso();
31532
+ return store.putTerminal({
31533
+ id,
31534
+ ...parts,
31535
+ deviceId: existing?.deviceId ?? deviceId,
31536
+ hostId: existing?.hostId ?? null,
31537
+ mirror: b.mirror,
31538
+ viewId: b.viewId,
31539
+ bindingSetAt: now,
31540
+ shows: existing?.shows ?? [],
31541
+ // A terminal recorded before its daemon ever reported is not open yet.
31542
+ lastSeenAt: existing?.lastSeenAt ?? (/* @__PURE__ */ new Date(0)).toISOString(),
31543
+ createdAt: existing?.createdAt ?? now
31544
+ });
31545
+ });
31546
+ }
31547
+ function asSurface(t) {
31548
+ return { ...t, viewId: terminalMirror(t) === "view" ? t.viewId : null };
31549
+ }
31550
+ function registerTerminalRoutes(app, ctx) {
31313
31551
  const { store } = ctx;
31314
31552
  const idOf = (req) => req.params.id;
31315
- app.get("/api/surfaces", async () => store.surfaces.list(void 0, [], "created_at, rowid"));
31553
+ const list = () => store.terminals.list(void 0, [], "created_at, rowid");
31554
+ app.get("/api/terminals", async () => list());
31555
+ app.put("/api/terminals/:id", async (req) => {
31556
+ const body2 = parse2(TerminalReport, req.body);
31557
+ return reportTerminal(ctx, idOf(req), body2, deviceOf(req).id);
31558
+ });
31559
+ app.put("/api/terminals/:id/binding", async (req) => {
31560
+ const body2 = parse2(TerminalBindingInput, req.body);
31561
+ return bindTerminal(ctx, idOf(req), body2, deviceOf(req).id);
31562
+ });
31563
+ app.delete("/api/terminals/:id", async (req) => {
31564
+ store.deleteTerminal(idOf(req));
31565
+ return { ok: true, id: idOf(req) };
31566
+ });
31567
+ app.get("/api/surfaces", async () => list().map(asSurface));
31316
31568
  app.put("/api/surfaces/:id", async (req) => {
31317
31569
  const body2 = parse2(SurfaceReport, req.body);
31318
- return reportSurface(ctx, idOf(req), body2, deviceOf(req).id);
31319
- });
31320
- app.delete("/api/surfaces/:id", async (req) => {
31321
- store.deleteSurface(idOf(req));
31322
- return { ok: true, id: idOf(req) };
31570
+ const t = reportTerminal(ctx, idOf(req), {
31571
+ kind: body2.kind,
31572
+ name: body2.name,
31573
+ machine: body2.machine,
31574
+ ...body2.hostId !== void 0 ? { hostId: body2.hostId } : {},
31575
+ ...body2.viewId ? { seed: { mirror: "view", viewId: body2.viewId } } : {}
31576
+ }, deviceOf(req).id);
31577
+ return asSurface(t);
31323
31578
  });
31579
+ app.delete("/api/surfaces/:id", async (req) => ({ ok: true, id: idOf(req) }));
31324
31580
  }
31325
31581
 
31326
31582
  // packages/coordinator/dist/routes/views.js
@@ -31376,8 +31632,8 @@ function registerViewRoutes(app, ctx) {
31376
31632
  });
31377
31633
  app.delete("/api/views/:id", async (req) => store.tx(() => {
31378
31634
  const v = store.views.require(idOf(req));
31379
- for (const x of store.surfaces.list("view_id = ?", [v.id])) {
31380
- store.putSurface({ ...x, viewId: null });
31635
+ for (const x of store.terminals.list("view_id = ?", [v.id])) {
31636
+ store.putTerminal({ ...x, mirror: "none", viewId: null });
31381
31637
  }
31382
31638
  store.deleteView(v.id);
31383
31639
  return { ok: true, id: v.id };
@@ -31385,9 +31641,11 @@ function registerViewRoutes(app, ctx) {
31385
31641
  app.post("/api/views/:id/sessions/:sessionId", async (req) => store.tx(() => {
31386
31642
  const { sessionId } = req.params;
31387
31643
  const v = store.views.require(idOf(req));
31388
- store.sessions.require(sessionId);
31644
+ const session = store.sessions.require(sessionId);
31389
31645
  if (v.sessionIds.includes(sessionId))
31390
31646
  return v;
31647
+ if (session.archivedAt)
31648
+ throw new SwitchyardError("conflict", "Unarchive this session before pinning it");
31391
31649
  return store.putView({
31392
31650
  ...v,
31393
31651
  sessionIds: [...v.sessionIds, sessionId],
@@ -31409,17 +31667,16 @@ function registerViewRoutes(app, ctx) {
31409
31667
  const body2 = parse2(ViewClientReport, req.body);
31410
31668
  return store.tx(() => {
31411
31669
  const v = store.views.require(idOf(req));
31412
- reportSurface(ctx, body2.id, { kind: body2.kind, name: body2.name, machine: body2.machine, viewId: v.id }, deviceOf(req).id);
31670
+ reportTerminal(ctx, body2.id, {
31671
+ kind: body2.kind,
31672
+ name: body2.name,
31673
+ machine: body2.machine,
31674
+ seed: { mirror: "view", viewId: v.id }
31675
+ }, deviceOf(req).id);
31413
31676
  return v;
31414
31677
  });
31415
31678
  });
31416
- app.delete("/api/views/:id/clients/:clientId", async (req) => store.tx(() => {
31417
- const { clientId: clientId2 } = req.params;
31418
- const v = store.views.require(idOf(req));
31419
- if (store.surfaces.get(clientId2)?.viewId === v.id)
31420
- store.deleteSurface(clientId2);
31421
- return v;
31422
- }));
31679
+ app.delete("/api/views/:id/clients/:clientId", async (req) => store.views.require(idOf(req)));
31423
31680
  }
31424
31681
 
31425
31682
  // packages/coordinator/dist/routes/workspaces.js
@@ -31597,11 +31854,11 @@ var Statements = class {
31597
31854
  constructor(db) {
31598
31855
  this.db = db;
31599
31856
  }
31600
- get(sql21) {
31601
- let s = this.cache.get(sql21);
31857
+ get(sql23) {
31858
+ let s = this.cache.get(sql23);
31602
31859
  if (!s) {
31603
- s = this.db.prepare(sql21);
31604
- this.cache.set(sql21, s);
31860
+ s = this.db.prepare(sql23);
31861
+ this.cache.set(sql23, s);
31605
31862
  }
31606
31863
  return s;
31607
31864
  }
@@ -31632,12 +31889,12 @@ var JsonRepo = class {
31632
31889
  }
31633
31890
  /** List with an optional SQL `WHERE` fragment over the indexed columns. */
31634
31891
  list(where, params = [], orderBy = "rowid") {
31635
- const sql21 = `SELECT json FROM ${this.table}${where ? ` WHERE ${where}` : ""} ORDER BY ${orderBy}`;
31636
- return this.st.get(sql21).all(...params).map((r) => JSON.parse(r.json));
31892
+ const sql23 = `SELECT json FROM ${this.table}${where ? ` WHERE ${where}` : ""} ORDER BY ${orderBy}`;
31893
+ return this.st.get(sql23).all(...params).map((r) => JSON.parse(r.json));
31637
31894
  }
31638
31895
  count(where, params = []) {
31639
- const sql21 = `SELECT COUNT(*) AS n FROM ${this.table}${where ? ` WHERE ${where}` : ""}`;
31640
- return this.st.get(sql21).get(...params).n;
31896
+ const sql23 = `SELECT COUNT(*) AS n FROM ${this.table}${where ? ` WHERE ${where}` : ""}`;
31897
+ return this.st.get(sql23).get(...params).n;
31641
31898
  }
31642
31899
  /**
31643
31900
  * Update by id, or insert when missing. `extra` columns are written in both cases when given
@@ -31690,7 +31947,7 @@ var Store2 = class {
31690
31947
  /** Trackers are REST resources: no events; their per-item data rides on tasks. */
31691
31948
  trackers;
31692
31949
  issues;
31693
- surfaces;
31950
+ terminals;
31694
31951
  sessions;
31695
31952
  interactions;
31696
31953
  tasks;
@@ -31734,7 +31991,7 @@ var Store2 = class {
31734
31991
  this.profiles = new JsonRepo(st, "profiles", "Profile", { name: (p) => p.name }, { created_at: () => now() });
31735
31992
  this.views = new JsonRepo(st, "views", "View", { name: (v) => v.name }, { created_at: () => now() });
31736
31993
  this.trackers = new JsonRepo(st, "trackers", "Tracker", { name: (t) => t.name }, { created_at: () => now() });
31737
- this.surfaces = new JsonRepo(st, "surfaces", "Surface", {
31994
+ this.terminals = new JsonRepo(st, "terminals", "Terminal", {
31738
31995
  device_id: (x) => x.deviceId,
31739
31996
  view_id: (x) => x.viewId,
31740
31997
  last_seen_at: (x) => x.lastSeenAt
@@ -31995,24 +32252,38 @@ var Store2 = class {
31995
32252
  return v;
31996
32253
  });
31997
32254
  }
32255
+ /** Remove a session from every view's pins. */
32256
+ unpinSession(sessionId) {
32257
+ this.tx(() => {
32258
+ for (const v of this.views.list()) {
32259
+ if (!v.sessionIds.includes(sessionId))
32260
+ continue;
32261
+ this.putView({
32262
+ ...v,
32263
+ sessionIds: v.sessionIds.filter((id) => id !== sessionId),
32264
+ updatedAt: this.nowIso()
32265
+ });
32266
+ }
32267
+ });
32268
+ }
31998
32269
  deleteView(id) {
31999
32270
  this.tx(() => {
32000
32271
  this.views.delete(id);
32001
32272
  this.appendEvent("view.deleted", {}, { id });
32002
32273
  });
32003
32274
  }
32004
- putSurface(x) {
32275
+ putTerminal(x) {
32005
32276
  return this.tx(() => {
32006
- this.surfaces.upsert(x);
32007
- this.appendEvent("surface.updated", {}, x);
32277
+ this.terminals.upsert(x);
32278
+ this.appendEvent("terminal.updated", {}, x);
32008
32279
  return x;
32009
32280
  });
32010
32281
  }
32011
- deleteSurface(id) {
32282
+ deleteTerminal(id) {
32012
32283
  this.tx(() => {
32013
- if (!this.surfaces.delete(id))
32284
+ if (!this.terminals.delete(id))
32014
32285
  return;
32015
- this.appendEvent("surface.deleted", {}, { id });
32286
+ this.appendEvent("terminal.deleted", {}, { id });
32016
32287
  });
32017
32288
  }
32018
32289
  putIssue(i) {
@@ -32030,7 +32301,10 @@ var Store2 = class {
32030
32301
  }
32031
32302
  putSession(s) {
32032
32303
  return this.tx(() => {
32304
+ const archiving = s.archivedAt !== null && this.sessions.get(s.id)?.archivedAt === null;
32033
32305
  this.sessions.upsert(s);
32306
+ if (archiving)
32307
+ this.unpinSession(s.id);
32034
32308
  this.appendEvent("session.updated", {
32035
32309
  sessionId: s.id,
32036
32310
  hostId: s.hostId,
@@ -32288,11 +32562,12 @@ var Store2 = class {
32288
32562
  }
32289
32563
  // ---- presence, push, notifications -----------------------------------------------------
32290
32564
  upsertPresence(p) {
32291
- this.st.get("INSERT INTO presence (device_id, foreground_until, interacted_at, viewing_session_id, updated_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT(device_id) DO UPDATE SET foreground_until = excluded.foreground_until, interacted_at = excluded.interacted_at, viewing_session_id = excluded.viewing_session_id, updated_at = excluded.updated_at").run(p.deviceId, p.foregroundUntil, p.interactedAt, p.viewingSessionId, p.updatedAt);
32565
+ this.st.get("INSERT INTO presence (device_id, terminal_id, foreground_until, interacted_at, viewing_session_id, updated_at) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT(device_id, terminal_id) DO UPDATE SET foreground_until = excluded.foreground_until, interacted_at = excluded.interacted_at, viewing_session_id = excluded.viewing_session_id, updated_at = excluded.updated_at").run(p.deviceId, p.terminalId ?? "", p.foregroundUntil, p.interactedAt, p.viewingSessionId, p.updatedAt);
32292
32566
  }
32293
32567
  presenceFromRow(r) {
32294
32568
  return {
32295
32569
  deviceId: r.device_id,
32570
+ terminalId: r.terminal_id || null,
32296
32571
  foregroundUntil: r.foreground_until ?? null,
32297
32572
  interactedAt: r.interacted_at ?? null,
32298
32573
  viewingSessionId: r.viewing_session_id ?? null,
@@ -32300,7 +32575,7 @@ var Store2 = class {
32300
32575
  };
32301
32576
  }
32302
32577
  getPresence(deviceId) {
32303
- const r = this.st.get("SELECT * FROM presence WHERE device_id = ?").get(deviceId);
32578
+ const r = this.st.get("SELECT * FROM presence WHERE device_id = ? AND terminal_id = ''").get(deviceId);
32304
32579
  return r ? this.presenceFromRow(r) : void 0;
32305
32580
  }
32306
32581
  listPresence() {
@@ -32469,7 +32744,7 @@ var Store2 = class {
32469
32744
  panels: this.listPanels(),
32470
32745
  devices: this.devices.list("is_admin = 0", [], "created_at"),
32471
32746
  issues: this.issues.list(void 0, [], "created_at, rowid"),
32472
- surfaces: this.surfaces.list(void 0, [], "created_at, rowid"),
32747
+ terminals: this.terminals.list(void 0, [], "created_at, rowid"),
32473
32748
  adapters: this.adaptersByHost(),
32474
32749
  dispatchPaused: this.dispatchPaused
32475
32750
  };
@@ -32855,7 +33130,7 @@ function createCoordinator(opts) {
32855
33130
  registerGitHubRoutes(app, ctx);
32856
33131
  registerProfileRoutes(app, ctx);
32857
33132
  registerViewRoutes(app, ctx);
32858
- registerSurfaceRoutes(app, ctx);
33133
+ registerTerminalRoutes(app, ctx);
32859
33134
  registerSessionRoutes(app, ctx);
32860
33135
  registerInteractionRoutes(app, ctx);
32861
33136
  registerAttentionRoutes(app, ctx);
@@ -32909,6 +33184,9 @@ function createCoordinator(opts) {
32909
33184
  const r = store.runRetention();
32910
33185
  if (r.deleted > 0)
32911
33186
  log.info(r, "event retention sweep");
33187
+ const stale3 = sweepStaleSessionState(store, attention);
33188
+ if (stale3.sessions + stale3.pins > 0)
33189
+ log.info(stale3, "cleared stale questions and pins");
32912
33190
  const archived = archiveEndedSessions(store);
32913
33191
  if (archived.length > 0)
32914
33192
  log.info({ sessions: archived.length }, "archived ended sessions");
@@ -33537,10 +33815,11 @@ function printDoctor(ctx, results) {
33537
33815
  }
33538
33816
 
33539
33817
  // packages/cli/dist/commands/herdr.js
33540
- import { spawn as spawn6 } from "node:child_process";
33818
+ import { execFile as execFile6, spawn as spawn6 } from "node:child_process";
33541
33819
  import { closeSync as closeSync3, existsSync as existsSync23, mkdirSync as mkdirSync11, openSync as openSync3, readFileSync as readFileSync13, writeFileSync as writeFileSync7 } from "node:fs";
33542
- import { homedir as homedir10, hostname as hostname4 } from "node:os";
33820
+ import { homedir as homedir10, hostname as hostname6 } from "node:os";
33543
33821
  import { dirname as dirname17, join as join28 } from "node:path";
33822
+ import { promisify } from "node:util";
33544
33823
 
33545
33824
  // packages/cli/dist/context.js
33546
33825
  function defaultCtx() {
@@ -33800,7 +34079,8 @@ function mirrorStateOf(client2) {
33800
34079
  hosts: Object.values(s.hosts),
33801
34080
  checkouts: Object.values(s.checkouts),
33802
34081
  views: Object.values(s.views),
33803
- issues: Object.values(s.issues ?? {})
34082
+ issues: Object.values(s.issues ?? {}),
34083
+ terminals: Object.values(s.terminals ?? {})
33804
34084
  };
33805
34085
  }
33806
34086
  function viewedSessions(st, view) {
@@ -33811,6 +34091,49 @@ function viewedSessions(st, view) {
33811
34091
  const scope = trackerScope(view, st.issues ?? []);
33812
34092
  return all.filter((s) => sessionInView(view, s, workspaces, scope));
33813
34093
  }
34094
+ var RECENT_MS = 48 * 60 * 6e4;
34095
+ function placedIn(s) {
34096
+ return s.place?.terminalId ?? s.external?.client ?? null;
34097
+ }
34098
+ function paneSession(st, terminalId2, pane) {
34099
+ const s = st.sessions.find((x) => x.archivedAt === null && x.external?.client === terminalId2 && x.place?.pane === pane && LIVE_RUNTIMES4.includes(x.runtime));
34100
+ return s?.id ?? null;
34101
+ }
34102
+ function isActive(s, now) {
34103
+ return LIVE_RUNTIMES4.includes(s.runtime) || !!s.unreadSince || now - Date.parse(s.lastActivityAt) < RECENT_MS;
34104
+ }
34105
+ function wantedSessions(st, view, now, terminalId2 = null) {
34106
+ const kept = new Map(viewedSessions(st, view).map((s) => [s.id, s]));
34107
+ const { branches } = buildBranches({
34108
+ workspaces: st.workspaces,
34109
+ sessions: st.sessions,
34110
+ issues: []
34111
+ });
34112
+ const out = /* @__PURE__ */ new Map();
34113
+ const add = (id) => {
34114
+ const s = id ? kept.get(id) : void 0;
34115
+ if (!s || terminalId2 && placedIn(s) === terminalId2)
34116
+ return;
34117
+ if (isActive(s, now))
34118
+ out.set(s.id, s);
34119
+ };
34120
+ const workspaces = Object.fromEntries(st.workspaces.map((w) => [w.id, w]));
34121
+ const scope = view ? trackerScope(view, st.issues ?? []) : null;
34122
+ const inView = (x) => !view || sessionInView(view, x, workspaces, scope);
34123
+ for (const b of branches) {
34124
+ const rep = b.primary && inView(b.primary) ? b.primary : b.extras.find(inView);
34125
+ add(rep?.id);
34126
+ }
34127
+ return [...out.values()].sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id));
34128
+ }
34129
+ function primaryIds(st) {
34130
+ const { branches } = buildBranches({
34131
+ workspaces: st.workspaces,
34132
+ sessions: st.sessions,
34133
+ issues: []
34134
+ });
34135
+ return new Set(branches.flatMap((b) => b.primary ? [b.primary.id] : []));
34136
+ }
33814
34137
  function lingeringSessions(st, view) {
33815
34138
  const out = /* @__PURE__ */ new Set();
33816
34139
  if (!view?.trackerId)
@@ -33832,7 +34155,14 @@ var SOURCE = "switchyard";
33832
34155
  var SESSION_TOKEN = "switchyard_session";
33833
34156
  var LABEL_MAX = 40;
33834
34157
  function emptyMemory() {
33835
- return { spaces: {}, ownTabs: {}, pending: {}, offered: /* @__PURE__ */ new Set(), titleOverrides: {} };
34158
+ return {
34159
+ spaces: {},
34160
+ ownTabs: {},
34161
+ pending: {},
34162
+ offered: /* @__PURE__ */ new Set(),
34163
+ titleOverrides: {},
34164
+ hidden: {}
34165
+ };
33836
34166
  }
33837
34167
  function cap2(label) {
33838
34168
  return label.length > LABEL_MAX ? `${label.slice(0, LABEL_MAX - 1)}\u2026` : label;
@@ -33875,7 +34205,7 @@ function claimedSession(p) {
33875
34205
  return token;
33876
34206
  return p.agent_session?.source === SOURCE ? p.agent_session.value : null;
33877
34207
  }
33878
- function planMirror(st, h, mem, now, view = null) {
34208
+ function planMirror(st, h, mem, now, view = null, terminalId2 = null) {
33879
34209
  const plan = {
33880
34210
  closeTabs: [],
33881
34211
  moves: [],
@@ -33890,6 +34220,7 @@ function planMirror(st, h, mem, now, view = null) {
33890
34220
  spaces: {}
33891
34221
  };
33892
34222
  const M = new Map(viewedSessions(st, view).map((s) => [s.id, s]));
34223
+ const W = new Map(wantedSessions(st, view, now, terminalId2).map((s) => [s.id, s]));
33893
34224
  const linger = lingeringSessions(st, view);
33894
34225
  const workspaces = [...h.workspaces].sort((a, b) => a.number - b.number);
33895
34226
  const present = new Set(workspaces.map((w) => w.workspace_id));
@@ -33942,9 +34273,12 @@ function planMirror(st, h, mem, now, view = null) {
33942
34273
  if (owners.size !== 1)
33943
34274
  continue;
33944
34275
  const sid = [...owners][0];
33945
- if (!sid || M.has(sid))
34276
+ if (!sid)
33946
34277
  continue;
33947
- if (t.tab_id === h.focusedTabId && linger.has(sid))
34278
+ const inactive = M.has(sid) && !W.has(sid) && mem.ownTabs[t.tab_id] === sid;
34279
+ if (M.has(sid) && !inactive)
34280
+ continue;
34281
+ if (t.tab_id === h.focusedTabId && (inactive || linger.has(sid)))
33948
34282
  continue;
33949
34283
  plan.closeTabs.push({ tabId: t.tab_id, sessionId: sid });
33950
34284
  }
@@ -33976,9 +34310,11 @@ function planMirror(st, h, mem, now, view = null) {
33976
34310
  return p !== void 0 && now - p.at < PENDING_MS;
33977
34311
  };
33978
34312
  const createdKeys = /* @__PURE__ */ new Set();
33979
- for (const s of M.values()) {
34313
+ for (const s of W.values()) {
33980
34314
  if (claimedPanes.has(s.id) || fresh(s.id))
33981
34315
  continue;
34316
+ if (mem.hidden[s.id] === s.lastActivityAt)
34317
+ continue;
33982
34318
  if (now - Date.parse(s.createdAt) < NEW_SESSION_GRACE_MS)
33983
34319
  continue;
33984
34320
  const key = spaceKey(s);
@@ -34054,7 +34390,7 @@ function planMirror(st, h, mem, now, view = null) {
34054
34390
  }
34055
34391
  plan.spaces[w.workspace_id] = { key, label: computed };
34056
34392
  }
34057
- const liveKeys = new Set([...M.values()].map(spaceKey));
34393
+ const liveKeys = new Set([...W.values(), ...[...claimedPanes.keys()].flatMap((sid) => M.get(sid) ?? [])].map(spaceKey));
34058
34394
  const claimedSpaces = new Set(h.panes.filter((p) => claimedSession(p) !== null).map((p) => p.workspace_id));
34059
34395
  for (const [id, rec] of Object.entries(mem.spaces)) {
34060
34396
  if (!present.has(id))
@@ -34322,9 +34658,9 @@ var MirrorDaemon = class {
34322
34658
  return [];
34323
34659
  const { call, log } = this.deps;
34324
34660
  const bound = this.deps.view?.() ?? null;
34325
- if (bound === "missing") {
34661
+ if (bound === "off") {
34326
34662
  if (!this.viewMissingLogged)
34327
- log(`no view named "${this.deps.viewName ?? ""}"; idle`);
34663
+ log("mirrors nothing; idle");
34328
34664
  this.viewMissingLogged = true;
34329
34665
  return [];
34330
34666
  }
@@ -34347,7 +34683,7 @@ var MirrorDaemon = class {
34347
34683
  }
34348
34684
  const h = await this.snapshot();
34349
34685
  this.remember(h);
34350
- const plan = planMirror(st, h, this.mem, this.now(), bound);
34686
+ const plan = planMirror(st, h, this.mem, this.now(), bound, this.deps.terminalId ?? null);
34351
34687
  const titleOf = (sid) => st.sessions.find((s) => s.id === sid)?.title ?? sid;
34352
34688
  const launcher = this.deps.launcherPath;
34353
34689
  const paneCmd = (sid) => launcherCommand(launcher, ["pane", sid]);
@@ -34475,6 +34811,10 @@ var MirrorDaemon = class {
34475
34811
  await runInPane(call, o.paneId, launcherCommand(launcher, args));
34476
34812
  note(`offered a new session in ${o.tabId}`);
34477
34813
  }
34814
+ for (const [sid, at] of Object.entries(this.mem.hidden)) {
34815
+ if (st.sessions.find((s) => s.id === sid)?.lastActivityAt !== at)
34816
+ delete this.mem.hidden[sid];
34817
+ }
34478
34818
  const claimed = new Set(h.panes.map(claimedSession).filter(Boolean));
34479
34819
  for (const [sid, p] of Object.entries(this.mem.pending)) {
34480
34820
  if (claimed.has(sid) || this.now() - p.at >= PENDING_MS * 4)
@@ -34488,6 +34828,7 @@ var MirrorDaemon = class {
34488
34828
  }
34489
34829
  this.mem.spaces = { ...plan.spaces, ...createdNow };
34490
34830
  this.save();
34831
+ this.deps.onShows?.([...claimed].sort());
34491
34832
  return done;
34492
34833
  }
34493
34834
  load() {
@@ -34508,9 +34849,10 @@ var MirrorDaemon = class {
34508
34849
  if (!st)
34509
34850
  return;
34510
34851
  const bound = this.deps.view?.() ?? null;
34511
- if (bound === "missing")
34852
+ if (bound === "off")
34512
34853
  return;
34513
34854
  const mirrored = new Map(viewedSessions(st, bound).map((s) => [s.id, s]));
34855
+ const primaries = primaryIds(st);
34514
34856
  switch (data.type) {
34515
34857
  case "tab_closed": {
34516
34858
  const tabId = String(data.tab_id);
@@ -34519,8 +34861,12 @@ var MirrorDaemon = class {
34519
34861
  for (const sid of this.sessionsOfTab.get(tabId) ?? []) {
34520
34862
  const s = mirrored.get(sid);
34521
34863
  const elsewhere = [...this.sessionsOfTab].some(([other, sids]) => other !== tabId && sids.includes(sid));
34522
- if (s && !elsewhere)
34864
+ if (!s || elsewhere)
34865
+ continue;
34866
+ if (primaries.has(s.id))
34523
34867
  await this.archive(s.id, s.title);
34868
+ else
34869
+ this.mem.hidden[s.id] = s.lastActivityAt;
34524
34870
  }
34525
34871
  return;
34526
34872
  }
@@ -34528,7 +34874,7 @@ var MirrorDaemon = class {
34528
34874
  const ws = String(data.workspace_id);
34529
34875
  for (const sid of new Set(this.sessionsOfSpace.get(ws) ?? [])) {
34530
34876
  const s = mirrored.get(sid);
34531
- if (s)
34877
+ if (s && primaries.has(s.id))
34532
34878
  await this.archive(s.id, s.title);
34533
34879
  }
34534
34880
  delete this.mem.spaces[ws];
@@ -34632,43 +34978,723 @@ function startPresence(api, surface, viewId, log) {
34632
34978
  }
34633
34979
 
34634
34980
  // packages/cli/dist/mirror/binding.js
34635
- function bindingRef(env, sessionName) {
34636
- return env.SWITCHYARD_VIEW?.trim() || sessionName;
34981
+ function terminalId(kind, name, machine) {
34982
+ return `${kind}:${name}@${machine}`;
34983
+ }
34984
+ function recordedBinding(st, id) {
34985
+ const t = st.terminals?.find((x) => x.id === id);
34986
+ if (!t)
34987
+ return "off";
34988
+ const mirror = terminalMirror(t);
34989
+ if (mirror === "all")
34990
+ return null;
34991
+ if (mirror === "view")
34992
+ return st.views.find((v) => v.id === t.viewId) ?? "off";
34993
+ return "off";
34994
+ }
34995
+ function seedBinding(env, name, st, wasMirroring) {
34996
+ const ref = env.SWITCHYARD_VIEW?.trim();
34997
+ if (ref) {
34998
+ const v = findView(st.views, ref);
34999
+ return v ? { mirror: "view", viewId: v.id } : void 0;
35000
+ }
35001
+ const named = wasMirroring ? findView(st.views, name) : null;
35002
+ return named ? { mirror: "view", viewId: named.id } : { mirror: "none" };
35003
+ }
35004
+ function legacyBinding(st, env, name) {
35005
+ return findView(st.views, env.SWITCHYARD_VIEW?.trim() || name) ?? "off";
35006
+ }
35007
+ function pickerBinding(st, env, id) {
35008
+ if (st.terminals?.some((t) => t.id === id))
35009
+ return recordedBinding(st, id);
35010
+ const ref = env.SWITCHYARD_VIEW?.trim();
35011
+ return ref && findView(st.views, ref) || "off";
35012
+ }
35013
+ async function pinNote(api, view, sessionId) {
35014
+ const views = await api.get("/api/views").catch(() => null);
35015
+ const v = views?.find((x) => x.id === view.id);
35016
+ if (!v?.sessionIds.includes(sessionId))
35017
+ return null;
35018
+ return `Pinned to view "${v.name}": it would not show there otherwise. Unpin it from the session menu.`;
34637
35019
  }
34638
- function viewOrMissing(st, ref) {
34639
- return findView(st.views, ref) ?? "missing";
35020
+ function offMessage(kind, id) {
35021
+ return `This ${kind} session mirrors nothing. Choose what it shows with: switchyard terminals bind ${id} --all (or --view <name>)`;
34640
35022
  }
34641
- function noViewMessage(kind, name) {
34642
- return `This ${kind} session has no Switchyard view. Create a view named "${name}" in Switchyard to mirror it.`;
35023
+ var EVERY_MS2 = 6e4;
35024
+ function unknownRoute(err) {
35025
+ return err instanceof ApiRequestError && err.status === 404 && /^No route /.test(err.message);
34643
35026
  }
34644
- function trackPresence(opts) {
34645
- let current = null;
34646
- const check = () => {
34647
- const v = opts.getView();
34648
- if (v?.id === current?.id)
35027
+ function syncTerminal(opts) {
35028
+ const { api, info, log } = opts;
35029
+ const path3 = `/api/terminals/${encodeURIComponent(info.id)}`;
35030
+ let mode = "unknown";
35031
+ let lastError = "";
35032
+ let lastShows = "";
35033
+ let warned = "";
35034
+ let stopped = false;
35035
+ let legacy = null;
35036
+ const legacyBound = () => {
35037
+ const st = opts.state();
35038
+ return st ? legacyBinding(st, opts.env, opts.legacyName?.() ?? info.name) : "off";
35039
+ };
35040
+ const followLegacy = () => {
35041
+ const v = legacyBound();
35042
+ const id = v && v !== "off" ? v.id : null;
35043
+ if (id === (legacy?.viewId ?? null))
34649
35044
  return;
34650
- const old = current;
34651
- current = null;
35045
+ const old = legacy;
35046
+ legacy = null;
34652
35047
  if (old)
34653
35048
  void old.stop();
34654
- if (v) {
34655
- const p = startPresence(opts.api, opts.surface, v.id, opts.log);
34656
- current = { id: v.id, stop: p.stop };
35049
+ if (id) {
35050
+ const p = startPresence(api, info, id, log);
35051
+ legacy = { viewId: id, stop: p.stop };
34657
35052
  }
34658
35053
  };
34659
- const off = opts.subscribe(check);
34660
- check();
35054
+ const warnIgnoredEnv = (st) => {
35055
+ const ref = opts.env.SWITCHYARD_VIEW?.trim();
35056
+ const t = st.terminals?.find((x) => x.id === info.id);
35057
+ if (!ref || !t?.bindingSetAt)
35058
+ return;
35059
+ const want = findView(st.views, ref);
35060
+ const same3 = terminalMirror(t) === "view" && want?.id === t.viewId;
35061
+ const key = `${ref}|${t.mirror}|${t.viewId}`;
35062
+ if (same3 || warned === key)
35063
+ return;
35064
+ warned = key;
35065
+ log(`SWITCHYARD_VIEW=${ref} is ignored: this terminal's recorded binding wins (switchyard terminals bind ${info.id} ...)`);
35066
+ };
35067
+ let inflight = false;
35068
+ let again = false;
35069
+ const send = async () => {
35070
+ if (stopped || mode === "legacy")
35071
+ return;
35072
+ if (inflight) {
35073
+ again = true;
35074
+ return;
35075
+ }
35076
+ inflight = true;
35077
+ try {
35078
+ await sendOnce();
35079
+ } finally {
35080
+ inflight = false;
35081
+ }
35082
+ if (again) {
35083
+ again = false;
35084
+ await send();
35085
+ }
35086
+ };
35087
+ const sendOnce = async () => {
35088
+ const st = opts.state();
35089
+ if (!st)
35090
+ return;
35091
+ const recorded = st.terminals?.find((x) => x.id === info.id);
35092
+ const shows = opts.shows?.();
35093
+ const body2 = {
35094
+ kind: info.kind,
35095
+ name: info.name,
35096
+ machine: info.machine,
35097
+ hostId: info.hostId,
35098
+ ...shows ? { shows } : {}
35099
+ };
35100
+ if (!recorded?.bindingSetAt) {
35101
+ const seed = seedBinding(opts.env, info.name, st, opts.wasMirroring);
35102
+ if (seed)
35103
+ body2.seed = seed;
35104
+ }
35105
+ try {
35106
+ const t = await api.request("PUT", path3, body2);
35107
+ if (mode !== "terminals") {
35108
+ mode = "terminals";
35109
+ log(`terminal ${info.id} mirrors ${describe(t)}`);
35110
+ }
35111
+ lastShows = JSON.stringify(shows ?? null);
35112
+ lastError = "";
35113
+ warnIgnoredEnv(st);
35114
+ } catch (err) {
35115
+ if (mode === "unknown" && unknownRoute(err)) {
35116
+ mode = "legacy";
35117
+ log("this coordinator has no terminals; binding by SWITCHYARD_VIEW or the session's name");
35118
+ followLegacy();
35119
+ return;
35120
+ }
35121
+ const m = err.message;
35122
+ if (m !== lastError)
35123
+ log(`terminal report failed: ${m}`);
35124
+ lastError = m;
35125
+ }
35126
+ };
35127
+ let lastBinding = "";
35128
+ const off = opts.subscribe(() => {
35129
+ if (mode === "legacy")
35130
+ return followLegacy();
35131
+ const st = opts.state();
35132
+ if (!st)
35133
+ return;
35134
+ if (mode === "unknown")
35135
+ void send();
35136
+ const t = st.terminals?.find((x) => x.id === info.id);
35137
+ const now = t ? describe(t) : "";
35138
+ if (t && lastBinding && now !== lastBinding)
35139
+ log(`terminal ${info.id} now mirrors ${now}`);
35140
+ if (t)
35141
+ lastBinding = now;
35142
+ });
35143
+ void send();
35144
+ const timer = setInterval(() => void send(), EVERY_MS2);
35145
+ timer.unref?.();
34661
35146
  return {
35147
+ binding() {
35148
+ if (mode === "legacy")
35149
+ return legacyBound();
35150
+ const st = opts.state();
35151
+ return st ? recordedBinding(st, info.id) : "off";
35152
+ },
35153
+ report() {
35154
+ if (JSON.stringify(opts.shows?.() ?? null) !== lastShows)
35155
+ void send();
35156
+ },
34662
35157
  async stop() {
35158
+ stopped = true;
34663
35159
  off();
34664
- await current?.stop();
34665
- current = null;
35160
+ clearInterval(timer);
35161
+ await legacy?.stop();
35162
+ legacy = null;
35163
+ }
35164
+ };
35165
+ }
35166
+ function describe(t) {
35167
+ const m = terminalMirror(t);
35168
+ return m === "view" ? `view ${t.viewId}` : m === "all" ? "everything" : "nothing";
35169
+ }
35170
+
35171
+ // packages/cli/dist/mirror/focus.js
35172
+ var EVERY_MS3 = 15e3;
35173
+ function startFocusPresence(opts) {
35174
+ let last = null;
35175
+ let lastSentAt = 0;
35176
+ let stopped = false;
35177
+ let running2 = false;
35178
+ let again = false;
35179
+ let lastError = "";
35180
+ const report = (sessionId) => opts.send({
35181
+ foreground: sessionId !== null,
35182
+ interactedAt: null,
35183
+ viewing: sessionId ? { sessionId } : null,
35184
+ terminalId: opts.terminalId
35185
+ });
35186
+ const check = async () => {
35187
+ if (stopped)
35188
+ return;
35189
+ if (running2) {
35190
+ again = true;
35191
+ return;
35192
+ }
35193
+ running2 = true;
35194
+ try {
35195
+ const now = Date.now();
35196
+ const sid = await opts.focused().catch((err) => {
35197
+ if (err.message !== lastError)
35198
+ opts.log(`focus check failed: ${err.message}`);
35199
+ lastError = err.message;
35200
+ return null;
35201
+ });
35202
+ const due = sid !== null && now - lastSentAt >= EVERY_MS3 - 1e3;
35203
+ if ((sid !== last || due) && report(sid)) {
35204
+ last = sid;
35205
+ lastSentAt = now;
35206
+ }
35207
+ } finally {
35208
+ running2 = false;
35209
+ }
35210
+ if (again) {
35211
+ again = false;
35212
+ await check();
35213
+ }
35214
+ };
35215
+ const timer = setInterval(() => void check(), opts.pollMs ?? EVERY_MS3);
35216
+ timer.unref?.();
35217
+ void check();
35218
+ return {
35219
+ check: () => void check(),
35220
+ stop() {
35221
+ stopped = true;
35222
+ clearInterval(timer);
35223
+ if (last !== null)
35224
+ report(null);
35225
+ }
35226
+ };
35227
+ }
35228
+ function herdrClientAttached(psLines2, name) {
35229
+ for (const line of psLines2) {
35230
+ const argv = line.trim().split(/\s+/);
35231
+ const i = argv.findIndex((a) => a === "herdr" || a.endsWith("/herdr"));
35232
+ if (i < 0)
35233
+ continue;
35234
+ const args = argv.slice(i + 1);
35235
+ if (args[0] === "session" && args[1] === "attach") {
35236
+ if (args[2] === name)
35237
+ return true;
35238
+ continue;
35239
+ }
35240
+ if (args.some((a) => !a.startsWith("-") && a !== name))
35241
+ continue;
35242
+ const s = args.indexOf("--session");
35243
+ const session = s >= 0 ? args[s + 1] : "default";
35244
+ if (session === name)
35245
+ return true;
35246
+ }
35247
+ return false;
35248
+ }
35249
+
35250
+ // packages/cli/dist/commands/terminals.js
35251
+ import { hostname as hostname4 } from "node:os";
35252
+
35253
+ // packages/cli/dist/commands/hosts.js
35254
+ async function resolveHost(api, ref) {
35255
+ const hosts = (await api.get("/api/hosts")).filter((h) => !h.revokedAt);
35256
+ const exact = hosts.find((h) => h.id === ref);
35257
+ if (exact)
35258
+ return exact;
35259
+ const named = hosts.filter((h) => h.name.toLowerCase() === ref.toLowerCase());
35260
+ if (named.length === 1)
35261
+ return named[0];
35262
+ if (named.length > 1)
35263
+ throw new CliError(`Several hosts are named "${ref}"; use the id`);
35264
+ const known = hosts.map((h) => `${h.name} (${h.id})`).join(", ") || "none";
35265
+ throw new CliError(`Unknown host "${ref}". Hosts: ${known}`);
35266
+ }
35267
+ function scanLine(scan, now = Date.now()) {
35268
+ if (!scan)
35269
+ return ["Not scanned yet."];
35270
+ if (scan.state === "running")
35271
+ return [`Scanning since ${ago(scan.startedAt, now)}.`];
35272
+ if (scan.state === "failed") {
35273
+ return [
35274
+ `Last scan failed ${ago(scan.finishedAt, now)}: ${scan.errors.at(-1) ?? "unknown error"}`
35275
+ ];
35276
+ }
35277
+ return [
35278
+ `Last scanned ${ago(scan.finishedAt, now)}: ${scan.repositories} repositories, ${scan.checkoutsAdded} new checkouts, ${scan.projectsCreated} new projects.`,
35279
+ ...scan.errors.map((e) => `! ${e}`)
35280
+ ];
35281
+ }
35282
+ async function hostsList(ctx, flags) {
35283
+ const { api } = connect(ctx, flags);
35284
+ const hosts = (await api.get("/api/hosts")).filter((h) => !h.revokedAt);
35285
+ printList(ctx, flags.json, hosts, ["ID", "NAME", "STATUS", "AGENT", "PROJECT FOLDERS"], hosts.map((h) => [
35286
+ h.id,
35287
+ h.name,
35288
+ h.connectivity,
35289
+ h.agentVersion,
35290
+ (h.projectFolders ?? []).join(", ") || "-"
35291
+ ]), "No hosts.");
35292
+ }
35293
+ async function hostsFolders(ctx, ref, flags) {
35294
+ const { api } = connect(ctx, flags);
35295
+ const changing = !!(flags.set || flags.add || flags.remove || flags.clear);
35296
+ if (flags.set && (flags.add || flags.remove || flags.clear) || flags.clear && (flags.add || flags.remove)) {
35297
+ throw new CliError("Use --set or --clear on its own, or --add/--remove");
35298
+ }
35299
+ const host = await resolveHost(api, ref);
35300
+ const current = host.projectFolders ?? [];
35301
+ if (!changing) {
35302
+ if (flags.json)
35303
+ ctx.out(JSON.stringify(host, null, 2));
35304
+ else {
35305
+ if (current.length === 0)
35306
+ ctx.out("No project folders.");
35307
+ for (const f of current)
35308
+ ctx.out(f);
35309
+ for (const l of scanLine(host.projectScan))
35310
+ ctx.out(l);
35311
+ }
35312
+ return host;
35313
+ }
35314
+ let next;
35315
+ if (flags.set)
35316
+ next = [...flags.set];
35317
+ else if (flags.clear)
35318
+ next = [];
35319
+ else {
35320
+ next = [...current];
35321
+ for (const f of flags.remove ?? []) {
35322
+ if (!next.includes(f))
35323
+ throw new CliError(`${f} is not a project folder of ${host.name}`);
35324
+ next = next.filter((x) => x !== f);
35325
+ }
35326
+ for (const f of flags.add ?? [])
35327
+ if (!next.includes(f))
35328
+ next.push(f);
35329
+ }
35330
+ const updated = await api.request("PATCH", `/api/hosts/${encodeURIComponent(host.id)}`, {
35331
+ projectFolders: next
35332
+ });
35333
+ if (flags.json) {
35334
+ ctx.out(JSON.stringify(updated, null, 2));
35335
+ return updated;
35336
+ }
35337
+ const folders = updated.projectFolders ?? [];
35338
+ ctx.out(`Project folders on ${updated.name}: ${folders.join(", ") || "none"}`);
35339
+ if (folders.length > 0 && updated.connectivity === "connected") {
35340
+ ctx.out(`Scanning in the background; \`switchyard hosts scan ${updated.name}\` waits for the result.`);
35341
+ }
35342
+ return updated;
35343
+ }
35344
+ async function hostsScan(ctx, ref, flags) {
35345
+ const { api } = connect(ctx, flags);
35346
+ const host = await resolveHost(api, ref);
35347
+ const r = await api.post(`/api/hosts/${encodeURIComponent(host.id)}/scan-projects`);
35348
+ if (flags.json) {
35349
+ ctx.out(JSON.stringify(r, null, 2));
35350
+ return r;
35351
+ }
35352
+ ctx.out(`Scanned ${host.name}: ${r.repositories} repositories, ${r.checkoutsAdded} new checkouts, ${r.projectsCreated} new projects`);
35353
+ for (const a of r.added)
35354
+ ctx.out(`+ ${a.name} ${a.path}${a.newProject ? " (new project)" : ""}`);
35355
+ for (const e of r.errors)
35356
+ ctx.out(`! ${e}`);
35357
+ return r;
35358
+ }
35359
+
35360
+ // packages/cli/dist/commands/work.js
35361
+ function byId2(list) {
35362
+ return new Map(list.map((x) => [x.id, x]));
35363
+ }
35364
+ async function resolveProject(api, ref) {
35365
+ const projects = await api.get("/api/projects");
35366
+ const exact = projects.find((p) => p.id === ref);
35367
+ if (exact)
35368
+ return exact;
35369
+ const named = projects.filter((p) => p.name.toLowerCase() === ref.toLowerCase());
35370
+ if (named.length === 1)
35371
+ return named[0];
35372
+ if (named.length > 1)
35373
+ throw new CliError(`Several projects are named "${ref}"; use the id`);
35374
+ const known = projects.map((p) => `${p.name} (${p.id})`).join(", ") || "none";
35375
+ throw new CliError(`Unknown project "${ref}". Projects: ${known}`);
35376
+ }
35377
+ async function sessionsList(ctx, flags) {
35378
+ const { api } = connect(ctx, flags);
35379
+ const projectId = flags.project ? (await resolveProject(api, flags.project)).id : void 0;
35380
+ const [sessions, projects, hosts] = await Promise.all([
35381
+ api.get(`/api/sessions${projectId ? `?projectId=${encodeURIComponent(projectId)}` : ""}`),
35382
+ api.get("/api/projects"),
35383
+ api.get("/api/hosts")
35384
+ ]);
35385
+ const p = byId2(projects);
35386
+ const h = byId2(hosts);
35387
+ printList(ctx, flags.json, sessions, ["ID", "RUNTIME", "PROJECT", "HOST", "ACTIVE", "TITLE"], sessions.map((s) => [
35388
+ s.id,
35389
+ s.runtime,
35390
+ s.projectId && p.get(s.projectId)?.name || "-",
35391
+ h.get(s.hostId)?.name ?? s.hostId,
35392
+ ago(s.lastActivityAt),
35393
+ s.title
35394
+ ]), "No sessions.");
35395
+ }
35396
+ async function sessionsImport(ctx, sessionFile, flags) {
35397
+ const { api } = connect(ctx, flags);
35398
+ let hostId;
35399
+ if (flags.host) {
35400
+ hostId = (await resolveHost(api, flags.host)).id;
35401
+ } else {
35402
+ const hosts = (await api.get("/api/hosts")).filter((x) => !x.revokedAt);
35403
+ if (hosts.length !== 1) {
35404
+ throw new CliError(`Choose a host with --host (${hosts.map((x) => `${x.name}: ${x.id}`).join(", ") || "none enrolled"})`);
35405
+ }
35406
+ hostId = hosts[0].id;
35407
+ }
35408
+ const projectId = flags.project ? (await resolveProject(api, flags.project)).id : null;
35409
+ const session = await api.post("/api/sessions/import", {
35410
+ hostId,
35411
+ sessionFile,
35412
+ projectId
35413
+ });
35414
+ if (flags.json)
35415
+ ctx.out(JSON.stringify(session, null, 2));
35416
+ else
35417
+ ctx.out(`Imported ${session.title} as ${session.id} (stopped; resume it to continue)`);
35418
+ return session;
35419
+ }
35420
+ function taskCreateBody(projectId, flags) {
35421
+ const body2 = {
35422
+ projectId,
35423
+ title: flags.title,
35424
+ objective: flags.objective ?? "",
35425
+ acceptanceCriteria: (flags.criteria ?? []).map((c) => c.trim()).filter(Boolean),
35426
+ state: flags.ready ? "ready" : "backlog"
35427
+ };
35428
+ if (flags.priority !== void 0)
35429
+ body2.priority = parsePriority(flags.priority);
35430
+ return body2;
35431
+ }
35432
+ function parsePriority(v) {
35433
+ const byName = PRIORITY_LABELS.findIndex((l) => l.toLowerCase() === v.toLowerCase());
35434
+ const n = byName >= 0 ? byName : Number(v);
35435
+ if (n === 0 || n === 1 || n === 2 || n === 3)
35436
+ return n;
35437
+ throw new CliError(`Priority must be 0-3 or one of ${PRIORITY_LABELS.join(", ")}`);
35438
+ }
35439
+ async function tasksCreate(ctx, flags) {
35440
+ const { api } = connect(ctx, flags);
35441
+ const project = await resolveProject(api, flags.project);
35442
+ const task = await api.post("/api/tasks", taskCreateBody(project.id, flags));
35443
+ if (flags.json)
35444
+ ctx.out(JSON.stringify(task, null, 2));
35445
+ else {
35446
+ ctx.out(`Created ${task.id}: ${task.title} (${task.state})`);
35447
+ if (task.state === "ready")
35448
+ ctx.out("Ready tasks start automatically when eligible.");
35449
+ }
35450
+ return task;
35451
+ }
35452
+ function parseStates(v) {
35453
+ if (!v)
35454
+ return void 0;
35455
+ const states = v.split(",").map((s) => s.trim()).filter(Boolean);
35456
+ for (const s of states) {
35457
+ if (!TaskState.safeParse(s).success) {
35458
+ throw new CliError(`Unknown state "${s}". States: ${TaskState.options.join(", ")}`);
34666
35459
  }
35460
+ }
35461
+ return states;
35462
+ }
35463
+ async function tasksList(ctx, flags) {
35464
+ const { api } = connect(ctx, flags);
35465
+ const states = parseStates(flags.state);
35466
+ const projectId = flags.project ? (await resolveProject(api, flags.project)).id : void 0;
35467
+ const q = new URLSearchParams();
35468
+ if (states)
35469
+ q.set("state", states.join(","));
35470
+ if (projectId)
35471
+ q.set("projectId", projectId);
35472
+ if (flags.all)
35473
+ q.set("includeHidden", "true");
35474
+ const qs = q.toString();
35475
+ const [tasks, projects] = await Promise.all([
35476
+ api.get(`/api/tasks${qs ? `?${qs}` : ""}`),
35477
+ api.get("/api/projects")
35478
+ ]);
35479
+ const p = byId2(projects);
35480
+ printList(ctx, flags.json, tasks, ["ID", "STATE", "PRIORITY", "PROJECT", "TITLE"], tasks.map((t) => [
35481
+ t.id,
35482
+ t.blocked ? `${t.state} (blocked)` : t.state,
35483
+ PRIORITY_LABELS[t.priority] ?? String(t.priority),
35484
+ p.get(t.projectId)?.name ?? t.projectId,
35485
+ t.title
35486
+ ]), "No tasks.");
35487
+ }
35488
+ async function tasksMove(ctx, id, to, flags) {
35489
+ if (to.includes(","))
35490
+ throw new CliError(`Give one target state, not a list ("${to}")`);
35491
+ const [state] = parseStates(to) ?? [];
35492
+ if (!state)
35493
+ throw new CliError("Give the target state");
35494
+ const { api } = connect(ctx, flags);
35495
+ const body2 = { to: state };
35496
+ if (flags.confirm)
35497
+ body2.confirm = true;
35498
+ if (flags.onRunning)
35499
+ body2.onRunning = flags.onRunning;
35500
+ const task = await api.post(`/api/tasks/${encodeURIComponent(id)}/move`, body2);
35501
+ if (flags.json)
35502
+ ctx.out(JSON.stringify(task, null, 2));
35503
+ else
35504
+ ctx.out(`Moved ${task.title} to ${task.state}`);
35505
+ return task;
35506
+ }
35507
+ async function automationsList(ctx, flags) {
35508
+ const { api } = connect(ctx, flags);
35509
+ const list = await api.get("/api/automations");
35510
+ printList(ctx, flags.json, list, ["ID", "ENABLED", "NEXT", "NAME", "TRIGGER"], list.map((a) => [a.id, a.enabled ? "yes" : "no", a.nextAt ?? "-", a.name, a.summary]), "No automations.");
35511
+ }
35512
+ async function automationsRun(ctx, id, flags) {
35513
+ const { api } = connect(ctx, flags);
35514
+ const res = await api.post(`/api/automations/${encodeURIComponent(id)}/run`, {});
35515
+ if (flags.json) {
35516
+ ctx.out(JSON.stringify(res, null, 2));
35517
+ return;
35518
+ }
35519
+ const o = res.occurrence;
35520
+ ctx.out(`Occurrence ${o.id}: ${o.state}${o.reason ? ` (${o.reason})` : ""}${res.task ? `; task ${res.task.id} "${res.task.title}" is ${res.task.state}` : ""}`);
35521
+ }
35522
+
35523
+ // packages/cli/dist/commands/views.js
35524
+ async function listTerminals(api) {
35525
+ try {
35526
+ return await api.get("/api/terminals");
35527
+ } catch (err) {
35528
+ if (!isUnknownRoute(err))
35529
+ throw err;
35530
+ return api.get("/api/surfaces");
35531
+ }
35532
+ }
35533
+ function isUnknownRoute(err) {
35534
+ return err instanceof ApiRequestError && err.status === 404 && /^No route /.test(err.message);
35535
+ }
35536
+ async function resolveView(api, ref) {
35537
+ const views = await api.get("/api/views");
35538
+ const v = findView(views, ref);
35539
+ if (v)
35540
+ return v;
35541
+ const known = views.map((x) => x.name).join(", ") || "none";
35542
+ throw new CliError(`Unknown view "${ref}". Views: ${known}`);
35543
+ }
35544
+ function checkMode(mode) {
35545
+ if (mode !== void 0 && mode !== "all" && mode !== "pinned") {
35546
+ throw new CliError('--mode must be "all" or "pinned"');
35547
+ }
35548
+ }
35549
+ async function viewsList(ctx, flags) {
35550
+ const { api } = connect(ctx, flags);
35551
+ const [views, projects, hosts, terminals] = await Promise.all([
35552
+ api.get("/api/views"),
35553
+ api.get("/api/projects"),
35554
+ api.get("/api/hosts"),
35555
+ listTerminals(api).catch(() => [])
35556
+ ]);
35557
+ const names = (ids2, all) => ids2 === null ? "any" : ids2.map((i) => all.find((x) => x.id === i)?.name ?? i).join(", ") || "-";
35558
+ printList(ctx, flags.json, views, ["NAME", "MODE", "PROJECTS", "HOSTS", "PINNED", "MIRRORED IN"], views.map((v) => [
35559
+ v.name,
35560
+ v.mode,
35561
+ names(v.projectIds, projects),
35562
+ names(v.hostIds, hosts),
35563
+ String(v.sessionIds.length),
35564
+ openTerminals(terminals, v.id).map((c) => `${c.kind} ${c.name} (${c.machine})`).join(", ") || "-"
35565
+ ]), "No views.");
35566
+ }
35567
+ async function ids(api, refs, kind) {
35568
+ if (!refs || refs.length === 0)
35569
+ return void 0;
35570
+ const out = [];
35571
+ for (const r of refs) {
35572
+ out.push((kind === "project" ? await resolveProject(api, r) : await resolveHost(api, r)).id);
35573
+ }
35574
+ return out;
35575
+ }
35576
+ async function viewsCreate(ctx, name, flags) {
35577
+ checkMode(flags.mode);
35578
+ const { api } = connect(ctx, flags);
35579
+ const projectIds = await ids(api, flags.project, "project");
35580
+ const hostIds = await ids(api, flags.host, "host");
35581
+ const v = await api.post("/api/views", {
35582
+ name,
35583
+ ...flags.mode ? { mode: flags.mode } : {},
35584
+ ...projectIds ? { projectIds } : {},
35585
+ ...hostIds ? { hostIds } : {}
35586
+ });
35587
+ ctx.out(`Created view ${v.name} (${v.id})`);
35588
+ }
35589
+ async function viewsEdit(ctx, ref, flags) {
35590
+ checkMode(flags.mode);
35591
+ const { api } = connect(ctx, flags);
35592
+ const v = await resolveView(api, ref);
35593
+ const projectIds = flags.anyProject ? null : await ids(api, flags.project, "project");
35594
+ const hostIds = flags.anyHost ? null : await ids(api, flags.host, "host");
35595
+ const body2 = {
35596
+ ...flags.name ? { name: flags.name } : {},
35597
+ ...flags.mode ? { mode: flags.mode } : {},
35598
+ ...projectIds !== void 0 ? { projectIds } : {},
35599
+ ...hostIds !== void 0 ? { hostIds } : {}
34667
35600
  };
35601
+ await api.request("PATCH", `/api/views/${encodeURIComponent(v.id)}`, body2);
35602
+ ctx.out(`Updated view ${flags.name ?? v.name}`);
35603
+ }
35604
+ async function viewsDelete(ctx, ref, flags) {
35605
+ const { api } = connect(ctx, flags);
35606
+ const v = await resolveView(api, ref);
35607
+ await api.request("DELETE", `/api/views/${encodeURIComponent(v.id)}`);
35608
+ ctx.out(`Deleted view ${v.name}`);
35609
+ }
35610
+ async function viewsPin(ctx, ref, sessionId, flags, unpin = false) {
35611
+ const { api } = connect(ctx, flags);
35612
+ const v = await resolveView(api, ref);
35613
+ const path3 = `/api/views/${encodeURIComponent(v.id)}/sessions/${encodeURIComponent(sessionId)}`;
35614
+ await api.request(unpin ? "DELETE" : "POST", path3);
35615
+ ctx.out(`${unpin ? "Unpinned" : "Pinned"} ${sessionId} ${unpin ? "from" : "in"} ${v.name}`);
35616
+ }
35617
+
35618
+ // packages/cli/dist/commands/terminals.js
35619
+ function mirrorText(t, views) {
35620
+ const m = terminalMirror(t);
35621
+ if (m === "all")
35622
+ return "everything";
35623
+ if (m === "view")
35624
+ return `view ${views.find((v) => v.id === t.viewId)?.name ?? t.viewId}`;
35625
+ return t.bindingSetAt ? "nothing" : "nothing (not recorded)";
35626
+ }
35627
+ function resolveTerminalRef(ref, known, machine = hostname4()) {
35628
+ if (/^(herdr|tmux):.+@[^@]+$/.test(ref))
35629
+ return ref;
35630
+ if (/^(herdr|tmux):[^@]+$/.test(ref))
35631
+ return `${ref}@${machine}`;
35632
+ const named = known.filter((t) => t.name === ref);
35633
+ const here = named.filter((t) => t.machine === machine);
35634
+ const pick = here.length === 1 ? here : named;
35635
+ if (pick.length === 1)
35636
+ return pick[0].id;
35637
+ if (pick.length > 1) {
35638
+ throw new CliError(`"${ref}" names several terminals: ${pick.map((t) => t.id).join(", ")}`);
35639
+ }
35640
+ throw new CliError(`Unknown terminal "${ref}". Give it as herdr:<session> or tmux:<session> (on this machine), or herdr:<session>@<machine>`);
35641
+ }
35642
+ async function bindingFromFlags(api, flags) {
35643
+ const chosen = [flags.view !== void 0, !!flags.all, !!flags.none].filter(Boolean).length;
35644
+ if (chosen !== 1)
35645
+ throw new CliError("Choose one of --view <name>, --all or --none");
35646
+ if (flags.all)
35647
+ return { mirror: "all" };
35648
+ if (flags.none)
35649
+ return { mirror: "none" };
35650
+ const views = await api.get("/api/views");
35651
+ const v = findView(views, flags.view);
35652
+ if (!v) {
35653
+ const known = views.map((x) => x.name).join(", ") || "none";
35654
+ throw new CliError(`Unknown view "${flags.view}". Views: ${known}`);
35655
+ }
35656
+ return { mirror: "view", viewId: v.id };
35657
+ }
35658
+ async function recordBinding(api, id, binding) {
35659
+ try {
35660
+ return await api.request("PUT", `/api/terminals/${encodeURIComponent(id)}/binding`, binding);
35661
+ } catch (err) {
35662
+ if (isUnknownRoute(err)) {
35663
+ throw new CliError("This coordinator cannot record bindings yet: upgrade it, or set SWITCHYARD_VIEW in the env file");
35664
+ }
35665
+ throw err;
35666
+ }
35667
+ }
35668
+ async function terminalsList(ctx, flags) {
35669
+ const { api } = connect(ctx, flags);
35670
+ const [terminals, views] = await Promise.all([listTerminals(api), api.get("/api/views")]);
35671
+ printList(ctx, flags.json, terminals, ["TERMINAL", "MIRRORS", "TABS", "DAEMON"], terminals.map((t) => [
35672
+ t.id,
35673
+ mirrorText(t, views),
35674
+ String(t.shows?.length ?? 0),
35675
+ terminalOpen(t) ? `seen ${ago(t.lastSeenAt)}` : "not running"
35676
+ ]), "No terminals yet: start a herdr or tmux session with the Switchyard plugin.");
35677
+ }
35678
+ async function terminalsBind(ctx, ref, flags) {
35679
+ const { api } = connect(ctx, flags);
35680
+ const binding = await bindingFromFlags(api, flags);
35681
+ const id = resolveTerminalRef(ref, await listTerminals(api).catch(() => []));
35682
+ const [t, views] = await Promise.all([
35683
+ recordBinding(api, id, binding),
35684
+ api.get("/api/views")
35685
+ ]);
35686
+ ctx.out(`${t.id} mirrors ${mirrorText(t, views)}`);
35687
+ }
35688
+ async function terminalsForget(ctx, ref, flags) {
35689
+ const { api } = connect(ctx, flags);
35690
+ const id = resolveTerminalRef(ref, await listTerminals(api));
35691
+ await api.request("DELETE", `/api/terminals/${encodeURIComponent(id)}`);
35692
+ ctx.out(`Forgot ${id}`);
34668
35693
  }
34669
35694
 
34670
35695
  // packages/cli/dist/herdr/new-session.js
34671
35696
  import { readFileSync as readFileSync12 } from "node:fs";
35697
+ import { hostname as hostname5 } from "node:os";
34672
35698
  import { join as join27 } from "node:path";
34673
35699
 
34674
35700
  // packages/cli/dist/mirror/choose.js
@@ -34733,6 +35759,10 @@ function workspaceItems(st, projectId) {
34733
35759
  };
34734
35760
  }).sort((a, b) => b.active.localeCompare(a.active) || Number(b.main) - Number(a.main) || a.item.label.localeCompare(b.item.label)).map((x) => x.item);
34735
35761
  }
35762
+ function openableSessions(st, workspaceId) {
35763
+ const hosts = terminalHostIds(st);
35764
+ return liveSessions(st).filter((s) => s.workspaceId === workspaceId && hosts.has(s.hostId) && s.provenance !== "subagent").sort((a, b) => Number(b.primary === true) - Number(a.primary === true) || b.lastActivityAt.localeCompare(a.lastActivityAt));
35765
+ }
34736
35766
  function newWorktreeItems(st, projectId, query) {
34737
35767
  const hosts = terminalHostIds(st);
34738
35768
  const branch = branchSlug2(query) || null;
@@ -34786,10 +35816,18 @@ async function chooseSession(st, screen, opts = {}) {
34786
35816
  if (step === "here") {
34787
35817
  out = await screen.pick({ crumbs: crumbs(), heading: "Start a session here?", hint: HINT_PICK }, [
34788
35818
  { label: `Start a session in ${spaceLabel(here.id, st)}`, value: "here" },
35819
+ ...openableSessions(st, here.id).map((s) => ({
35820
+ label: `Open ${s.title}`,
35821
+ detail: s.primary ? `${s.runtime} \xB7 primary` : s.runtime,
35822
+ value: `open:${s.id}`
35823
+ })),
34789
35824
  { label: "Choose another project or workspace\u2026", value: "other" }
34790
35825
  ]);
34791
35826
  if (out.kind === "ok") {
34792
35827
  typed[step] = out.query;
35828
+ if (typeof out.value === "string" && out.value.startsWith("open:")) {
35829
+ return { openSessionId: out.value.slice(5) };
35830
+ }
34793
35831
  if (out.value === "here") {
34794
35832
  projectId = here.projectId;
34795
35833
  workspace = { kind: "existing", workspaceId: here.id };
@@ -35453,10 +36491,11 @@ async function herdrNew(ctx, flags, io) {
35453
36491
  ctx.err("Connecting to Switchyard\u2026");
35454
36492
  const { client: client2, state } = await loadMirrorState(ctx, flags);
35455
36493
  const name = herdrSessionName(ctx.env);
35456
- const bound = viewOrMissing(state(), bindingRef(ctx.env, name));
35457
- if (bound === "missing") {
36494
+ const id = terminalId("herdr", name, hostname5());
36495
+ const bound = pickerBinding(state(), ctx.env, id);
36496
+ if (bound === "off") {
35458
36497
  client2.close();
35459
- ctx.err(noViewMessage("herdr", bindingRef(ctx.env, name)));
36498
+ ctx.err(offMessage("herdr", id));
35460
36499
  return;
35461
36500
  }
35462
36501
  const screen = new Screen(io ?? {
@@ -35465,6 +36504,7 @@ async function herdrNew(ctx, flags, io) {
35465
36504
  color: !("NO_COLOR" in ctx.env)
35466
36505
  });
35467
36506
  let created = null;
36507
+ let opened = null;
35468
36508
  try {
35469
36509
  const choice = await chooseSession(state(), screen, {
35470
36510
  ...flags.workspace ? { workspaceId: flags.workspace } : {}
@@ -35474,18 +36514,28 @@ async function herdrNew(ctx, flags, io) {
35474
36514
  ctx.err("Kept this tab as a shell.");
35475
36515
  return;
35476
36516
  }
35477
- created = await client2.api.post("/api/sessions", {
35478
- ...choice,
35479
- prompt: "",
35480
- viewId: bound.id
35481
- });
35482
- ctx.err(`Starting ${created.title}\u2026`);
36517
+ if ("openSessionId" in choice) {
36518
+ opened = choice.openSessionId;
36519
+ } else {
36520
+ created = await client2.api.post("/api/sessions", {
36521
+ ...choice,
36522
+ prompt: "",
36523
+ ...bound ? { viewId: bound.id } : {}
36524
+ });
36525
+ ctx.err(`Starting ${created.title}\u2026`);
36526
+ if (bound) {
36527
+ const note = await pinNote(client2.api, bound, created.id);
36528
+ if (note)
36529
+ ctx.err(note);
36530
+ }
36531
+ }
35483
36532
  } finally {
35484
36533
  screen.leave();
35485
36534
  client2.close();
35486
36535
  }
35487
- if (created)
35488
- await herdrPane(ctx, created.id, flags);
36536
+ const show = created?.id ?? opened;
36537
+ if (show)
36538
+ await herdrPane(ctx, show, flags);
35489
36539
  }
35490
36540
  async function newHere(ctx) {
35491
36541
  const call = (method, params) => herdrCall(method, params);
@@ -35507,6 +36557,7 @@ async function newHere(ctx) {
35507
36557
  }
35508
36558
 
35509
36559
  // packages/cli/dist/commands/herdr.js
36560
+ var execFileP = promisify(execFile6);
35510
36561
  function pidAlive2(pid) {
35511
36562
  try {
35512
36563
  process.kill(pid, 0);
@@ -35537,7 +36588,9 @@ async function herdrDaemon(ctx, flags) {
35537
36588
  const logFile = join28(dir, "daemon.log");
35538
36589
  const socket = herdrSocketPath(env);
35539
36590
  const call = (method, params) => herdrCall(method, params, socket);
35540
- const ref = bindingRef(env, herdrSessionName(env));
36591
+ const name = herdrSessionName(env);
36592
+ const machine = hostname6();
36593
+ const id = terminalId("herdr", name, machine);
35541
36594
  if (flags.once) {
35542
36595
  const { client: client3, state } = await loadMirrorState(ctx, flags);
35543
36596
  try {
@@ -35549,8 +36602,7 @@ async function herdrDaemon(ctx, flags) {
35549
36602
  state,
35550
36603
  onStateChange: () => () => {
35551
36604
  },
35552
- view: () => viewOrMissing(state(), ref),
35553
- viewName: ref,
36605
+ view: () => pickerBinding(state(), env, id),
35554
36606
  stateDir: dir,
35555
36607
  launcherPath,
35556
36608
  log: () => {
@@ -35594,49 +36646,83 @@ async function herdrDaemon(ctx, flags) {
35594
36646
  return;
35595
36647
  writeFileSync7(pidFile, String(process.pid));
35596
36648
  const log = (line) => ctx.out(`${(/* @__PURE__ */ new Date()).toISOString()} ${line}`);
35597
- log(`daemon started (pid ${process.pid}, herdr session ${herdrSessionName(env)})`);
36649
+ log(`daemon started (pid ${process.pid}, herdr session ${name})`);
35598
36650
  const { client: client2 } = await loadMirrorState(ctx, flags, 24 * 60 * 6e4);
35599
36651
  client2.onLogout((reason3) => {
35600
36652
  log(`signed out: ${reason3}`);
35601
36653
  process.exit(1);
35602
36654
  });
36655
+ let shows;
36656
+ const terminal = syncTerminal({
36657
+ api: client2.api,
36658
+ info: {
36659
+ id,
36660
+ kind: "herdr",
36661
+ name,
36662
+ machine,
36663
+ hostId: localHostId(env, client2.api.baseUrl)
36664
+ },
36665
+ state: () => client2.store.getState().synced ? mirrorStateOf(client2) : null,
36666
+ subscribe: (fn) => client2.store.subscribe(fn),
36667
+ env,
36668
+ shows: () => shows,
36669
+ wasMirroring: ownsSpaces(dir),
36670
+ log
36671
+ });
36672
+ const focus = startFocusPresence({
36673
+ terminalId: id,
36674
+ send: (presence) => client2.send({ type: "presence", presence }),
36675
+ focused: async () => {
36676
+ if (!herdrClientAttached(await psLines(), name))
36677
+ return null;
36678
+ const snap = (await call("session.snapshot", {}))?.snapshot ?? {};
36679
+ const pane = (snap.panes ?? []).find((p) => p.pane_id === snap.focused_pane_id);
36680
+ if (!pane)
36681
+ return null;
36682
+ return claimedSession(pane) ?? paneSession(mirrorStateOf(client2), id, pane.pane_id);
36683
+ },
36684
+ log
36685
+ });
35603
36686
  const daemon = new MirrorDaemon({
35604
36687
  call,
35605
- subscribe: (types, onEvent, onEnd) => herdrSubscribe(types, onEvent, onEnd, socket),
36688
+ // Focus events only update what this terminal reports as viewed.
36689
+ subscribe: (types, onEvent, onEnd) => herdrSubscribe([...types, ...FOCUS_EVENTS], (data) => data.type.endsWith("_focused") ? focus.check() : onEvent(data), onEnd, socket),
35606
36690
  api: client2.api,
35607
36691
  state: () => client2.store.getState().synced ? mirrorStateOf(client2) : null,
35608
36692
  onStateChange: (fn) => client2.store.subscribe(fn),
35609
- view: () => viewOrMissing(mirrorStateOf(client2), ref),
35610
- viewName: ref,
36693
+ view: () => terminal.binding(),
36694
+ terminalId: id,
36695
+ onShows: (ids2) => {
36696
+ shows = ids2;
36697
+ terminal.report();
36698
+ },
35611
36699
  stateDir: dir,
35612
36700
  launcherPath,
35613
36701
  log
35614
36702
  });
35615
36703
  await daemon.start();
35616
- const name = herdrSessionName(env);
35617
- const machine = hostname4();
35618
- const presence = trackPresence({
35619
- api: client2.api,
35620
- getView: () => {
35621
- const v = viewOrMissing(mirrorStateOf(client2), ref);
35622
- return v === "missing" ? null : v;
35623
- },
35624
- subscribe: (fn) => client2.store.subscribe(fn),
35625
- surface: {
35626
- id: `herdr:${name}@${machine}`,
35627
- kind: "herdr",
35628
- name,
35629
- machine,
35630
- hostId: localHostId(env, client2.api.baseUrl)
35631
- },
35632
- log
35633
- });
35634
- const leave = () => void presence.stop().finally(() => process.exit(0));
36704
+ const leave = () => {
36705
+ focus.stop();
36706
+ void terminal.stop().finally(() => process.exit(0));
36707
+ };
35635
36708
  process.once("SIGTERM", leave);
35636
36709
  process.once("SIGINT", leave);
35637
36710
  await new Promise(() => {
35638
36711
  });
35639
36712
  }
36713
+ var FOCUS_EVENTS = ["pane.focused", "tab.focused", "workspace.focused"];
36714
+ async function psLines() {
36715
+ const { stdout } = await execFileP("ps", ["-axo", "args="], { maxBuffer: 8 * 1024 * 1024 });
36716
+ return stdout.split("\n");
36717
+ }
36718
+ function ownsSpaces(dir) {
36719
+ try {
36720
+ const raw = JSON.parse(readFileSync13(join28(dir, "spaces.json"), "utf8"));
36721
+ return Object.keys(raw.spaces ?? {}).length > 0;
36722
+ } catch {
36723
+ return false;
36724
+ }
36725
+ }
35640
36726
  function writePairFile(ctx, kind, session, flags) {
35641
36727
  const base = ctx.env.XDG_CONFIG_HOME?.trim() || join28(homedir10(), ".config");
35642
36728
  const path3 = join28(base, `switchyard-${kind}`, `${session}.env`);
@@ -35646,17 +36732,29 @@ function writePairFile(ctx, kind, session, flags) {
35646
36732
  const q = (v) => `"${v.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`;
35647
36733
  const lines = [
35648
36734
  flags.cli ? `SWITCHYARD_CLI=${q(flags.cli)}` : null,
35649
- flags.clientConfig ? `SWITCHYARD_CLIENT_CONFIG=${q(flags.clientConfig)}` : null,
35650
- flags.view ? `SWITCHYARD_VIEW=${q(flags.view)}` : null
36735
+ flags.clientConfig ? `SWITCHYARD_CLIENT_CONFIG=${q(flags.clientConfig)}` : null
35651
36736
  ].filter(Boolean);
35652
36737
  mkdirSync11(dirname17(path3), { recursive: true });
35653
36738
  writeFileSync7(path3, `${lines.join("\n")}${lines.length ? "\n" : ""}`, { mode: 384 });
35654
36739
  return path3;
35655
36740
  }
36741
+ async function pairBinding(ctx, kind, session, flags) {
36742
+ if (flags.view === void 0 && !flags.all && !flags.none) {
36743
+ ctx.out(`It mirrors nothing until you choose: switchyard terminals bind ${kind}:${session} --all (or --view <name>)`);
36744
+ return;
36745
+ }
36746
+ const c = flags.clientConfig ? { ...ctx, paths: { ...ctx.paths, clientConfig: flags.clientConfig } } : ctx;
36747
+ const { api } = connect(c, flags);
36748
+ const binding = await bindingFromFlags(api, flags);
36749
+ const t = await recordBinding(api, terminalId(kind, session, hostname6()), binding);
36750
+ const views = await api.get("/api/views");
36751
+ ctx.out(`${t.id} mirrors ${mirrorText(t, views)}`);
36752
+ }
35656
36753
  async function herdrPair(ctx, flags) {
35657
36754
  const session = flags.session ?? "default";
35658
36755
  const path3 = writePairFile(ctx, "herdr", session, flags);
35659
36756
  ctx.out(`Wrote ${path3}`);
36757
+ await pairBinding(ctx, "herdr", session, flags);
35660
36758
  ctx.out(`Start it with: ${session === "default" ? "herdr" : `herdr --session ${session}`}`);
35661
36759
  }
35662
36760
  async function herdrStatus(ctx, flags) {
@@ -35687,12 +36785,12 @@ async function herdrStatus(ctx, flags) {
35687
36785
 
35688
36786
  // packages/cli/dist/commands/host.js
35689
36787
  import { existsSync as existsSync25, mkdirSync as mkdirSync13 } from "node:fs";
35690
- import { hostname as hostname5 } from "node:os";
36788
+ import { hostname as hostname7 } from "node:os";
35691
36789
  import { dirname as dirname19, join as join30, resolve as resolve15 } from "node:path";
35692
36790
  import { DatabaseSync as DatabaseSync4 } from "node:sqlite";
35693
36791
 
35694
36792
  // packages/cli/dist/commands/service.js
35695
- import { execFile as execFile6 } from "node:child_process";
36793
+ import { execFile as execFile7 } from "node:child_process";
35696
36794
  import { existsSync as existsSync24, mkdirSync as mkdirSync12, readFileSync as readFileSync14, writeFileSync as writeFileSync8 } from "node:fs";
35697
36795
  import { homedir as homedir11 } from "node:os";
35698
36796
  import { dirname as dirname18, join as join29, resolve as resolve14 } from "node:path";
@@ -35843,7 +36941,7 @@ function defaultInstallDeps() {
35843
36941
  platform: process.platform,
35844
36942
  home: homedir11(),
35845
36943
  uid: process.getuid?.() ?? 0,
35846
- run: (cmd) => new Promise((resolve16) => execFile6(cmd[0], cmd.slice(1), (err, stdout, stderr) => resolve16({ ok: !err, output: `${stdout}${stderr}`.trim() })))
36944
+ run: (cmd) => new Promise((resolve16) => execFile7(cmd[0], cmd.slice(1), (err, stdout, stderr) => resolve16({ ok: !err, output: `${stdout}${stderr}`.trim() })))
35847
36945
  };
35848
36946
  }
35849
36947
  async function installService(ctx, flags, deps = defaultInstallDeps()) {
@@ -35903,7 +37001,7 @@ async function hostEnroll(ctx, flags) {
35903
37001
  if (!flags.token === !flags.secret) {
35904
37002
  throw new CliError("Pass exactly one of --token or --secret");
35905
37003
  }
35906
- const name = flags.name ?? hostname5().replace(/\.local$/, "");
37004
+ const name = flags.name ?? hostname7().replace(/\.local$/, "");
35907
37005
  const cfg = await enroll({
35908
37006
  coordinatorUrl: flags.coordinator,
35909
37007
  ...flags.token ? { token: flags.token } : { secret: flags.secret },
@@ -36045,121 +37143,14 @@ function hostPiExtension(ctx) {
36045
37143
  ctx.out(terminalExtensionPath());
36046
37144
  }
36047
37145
 
36048
- // packages/cli/dist/commands/hosts.js
36049
- async function resolveHost(api, ref) {
36050
- const hosts = (await api.get("/api/hosts")).filter((h) => !h.revokedAt);
36051
- const exact = hosts.find((h) => h.id === ref);
36052
- if (exact)
36053
- return exact;
36054
- const named = hosts.filter((h) => h.name.toLowerCase() === ref.toLowerCase());
36055
- if (named.length === 1)
36056
- return named[0];
36057
- if (named.length > 1)
36058
- throw new CliError(`Several hosts are named "${ref}"; use the id`);
36059
- const known = hosts.map((h) => `${h.name} (${h.id})`).join(", ") || "none";
36060
- throw new CliError(`Unknown host "${ref}". Hosts: ${known}`);
36061
- }
36062
- function scanLine(scan, now = Date.now()) {
36063
- if (!scan)
36064
- return ["Not scanned yet."];
36065
- if (scan.state === "running")
36066
- return [`Scanning since ${ago(scan.startedAt, now)}.`];
36067
- if (scan.state === "failed") {
36068
- return [
36069
- `Last scan failed ${ago(scan.finishedAt, now)}: ${scan.errors.at(-1) ?? "unknown error"}`
36070
- ];
36071
- }
36072
- return [
36073
- `Last scanned ${ago(scan.finishedAt, now)}: ${scan.repositories} repositories, ${scan.checkoutsAdded} new checkouts, ${scan.projectsCreated} new projects.`,
36074
- ...scan.errors.map((e) => `! ${e}`)
36075
- ];
36076
- }
36077
- async function hostsList(ctx, flags) {
36078
- const { api } = connect(ctx, flags);
36079
- const hosts = (await api.get("/api/hosts")).filter((h) => !h.revokedAt);
36080
- printList(ctx, flags.json, hosts, ["ID", "NAME", "STATUS", "AGENT", "PROJECT FOLDERS"], hosts.map((h) => [
36081
- h.id,
36082
- h.name,
36083
- h.connectivity,
36084
- h.agentVersion,
36085
- (h.projectFolders ?? []).join(", ") || "-"
36086
- ]), "No hosts.");
36087
- }
36088
- async function hostsFolders(ctx, ref, flags) {
36089
- const { api } = connect(ctx, flags);
36090
- const changing = !!(flags.set || flags.add || flags.remove || flags.clear);
36091
- if (flags.set && (flags.add || flags.remove || flags.clear) || flags.clear && (flags.add || flags.remove)) {
36092
- throw new CliError("Use --set or --clear on its own, or --add/--remove");
36093
- }
36094
- const host = await resolveHost(api, ref);
36095
- const current = host.projectFolders ?? [];
36096
- if (!changing) {
36097
- if (flags.json)
36098
- ctx.out(JSON.stringify(host, null, 2));
36099
- else {
36100
- if (current.length === 0)
36101
- ctx.out("No project folders.");
36102
- for (const f of current)
36103
- ctx.out(f);
36104
- for (const l of scanLine(host.projectScan))
36105
- ctx.out(l);
36106
- }
36107
- return host;
36108
- }
36109
- let next;
36110
- if (flags.set)
36111
- next = [...flags.set];
36112
- else if (flags.clear)
36113
- next = [];
36114
- else {
36115
- next = [...current];
36116
- for (const f of flags.remove ?? []) {
36117
- if (!next.includes(f))
36118
- throw new CliError(`${f} is not a project folder of ${host.name}`);
36119
- next = next.filter((x) => x !== f);
36120
- }
36121
- for (const f of flags.add ?? [])
36122
- if (!next.includes(f))
36123
- next.push(f);
36124
- }
36125
- const updated = await api.request("PATCH", `/api/hosts/${encodeURIComponent(host.id)}`, {
36126
- projectFolders: next
36127
- });
36128
- if (flags.json) {
36129
- ctx.out(JSON.stringify(updated, null, 2));
36130
- return updated;
36131
- }
36132
- const folders = updated.projectFolders ?? [];
36133
- ctx.out(`Project folders on ${updated.name}: ${folders.join(", ") || "none"}`);
36134
- if (folders.length > 0 && updated.connectivity === "connected") {
36135
- ctx.out(`Scanning in the background; \`switchyard hosts scan ${updated.name}\` waits for the result.`);
36136
- }
36137
- return updated;
36138
- }
36139
- async function hostsScan(ctx, ref, flags) {
36140
- const { api } = connect(ctx, flags);
36141
- const host = await resolveHost(api, ref);
36142
- const r = await api.post(`/api/hosts/${encodeURIComponent(host.id)}/scan-projects`);
36143
- if (flags.json) {
36144
- ctx.out(JSON.stringify(r, null, 2));
36145
- return r;
36146
- }
36147
- ctx.out(`Scanned ${host.name}: ${r.repositories} repositories, ${r.checkoutsAdded} new checkouts, ${r.projectsCreated} new projects`);
36148
- for (const a of r.added)
36149
- ctx.out(`+ ${a.name} ${a.path}${a.newProject ? " (new project)" : ""}`);
36150
- for (const e of r.errors)
36151
- ctx.out(`! ${e}`);
36152
- return r;
36153
- }
36154
-
36155
37146
  // packages/cli/dist/commands/tmux.js
36156
37147
  import { spawn as spawn8 } from "node:child_process";
36157
37148
  import { closeSync as closeSync4, existsSync as existsSync28, openSync as openSync4, readFileSync as readFileSync16, writeFileSync as writeFileSync11 } from "node:fs";
36158
- import { hostname as hostname6 } from "node:os";
37149
+ import { hostname as hostname9 } from "node:os";
36159
37150
  import { join as join33 } from "node:path";
36160
37151
 
36161
37152
  // packages/cli/dist/tmux/client.js
36162
- import { execFile as execFile7, spawn as spawn7 } from "node:child_process";
37153
+ import { execFile as execFile8, spawn as spawn7 } from "node:child_process";
36163
37154
  var TmuxUnavailable = class extends Error {
36164
37155
  constructor(message) {
36165
37156
  super(message);
@@ -36173,7 +37164,7 @@ var TmuxError = class extends Error {
36173
37164
  }
36174
37165
  };
36175
37166
  var tmuxRun = (args) => new Promise((resolve16, reject) => {
36176
- execFile7("tmux", args, { timeout: 5e3 }, (err, stdout, stderr) => {
37167
+ execFile8("tmux", args, { timeout: 5e3 }, (err, stdout, stderr) => {
36177
37168
  if (!err)
36178
37169
  return resolve16(stdout);
36179
37170
  if (err.code === "ENOENT") {
@@ -36254,7 +37245,14 @@ var WINDOW_OPTION = "@switchyard_session";
36254
37245
  var LABEL_MAX2 = 40;
36255
37246
  var SHELLS = ["sh", "bash", "zsh", "fish", "dash"];
36256
37247
  function emptyTmuxMemory() {
36257
- return { ownWindows: {}, pending: {}, offered: /* @__PURE__ */ new Set(), added: /* @__PURE__ */ new Set(), titleOverrides: {} };
37248
+ return {
37249
+ ownWindows: {},
37250
+ pending: {},
37251
+ offered: /* @__PURE__ */ new Set(),
37252
+ added: /* @__PURE__ */ new Set(),
37253
+ titleOverrides: {},
37254
+ hidden: {}
37255
+ };
36258
37256
  }
36259
37257
  function cap3(label) {
36260
37258
  return label.length > LABEL_MAX2 ? `${label.slice(0, LABEL_MAX2 - 1)}\u2026` : label;
@@ -36270,7 +37268,7 @@ function titleFromWindowName(name, s, st) {
36270
37268
  const prefix = `${prefixOf(s, st)} \xB7 `;
36271
37269
  return name.startsWith(prefix) ? name.slice(prefix.length) : name;
36272
37270
  }
36273
- function planTmux(st, view, windows, mem, now) {
37271
+ function planTmux(st, view, windows, mem, now, terminalId2 = null) {
36274
37272
  const plan = {
36275
37273
  closeWindows: [],
36276
37274
  createWindows: [],
@@ -36279,6 +37277,7 @@ function planTmux(st, view, windows, mem, now) {
36279
37277
  offers: []
36280
37278
  };
36281
37279
  const M = new Map(viewedSessions(st, view).map((s) => [s.id, s]));
37280
+ const W = new Map(wantedSessions(st, view, now, terminalId2).map((s) => [s.id, s]));
36282
37281
  const linger = lingeringSessions(st, view);
36283
37282
  const claimed = /* @__PURE__ */ new Set();
36284
37283
  for (const w of windows) {
@@ -36286,8 +37285,9 @@ function planTmux(st, view, windows, mem, now) {
36286
37285
  continue;
36287
37286
  claimed.add(w.sessionId);
36288
37287
  const s = M.get(w.sessionId);
36289
- if (!s) {
36290
- if (w.active && linger.has(w.sessionId))
37288
+ const inactive = !!s && !W.has(s.id) && mem.ownWindows[w.windowId] === s.id;
37289
+ if (!s || inactive) {
37290
+ if (w.active && (inactive || linger.has(w.sessionId)))
36291
37291
  continue;
36292
37292
  plan.closeWindows.push({ windowId: w.windowId, sessionId: w.sessionId });
36293
37293
  continue;
@@ -36298,9 +37298,11 @@ function planTmux(st, view, windows, mem, now) {
36298
37298
  if (w.name !== name)
36299
37299
  plan.renames.push({ windowId: w.windowId, name });
36300
37300
  }
36301
- for (const s of M.values()) {
37301
+ for (const s of W.values()) {
36302
37302
  if (claimed.has(s.id))
36303
37303
  continue;
37304
+ if (mem.hidden[s.id] === s.lastActivityAt)
37305
+ continue;
36304
37306
  const p = mem.pending[s.id];
36305
37307
  if (p && now - p.at < PENDING_MS)
36306
37308
  continue;
@@ -36465,11 +37467,11 @@ var TmuxDaemon = class {
36465
37467
  if (!st)
36466
37468
  return [];
36467
37469
  const { run, log } = this.deps;
36468
- const name = await this.currentName();
36469
- const bound = this.deps.view?.(name) ?? null;
36470
- if (bound === "missing") {
37470
+ await this.currentName();
37471
+ const bound = this.deps.view?.() ?? null;
37472
+ if (bound === "off") {
36471
37473
  if (!this.viewMissingLogged)
36472
- log(`no view named "${name}"; idle`);
37474
+ log("mirrors nothing; idle");
36473
37475
  this.viewMissingLogged = true;
36474
37476
  return [];
36475
37477
  }
@@ -36495,7 +37497,7 @@ var TmuxDaemon = class {
36495
37497
  }
36496
37498
  const windows = await this.snapshot();
36497
37499
  this.sessionOfWindow = new Map(windows.filter((w) => w.sessionId).map((w) => [w.windowId, w.sessionId]));
36498
- const plan = planTmux(st, bound, windows, this.mem, now);
37500
+ const plan = planTmux(st, bound, windows, this.mem, now, this.deps.terminalId ?? null);
36499
37501
  const launcher = this.deps.launcherPath;
36500
37502
  const exists2 = this.deps.exists ?? existsSync26;
36501
37503
  const q = (args) => launcherCommand(launcher, args);
@@ -36554,6 +37556,10 @@ var TmuxDaemon = class {
36554
37556
  note(`offered a new session in ${o.windowId}`);
36555
37557
  }
36556
37558
  const claimed = new Set(windows.map((w) => w.sessionId).filter(Boolean));
37559
+ for (const [sid, at] of Object.entries(this.mem.hidden)) {
37560
+ if (st.sessions.find((s) => s.id === sid)?.lastActivityAt !== at)
37561
+ delete this.mem.hidden[sid];
37562
+ }
36557
37563
  for (const [sid, p] of Object.entries(this.mem.pending)) {
36558
37564
  if (claimed.has(sid) || now - p.at >= PENDING_MS * 4)
36559
37565
  delete this.mem.pending[sid];
@@ -36565,6 +37571,7 @@ var TmuxDaemon = class {
36565
37571
  }
36566
37572
  }
36567
37573
  this.save();
37574
+ this.deps.onShows?.([...claimed].sort());
36568
37575
  return done;
36569
37576
  }
36570
37577
  load() {
@@ -36588,8 +37595,8 @@ var TmuxDaemon = class {
36588
37595
  const st = this.deps.state();
36589
37596
  if (!st)
36590
37597
  return;
36591
- const bound = this.deps.view?.(await this.currentName()) ?? null;
36592
- if (bound === "missing")
37598
+ const bound = this.deps.view?.() ?? null;
37599
+ if (bound === "off")
36593
37600
  return;
36594
37601
  const mirrored = new Map(viewedSessions(st, bound).map((s2) => [s2.id, s2]));
36595
37602
  if (e.type === "window-close") {
@@ -36602,6 +37609,10 @@ var TmuxDaemon = class {
36602
37609
  const elsewhere = [...this.sessionOfWindow].some(([w, other]) => w !== e.windowId && other === sid2);
36603
37610
  if (!s2 || elsewhere)
36604
37611
  return;
37612
+ if (!primaryIds(st).has(s2.id)) {
37613
+ this.mem.hidden[s2.id] = s2.lastActivityAt;
37614
+ return;
37615
+ }
36605
37616
  try {
36606
37617
  const r = await archiveSession2(this.deps.api, s2.id, s2.title);
36607
37618
  if (r.ok)
@@ -36680,6 +37691,7 @@ function tmuxLauncherExists(env = process.env) {
36680
37691
 
36681
37692
  // packages/cli/dist/tmux/new-session.js
36682
37693
  import { spawnSync } from "node:child_process";
37694
+ import { hostname as hostname8 } from "node:os";
36683
37695
 
36684
37696
  // packages/cli/dist/tmux/pane.js
36685
37697
  var defaultDeps2 = () => ({ run: tmuxRun, runRaw: runRawTerminal, readKey });
@@ -36712,23 +37724,35 @@ async function tmuxPane(ctx, sessionId, flags, deps = defaultDeps2()) {
36712
37724
  }
36713
37725
 
36714
37726
  // packages/cli/dist/tmux/new-session.js
37727
+ async function lastWindowWorkspace(st) {
37728
+ try {
37729
+ const sid = (await tmuxRun(["display-message", "-p", "-t", "!", `#{${WINDOW_OPTION}}`])).trim();
37730
+ const ws = st.sessions.find((s) => s.id === sid)?.workspaceId;
37731
+ return ws && st.workspaces.some((w) => w.id === ws && w.archivedAt === null) ? ws : void 0;
37732
+ } catch {
37733
+ return void 0;
37734
+ }
37735
+ }
36715
37736
  async function tmuxNew(ctx, flags, io) {
36716
37737
  ctx.err("Connecting to Switchyard\u2026");
36717
37738
  const { client: client2, state } = await loadMirrorState(ctx, flags);
36718
37739
  const name = await tmuxSessionName(ctx.env);
36719
- const bound = viewOrMissing(state(), bindingRef(ctx.env, name));
36720
- if (bound === "missing") {
37740
+ const id = terminalId("tmux", name, hostname8());
37741
+ const bound = pickerBinding(state(), ctx.env, id);
37742
+ if (bound === "off") {
36721
37743
  client2.close();
36722
- ctx.err(noViewMessage("tmux", bindingRef(ctx.env, name)));
37744
+ ctx.err(offMessage("tmux", id));
36723
37745
  if (!io)
36724
37746
  spawnSync(ctx.env.SHELL || "/bin/sh", [], { stdio: "inherit" });
36725
37747
  return;
36726
37748
  }
36727
37749
  const screen = new Screen(io ?? { input: process.stdin, output: process.stdout, color: !("NO_COLOR" in ctx.env) });
36728
37750
  let created = null;
37751
+ let opened = null;
37752
+ const workspace = flags.workspace ?? (io ? void 0 : await lastWindowWorkspace(state()));
36729
37753
  try {
36730
37754
  const choice = await chooseSession(state(), screen, {
36731
- ...flags.workspace ? { workspaceId: flags.workspace } : {}
37755
+ ...workspace ? { workspaceId: workspace } : {}
36732
37756
  });
36733
37757
  screen.leave();
36734
37758
  if (!choice) {
@@ -36737,18 +37761,28 @@ async function tmuxNew(ctx, flags, io) {
36737
37761
  spawnSync(ctx.env.SHELL || "/bin/sh", [], { stdio: "inherit" });
36738
37762
  return;
36739
37763
  }
36740
- created = await client2.api.post("/api/sessions", {
36741
- ...choice,
36742
- prompt: "",
36743
- viewId: bound.id
36744
- });
36745
- ctx.err(`Starting ${created.title}\u2026`);
37764
+ if ("openSessionId" in choice) {
37765
+ opened = choice.openSessionId;
37766
+ } else {
37767
+ created = await client2.api.post("/api/sessions", {
37768
+ ...choice,
37769
+ prompt: "",
37770
+ ...bound ? { viewId: bound.id } : {}
37771
+ });
37772
+ ctx.err(`Starting ${created.title}\u2026`);
37773
+ if (bound) {
37774
+ const note = await pinNote(client2.api, bound, created.id);
37775
+ if (note)
37776
+ ctx.err(note);
37777
+ }
37778
+ }
36746
37779
  } finally {
36747
37780
  screen.leave();
36748
37781
  client2.close();
36749
37782
  }
36750
- if (created)
36751
- await tmuxPane(ctx, created.id, flags);
37783
+ const show = created?.id ?? opened;
37784
+ if (show)
37785
+ await tmuxPane(ctx, show, flags);
36752
37786
  }
36753
37787
 
36754
37788
  // packages/cli/dist/commands/tmux.js
@@ -36771,16 +37805,17 @@ async function tmuxDaemon(ctx, flags) {
36771
37805
  const name0 = await tmuxSessionName(env);
36772
37806
  let session = name0;
36773
37807
  try {
36774
- const id = (await tmuxRun(["display-message", "-p", "-t", tmuxTarget(name0), "#{session_id}"])).trim();
36775
- if (id)
36776
- session = id;
37808
+ const id2 = (await tmuxRun(["display-message", "-p", "-t", tmuxTarget(name0), "#{session_id}"])).trim();
37809
+ if (id2)
37810
+ session = id2;
36777
37811
  } catch {
36778
37812
  }
36779
37813
  const sessionName = async () => (await tmuxRun(["display-message", "-p", "-t", tmuxTarget(session), "#S"])).trim() || name0;
36780
37814
  const dir = tmuxSessionStateDir(name0, env);
36781
37815
  const pidFile = join33(dir, "daemon.pid");
36782
37816
  const logFile = join33(dir, "daemon.log");
36783
- const viewOf = (st, name) => viewOrMissing(st, bindingRef(env, name));
37817
+ const machine = hostname9();
37818
+ const id = terminalId("tmux", name0, machine);
36784
37819
  if (flags.once) {
36785
37820
  const { client: client3, state } = await loadMirrorState(ctx, flags);
36786
37821
  try {
@@ -36793,7 +37828,7 @@ async function tmuxDaemon(ctx, flags) {
36793
37828
  state,
36794
37829
  onStateChange: () => () => {
36795
37830
  },
36796
- view: (n) => viewOf(state(), n),
37831
+ view: () => pickerBinding(state(), env, id),
36797
37832
  sessionName,
36798
37833
  stateDir: dir,
36799
37834
  launcherPath,
@@ -36850,6 +37885,24 @@ async function tmuxDaemon(ctx, flags) {
36850
37885
  });
36851
37886
  let currentName = name0;
36852
37887
  const trackedName = async () => currentName = await sessionName();
37888
+ let shows;
37889
+ const terminal = syncTerminal({
37890
+ api: client2.api,
37891
+ info: {
37892
+ id,
37893
+ kind: "tmux",
37894
+ name: name0,
37895
+ machine,
37896
+ hostId: localHostId(ctx.env, client2.api.baseUrl)
37897
+ },
37898
+ state: () => client2.store.getState().synced ? mirrorStateOf(client2) : null,
37899
+ subscribe: (fn) => client2.store.subscribe(fn),
37900
+ env,
37901
+ shows: () => shows,
37902
+ wasMirroring: ownsWindows(dir),
37903
+ legacyName: () => currentName,
37904
+ log
37905
+ });
36853
37906
  const daemon = new TmuxDaemon({
36854
37907
  run: tmuxRun,
36855
37908
  control: tmuxControl,
@@ -36857,36 +37910,56 @@ async function tmuxDaemon(ctx, flags) {
36857
37910
  session,
36858
37911
  state: () => client2.store.getState().synced ? mirrorStateOf(client2) : null,
36859
37912
  onStateChange: (fn) => client2.store.subscribe(fn),
36860
- view: (n) => viewOf(mirrorStateOf(client2), n),
37913
+ view: () => terminal.binding(),
37914
+ terminalId: id,
37915
+ onShows: (ids2) => {
37916
+ shows = ids2;
37917
+ terminal.report();
37918
+ },
36861
37919
  sessionName: trackedName,
36862
37920
  stateDir: dir,
36863
37921
  launcherPath,
36864
37922
  log
36865
37923
  });
36866
37924
  await daemon.start();
36867
- const machine = hostname6();
36868
- const presence = trackPresence({
36869
- api: client2.api,
36870
- getView: () => {
36871
- const v = viewOf(mirrorStateOf(client2), currentName);
36872
- return v === "missing" ? null : v;
36873
- },
36874
- subscribe: (fn) => client2.store.subscribe(fn),
36875
- surface: {
36876
- id: `tmux:${name0}@${machine}`,
36877
- kind: "tmux",
36878
- name: name0,
36879
- machine,
36880
- hostId: localHostId(ctx.env, client2.api.baseUrl)
37925
+ const focus = startFocusPresence({
37926
+ terminalId: id,
37927
+ send: (presence) => client2.send({ type: "presence", presence }),
37928
+ // Polled: a window or pane switch shows within one check (5 s).
37929
+ pollMs: 5e3,
37930
+ focused: async () => {
37931
+ const out = await tmuxRun([
37932
+ "display-message",
37933
+ "-p",
37934
+ "-t",
37935
+ // A pane target: `=name` alone names no pane here.
37936
+ session.startsWith("$") ? session : `${tmuxTarget(session)}:`,
37937
+ `#{session_attached} #{pane_id} #{${WINDOW_OPTION}}`
37938
+ ]);
37939
+ const [attached, pane, sid] = out.trim().split(" ");
37940
+ if (!(Number(attached) > 0))
37941
+ return null;
37942
+ return sid || (pane ? paneSession(mirrorStateOf(client2), id, pane) : null);
36881
37943
  },
36882
37944
  log
36883
37945
  });
36884
- const leave = () => void presence.stop().finally(() => process.exit(0));
37946
+ const leave = () => {
37947
+ focus.stop();
37948
+ void terminal.stop().finally(() => process.exit(0));
37949
+ };
36885
37950
  process.once("SIGTERM", leave);
36886
37951
  process.once("SIGINT", leave);
36887
37952
  await new Promise(() => {
36888
37953
  });
36889
37954
  }
37955
+ function ownsWindows(dir) {
37956
+ try {
37957
+ const raw = JSON.parse(readFileSync16(join33(dir, "windows.json"), "utf8"));
37958
+ return Object.keys(raw.ownWindows ?? {}).length > 0;
37959
+ } catch {
37960
+ return false;
37961
+ }
37962
+ }
36890
37963
  async function tmuxStatus(ctx, flags) {
36891
37964
  const { api } = connect(ctx, flags);
36892
37965
  const sessions = await api.get("/api/sessions");
@@ -36921,6 +37994,7 @@ async function tmuxPair(ctx, flags) {
36921
37994
  const session = flags.session ?? "switchyard";
36922
37995
  const path3 = writePairFile(ctx, "tmux", session, flags);
36923
37996
  ctx.out(`Wrote ${path3}`);
37997
+ await pairBinding(ctx, "tmux", session, flags);
36924
37998
  ctx.out("Load the plugin in .tmux.conf: run-shell <repo>/integrations/tmux/switchyard.tmux");
36925
37999
  ctx.out(`Then start it with: tmux new-session -s ${session}`);
36926
38000
  }
@@ -37085,252 +38159,6 @@ async function tuiCommand(ctx, sessionId, flags, run = runRawTerminal) {
37085
38159
  throw new CliError(result2.message);
37086
38160
  }
37087
38161
 
37088
- // packages/cli/dist/commands/work.js
37089
- function byId2(list) {
37090
- return new Map(list.map((x) => [x.id, x]));
37091
- }
37092
- async function resolveProject(api, ref) {
37093
- const projects = await api.get("/api/projects");
37094
- const exact = projects.find((p) => p.id === ref);
37095
- if (exact)
37096
- return exact;
37097
- const named = projects.filter((p) => p.name.toLowerCase() === ref.toLowerCase());
37098
- if (named.length === 1)
37099
- return named[0];
37100
- if (named.length > 1)
37101
- throw new CliError(`Several projects are named "${ref}"; use the id`);
37102
- const known = projects.map((p) => `${p.name} (${p.id})`).join(", ") || "none";
37103
- throw new CliError(`Unknown project "${ref}". Projects: ${known}`);
37104
- }
37105
- async function sessionsList(ctx, flags) {
37106
- const { api } = connect(ctx, flags);
37107
- const projectId = flags.project ? (await resolveProject(api, flags.project)).id : void 0;
37108
- const [sessions, projects, hosts] = await Promise.all([
37109
- api.get(`/api/sessions${projectId ? `?projectId=${encodeURIComponent(projectId)}` : ""}`),
37110
- api.get("/api/projects"),
37111
- api.get("/api/hosts")
37112
- ]);
37113
- const p = byId2(projects);
37114
- const h = byId2(hosts);
37115
- printList(ctx, flags.json, sessions, ["ID", "RUNTIME", "PROJECT", "HOST", "ACTIVE", "TITLE"], sessions.map((s) => [
37116
- s.id,
37117
- s.runtime,
37118
- s.projectId && p.get(s.projectId)?.name || "-",
37119
- h.get(s.hostId)?.name ?? s.hostId,
37120
- ago(s.lastActivityAt),
37121
- s.title
37122
- ]), "No sessions.");
37123
- }
37124
- async function sessionsImport(ctx, sessionFile, flags) {
37125
- const { api } = connect(ctx, flags);
37126
- let hostId;
37127
- if (flags.host) {
37128
- hostId = (await resolveHost(api, flags.host)).id;
37129
- } else {
37130
- const hosts = (await api.get("/api/hosts")).filter((x) => !x.revokedAt);
37131
- if (hosts.length !== 1) {
37132
- throw new CliError(`Choose a host with --host (${hosts.map((x) => `${x.name}: ${x.id}`).join(", ") || "none enrolled"})`);
37133
- }
37134
- hostId = hosts[0].id;
37135
- }
37136
- const projectId = flags.project ? (await resolveProject(api, flags.project)).id : null;
37137
- const session = await api.post("/api/sessions/import", {
37138
- hostId,
37139
- sessionFile,
37140
- projectId
37141
- });
37142
- if (flags.json)
37143
- ctx.out(JSON.stringify(session, null, 2));
37144
- else
37145
- ctx.out(`Imported ${session.title} as ${session.id} (stopped; resume it to continue)`);
37146
- return session;
37147
- }
37148
- function taskCreateBody(projectId, flags) {
37149
- const body2 = {
37150
- projectId,
37151
- title: flags.title,
37152
- objective: flags.objective ?? "",
37153
- acceptanceCriteria: (flags.criteria ?? []).map((c) => c.trim()).filter(Boolean),
37154
- state: flags.ready ? "ready" : "backlog"
37155
- };
37156
- if (flags.priority !== void 0)
37157
- body2.priority = parsePriority(flags.priority);
37158
- return body2;
37159
- }
37160
- function parsePriority(v) {
37161
- const byName = PRIORITY_LABELS.findIndex((l) => l.toLowerCase() === v.toLowerCase());
37162
- const n = byName >= 0 ? byName : Number(v);
37163
- if (n === 0 || n === 1 || n === 2 || n === 3)
37164
- return n;
37165
- throw new CliError(`Priority must be 0-3 or one of ${PRIORITY_LABELS.join(", ")}`);
37166
- }
37167
- async function tasksCreate(ctx, flags) {
37168
- const { api } = connect(ctx, flags);
37169
- const project = await resolveProject(api, flags.project);
37170
- const task = await api.post("/api/tasks", taskCreateBody(project.id, flags));
37171
- if (flags.json)
37172
- ctx.out(JSON.stringify(task, null, 2));
37173
- else {
37174
- ctx.out(`Created ${task.id}: ${task.title} (${task.state})`);
37175
- if (task.state === "ready")
37176
- ctx.out("Ready tasks start automatically when eligible.");
37177
- }
37178
- return task;
37179
- }
37180
- function parseStates(v) {
37181
- if (!v)
37182
- return void 0;
37183
- const states = v.split(",").map((s) => s.trim()).filter(Boolean);
37184
- for (const s of states) {
37185
- if (!TaskState.safeParse(s).success) {
37186
- throw new CliError(`Unknown state "${s}". States: ${TaskState.options.join(", ")}`);
37187
- }
37188
- }
37189
- return states;
37190
- }
37191
- async function tasksList(ctx, flags) {
37192
- const { api } = connect(ctx, flags);
37193
- const states = parseStates(flags.state);
37194
- const projectId = flags.project ? (await resolveProject(api, flags.project)).id : void 0;
37195
- const q = new URLSearchParams();
37196
- if (states)
37197
- q.set("state", states.join(","));
37198
- if (projectId)
37199
- q.set("projectId", projectId);
37200
- if (flags.all)
37201
- q.set("includeHidden", "true");
37202
- const qs = q.toString();
37203
- const [tasks, projects] = await Promise.all([
37204
- api.get(`/api/tasks${qs ? `?${qs}` : ""}`),
37205
- api.get("/api/projects")
37206
- ]);
37207
- const p = byId2(projects);
37208
- printList(ctx, flags.json, tasks, ["ID", "STATE", "PRIORITY", "PROJECT", "TITLE"], tasks.map((t) => [
37209
- t.id,
37210
- t.blocked ? `${t.state} (blocked)` : t.state,
37211
- PRIORITY_LABELS[t.priority] ?? String(t.priority),
37212
- p.get(t.projectId)?.name ?? t.projectId,
37213
- t.title
37214
- ]), "No tasks.");
37215
- }
37216
- async function tasksMove(ctx, id, to, flags) {
37217
- if (to.includes(","))
37218
- throw new CliError(`Give one target state, not a list ("${to}")`);
37219
- const [state] = parseStates(to) ?? [];
37220
- if (!state)
37221
- throw new CliError("Give the target state");
37222
- const { api } = connect(ctx, flags);
37223
- const body2 = { to: state };
37224
- if (flags.confirm)
37225
- body2.confirm = true;
37226
- if (flags.onRunning)
37227
- body2.onRunning = flags.onRunning;
37228
- const task = await api.post(`/api/tasks/${encodeURIComponent(id)}/move`, body2);
37229
- if (flags.json)
37230
- ctx.out(JSON.stringify(task, null, 2));
37231
- else
37232
- ctx.out(`Moved ${task.title} to ${task.state}`);
37233
- return task;
37234
- }
37235
- async function automationsList(ctx, flags) {
37236
- const { api } = connect(ctx, flags);
37237
- const list = await api.get("/api/automations");
37238
- printList(ctx, flags.json, list, ["ID", "ENABLED", "NEXT", "NAME", "TRIGGER"], list.map((a) => [a.id, a.enabled ? "yes" : "no", a.nextAt ?? "-", a.name, a.summary]), "No automations.");
37239
- }
37240
- async function automationsRun(ctx, id, flags) {
37241
- const { api } = connect(ctx, flags);
37242
- const res = await api.post(`/api/automations/${encodeURIComponent(id)}/run`, {});
37243
- if (flags.json) {
37244
- ctx.out(JSON.stringify(res, null, 2));
37245
- return;
37246
- }
37247
- const o = res.occurrence;
37248
- ctx.out(`Occurrence ${o.id}: ${o.state}${o.reason ? ` (${o.reason})` : ""}${res.task ? `; task ${res.task.id} "${res.task.title}" is ${res.task.state}` : ""}`);
37249
- }
37250
-
37251
- // packages/cli/dist/commands/views.js
37252
- async function resolveView(api, ref) {
37253
- const views = await api.get("/api/views");
37254
- const v = findView(views, ref);
37255
- if (v)
37256
- return v;
37257
- const known = views.map((x) => x.name).join(", ") || "none";
37258
- throw new CliError(`Unknown view "${ref}". Views: ${known}`);
37259
- }
37260
- function checkMode(mode) {
37261
- if (mode !== void 0 && mode !== "all" && mode !== "pinned") {
37262
- throw new CliError('--mode must be "all" or "pinned"');
37263
- }
37264
- }
37265
- async function viewsList(ctx, flags) {
37266
- const { api } = connect(ctx, flags);
37267
- const [views, projects, hosts, surfaces] = await Promise.all([
37268
- api.get("/api/views"),
37269
- api.get("/api/projects"),
37270
- api.get("/api/hosts"),
37271
- api.get("/api/surfaces").catch(() => [])
37272
- ]);
37273
- const names = (ids2, all) => ids2 === null ? "any" : ids2.map((i) => all.find((x) => x.id === i)?.name ?? i).join(", ") || "-";
37274
- printList(ctx, flags.json, views, ["NAME", "MODE", "PROJECTS", "HOSTS", "PINNED", "OPEN IN"], views.map((v) => [
37275
- v.name,
37276
- v.mode,
37277
- names(v.projectIds, projects),
37278
- names(v.hostIds, hosts),
37279
- String(v.sessionIds.length),
37280
- openSurfaces(surfaces, v.id).map((c) => `${c.kind} ${c.name} (${c.machine})`).join(", ") || "-"
37281
- ]), "No views.");
37282
- }
37283
- async function ids(api, refs, kind) {
37284
- if (!refs || refs.length === 0)
37285
- return void 0;
37286
- const out = [];
37287
- for (const r of refs) {
37288
- out.push((kind === "project" ? await resolveProject(api, r) : await resolveHost(api, r)).id);
37289
- }
37290
- return out;
37291
- }
37292
- async function viewsCreate(ctx, name, flags) {
37293
- checkMode(flags.mode);
37294
- const { api } = connect(ctx, flags);
37295
- const projectIds = await ids(api, flags.project, "project");
37296
- const hostIds = await ids(api, flags.host, "host");
37297
- const v = await api.post("/api/views", {
37298
- name,
37299
- ...flags.mode ? { mode: flags.mode } : {},
37300
- ...projectIds ? { projectIds } : {},
37301
- ...hostIds ? { hostIds } : {}
37302
- });
37303
- ctx.out(`Created view ${v.name} (${v.id})`);
37304
- }
37305
- async function viewsEdit(ctx, ref, flags) {
37306
- checkMode(flags.mode);
37307
- const { api } = connect(ctx, flags);
37308
- const v = await resolveView(api, ref);
37309
- const projectIds = flags.anyProject ? null : await ids(api, flags.project, "project");
37310
- const hostIds = flags.anyHost ? null : await ids(api, flags.host, "host");
37311
- const body2 = {
37312
- ...flags.name ? { name: flags.name } : {},
37313
- ...flags.mode ? { mode: flags.mode } : {},
37314
- ...projectIds !== void 0 ? { projectIds } : {},
37315
- ...hostIds !== void 0 ? { hostIds } : {}
37316
- };
37317
- await api.request("PATCH", `/api/views/${encodeURIComponent(v.id)}`, body2);
37318
- ctx.out(`Updated view ${flags.name ?? v.name}`);
37319
- }
37320
- async function viewsDelete(ctx, ref, flags) {
37321
- const { api } = connect(ctx, flags);
37322
- const v = await resolveView(api, ref);
37323
- await api.request("DELETE", `/api/views/${encodeURIComponent(v.id)}`);
37324
- ctx.out(`Deleted view ${v.name}`);
37325
- }
37326
- async function viewsPin(ctx, ref, sessionId, flags, unpin = false) {
37327
- const { api } = connect(ctx, flags);
37328
- const v = await resolveView(api, ref);
37329
- const path3 = `/api/views/${encodeURIComponent(v.id)}/sessions/${encodeURIComponent(sessionId)}`;
37330
- await api.request(unpin ? "DELETE" : "POST", path3);
37331
- ctx.out(`${unpin ? "Unpinned" : "Pinned"} ${sessionId} ${unpin ? "from" : "in"} ${v.name}`);
37332
- }
37333
-
37334
38162
  // packages/cli/dist/main.js
37335
38163
  var CLI_VERSION = JSON.parse(readFileSync17(new URL("../package.json", import.meta.url), "utf8")).version;
37336
38164
  function describeError(err) {
@@ -37427,10 +38255,12 @@ function buildProgram(ctx = defaultCtx()) {
37427
38255
  connectionOptions(herdr.command("status").description("Which herdr tab shows which session")).action(async (o) => {
37428
38256
  await herdrStatus(ctx, connFlags(o));
37429
38257
  });
37430
- herdr.command("pair").description("Pair a herdr session (default: the unnamed one) with Switchyard").option("--session <name>", "herdr session name (default: default)").option("--view <name>", "view to mirror (default: every session)").option("--cli <command>", "how to run switchyard").option("--client-config <path>", "client.json to use").option("--force", "replace an existing pairing").action(async (o) => {
38258
+ herdr.command("pair").description("Pair a herdr session (default: the unnamed one) with Switchyard").option("--session <name>", "herdr session name (default: default)").option("--view <name>", "mirror this view (recorded with the coordinator)").option("--all", "mirror every session").option("--none", "mirror nothing").option("--cli <command>", "how to run switchyard").option("--client-config <path>", "client.json to use").option("--force", "replace an existing pairing").action(async (o) => {
37431
38259
  await herdrPair(ctx, {
37432
38260
  session: o.session,
37433
38261
  view: o.view,
38262
+ all: o.all,
38263
+ none: o.none,
37434
38264
  cli: o.cli,
37435
38265
  clientConfig: o.clientConfig,
37436
38266
  force: o.force
@@ -37449,16 +38279,22 @@ function buildProgram(ctx = defaultCtx()) {
37449
38279
  connectionOptions(tmux.command("status").description("Which tmux window shows which session")).action(async (o) => {
37450
38280
  await tmuxStatus(ctx, connFlags(o));
37451
38281
  });
37452
- tmux.command("pair").description("Pair a tmux session (default: switchyard) with Switchyard").option("--session <name>", "tmux session name (default: switchyard)").option("--view <name>", "view to mirror (default: every session)").option("--cli <command>", "how to run switchyard").option("--client-config <path>", "client.json to use").option("--force", "replace an existing pairing").action(async (o) => {
38282
+ tmux.command("pair").description("Pair a tmux session (default: switchyard) with Switchyard").option("--session <name>", "tmux session name (default: switchyard)").option("--view <name>", "mirror this view (recorded with the coordinator)").option("--all", "mirror every session").option("--none", "mirror nothing").option("--cli <command>", "how to run switchyard").option("--client-config <path>", "client.json to use").option("--force", "replace an existing pairing").action(async (o) => {
37453
38283
  await tmuxPair(ctx, {
37454
38284
  session: o.session,
37455
38285
  view: o.view,
38286
+ all: o.all,
38287
+ none: o.none,
37456
38288
  cli: o.cli,
37457
38289
  clientConfig: o.clientConfig,
37458
38290
  force: o.force
37459
38291
  });
37460
38292
  });
37461
- const views = program.command("views").description("Views: named sets of projects and pins that surfaces show");
38293
+ const terminals = program.command("terminals").description("Terminals: herdr and tmux sessions, and what each one mirrors");
38294
+ connectionOptions(terminals.command("list").description("List terminals")).option("--json", "JSON output").action((o) => terminalsList(ctx, { ...connFlags(o), json: o.json }));
38295
+ connectionOptions(terminals.command("bind <terminal>").description("Choose what a terminal mirrors (herdr:<session>, tmux:<session> or a full id)")).option("--view <name>", "a view").option("--all", "every session").option("--none", "nothing").action((ref, o) => terminalsBind(ctx, ref, { ...connFlags(o), view: o.view, all: o.all, none: o.none }));
38296
+ connectionOptions(terminals.command("forget <terminal>").description("Forget a terminal and its binding")).action((ref, o) => terminalsForget(ctx, ref, connFlags(o)));
38297
+ const views = program.command("views").description("Views: named sets of projects and pins that terminals can mirror");
37462
38298
  const collect = (v, prev = []) => [...prev, v];
37463
38299
  connectionOptions(views.command("list").description("List views")).option("--json", "JSON output").action((o) => viewsList(ctx, { ...connFlags(o), json: o.json }));
37464
38300
  connectionOptions(views.command("create <name>").description("Create a view")).option("--mode <mode>", "all (matching or pinned) or pinned (pinned only)").option("--project <project>", "limit to a project (repeatable)", collect).option("--host <host>", "limit to a host (repeatable)", collect).action((name, o) => viewsCreate(ctx, name, {