@spencerboucher/switchyard 0.18.1 → 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 +9 -6
  2. package/dist/bridge/enroll.js +36 -6
  3. package/dist/bridge/switchyard-terminal.js +2 -1
  4. package/dist/policies/worker.js +48 -21
  5. package/dist/switchyard.mjs +1435 -617
  6. package/package.json +1 -1
  7. package/web-dist/assets/AutomationView-B4O_teaB.js +2 -0
  8. package/web-dist/assets/{AutomationView-DU4GvjqD.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-Bo-ScAiV.js → Markdown-BPWc6K6m.js} +2 -2
  20. package/web-dist/assets/{Markdown-Bo-ScAiV.js.map → Markdown-BPWc6K6m.js.map} +1 -1
  21. package/web-dist/assets/{Priority-f7KceEZQ.js → Priority-ZGpTH645.js} +2 -2
  22. package/web-dist/assets/{Priority-f7KceEZQ.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-B04kPhBs.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-BgpFIjqW.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-CHlMHtMT.js → UINodeRenderer-BaANWHvJ.js} +3 -3
  34. package/web-dist/assets/{UINodeRenderer-CHlMHtMT.js.map → UINodeRenderer-BaANWHvJ.js.map} +1 -1
  35. package/web-dist/assets/UnfilteredNote-zVO8ajSi.js +2 -0
  36. package/web-dist/assets/{UnfilteredNote-DzKbzrjZ.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-DTTGHyoo.js.map → automations-IX9DQNk8.js.map} +1 -1
  49. package/web-dist/assets/board-BUAI4L7M.js +6 -0
  50. package/web-dist/assets/{board-Blv0pC_z.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-DZMOHGS9.js → core.esm-C4dCvG0s.js} +2 -2
  60. package/web-dist/assets/{core.esm-DZMOHGS9.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-Q2nvYHjg.js → describe-BeFxHr2Y.js} +3 -3
  64. package/web-dist/assets/{describe-Q2nvYHjg.js.map → describe-BeFxHr2Y.js.map} +1 -1
  65. package/web-dist/assets/enroll-GUEF5Uxu.js +2 -0
  66. package/web-dist/assets/{enroll-wAPt550I.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-CpCxpJ43.js → keyboardLayers-BZOygMAH.js} +2 -2
  75. package/web-dist/assets/{keyboardLayers-CpCxpJ43.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-D1YpQrbP.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-CdBAajey.js → queue-DWSd1kia.js} +2 -2
  93. package/web-dist/assets/{queue-CdBAajey.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-f_A68-u-.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-eMNouLWh.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-CjCVyQra.js.map → useNow-DXyC-YfE.js.map} +1 -1
  114. package/web-dist/assets/{useResource-BvhL-G6a.js → useResource-DYNGG9XS.js} +2 -2
  115. package/web-dist/assets/{useResource-BvhL-G6a.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-DU4GvjqD.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-C3H45DAY.js +0 -4
  127. package/web-dist/assets/InteractionCard-C3H45DAY.js.map +0 -1
  128. package/web-dist/assets/Select-B04kPhBs.js +0 -2
  129. package/web-dist/assets/Tabs-BgpFIjqW.js +0 -2
  130. package/web-dist/assets/UnfilteredNote-DzKbzrjZ.js +0 -2
  131. package/web-dist/assets/ViewSelect-Dz7vh4fq.js +0 -2
  132. package/web-dist/assets/ViewSelect-Dz7vh4fq.js.map +0 -1
  133. package/web-dist/assets/api-C9NJpI9q.js +0 -2
  134. package/web-dist/assets/api-C9NJpI9q.js.map +0 -1
  135. package/web-dist/assets/attention-BMxYQaCW.js +0 -2
  136. package/web-dist/assets/attention-BMxYQaCW.js.map +0 -1
  137. package/web-dist/assets/automations-DTTGHyoo.js +0 -2
  138. package/web-dist/assets/board-Blv0pC_z.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-BsVbn6T3.js +0 -25
  142. package/web-dist/assets/code-BsVbn6T3.js.map +0 -1
  143. package/web-dist/assets/enroll-wAPt550I.js +0 -2
  144. package/web-dist/assets/index-9TW72kVM.css +0 -2
  145. package/web-dist/assets/index-Du1kfnPp.js +0 -17
  146. package/web-dist/assets/index-Du1kfnPp.js.map +0 -1
  147. package/web-dist/assets/more-D1YpQrbP.js +0 -2
  148. package/web-dist/assets/policyLogic-Dk_rwjQS.js +0 -2
  149. package/web-dist/assets/policyLogic-Dk_rwjQS.js.map +0 -1
  150. package/web-dist/assets/repo-CTLrFN0k.js +0 -2
  151. package/web-dist/assets/repo-CTLrFN0k.js.map +0 -1
  152. package/web-dist/assets/selection-DDKGpSXL.js +0 -7
  153. package/web-dist/assets/selection-DDKGpSXL.js.map +0 -1
  154. package/web-dist/assets/settings-C3rhTyqj.js +0 -12
  155. package/web-dist/assets/settings-C3rhTyqj.js.map +0 -1
  156. package/web-dist/assets/states-f_A68-u-.js.map +0 -1
  157. package/web-dist/assets/terminal-login-eMNouLWh.js +0 -2
  158. package/web-dist/assets/trackers-BKCB5pxU.js +0 -2
  159. package/web-dist/assets/trackers-BKCB5pxU.js.map +0 -1
  160. package/web-dist/assets/useNow-CjCVyQra.js +0 -2
  161. package/web-dist/assets/workboard-Btp-KIzn.js +0 -3
  162. package/web-dist/assets/workboard-Btp-KIzn.js.map +0 -1
@@ -1165,31 +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
- /**
1173
- * The source surface (`herdr:<session>@<machine>`): sessions started in it
1174
- * (`Session.startedIn`) belong to this view.
1175
- */
1176
- clientId: z6.string().min(1).max(200).nullable().optional(),
1177
1172
  createdAt: Iso,
1178
1173
  updatedAt: Iso
1179
1174
  });
1180
- var SurfaceKind = z6.enum(["herdr", "tmux"]);
1181
- var Surface = z6.object({
1175
+ var TerminalKind = z6.enum(["herdr", "tmux"]);
1176
+ var TerminalMirror = z6.enum(["none", "all", "view"]);
1177
+ var Terminal = z6.object({
1182
1178
  /** `${kind}:${name}@${machine}` */
1183
1179
  id: z6.string().min(1).max(200),
1184
- kind: SurfaceKind,
1180
+ kind: TerminalKind,
1185
1181
  name: z6.string().min(1),
1186
1182
  machine: z6.string().min(1),
1187
1183
  deviceId: Id4,
1188
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). */
1189
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(),
1190
1193
  lastSeenAt: Iso,
1191
1194
  createdAt: Iso
1192
1195
  });
1196
+ function terminalMirror(t) {
1197
+ return t.mirror ?? (t.viewId ? "view" : "none");
1198
+ }
1193
1199
  var RuntimeState = z6.enum([
1194
1200
  "starting",
1195
1201
  "idle",
@@ -1251,12 +1257,18 @@ var Session = z6.object({
1251
1257
  * in, when known). Switchyard never shows or closes that terminal.
1252
1258
  */
1253
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(),
1254
1268
  /** The session this subagent was started by (coordinator-owned). */
1255
1269
  parentSessionId: Id4.nullable().optional(),
1256
1270
  /** Chosen as its branch's primary session (coordinator-owned); without one the primary is derived. */
1257
1271
  primary: z6.boolean().optional(),
1258
- /** The surface this Pi was started in, e.g. `herdr:default@mac` (coordinator-owned, set once). */
1259
- startedIn: z6.string().min(1).max(200).nullable().optional(),
1260
1272
  /** Set when the session finished or failed with nobody viewing it; cleared when viewed (coordinator-owned). */
1261
1273
  unreadSince: Iso.nullable().optional(),
1262
1274
  /** Identity of the adapter presentation currently installed on the host. */
@@ -1487,6 +1499,11 @@ var AttentionReason = z6.enum([
1487
1499
  "host_unreachable",
1488
1500
  "cache_expiring"
1489
1501
  ]);
1502
+ var INPUT_ATTENTION_REASONS = [
1503
+ "needs_input",
1504
+ "unsupported_interaction"
1505
+ ];
1506
+ var isInputAttentionReason = (r) => INPUT_ATTENTION_REASONS.includes(r);
1490
1507
  var AttentionItem = z6.object({
1491
1508
  id: Id4,
1492
1509
  sessionId: Id4.nullable(),
@@ -2223,13 +2240,15 @@ var EventDataSchemas = {
2223
2240
  "device.updated": Device,
2224
2241
  "issue.updated": TrackedIssue,
2225
2242
  "issue.deleted": z11.object({ id: z11.string() }),
2226
- "surface.updated": Surface,
2227
- "surface.deleted": z11.object({ id: z11.string() }),
2243
+ "terminal.updated": Terminal,
2244
+ "terminal.deleted": z11.object({ id: z11.string() }),
2228
2245
  "settings.updated": z11.object({ dispatchPaused: z11.boolean() })
2229
2246
  };
2230
2247
  var EVENT_TYPES = Object.keys(EventDataSchemas);
2231
2248
  var LEGACY_EVENT_TYPES = {
2232
- "workspace.removed": "workspace.deleted"
2249
+ "workspace.removed": "workspace.deleted",
2250
+ "surface.updated": "terminal.updated",
2251
+ "surface.deleted": "terminal.deleted"
2233
2252
  };
2234
2253
  function canonicalEventType(type) {
2235
2254
  return LEGACY_EVENT_TYPES[type] ?? type;
@@ -3142,7 +3161,17 @@ var MeResponse = z14.object({
3142
3161
  admin: z14.boolean(),
3143
3162
  publicUrl: z14.string()
3144
3163
  });
3145
- 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({
3146
3175
  kind: true,
3147
3176
  name: true,
3148
3177
  machine: true,
@@ -3152,8 +3181,7 @@ var ViewInput = View.pick({
3152
3181
  name: true,
3153
3182
  mode: true,
3154
3183
  projectIds: true,
3155
- hostIds: true,
3156
- clientId: true
3184
+ hostIds: true
3157
3185
  }).partial({
3158
3186
  mode: true,
3159
3187
  projectIds: true,
@@ -3173,7 +3201,7 @@ function reconnectDelay(attempt, steps = RECONNECT_BACKOFF_MS, random = Math.ran
3173
3201
  }
3174
3202
 
3175
3203
  // packages/protocol/dist/views.js
3176
- var SURFACE_OPEN_MS = 10 * 6e4;
3204
+ var TERMINAL_OPEN_MS = 10 * 6e4;
3177
3205
  var LIVE_RUNTIMES = ["starting", "idle", "running", "waiting_input"];
3178
3206
  function isLiveRuntime(r) {
3179
3207
  return LIVE_RUNTIMES.includes(r);
@@ -3208,8 +3236,6 @@ function sessionViewReason(view, s, workspaces, scope) {
3208
3236
  return null;
3209
3237
  if (view.sessionIds.includes(s.id))
3210
3238
  return "pinned";
3211
- if (view.clientId && s.startedIn === view.clientId)
3212
- return "client";
3213
3239
  if (view.mode === "pinned")
3214
3240
  return null;
3215
3241
  const projectId = s.projectId ?? (s.workspaceId ? workspaceOf(workspaces, s.workspaceId)?.projectId : null) ?? null;
@@ -3234,8 +3260,11 @@ ${ws.branch}`))
3234
3260
  function sessionInView(view, s, workspaces, scope) {
3235
3261
  return sessionViewReason(view, s, workspaces, scope) !== null;
3236
3262
  }
3237
- function openSurfaces(surfaces, viewId, now = Date.now()) {
3238
- 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));
3239
3268
  }
3240
3269
  function findView(views, ref) {
3241
3270
  const byId3 = views.find((v) => v.id === ref);
@@ -3433,15 +3462,22 @@ var SyncState = z15.object({
3433
3462
  devices: z15.array(Device),
3434
3463
  /** Tracked issues; absent from older coordinators. */
3435
3464
  issues: z15.array(TrackedIssue).default([]),
3436
- /** Terminal surfaces; absent from older coordinators. */
3437
- 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(),
3438
3469
  adapters: z15.record(z15.string(), z15.array(AdapterInfo)),
3439
3470
  dispatchPaused: z15.boolean()
3440
3471
  });
3441
3472
  var Presence = z15.object({
3442
3473
  foreground: z15.boolean(),
3443
3474
  interactedAt: z15.string().nullable(),
3444
- 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()
3445
3481
  });
3446
3482
  var CLIENT_CAPABILITIES = ["adapter.slots.v1", "timeline.cards.v1"];
3447
3483
  var ClientToServer = z15.discriminatedUnion("type", [
@@ -3611,7 +3647,7 @@ function emptyState() {
3611
3647
  interactions: {},
3612
3648
  panels: {},
3613
3649
  devices: {},
3614
- surfaces: {},
3650
+ terminals: {},
3615
3651
  issues: {},
3616
3652
  dispatchPaused: false
3617
3653
  };
@@ -3662,7 +3698,7 @@ function applySnapshot(state, seq, snap) {
3662
3698
  interactions: byId(snap.interactions),
3663
3699
  panels,
3664
3700
  devices: byId(snap.devices),
3665
- surfaces: byId(snap.surfaces ?? []),
3701
+ terminals: byId(snap.terminals ?? snap.surfaces ?? []),
3666
3702
  issues: byId(snap.issues ?? []),
3667
3703
  dispatchPaused: snap.dispatchPaused
3668
3704
  };
@@ -3786,13 +3822,13 @@ function reduceEvent(state, type, data) {
3786
3822
  const d = data;
3787
3823
  return { ...state, issues: drop(state.issues, d.id) };
3788
3824
  }
3789
- case "surface.updated": {
3825
+ case "terminal.updated": {
3790
3826
  const d = data;
3791
- return { ...state, surfaces: put(state.surfaces, d.id, d) };
3827
+ return { ...state, terminals: put(state.terminals, d.id, d) };
3792
3828
  }
3793
- case "surface.deleted": {
3829
+ case "terminal.deleted": {
3794
3830
  const d = data;
3795
- return { ...state, surfaces: drop(state.surfaces, d.id) };
3831
+ return { ...state, terminals: drop(state.terminals, d.id) };
3796
3832
  }
3797
3833
  case "settings.updated": {
3798
3834
  const d = data;
@@ -6926,7 +6962,7 @@ function isEnrollMeta(v) {
6926
6962
  if (!v || typeof v !== "object")
6927
6963
  return false;
6928
6964
  const m = v;
6929
- 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";
6930
6966
  }
6931
6967
  function readEnrollMeta(socketPath) {
6932
6968
  try {
@@ -11353,15 +11389,15 @@ var HostDb = class {
11353
11389
  else
11354
11390
  fn();
11355
11391
  }
11356
- run(sql20, params = []) {
11357
- const r = this.db.prepare(sql20).run(...params);
11392
+ run(sql23, params = []) {
11393
+ const r = this.db.prepare(sql23).run(...params);
11358
11394
  return { changes: Number(r.changes), lastInsertRowid: Number(r.lastInsertRowid) };
11359
11395
  }
11360
- get(sql20, params = []) {
11361
- return this.db.prepare(sql20).get(...params);
11396
+ get(sql23, params = []) {
11397
+ return this.db.prepare(sql23).get(...params);
11362
11398
  }
11363
- all(sql20, params = []) {
11364
- return this.db.prepare(sql20).all(...params);
11399
+ all(sql23, params = []) {
11400
+ return this.db.prepare(sql23).all(...params);
11365
11401
  }
11366
11402
  // ---- meta ----
11367
11403
  getMeta(key) {
@@ -11371,12 +11407,12 @@ var HostDb = class {
11371
11407
  this.run("INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value", [key, value]);
11372
11408
  }
11373
11409
  // ---- JSON row helpers ----
11374
- getJson(sql20, params = []) {
11375
- const r = this.get(sql20, params);
11410
+ getJson(sql23, params = []) {
11411
+ const r = this.get(sql23, params);
11376
11412
  return r ? JSON.parse(r.json) : void 0;
11377
11413
  }
11378
- allJson(sql20, params = []) {
11379
- return this.all(sql20, params).map((r) => JSON.parse(r.json));
11414
+ allJson(sql23, params = []) {
11415
+ return this.all(sql23, params).map((r) => JSON.parse(r.json));
11380
11416
  }
11381
11417
  close() {
11382
11418
  try {
@@ -15042,6 +15078,7 @@ var RESTART_TERMINAL_LOST_DETAIL = "Host agent restarted and the terminal sessio
15042
15078
  var terminalLostNotice = (reason3) => `Host agent restarted and the terminal session had ended (${reason3}); resume to continue`;
15043
15079
  var QUEUED_ANSWER_SUMMARY = "Answered from your earlier form";
15044
15080
  var PI_CLOSED_SUMMARY = "Pi closed this question (timeout or abort)";
15081
+ var PI_EXITED_SUMMARY = "Pi exited before this question was answered";
15045
15082
  var UNSUPPORTED_TITLE = "Terminal-only interface requested";
15046
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.";
15047
15084
  var PROMPT_NOT_SENT = "The launch prompt was not sent to Pi";
@@ -15251,7 +15288,7 @@ var SessionSupervisor = class {
15251
15288
  rec.queue = { steering: [], followUp: [] };
15252
15289
  rec.terminal = null;
15253
15290
  rec.external = null;
15254
- this.expirePending(rec.id, lost.expireSummary);
15291
+ this.expirePending(rec.id, lost.expireSummary, true);
15255
15292
  if (next === "interrupted") {
15256
15293
  const item = {
15257
15294
  id: newId("itm"),
@@ -15742,6 +15779,7 @@ var SessionSupervisor = class {
15742
15779
  rec.runtimeDetail = "Attaching to your terminal\u2026";
15743
15780
  rec.terminal = { socketPath };
15744
15781
  rec.external = { client: meta.client };
15782
+ rec.place = meta.client ? { terminalId: meta.client, pane: meta.pane ?? null } : null;
15745
15783
  rec.endedAt = null;
15746
15784
  rec.lastActivityAt = now;
15747
15785
  this.records.set(rec.id, rec);
@@ -15790,6 +15828,7 @@ var SessionSupervisor = class {
15790
15828
  createdAt: rec.createdAt,
15791
15829
  terminal: rec.terminal != null && !rec.external,
15792
15830
  external: rec.external ?? null,
15831
+ place: rec.place ?? null,
15793
15832
  ...rec.bridge ? { bridge: rec.bridge } : {},
15794
15833
  ...rec.adapterGeneration ? { adapterGeneration: rec.adapterGeneration } : {}
15795
15834
  };
@@ -16012,6 +16051,7 @@ var SessionSupervisor = class {
16012
16051
  }, "session started");
16013
16052
  const socketPath = ms.terminalSocket;
16014
16053
  rec.terminal = socketPath ? { socketPath } : null;
16054
+ rec.place = null;
16015
16055
  this.db.tx(() => this.saveAndEmit(rec));
16016
16056
  } catch (err) {
16017
16057
  if (ms.process)
@@ -16763,7 +16803,17 @@ var SessionSupervisor = class {
16763
16803
  rec.external = null;
16764
16804
  this.db.tx(() => this.saveAndEmit(rec));
16765
16805
  }
16766
- 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
+ });
16767
16817
  });
16768
16818
  }
16769
16819
  teardown(l) {
@@ -17114,7 +17164,7 @@ var SessionSupervisor = class {
17114
17164
  state: "expired",
17115
17165
  resolution: {
17116
17166
  by: "pi",
17117
- 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,
17118
17168
  at: nowIso()
17119
17169
  }
17120
17170
  });
@@ -17348,8 +17398,13 @@ var SessionSupervisor = class {
17348
17398
  });
17349
17399
  return next;
17350
17400
  }
17351
- expirePending(sessionId, summary) {
17352
- 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) {
17353
17408
  this.updateInteraction(i, {
17354
17409
  state: "expired",
17355
17410
  resolution: { by: "host", summary, at: nowIso() }
@@ -18449,14 +18504,53 @@ var AttentionService = class {
18449
18504
  resolve(filter) {
18450
18505
  return this.store.tx(() => {
18451
18506
  const items = this.open(filter).filter((a) => !filter.interactionId || a.interactionId === filter.interactionId);
18452
- const now = this.store.nowIso();
18453
- const out = [];
18454
- for (const a of items) {
18455
- const resolved = this.store.putAttention({ ...a, resolvedAt: now });
18456
- out.push(resolved);
18457
- this.store.afterCommit(() => this.hub.emit("attention.resolved", resolved));
18458
- }
18459
- 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() });
18460
18554
  });
18461
18555
  }
18462
18556
  acknowledge(id) {
@@ -18750,9 +18844,6 @@ var Auth = class {
18750
18844
  push: { ...d.push, subscribed: false }
18751
18845
  };
18752
18846
  this.store.deletePushSubscriptionsForDevice(id);
18753
- for (const x of this.store.surfaces.list("device_id = ?", [id])) {
18754
- this.store.deleteSurface(x.id);
18755
- }
18756
18847
  return this.store.putDevice(updated);
18757
18848
  });
18758
18849
  this.hub.emit("device.revoked", { deviceId: id });
@@ -27491,6 +27582,7 @@ var ClientHub = class {
27491
27582
  const p = msg.presence;
27492
27583
  this.store.upsertPresence({
27493
27584
  deviceId: conn.deviceId,
27585
+ terminalId: p.terminalId ?? null,
27494
27586
  foregroundUntil: p.foreground ? new Date(now.getTime() + this.opts.foregroundLeaseMs).toISOString() : null,
27495
27587
  interactedAt: p.interactedAt,
27496
27588
  viewingSessionId: p.viewing?.sessionId ?? null,
@@ -28225,6 +28317,43 @@ UPDATE sessions
28225
28317
  AND COALESCE(json_extract(json, '$.lastAssistantText'), '') = '';
28226
28318
  `;
28227
28319
 
28320
+ // packages/coordinator/dist/db/migrations/020_drop_view_sources.js
28321
+ var sql20 = `
28322
+ UPDATE views SET json = json_remove(json, '$.clientId')
28323
+ WHERE json_type(json, '$.clientId') IS NOT NULL;
28324
+ UPDATE sessions SET json = json_remove(json, '$.startedIn')
28325
+ WHERE json_type(json, '$.startedIn') IS NOT NULL;
28326
+ `;
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
+
28228
28357
  // packages/coordinator/dist/db/index.js
28229
28358
  var MIGRATIONS2 = [
28230
28359
  { version: 1, name: "001_init", sql },
@@ -28245,7 +28374,10 @@ var MIGRATIONS2 = [
28245
28374
  { version: 16, name: "016_session_links", sql: sql16 },
28246
28375
  { version: 17, name: "017_surfaces", sql: sql17 },
28247
28376
  { version: 18, name: "018_panel_event_seq", sql: sql18 },
28248
- { version: 19, name: "019_unread_needs_output", sql: sql19 }
28377
+ { version: 19, name: "019_unread_needs_output", sql: sql19 },
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 }
28249
28381
  ];
28250
28382
  var LATEST_MIGRATION = MIGRATIONS2[MIGRATIONS2.length - 1].version;
28251
28383
  function openDb(path3) {
@@ -28414,6 +28546,7 @@ async function refreshSubagentTranscript(ctx, session) {
28414
28546
  // packages/coordinator/dist/host-hub.js
28415
28547
  var HOST_SESSION_FIELDS = [
28416
28548
  "external",
28549
+ "place",
28417
28550
  "title",
28418
28551
  "subtitle",
28419
28552
  "cwd",
@@ -29198,11 +29331,15 @@ var HostHub = class {
29198
29331
  this.store.appendEvent("diagnostic", { hostId, sessionId: d.sessionId ?? void 0 }, d);
29199
29332
  const att = raw.attention;
29200
29333
  const sessionId = d.sessionId ?? ev.sessionId ?? null;
29201
- 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) {
29202
29336
  const given = att.reason ?? "needs_input";
29203
- 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;
29204
29341
  this.attention.raise({
29205
- reason: reason3.success ? reason3.data : "unsupported_interaction",
29342
+ reason: reason3,
29206
29343
  sessionId,
29207
29344
  summary: typeof att.summary === "string" && att.summary.trim() ? att.summary.slice(0, 500) : d.message
29208
29345
  });
@@ -29319,11 +29456,11 @@ var HostHub = class {
29319
29456
  if ((finished && produced || failed) && !next.unreadSince && !this.beingViewed(id)) {
29320
29457
  next.unreadSince = this.store.nowIso();
29321
29458
  }
29322
- if (next.external?.client && !next.startedIn)
29323
- next.startedIn = next.external.client;
29324
29459
  if (existing && JSON.stringify(existing) === JSON.stringify(next))
29325
29460
  return;
29326
29461
  this.store.putSession(next);
29462
+ if (!isLiveRuntime(next.runtime))
29463
+ this.attention.endSessionInput(id);
29327
29464
  if (partial.bridge !== void 0) {
29328
29465
  this.store.afterCommit(() => this.retryDeferred(hostId));
29329
29466
  }
@@ -29358,6 +29495,18 @@ var HostHub = class {
29358
29495
  }
29359
29496
  /** Keep `needs_input` / `unsupported_interaction` attention in line with interaction state. */
29360
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
+ }
29361
29510
  if (i.state === "pending") {
29362
29511
  this.attention.raise({
29363
29512
  reason: "needs_input",
@@ -30143,6 +30292,7 @@ function registerAttentionRoutes(app, ctx) {
30143
30292
  return ctx.store.attention.list(where.join(" AND ") || void 0, params, `${orderBy} LIMIT ${q.limit}`);
30144
30293
  });
30145
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));
30146
30296
  }
30147
30297
 
30148
30298
  // packages/coordinator/dist/routes/auth.js
@@ -30512,14 +30662,13 @@ function archiveEndedSessions(store, days = sessionArchiveDays(store)) {
30512
30662
  const now = store.nowIso();
30513
30663
  const cutoff = new Date(Date.parse(now) - days * 864e5).toISOString();
30514
30664
  const sessions = store.sessions.list("archived_at IS NULL");
30515
- const pinned = new Set(store.views.list().flatMap((v) => v.sessionIds));
30516
- 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));
30517
30666
  const { branches } = buildBranches({
30518
30667
  workspaces: store.workspaces.list("archived_at IS NULL"),
30519
30668
  sessions,
30520
30669
  issues: []
30521
30670
  });
30522
- 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);
30523
30672
  const archived = /* @__PURE__ */ new Map();
30524
30673
  const archive = (s) => {
30525
30674
  archived.set(s.id, store.putSession({ ...s, archivedAt: now }));
@@ -30531,7 +30680,7 @@ function archiveEndedSessions(store, days = sessionArchiveDays(store)) {
30531
30680
  const known = new Map(sessions.map((s) => [s.id, s]));
30532
30681
  for (const b of branches) {
30533
30682
  for (const s of b.subagents) {
30534
- if (isLiveRuntime(s.runtime) || waiting.has(s.id) || pinned.has(s.id))
30683
+ if (isLiveRuntime(s.runtime) || waiting.has(s.id))
30535
30684
  continue;
30536
30685
  const parentGone = !!s.parentSessionId && (archived.has(s.parentSessionId) || !known.has(s.parentSessionId));
30537
30686
  if (parentGone || stale3(s))
@@ -30544,6 +30693,38 @@ function archiveEndedSessions(store, days = sessionArchiveDays(store)) {
30544
30693
  function sessionArchiveDays(store) {
30545
30694
  return store.getSetting("sessionArchiveDays", DEFAULT_SESSION_ARCHIVE_DAYS);
30546
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
+ }
30547
30728
 
30548
30729
  // packages/coordinator/dist/routes/ops.js
30549
30730
  function registerOpsRoutes(app, ctx) {
@@ -31282,48 +31463,120 @@ function registerSessionRoutes(app, ctx) {
31282
31463
  });
31283
31464
  }
31284
31465
 
31285
- // packages/coordinator/dist/routes/surfaces.js
31286
- var SURFACE_REWRITE_MS = 5 * 6e4;
31287
- 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) {
31288
31484
  const { store } = ctx;
31289
31485
  if (id !== `${body2.kind}:${body2.name}@${body2.machine}`) {
31290
- 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");
31291
31487
  }
31292
31488
  return store.tx(() => {
31293
- if (body2.viewId !== null)
31294
- store.views.require(body2.viewId);
31295
- const existing = store.surfaces.get(id);
31489
+ const existing = store.terminals.get(id);
31296
31490
  const asked = body2.hostId === void 0 ? existing?.hostId ?? null : body2.hostId;
31297
31491
  const hostId = asked && store.hosts.get(asked) ? asked : null;
31298
31492
  const now = store.now();
31299
- 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) {
31300
31504
  return existing;
31301
31505
  }
31302
- return store.putSurface({
31506
+ return store.putTerminal({
31303
31507
  id,
31304
31508
  kind: body2.kind,
31305
31509
  name: body2.name,
31306
31510
  machine: body2.machine,
31307
31511
  deviceId,
31308
31512
  hostId,
31309
- viewId: body2.viewId,
31513
+ mirror,
31514
+ viewId,
31515
+ bindingSetAt,
31516
+ shows,
31310
31517
  lastSeenAt: now.toISOString(),
31311
31518
  createdAt: existing?.createdAt ?? now.toISOString()
31312
31519
  });
31313
31520
  });
31314
31521
  }
31315
- 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) {
31316
31551
  const { store } = ctx;
31317
31552
  const idOf = (req) => req.params.id;
31318
- 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));
31319
31568
  app.put("/api/surfaces/:id", async (req) => {
31320
31569
  const body2 = parse2(SurfaceReport, req.body);
31321
- return reportSurface(ctx, idOf(req), body2, deviceOf(req).id);
31322
- });
31323
- app.delete("/api/surfaces/:id", async (req) => {
31324
- store.deleteSurface(idOf(req));
31325
- 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);
31326
31578
  });
31579
+ app.delete("/api/surfaces/:id", async (req) => ({ ok: true, id: idOf(req) }));
31327
31580
  }
31328
31581
 
31329
31582
  // packages/coordinator/dist/routes/views.js
@@ -31379,8 +31632,8 @@ function registerViewRoutes(app, ctx) {
31379
31632
  });
31380
31633
  app.delete("/api/views/:id", async (req) => store.tx(() => {
31381
31634
  const v = store.views.require(idOf(req));
31382
- for (const x of store.surfaces.list("view_id = ?", [v.id])) {
31383
- 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 });
31384
31637
  }
31385
31638
  store.deleteView(v.id);
31386
31639
  return { ok: true, id: v.id };
@@ -31388,9 +31641,11 @@ function registerViewRoutes(app, ctx) {
31388
31641
  app.post("/api/views/:id/sessions/:sessionId", async (req) => store.tx(() => {
31389
31642
  const { sessionId } = req.params;
31390
31643
  const v = store.views.require(idOf(req));
31391
- store.sessions.require(sessionId);
31644
+ const session = store.sessions.require(sessionId);
31392
31645
  if (v.sessionIds.includes(sessionId))
31393
31646
  return v;
31647
+ if (session.archivedAt)
31648
+ throw new SwitchyardError("conflict", "Unarchive this session before pinning it");
31394
31649
  return store.putView({
31395
31650
  ...v,
31396
31651
  sessionIds: [...v.sessionIds, sessionId],
@@ -31412,17 +31667,16 @@ function registerViewRoutes(app, ctx) {
31412
31667
  const body2 = parse2(ViewClientReport, req.body);
31413
31668
  return store.tx(() => {
31414
31669
  const v = store.views.require(idOf(req));
31415
- 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);
31416
31676
  return v;
31417
31677
  });
31418
31678
  });
31419
- app.delete("/api/views/:id/clients/:clientId", async (req) => store.tx(() => {
31420
- const { clientId: clientId2 } = req.params;
31421
- const v = store.views.require(idOf(req));
31422
- if (store.surfaces.get(clientId2)?.viewId === v.id)
31423
- store.deleteSurface(clientId2);
31424
- return v;
31425
- }));
31679
+ app.delete("/api/views/:id/clients/:clientId", async (req) => store.views.require(idOf(req)));
31426
31680
  }
31427
31681
 
31428
31682
  // packages/coordinator/dist/routes/workspaces.js
@@ -31600,11 +31854,11 @@ var Statements = class {
31600
31854
  constructor(db) {
31601
31855
  this.db = db;
31602
31856
  }
31603
- get(sql20) {
31604
- let s = this.cache.get(sql20);
31857
+ get(sql23) {
31858
+ let s = this.cache.get(sql23);
31605
31859
  if (!s) {
31606
- s = this.db.prepare(sql20);
31607
- this.cache.set(sql20, s);
31860
+ s = this.db.prepare(sql23);
31861
+ this.cache.set(sql23, s);
31608
31862
  }
31609
31863
  return s;
31610
31864
  }
@@ -31635,12 +31889,12 @@ var JsonRepo = class {
31635
31889
  }
31636
31890
  /** List with an optional SQL `WHERE` fragment over the indexed columns. */
31637
31891
  list(where, params = [], orderBy = "rowid") {
31638
- const sql20 = `SELECT json FROM ${this.table}${where ? ` WHERE ${where}` : ""} ORDER BY ${orderBy}`;
31639
- return this.st.get(sql20).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));
31640
31894
  }
31641
31895
  count(where, params = []) {
31642
- const sql20 = `SELECT COUNT(*) AS n FROM ${this.table}${where ? ` WHERE ${where}` : ""}`;
31643
- return this.st.get(sql20).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;
31644
31898
  }
31645
31899
  /**
31646
31900
  * Update by id, or insert when missing. `extra` columns are written in both cases when given
@@ -31693,7 +31947,7 @@ var Store2 = class {
31693
31947
  /** Trackers are REST resources: no events; their per-item data rides on tasks. */
31694
31948
  trackers;
31695
31949
  issues;
31696
- surfaces;
31950
+ terminals;
31697
31951
  sessions;
31698
31952
  interactions;
31699
31953
  tasks;
@@ -31737,7 +31991,7 @@ var Store2 = class {
31737
31991
  this.profiles = new JsonRepo(st, "profiles", "Profile", { name: (p) => p.name }, { created_at: () => now() });
31738
31992
  this.views = new JsonRepo(st, "views", "View", { name: (v) => v.name }, { created_at: () => now() });
31739
31993
  this.trackers = new JsonRepo(st, "trackers", "Tracker", { name: (t) => t.name }, { created_at: () => now() });
31740
- this.surfaces = new JsonRepo(st, "surfaces", "Surface", {
31994
+ this.terminals = new JsonRepo(st, "terminals", "Terminal", {
31741
31995
  device_id: (x) => x.deviceId,
31742
31996
  view_id: (x) => x.viewId,
31743
31997
  last_seen_at: (x) => x.lastSeenAt
@@ -31998,24 +32252,38 @@ var Store2 = class {
31998
32252
  return v;
31999
32253
  });
32000
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
+ }
32001
32269
  deleteView(id) {
32002
32270
  this.tx(() => {
32003
32271
  this.views.delete(id);
32004
32272
  this.appendEvent("view.deleted", {}, { id });
32005
32273
  });
32006
32274
  }
32007
- putSurface(x) {
32275
+ putTerminal(x) {
32008
32276
  return this.tx(() => {
32009
- this.surfaces.upsert(x);
32010
- this.appendEvent("surface.updated", {}, x);
32277
+ this.terminals.upsert(x);
32278
+ this.appendEvent("terminal.updated", {}, x);
32011
32279
  return x;
32012
32280
  });
32013
32281
  }
32014
- deleteSurface(id) {
32282
+ deleteTerminal(id) {
32015
32283
  this.tx(() => {
32016
- if (!this.surfaces.delete(id))
32284
+ if (!this.terminals.delete(id))
32017
32285
  return;
32018
- this.appendEvent("surface.deleted", {}, { id });
32286
+ this.appendEvent("terminal.deleted", {}, { id });
32019
32287
  });
32020
32288
  }
32021
32289
  putIssue(i) {
@@ -32033,7 +32301,10 @@ var Store2 = class {
32033
32301
  }
32034
32302
  putSession(s) {
32035
32303
  return this.tx(() => {
32304
+ const archiving = s.archivedAt !== null && this.sessions.get(s.id)?.archivedAt === null;
32036
32305
  this.sessions.upsert(s);
32306
+ if (archiving)
32307
+ this.unpinSession(s.id);
32037
32308
  this.appendEvent("session.updated", {
32038
32309
  sessionId: s.id,
32039
32310
  hostId: s.hostId,
@@ -32291,11 +32562,12 @@ var Store2 = class {
32291
32562
  }
32292
32563
  // ---- presence, push, notifications -----------------------------------------------------
32293
32564
  upsertPresence(p) {
32294
- 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);
32295
32566
  }
32296
32567
  presenceFromRow(r) {
32297
32568
  return {
32298
32569
  deviceId: r.device_id,
32570
+ terminalId: r.terminal_id || null,
32299
32571
  foregroundUntil: r.foreground_until ?? null,
32300
32572
  interactedAt: r.interacted_at ?? null,
32301
32573
  viewingSessionId: r.viewing_session_id ?? null,
@@ -32303,7 +32575,7 @@ var Store2 = class {
32303
32575
  };
32304
32576
  }
32305
32577
  getPresence(deviceId) {
32306
- 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);
32307
32579
  return r ? this.presenceFromRow(r) : void 0;
32308
32580
  }
32309
32581
  listPresence() {
@@ -32472,7 +32744,7 @@ var Store2 = class {
32472
32744
  panels: this.listPanels(),
32473
32745
  devices: this.devices.list("is_admin = 0", [], "created_at"),
32474
32746
  issues: this.issues.list(void 0, [], "created_at, rowid"),
32475
- surfaces: this.surfaces.list(void 0, [], "created_at, rowid"),
32747
+ terminals: this.terminals.list(void 0, [], "created_at, rowid"),
32476
32748
  adapters: this.adaptersByHost(),
32477
32749
  dispatchPaused: this.dispatchPaused
32478
32750
  };
@@ -32858,7 +33130,7 @@ function createCoordinator(opts) {
32858
33130
  registerGitHubRoutes(app, ctx);
32859
33131
  registerProfileRoutes(app, ctx);
32860
33132
  registerViewRoutes(app, ctx);
32861
- registerSurfaceRoutes(app, ctx);
33133
+ registerTerminalRoutes(app, ctx);
32862
33134
  registerSessionRoutes(app, ctx);
32863
33135
  registerInteractionRoutes(app, ctx);
32864
33136
  registerAttentionRoutes(app, ctx);
@@ -32912,6 +33184,9 @@ function createCoordinator(opts) {
32912
33184
  const r = store.runRetention();
32913
33185
  if (r.deleted > 0)
32914
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");
32915
33190
  const archived = archiveEndedSessions(store);
32916
33191
  if (archived.length > 0)
32917
33192
  log.info({ sessions: archived.length }, "archived ended sessions");
@@ -33540,10 +33815,11 @@ function printDoctor(ctx, results) {
33540
33815
  }
33541
33816
 
33542
33817
  // packages/cli/dist/commands/herdr.js
33543
- import { spawn as spawn6 } from "node:child_process";
33818
+ import { execFile as execFile6, spawn as spawn6 } from "node:child_process";
33544
33819
  import { closeSync as closeSync3, existsSync as existsSync23, mkdirSync as mkdirSync11, openSync as openSync3, readFileSync as readFileSync13, writeFileSync as writeFileSync7 } from "node:fs";
33545
- import { homedir as homedir10, hostname as hostname4 } from "node:os";
33820
+ import { homedir as homedir10, hostname as hostname6 } from "node:os";
33546
33821
  import { dirname as dirname17, join as join28 } from "node:path";
33822
+ import { promisify } from "node:util";
33547
33823
 
33548
33824
  // packages/cli/dist/context.js
33549
33825
  function defaultCtx() {
@@ -33803,7 +34079,8 @@ function mirrorStateOf(client2) {
33803
34079
  hosts: Object.values(s.hosts),
33804
34080
  checkouts: Object.values(s.checkouts),
33805
34081
  views: Object.values(s.views),
33806
- issues: Object.values(s.issues ?? {})
34082
+ issues: Object.values(s.issues ?? {}),
34083
+ terminals: Object.values(s.terminals ?? {})
33807
34084
  };
33808
34085
  }
33809
34086
  function viewedSessions(st, view) {
@@ -33814,6 +34091,49 @@ function viewedSessions(st, view) {
33814
34091
  const scope = trackerScope(view, st.issues ?? []);
33815
34092
  return all.filter((s) => sessionInView(view, s, workspaces, scope));
33816
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
+ }
33817
34137
  function lingeringSessions(st, view) {
33818
34138
  const out = /* @__PURE__ */ new Set();
33819
34139
  if (!view?.trackerId)
@@ -33835,7 +34155,14 @@ var SOURCE = "switchyard";
33835
34155
  var SESSION_TOKEN = "switchyard_session";
33836
34156
  var LABEL_MAX = 40;
33837
34157
  function emptyMemory() {
33838
- 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
+ };
33839
34166
  }
33840
34167
  function cap2(label) {
33841
34168
  return label.length > LABEL_MAX ? `${label.slice(0, LABEL_MAX - 1)}\u2026` : label;
@@ -33878,7 +34205,7 @@ function claimedSession(p) {
33878
34205
  return token;
33879
34206
  return p.agent_session?.source === SOURCE ? p.agent_session.value : null;
33880
34207
  }
33881
- function planMirror(st, h, mem, now, view = null) {
34208
+ function planMirror(st, h, mem, now, view = null, terminalId2 = null) {
33882
34209
  const plan = {
33883
34210
  closeTabs: [],
33884
34211
  moves: [],
@@ -33893,6 +34220,7 @@ function planMirror(st, h, mem, now, view = null) {
33893
34220
  spaces: {}
33894
34221
  };
33895
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]));
33896
34224
  const linger = lingeringSessions(st, view);
33897
34225
  const workspaces = [...h.workspaces].sort((a, b) => a.number - b.number);
33898
34226
  const present = new Set(workspaces.map((w) => w.workspace_id));
@@ -33945,9 +34273,12 @@ function planMirror(st, h, mem, now, view = null) {
33945
34273
  if (owners.size !== 1)
33946
34274
  continue;
33947
34275
  const sid = [...owners][0];
33948
- if (!sid || M.has(sid))
34276
+ if (!sid)
34277
+ continue;
34278
+ const inactive = M.has(sid) && !W.has(sid) && mem.ownTabs[t.tab_id] === sid;
34279
+ if (M.has(sid) && !inactive)
33949
34280
  continue;
33950
- if (t.tab_id === h.focusedTabId && linger.has(sid))
34281
+ if (t.tab_id === h.focusedTabId && (inactive || linger.has(sid)))
33951
34282
  continue;
33952
34283
  plan.closeTabs.push({ tabId: t.tab_id, sessionId: sid });
33953
34284
  }
@@ -33979,9 +34310,11 @@ function planMirror(st, h, mem, now, view = null) {
33979
34310
  return p !== void 0 && now - p.at < PENDING_MS;
33980
34311
  };
33981
34312
  const createdKeys = /* @__PURE__ */ new Set();
33982
- for (const s of M.values()) {
34313
+ for (const s of W.values()) {
33983
34314
  if (claimedPanes.has(s.id) || fresh(s.id))
33984
34315
  continue;
34316
+ if (mem.hidden[s.id] === s.lastActivityAt)
34317
+ continue;
33985
34318
  if (now - Date.parse(s.createdAt) < NEW_SESSION_GRACE_MS)
33986
34319
  continue;
33987
34320
  const key = spaceKey(s);
@@ -34057,7 +34390,7 @@ function planMirror(st, h, mem, now, view = null) {
34057
34390
  }
34058
34391
  plan.spaces[w.workspace_id] = { key, label: computed };
34059
34392
  }
34060
- const liveKeys = new Set([...M.values()].map(spaceKey));
34393
+ const liveKeys = new Set([...W.values(), ...[...claimedPanes.keys()].flatMap((sid) => M.get(sid) ?? [])].map(spaceKey));
34061
34394
  const claimedSpaces = new Set(h.panes.filter((p) => claimedSession(p) !== null).map((p) => p.workspace_id));
34062
34395
  for (const [id, rec] of Object.entries(mem.spaces)) {
34063
34396
  if (!present.has(id))
@@ -34325,9 +34658,9 @@ var MirrorDaemon = class {
34325
34658
  return [];
34326
34659
  const { call, log } = this.deps;
34327
34660
  const bound = this.deps.view?.() ?? null;
34328
- if (bound === "missing") {
34661
+ if (bound === "off") {
34329
34662
  if (!this.viewMissingLogged)
34330
- log(`no view named "${this.deps.viewName ?? ""}"; idle`);
34663
+ log("mirrors nothing; idle");
34331
34664
  this.viewMissingLogged = true;
34332
34665
  return [];
34333
34666
  }
@@ -34350,7 +34683,7 @@ var MirrorDaemon = class {
34350
34683
  }
34351
34684
  const h = await this.snapshot();
34352
34685
  this.remember(h);
34353
- 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);
34354
34687
  const titleOf = (sid) => st.sessions.find((s) => s.id === sid)?.title ?? sid;
34355
34688
  const launcher = this.deps.launcherPath;
34356
34689
  const paneCmd = (sid) => launcherCommand(launcher, ["pane", sid]);
@@ -34478,6 +34811,10 @@ var MirrorDaemon = class {
34478
34811
  await runInPane(call, o.paneId, launcherCommand(launcher, args));
34479
34812
  note(`offered a new session in ${o.tabId}`);
34480
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
+ }
34481
34818
  const claimed = new Set(h.panes.map(claimedSession).filter(Boolean));
34482
34819
  for (const [sid, p] of Object.entries(this.mem.pending)) {
34483
34820
  if (claimed.has(sid) || this.now() - p.at >= PENDING_MS * 4)
@@ -34491,6 +34828,7 @@ var MirrorDaemon = class {
34491
34828
  }
34492
34829
  this.mem.spaces = { ...plan.spaces, ...createdNow };
34493
34830
  this.save();
34831
+ this.deps.onShows?.([...claimed].sort());
34494
34832
  return done;
34495
34833
  }
34496
34834
  load() {
@@ -34511,9 +34849,10 @@ var MirrorDaemon = class {
34511
34849
  if (!st)
34512
34850
  return;
34513
34851
  const bound = this.deps.view?.() ?? null;
34514
- if (bound === "missing")
34852
+ if (bound === "off")
34515
34853
  return;
34516
34854
  const mirrored = new Map(viewedSessions(st, bound).map((s) => [s.id, s]));
34855
+ const primaries = primaryIds(st);
34517
34856
  switch (data.type) {
34518
34857
  case "tab_closed": {
34519
34858
  const tabId = String(data.tab_id);
@@ -34522,8 +34861,12 @@ var MirrorDaemon = class {
34522
34861
  for (const sid of this.sessionsOfTab.get(tabId) ?? []) {
34523
34862
  const s = mirrored.get(sid);
34524
34863
  const elsewhere = [...this.sessionsOfTab].some(([other, sids]) => other !== tabId && sids.includes(sid));
34525
- if (s && !elsewhere)
34864
+ if (!s || elsewhere)
34865
+ continue;
34866
+ if (primaries.has(s.id))
34526
34867
  await this.archive(s.id, s.title);
34868
+ else
34869
+ this.mem.hidden[s.id] = s.lastActivityAt;
34527
34870
  }
34528
34871
  return;
34529
34872
  }
@@ -34531,7 +34874,7 @@ var MirrorDaemon = class {
34531
34874
  const ws = String(data.workspace_id);
34532
34875
  for (const sid of new Set(this.sessionsOfSpace.get(ws) ?? [])) {
34533
34876
  const s = mirrored.get(sid);
34534
- if (s)
34877
+ if (s && primaries.has(s.id))
34535
34878
  await this.archive(s.id, s.title);
34536
34879
  }
34537
34880
  delete this.mem.spaces[ws];
@@ -34635,43 +34978,723 @@ function startPresence(api, surface, viewId, log) {
34635
34978
  }
34636
34979
 
34637
34980
  // packages/cli/dist/mirror/binding.js
34638
- function bindingRef(env, sessionName) {
34639
- 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.`;
34640
35019
  }
34641
- function viewOrMissing(st, ref) {
34642
- 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>)`;
34643
35022
  }
34644
- function noViewMessage(kind, name) {
34645
- 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);
34646
35026
  }
34647
- function trackPresence(opts) {
34648
- let current = null;
34649
- const check = () => {
34650
- const v = opts.getView();
34651
- 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))
34652
35044
  return;
34653
- const old = current;
34654
- current = null;
35045
+ const old = legacy;
35046
+ legacy = null;
34655
35047
  if (old)
34656
35048
  void old.stop();
34657
- if (v) {
34658
- const p = startPresence(opts.api, opts.surface, v.id, opts.log);
34659
- 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 };
34660
35052
  }
34661
35053
  };
34662
- const off = opts.subscribe(check);
34663
- 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?.();
34664
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
+ },
34665
35157
  async stop() {
35158
+ stopped = true;
34666
35159
  off();
34667
- await current?.stop();
34668
- 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(", ")}`);
34669
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 } : {}
34670
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}`);
34671
35693
  }
34672
35694
 
34673
35695
  // packages/cli/dist/herdr/new-session.js
34674
35696
  import { readFileSync as readFileSync12 } from "node:fs";
35697
+ import { hostname as hostname5 } from "node:os";
34675
35698
  import { join as join27 } from "node:path";
34676
35699
 
34677
35700
  // packages/cli/dist/mirror/choose.js
@@ -34736,6 +35759,10 @@ function workspaceItems(st, projectId) {
34736
35759
  };
34737
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);
34738
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
+ }
34739
35766
  function newWorktreeItems(st, projectId, query) {
34740
35767
  const hosts = terminalHostIds(st);
34741
35768
  const branch = branchSlug2(query) || null;
@@ -34789,10 +35816,18 @@ async function chooseSession(st, screen, opts = {}) {
34789
35816
  if (step === "here") {
34790
35817
  out = await screen.pick({ crumbs: crumbs(), heading: "Start a session here?", hint: HINT_PICK }, [
34791
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
+ })),
34792
35824
  { label: "Choose another project or workspace\u2026", value: "other" }
34793
35825
  ]);
34794
35826
  if (out.kind === "ok") {
34795
35827
  typed[step] = out.query;
35828
+ if (typeof out.value === "string" && out.value.startsWith("open:")) {
35829
+ return { openSessionId: out.value.slice(5) };
35830
+ }
34796
35831
  if (out.value === "here") {
34797
35832
  projectId = here.projectId;
34798
35833
  workspace = { kind: "existing", workspaceId: here.id };
@@ -35456,10 +36491,11 @@ async function herdrNew(ctx, flags, io) {
35456
36491
  ctx.err("Connecting to Switchyard\u2026");
35457
36492
  const { client: client2, state } = await loadMirrorState(ctx, flags);
35458
36493
  const name = herdrSessionName(ctx.env);
35459
- const bound = viewOrMissing(state(), bindingRef(ctx.env, name));
35460
- if (bound === "missing") {
36494
+ const id = terminalId("herdr", name, hostname5());
36495
+ const bound = pickerBinding(state(), ctx.env, id);
36496
+ if (bound === "off") {
35461
36497
  client2.close();
35462
- ctx.err(noViewMessage("herdr", bindingRef(ctx.env, name)));
36498
+ ctx.err(offMessage("herdr", id));
35463
36499
  return;
35464
36500
  }
35465
36501
  const screen = new Screen(io ?? {
@@ -35468,6 +36504,7 @@ async function herdrNew(ctx, flags, io) {
35468
36504
  color: !("NO_COLOR" in ctx.env)
35469
36505
  });
35470
36506
  let created = null;
36507
+ let opened = null;
35471
36508
  try {
35472
36509
  const choice = await chooseSession(state(), screen, {
35473
36510
  ...flags.workspace ? { workspaceId: flags.workspace } : {}
@@ -35477,18 +36514,28 @@ async function herdrNew(ctx, flags, io) {
35477
36514
  ctx.err("Kept this tab as a shell.");
35478
36515
  return;
35479
36516
  }
35480
- created = await client2.api.post("/api/sessions", {
35481
- ...choice,
35482
- prompt: "",
35483
- viewId: bound.id
35484
- });
35485
- 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
+ }
35486
36532
  } finally {
35487
36533
  screen.leave();
35488
36534
  client2.close();
35489
36535
  }
35490
- if (created)
35491
- await herdrPane(ctx, created.id, flags);
36536
+ const show = created?.id ?? opened;
36537
+ if (show)
36538
+ await herdrPane(ctx, show, flags);
35492
36539
  }
35493
36540
  async function newHere(ctx) {
35494
36541
  const call = (method, params) => herdrCall(method, params);
@@ -35510,6 +36557,7 @@ async function newHere(ctx) {
35510
36557
  }
35511
36558
 
35512
36559
  // packages/cli/dist/commands/herdr.js
36560
+ var execFileP = promisify(execFile6);
35513
36561
  function pidAlive2(pid) {
35514
36562
  try {
35515
36563
  process.kill(pid, 0);
@@ -35540,7 +36588,9 @@ async function herdrDaemon(ctx, flags) {
35540
36588
  const logFile = join28(dir, "daemon.log");
35541
36589
  const socket = herdrSocketPath(env);
35542
36590
  const call = (method, params) => herdrCall(method, params, socket);
35543
- const ref = bindingRef(env, herdrSessionName(env));
36591
+ const name = herdrSessionName(env);
36592
+ const machine = hostname6();
36593
+ const id = terminalId("herdr", name, machine);
35544
36594
  if (flags.once) {
35545
36595
  const { client: client3, state } = await loadMirrorState(ctx, flags);
35546
36596
  try {
@@ -35552,8 +36602,7 @@ async function herdrDaemon(ctx, flags) {
35552
36602
  state,
35553
36603
  onStateChange: () => () => {
35554
36604
  },
35555
- view: () => viewOrMissing(state(), ref),
35556
- viewName: ref,
36605
+ view: () => pickerBinding(state(), env, id),
35557
36606
  stateDir: dir,
35558
36607
  launcherPath,
35559
36608
  log: () => {
@@ -35597,49 +36646,83 @@ async function herdrDaemon(ctx, flags) {
35597
36646
  return;
35598
36647
  writeFileSync7(pidFile, String(process.pid));
35599
36648
  const log = (line) => ctx.out(`${(/* @__PURE__ */ new Date()).toISOString()} ${line}`);
35600
- log(`daemon started (pid ${process.pid}, herdr session ${herdrSessionName(env)})`);
36649
+ log(`daemon started (pid ${process.pid}, herdr session ${name})`);
35601
36650
  const { client: client2 } = await loadMirrorState(ctx, flags, 24 * 60 * 6e4);
35602
36651
  client2.onLogout((reason3) => {
35603
36652
  log(`signed out: ${reason3}`);
35604
36653
  process.exit(1);
35605
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
+ });
35606
36686
  const daemon = new MirrorDaemon({
35607
36687
  call,
35608
- 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),
35609
36690
  api: client2.api,
35610
36691
  state: () => client2.store.getState().synced ? mirrorStateOf(client2) : null,
35611
36692
  onStateChange: (fn) => client2.store.subscribe(fn),
35612
- view: () => viewOrMissing(mirrorStateOf(client2), ref),
35613
- viewName: ref,
36693
+ view: () => terminal.binding(),
36694
+ terminalId: id,
36695
+ onShows: (ids2) => {
36696
+ shows = ids2;
36697
+ terminal.report();
36698
+ },
35614
36699
  stateDir: dir,
35615
36700
  launcherPath,
35616
36701
  log
35617
36702
  });
35618
36703
  await daemon.start();
35619
- const name = herdrSessionName(env);
35620
- const machine = hostname4();
35621
- const presence = trackPresence({
35622
- api: client2.api,
35623
- getView: () => {
35624
- const v = viewOrMissing(mirrorStateOf(client2), ref);
35625
- return v === "missing" ? null : v;
35626
- },
35627
- subscribe: (fn) => client2.store.subscribe(fn),
35628
- surface: {
35629
- id: `herdr:${name}@${machine}`,
35630
- kind: "herdr",
35631
- name,
35632
- machine,
35633
- hostId: localHostId(env, client2.api.baseUrl)
35634
- },
35635
- log
35636
- });
35637
- const leave = () => void presence.stop().finally(() => process.exit(0));
36704
+ const leave = () => {
36705
+ focus.stop();
36706
+ void terminal.stop().finally(() => process.exit(0));
36707
+ };
35638
36708
  process.once("SIGTERM", leave);
35639
36709
  process.once("SIGINT", leave);
35640
36710
  await new Promise(() => {
35641
36711
  });
35642
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
+ }
35643
36726
  function writePairFile(ctx, kind, session, flags) {
35644
36727
  const base = ctx.env.XDG_CONFIG_HOME?.trim() || join28(homedir10(), ".config");
35645
36728
  const path3 = join28(base, `switchyard-${kind}`, `${session}.env`);
@@ -35649,17 +36732,29 @@ function writePairFile(ctx, kind, session, flags) {
35649
36732
  const q = (v) => `"${v.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`;
35650
36733
  const lines = [
35651
36734
  flags.cli ? `SWITCHYARD_CLI=${q(flags.cli)}` : null,
35652
- flags.clientConfig ? `SWITCHYARD_CLIENT_CONFIG=${q(flags.clientConfig)}` : null,
35653
- flags.view ? `SWITCHYARD_VIEW=${q(flags.view)}` : null
36735
+ flags.clientConfig ? `SWITCHYARD_CLIENT_CONFIG=${q(flags.clientConfig)}` : null
35654
36736
  ].filter(Boolean);
35655
36737
  mkdirSync11(dirname17(path3), { recursive: true });
35656
36738
  writeFileSync7(path3, `${lines.join("\n")}${lines.length ? "\n" : ""}`, { mode: 384 });
35657
36739
  return path3;
35658
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
+ }
35659
36753
  async function herdrPair(ctx, flags) {
35660
36754
  const session = flags.session ?? "default";
35661
36755
  const path3 = writePairFile(ctx, "herdr", session, flags);
35662
36756
  ctx.out(`Wrote ${path3}`);
36757
+ await pairBinding(ctx, "herdr", session, flags);
35663
36758
  ctx.out(`Start it with: ${session === "default" ? "herdr" : `herdr --session ${session}`}`);
35664
36759
  }
35665
36760
  async function herdrStatus(ctx, flags) {
@@ -35690,12 +36785,12 @@ async function herdrStatus(ctx, flags) {
35690
36785
 
35691
36786
  // packages/cli/dist/commands/host.js
35692
36787
  import { existsSync as existsSync25, mkdirSync as mkdirSync13 } from "node:fs";
35693
- import { hostname as hostname5 } from "node:os";
36788
+ import { hostname as hostname7 } from "node:os";
35694
36789
  import { dirname as dirname19, join as join30, resolve as resolve15 } from "node:path";
35695
36790
  import { DatabaseSync as DatabaseSync4 } from "node:sqlite";
35696
36791
 
35697
36792
  // packages/cli/dist/commands/service.js
35698
- import { execFile as execFile6 } from "node:child_process";
36793
+ import { execFile as execFile7 } from "node:child_process";
35699
36794
  import { existsSync as existsSync24, mkdirSync as mkdirSync12, readFileSync as readFileSync14, writeFileSync as writeFileSync8 } from "node:fs";
35700
36795
  import { homedir as homedir11 } from "node:os";
35701
36796
  import { dirname as dirname18, join as join29, resolve as resolve14 } from "node:path";
@@ -35846,7 +36941,7 @@ function defaultInstallDeps() {
35846
36941
  platform: process.platform,
35847
36942
  home: homedir11(),
35848
36943
  uid: process.getuid?.() ?? 0,
35849
- 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() })))
35850
36945
  };
35851
36946
  }
35852
36947
  async function installService(ctx, flags, deps = defaultInstallDeps()) {
@@ -35906,7 +37001,7 @@ async function hostEnroll(ctx, flags) {
35906
37001
  if (!flags.token === !flags.secret) {
35907
37002
  throw new CliError("Pass exactly one of --token or --secret");
35908
37003
  }
35909
- const name = flags.name ?? hostname5().replace(/\.local$/, "");
37004
+ const name = flags.name ?? hostname7().replace(/\.local$/, "");
35910
37005
  const cfg = await enroll({
35911
37006
  coordinatorUrl: flags.coordinator,
35912
37007
  ...flags.token ? { token: flags.token } : { secret: flags.secret },
@@ -36048,121 +37143,14 @@ function hostPiExtension(ctx) {
36048
37143
  ctx.out(terminalExtensionPath());
36049
37144
  }
36050
37145
 
36051
- // packages/cli/dist/commands/hosts.js
36052
- async function resolveHost(api, ref) {
36053
- const hosts = (await api.get("/api/hosts")).filter((h) => !h.revokedAt);
36054
- const exact = hosts.find((h) => h.id === ref);
36055
- if (exact)
36056
- return exact;
36057
- const named = hosts.filter((h) => h.name.toLowerCase() === ref.toLowerCase());
36058
- if (named.length === 1)
36059
- return named[0];
36060
- if (named.length > 1)
36061
- throw new CliError(`Several hosts are named "${ref}"; use the id`);
36062
- const known = hosts.map((h) => `${h.name} (${h.id})`).join(", ") || "none";
36063
- throw new CliError(`Unknown host "${ref}". Hosts: ${known}`);
36064
- }
36065
- function scanLine(scan, now = Date.now()) {
36066
- if (!scan)
36067
- return ["Not scanned yet."];
36068
- if (scan.state === "running")
36069
- return [`Scanning since ${ago(scan.startedAt, now)}.`];
36070
- if (scan.state === "failed") {
36071
- return [
36072
- `Last scan failed ${ago(scan.finishedAt, now)}: ${scan.errors.at(-1) ?? "unknown error"}`
36073
- ];
36074
- }
36075
- return [
36076
- `Last scanned ${ago(scan.finishedAt, now)}: ${scan.repositories} repositories, ${scan.checkoutsAdded} new checkouts, ${scan.projectsCreated} new projects.`,
36077
- ...scan.errors.map((e) => `! ${e}`)
36078
- ];
36079
- }
36080
- async function hostsList(ctx, flags) {
36081
- const { api } = connect(ctx, flags);
36082
- const hosts = (await api.get("/api/hosts")).filter((h) => !h.revokedAt);
36083
- printList(ctx, flags.json, hosts, ["ID", "NAME", "STATUS", "AGENT", "PROJECT FOLDERS"], hosts.map((h) => [
36084
- h.id,
36085
- h.name,
36086
- h.connectivity,
36087
- h.agentVersion,
36088
- (h.projectFolders ?? []).join(", ") || "-"
36089
- ]), "No hosts.");
36090
- }
36091
- async function hostsFolders(ctx, ref, flags) {
36092
- const { api } = connect(ctx, flags);
36093
- const changing = !!(flags.set || flags.add || flags.remove || flags.clear);
36094
- if (flags.set && (flags.add || flags.remove || flags.clear) || flags.clear && (flags.add || flags.remove)) {
36095
- throw new CliError("Use --set or --clear on its own, or --add/--remove");
36096
- }
36097
- const host = await resolveHost(api, ref);
36098
- const current = host.projectFolders ?? [];
36099
- if (!changing) {
36100
- if (flags.json)
36101
- ctx.out(JSON.stringify(host, null, 2));
36102
- else {
36103
- if (current.length === 0)
36104
- ctx.out("No project folders.");
36105
- for (const f of current)
36106
- ctx.out(f);
36107
- for (const l of scanLine(host.projectScan))
36108
- ctx.out(l);
36109
- }
36110
- return host;
36111
- }
36112
- let next;
36113
- if (flags.set)
36114
- next = [...flags.set];
36115
- else if (flags.clear)
36116
- next = [];
36117
- else {
36118
- next = [...current];
36119
- for (const f of flags.remove ?? []) {
36120
- if (!next.includes(f))
36121
- throw new CliError(`${f} is not a project folder of ${host.name}`);
36122
- next = next.filter((x) => x !== f);
36123
- }
36124
- for (const f of flags.add ?? [])
36125
- if (!next.includes(f))
36126
- next.push(f);
36127
- }
36128
- const updated = await api.request("PATCH", `/api/hosts/${encodeURIComponent(host.id)}`, {
36129
- projectFolders: next
36130
- });
36131
- if (flags.json) {
36132
- ctx.out(JSON.stringify(updated, null, 2));
36133
- return updated;
36134
- }
36135
- const folders = updated.projectFolders ?? [];
36136
- ctx.out(`Project folders on ${updated.name}: ${folders.join(", ") || "none"}`);
36137
- if (folders.length > 0 && updated.connectivity === "connected") {
36138
- ctx.out(`Scanning in the background; \`switchyard hosts scan ${updated.name}\` waits for the result.`);
36139
- }
36140
- return updated;
36141
- }
36142
- async function hostsScan(ctx, ref, flags) {
36143
- const { api } = connect(ctx, flags);
36144
- const host = await resolveHost(api, ref);
36145
- const r = await api.post(`/api/hosts/${encodeURIComponent(host.id)}/scan-projects`);
36146
- if (flags.json) {
36147
- ctx.out(JSON.stringify(r, null, 2));
36148
- return r;
36149
- }
36150
- ctx.out(`Scanned ${host.name}: ${r.repositories} repositories, ${r.checkoutsAdded} new checkouts, ${r.projectsCreated} new projects`);
36151
- for (const a of r.added)
36152
- ctx.out(`+ ${a.name} ${a.path}${a.newProject ? " (new project)" : ""}`);
36153
- for (const e of r.errors)
36154
- ctx.out(`! ${e}`);
36155
- return r;
36156
- }
36157
-
36158
37146
  // packages/cli/dist/commands/tmux.js
36159
37147
  import { spawn as spawn8 } from "node:child_process";
36160
37148
  import { closeSync as closeSync4, existsSync as existsSync28, openSync as openSync4, readFileSync as readFileSync16, writeFileSync as writeFileSync11 } from "node:fs";
36161
- import { hostname as hostname6 } from "node:os";
37149
+ import { hostname as hostname9 } from "node:os";
36162
37150
  import { join as join33 } from "node:path";
36163
37151
 
36164
37152
  // packages/cli/dist/tmux/client.js
36165
- import { execFile as execFile7, spawn as spawn7 } from "node:child_process";
37153
+ import { execFile as execFile8, spawn as spawn7 } from "node:child_process";
36166
37154
  var TmuxUnavailable = class extends Error {
36167
37155
  constructor(message) {
36168
37156
  super(message);
@@ -36176,7 +37164,7 @@ var TmuxError = class extends Error {
36176
37164
  }
36177
37165
  };
36178
37166
  var tmuxRun = (args) => new Promise((resolve16, reject) => {
36179
- execFile7("tmux", args, { timeout: 5e3 }, (err, stdout, stderr) => {
37167
+ execFile8("tmux", args, { timeout: 5e3 }, (err, stdout, stderr) => {
36180
37168
  if (!err)
36181
37169
  return resolve16(stdout);
36182
37170
  if (err.code === "ENOENT") {
@@ -36257,7 +37245,14 @@ var WINDOW_OPTION = "@switchyard_session";
36257
37245
  var LABEL_MAX2 = 40;
36258
37246
  var SHELLS = ["sh", "bash", "zsh", "fish", "dash"];
36259
37247
  function emptyTmuxMemory() {
36260
- 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
+ };
36261
37256
  }
36262
37257
  function cap3(label) {
36263
37258
  return label.length > LABEL_MAX2 ? `${label.slice(0, LABEL_MAX2 - 1)}\u2026` : label;
@@ -36273,7 +37268,7 @@ function titleFromWindowName(name, s, st) {
36273
37268
  const prefix = `${prefixOf(s, st)} \xB7 `;
36274
37269
  return name.startsWith(prefix) ? name.slice(prefix.length) : name;
36275
37270
  }
36276
- function planTmux(st, view, windows, mem, now) {
37271
+ function planTmux(st, view, windows, mem, now, terminalId2 = null) {
36277
37272
  const plan = {
36278
37273
  closeWindows: [],
36279
37274
  createWindows: [],
@@ -36282,6 +37277,7 @@ function planTmux(st, view, windows, mem, now) {
36282
37277
  offers: []
36283
37278
  };
36284
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]));
36285
37281
  const linger = lingeringSessions(st, view);
36286
37282
  const claimed = /* @__PURE__ */ new Set();
36287
37283
  for (const w of windows) {
@@ -36289,8 +37285,9 @@ function planTmux(st, view, windows, mem, now) {
36289
37285
  continue;
36290
37286
  claimed.add(w.sessionId);
36291
37287
  const s = M.get(w.sessionId);
36292
- if (!s) {
36293
- 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)))
36294
37291
  continue;
36295
37292
  plan.closeWindows.push({ windowId: w.windowId, sessionId: w.sessionId });
36296
37293
  continue;
@@ -36301,9 +37298,11 @@ function planTmux(st, view, windows, mem, now) {
36301
37298
  if (w.name !== name)
36302
37299
  plan.renames.push({ windowId: w.windowId, name });
36303
37300
  }
36304
- for (const s of M.values()) {
37301
+ for (const s of W.values()) {
36305
37302
  if (claimed.has(s.id))
36306
37303
  continue;
37304
+ if (mem.hidden[s.id] === s.lastActivityAt)
37305
+ continue;
36307
37306
  const p = mem.pending[s.id];
36308
37307
  if (p && now - p.at < PENDING_MS)
36309
37308
  continue;
@@ -36468,11 +37467,11 @@ var TmuxDaemon = class {
36468
37467
  if (!st)
36469
37468
  return [];
36470
37469
  const { run, log } = this.deps;
36471
- const name = await this.currentName();
36472
- const bound = this.deps.view?.(name) ?? null;
36473
- if (bound === "missing") {
37470
+ await this.currentName();
37471
+ const bound = this.deps.view?.() ?? null;
37472
+ if (bound === "off") {
36474
37473
  if (!this.viewMissingLogged)
36475
- log(`no view named "${name}"; idle`);
37474
+ log("mirrors nothing; idle");
36476
37475
  this.viewMissingLogged = true;
36477
37476
  return [];
36478
37477
  }
@@ -36498,7 +37497,7 @@ var TmuxDaemon = class {
36498
37497
  }
36499
37498
  const windows = await this.snapshot();
36500
37499
  this.sessionOfWindow = new Map(windows.filter((w) => w.sessionId).map((w) => [w.windowId, w.sessionId]));
36501
- const plan = planTmux(st, bound, windows, this.mem, now);
37500
+ const plan = planTmux(st, bound, windows, this.mem, now, this.deps.terminalId ?? null);
36502
37501
  const launcher = this.deps.launcherPath;
36503
37502
  const exists2 = this.deps.exists ?? existsSync26;
36504
37503
  const q = (args) => launcherCommand(launcher, args);
@@ -36557,6 +37556,10 @@ var TmuxDaemon = class {
36557
37556
  note(`offered a new session in ${o.windowId}`);
36558
37557
  }
36559
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
+ }
36560
37563
  for (const [sid, p] of Object.entries(this.mem.pending)) {
36561
37564
  if (claimed.has(sid) || now - p.at >= PENDING_MS * 4)
36562
37565
  delete this.mem.pending[sid];
@@ -36568,6 +37571,7 @@ var TmuxDaemon = class {
36568
37571
  }
36569
37572
  }
36570
37573
  this.save();
37574
+ this.deps.onShows?.([...claimed].sort());
36571
37575
  return done;
36572
37576
  }
36573
37577
  load() {
@@ -36591,8 +37595,8 @@ var TmuxDaemon = class {
36591
37595
  const st = this.deps.state();
36592
37596
  if (!st)
36593
37597
  return;
36594
- const bound = this.deps.view?.(await this.currentName()) ?? null;
36595
- if (bound === "missing")
37598
+ const bound = this.deps.view?.() ?? null;
37599
+ if (bound === "off")
36596
37600
  return;
36597
37601
  const mirrored = new Map(viewedSessions(st, bound).map((s2) => [s2.id, s2]));
36598
37602
  if (e.type === "window-close") {
@@ -36605,6 +37609,10 @@ var TmuxDaemon = class {
36605
37609
  const elsewhere = [...this.sessionOfWindow].some(([w, other]) => w !== e.windowId && other === sid2);
36606
37610
  if (!s2 || elsewhere)
36607
37611
  return;
37612
+ if (!primaryIds(st).has(s2.id)) {
37613
+ this.mem.hidden[s2.id] = s2.lastActivityAt;
37614
+ return;
37615
+ }
36608
37616
  try {
36609
37617
  const r = await archiveSession2(this.deps.api, s2.id, s2.title);
36610
37618
  if (r.ok)
@@ -36683,6 +37691,7 @@ function tmuxLauncherExists(env = process.env) {
36683
37691
 
36684
37692
  // packages/cli/dist/tmux/new-session.js
36685
37693
  import { spawnSync } from "node:child_process";
37694
+ import { hostname as hostname8 } from "node:os";
36686
37695
 
36687
37696
  // packages/cli/dist/tmux/pane.js
36688
37697
  var defaultDeps2 = () => ({ run: tmuxRun, runRaw: runRawTerminal, readKey });
@@ -36715,23 +37724,35 @@ async function tmuxPane(ctx, sessionId, flags, deps = defaultDeps2()) {
36715
37724
  }
36716
37725
 
36717
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
+ }
36718
37736
  async function tmuxNew(ctx, flags, io) {
36719
37737
  ctx.err("Connecting to Switchyard\u2026");
36720
37738
  const { client: client2, state } = await loadMirrorState(ctx, flags);
36721
37739
  const name = await tmuxSessionName(ctx.env);
36722
- const bound = viewOrMissing(state(), bindingRef(ctx.env, name));
36723
- if (bound === "missing") {
37740
+ const id = terminalId("tmux", name, hostname8());
37741
+ const bound = pickerBinding(state(), ctx.env, id);
37742
+ if (bound === "off") {
36724
37743
  client2.close();
36725
- ctx.err(noViewMessage("tmux", bindingRef(ctx.env, name)));
37744
+ ctx.err(offMessage("tmux", id));
36726
37745
  if (!io)
36727
37746
  spawnSync(ctx.env.SHELL || "/bin/sh", [], { stdio: "inherit" });
36728
37747
  return;
36729
37748
  }
36730
37749
  const screen = new Screen(io ?? { input: process.stdin, output: process.stdout, color: !("NO_COLOR" in ctx.env) });
36731
37750
  let created = null;
37751
+ let opened = null;
37752
+ const workspace = flags.workspace ?? (io ? void 0 : await lastWindowWorkspace(state()));
36732
37753
  try {
36733
37754
  const choice = await chooseSession(state(), screen, {
36734
- ...flags.workspace ? { workspaceId: flags.workspace } : {}
37755
+ ...workspace ? { workspaceId: workspace } : {}
36735
37756
  });
36736
37757
  screen.leave();
36737
37758
  if (!choice) {
@@ -36740,18 +37761,28 @@ async function tmuxNew(ctx, flags, io) {
36740
37761
  spawnSync(ctx.env.SHELL || "/bin/sh", [], { stdio: "inherit" });
36741
37762
  return;
36742
37763
  }
36743
- created = await client2.api.post("/api/sessions", {
36744
- ...choice,
36745
- prompt: "",
36746
- viewId: bound.id
36747
- });
36748
- 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
+ }
36749
37779
  } finally {
36750
37780
  screen.leave();
36751
37781
  client2.close();
36752
37782
  }
36753
- if (created)
36754
- await tmuxPane(ctx, created.id, flags);
37783
+ const show = created?.id ?? opened;
37784
+ if (show)
37785
+ await tmuxPane(ctx, show, flags);
36755
37786
  }
36756
37787
 
36757
37788
  // packages/cli/dist/commands/tmux.js
@@ -36774,16 +37805,17 @@ async function tmuxDaemon(ctx, flags) {
36774
37805
  const name0 = await tmuxSessionName(env);
36775
37806
  let session = name0;
36776
37807
  try {
36777
- const id = (await tmuxRun(["display-message", "-p", "-t", tmuxTarget(name0), "#{session_id}"])).trim();
36778
- if (id)
36779
- session = id;
37808
+ const id2 = (await tmuxRun(["display-message", "-p", "-t", tmuxTarget(name0), "#{session_id}"])).trim();
37809
+ if (id2)
37810
+ session = id2;
36780
37811
  } catch {
36781
37812
  }
36782
37813
  const sessionName = async () => (await tmuxRun(["display-message", "-p", "-t", tmuxTarget(session), "#S"])).trim() || name0;
36783
37814
  const dir = tmuxSessionStateDir(name0, env);
36784
37815
  const pidFile = join33(dir, "daemon.pid");
36785
37816
  const logFile = join33(dir, "daemon.log");
36786
- const viewOf = (st, name) => viewOrMissing(st, bindingRef(env, name));
37817
+ const machine = hostname9();
37818
+ const id = terminalId("tmux", name0, machine);
36787
37819
  if (flags.once) {
36788
37820
  const { client: client3, state } = await loadMirrorState(ctx, flags);
36789
37821
  try {
@@ -36796,7 +37828,7 @@ async function tmuxDaemon(ctx, flags) {
36796
37828
  state,
36797
37829
  onStateChange: () => () => {
36798
37830
  },
36799
- view: (n) => viewOf(state(), n),
37831
+ view: () => pickerBinding(state(), env, id),
36800
37832
  sessionName,
36801
37833
  stateDir: dir,
36802
37834
  launcherPath,
@@ -36853,6 +37885,24 @@ async function tmuxDaemon(ctx, flags) {
36853
37885
  });
36854
37886
  let currentName = name0;
36855
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
+ });
36856
37906
  const daemon = new TmuxDaemon({
36857
37907
  run: tmuxRun,
36858
37908
  control: tmuxControl,
@@ -36860,36 +37910,56 @@ async function tmuxDaemon(ctx, flags) {
36860
37910
  session,
36861
37911
  state: () => client2.store.getState().synced ? mirrorStateOf(client2) : null,
36862
37912
  onStateChange: (fn) => client2.store.subscribe(fn),
36863
- view: (n) => viewOf(mirrorStateOf(client2), n),
37913
+ view: () => terminal.binding(),
37914
+ terminalId: id,
37915
+ onShows: (ids2) => {
37916
+ shows = ids2;
37917
+ terminal.report();
37918
+ },
36864
37919
  sessionName: trackedName,
36865
37920
  stateDir: dir,
36866
37921
  launcherPath,
36867
37922
  log
36868
37923
  });
36869
37924
  await daemon.start();
36870
- const machine = hostname6();
36871
- const presence = trackPresence({
36872
- api: client2.api,
36873
- getView: () => {
36874
- const v = viewOf(mirrorStateOf(client2), currentName);
36875
- return v === "missing" ? null : v;
36876
- },
36877
- subscribe: (fn) => client2.store.subscribe(fn),
36878
- surface: {
36879
- id: `tmux:${name0}@${machine}`,
36880
- kind: "tmux",
36881
- name: name0,
36882
- machine,
36883
- 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);
36884
37943
  },
36885
37944
  log
36886
37945
  });
36887
- const leave = () => void presence.stop().finally(() => process.exit(0));
37946
+ const leave = () => {
37947
+ focus.stop();
37948
+ void terminal.stop().finally(() => process.exit(0));
37949
+ };
36888
37950
  process.once("SIGTERM", leave);
36889
37951
  process.once("SIGINT", leave);
36890
37952
  await new Promise(() => {
36891
37953
  });
36892
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
+ }
36893
37963
  async function tmuxStatus(ctx, flags) {
36894
37964
  const { api } = connect(ctx, flags);
36895
37965
  const sessions = await api.get("/api/sessions");
@@ -36924,6 +37994,7 @@ async function tmuxPair(ctx, flags) {
36924
37994
  const session = flags.session ?? "switchyard";
36925
37995
  const path3 = writePairFile(ctx, "tmux", session, flags);
36926
37996
  ctx.out(`Wrote ${path3}`);
37997
+ await pairBinding(ctx, "tmux", session, flags);
36927
37998
  ctx.out("Load the plugin in .tmux.conf: run-shell <repo>/integrations/tmux/switchyard.tmux");
36928
37999
  ctx.out(`Then start it with: tmux new-session -s ${session}`);
36929
38000
  }
@@ -37088,264 +38159,6 @@ async function tuiCommand(ctx, sessionId, flags, run = runRawTerminal) {
37088
38159
  throw new CliError(result2.message);
37089
38160
  }
37090
38161
 
37091
- // packages/cli/dist/commands/views.js
37092
- import { hostname as hostname7 } from "node:os";
37093
-
37094
- // packages/cli/dist/commands/work.js
37095
- function byId2(list) {
37096
- return new Map(list.map((x) => [x.id, x]));
37097
- }
37098
- async function resolveProject(api, ref) {
37099
- const projects = await api.get("/api/projects");
37100
- const exact = projects.find((p) => p.id === ref);
37101
- if (exact)
37102
- return exact;
37103
- const named = projects.filter((p) => p.name.toLowerCase() === ref.toLowerCase());
37104
- if (named.length === 1)
37105
- return named[0];
37106
- if (named.length > 1)
37107
- throw new CliError(`Several projects are named "${ref}"; use the id`);
37108
- const known = projects.map((p) => `${p.name} (${p.id})`).join(", ") || "none";
37109
- throw new CliError(`Unknown project "${ref}". Projects: ${known}`);
37110
- }
37111
- async function sessionsList(ctx, flags) {
37112
- const { api } = connect(ctx, flags);
37113
- const projectId = flags.project ? (await resolveProject(api, flags.project)).id : void 0;
37114
- const [sessions, projects, hosts] = await Promise.all([
37115
- api.get(`/api/sessions${projectId ? `?projectId=${encodeURIComponent(projectId)}` : ""}`),
37116
- api.get("/api/projects"),
37117
- api.get("/api/hosts")
37118
- ]);
37119
- const p = byId2(projects);
37120
- const h = byId2(hosts);
37121
- printList(ctx, flags.json, sessions, ["ID", "RUNTIME", "PROJECT", "HOST", "ACTIVE", "TITLE"], sessions.map((s) => [
37122
- s.id,
37123
- s.runtime,
37124
- s.projectId && p.get(s.projectId)?.name || "-",
37125
- h.get(s.hostId)?.name ?? s.hostId,
37126
- ago(s.lastActivityAt),
37127
- s.title
37128
- ]), "No sessions.");
37129
- }
37130
- async function sessionsImport(ctx, sessionFile, flags) {
37131
- const { api } = connect(ctx, flags);
37132
- let hostId;
37133
- if (flags.host) {
37134
- hostId = (await resolveHost(api, flags.host)).id;
37135
- } else {
37136
- const hosts = (await api.get("/api/hosts")).filter((x) => !x.revokedAt);
37137
- if (hosts.length !== 1) {
37138
- throw new CliError(`Choose a host with --host (${hosts.map((x) => `${x.name}: ${x.id}`).join(", ") || "none enrolled"})`);
37139
- }
37140
- hostId = hosts[0].id;
37141
- }
37142
- const projectId = flags.project ? (await resolveProject(api, flags.project)).id : null;
37143
- const session = await api.post("/api/sessions/import", {
37144
- hostId,
37145
- sessionFile,
37146
- projectId
37147
- });
37148
- if (flags.json)
37149
- ctx.out(JSON.stringify(session, null, 2));
37150
- else
37151
- ctx.out(`Imported ${session.title} as ${session.id} (stopped; resume it to continue)`);
37152
- return session;
37153
- }
37154
- function taskCreateBody(projectId, flags) {
37155
- const body2 = {
37156
- projectId,
37157
- title: flags.title,
37158
- objective: flags.objective ?? "",
37159
- acceptanceCriteria: (flags.criteria ?? []).map((c) => c.trim()).filter(Boolean),
37160
- state: flags.ready ? "ready" : "backlog"
37161
- };
37162
- if (flags.priority !== void 0)
37163
- body2.priority = parsePriority(flags.priority);
37164
- return body2;
37165
- }
37166
- function parsePriority(v) {
37167
- const byName = PRIORITY_LABELS.findIndex((l) => l.toLowerCase() === v.toLowerCase());
37168
- const n = byName >= 0 ? byName : Number(v);
37169
- if (n === 0 || n === 1 || n === 2 || n === 3)
37170
- return n;
37171
- throw new CliError(`Priority must be 0-3 or one of ${PRIORITY_LABELS.join(", ")}`);
37172
- }
37173
- async function tasksCreate(ctx, flags) {
37174
- const { api } = connect(ctx, flags);
37175
- const project = await resolveProject(api, flags.project);
37176
- const task = await api.post("/api/tasks", taskCreateBody(project.id, flags));
37177
- if (flags.json)
37178
- ctx.out(JSON.stringify(task, null, 2));
37179
- else {
37180
- ctx.out(`Created ${task.id}: ${task.title} (${task.state})`);
37181
- if (task.state === "ready")
37182
- ctx.out("Ready tasks start automatically when eligible.");
37183
- }
37184
- return task;
37185
- }
37186
- function parseStates(v) {
37187
- if (!v)
37188
- return void 0;
37189
- const states = v.split(",").map((s) => s.trim()).filter(Boolean);
37190
- for (const s of states) {
37191
- if (!TaskState.safeParse(s).success) {
37192
- throw new CliError(`Unknown state "${s}". States: ${TaskState.options.join(", ")}`);
37193
- }
37194
- }
37195
- return states;
37196
- }
37197
- async function tasksList(ctx, flags) {
37198
- const { api } = connect(ctx, flags);
37199
- const states = parseStates(flags.state);
37200
- const projectId = flags.project ? (await resolveProject(api, flags.project)).id : void 0;
37201
- const q = new URLSearchParams();
37202
- if (states)
37203
- q.set("state", states.join(","));
37204
- if (projectId)
37205
- q.set("projectId", projectId);
37206
- if (flags.all)
37207
- q.set("includeHidden", "true");
37208
- const qs = q.toString();
37209
- const [tasks, projects] = await Promise.all([
37210
- api.get(`/api/tasks${qs ? `?${qs}` : ""}`),
37211
- api.get("/api/projects")
37212
- ]);
37213
- const p = byId2(projects);
37214
- printList(ctx, flags.json, tasks, ["ID", "STATE", "PRIORITY", "PROJECT", "TITLE"], tasks.map((t) => [
37215
- t.id,
37216
- t.blocked ? `${t.state} (blocked)` : t.state,
37217
- PRIORITY_LABELS[t.priority] ?? String(t.priority),
37218
- p.get(t.projectId)?.name ?? t.projectId,
37219
- t.title
37220
- ]), "No tasks.");
37221
- }
37222
- async function tasksMove(ctx, id, to, flags) {
37223
- if (to.includes(","))
37224
- throw new CliError(`Give one target state, not a list ("${to}")`);
37225
- const [state] = parseStates(to) ?? [];
37226
- if (!state)
37227
- throw new CliError("Give the target state");
37228
- const { api } = connect(ctx, flags);
37229
- const body2 = { to: state };
37230
- if (flags.confirm)
37231
- body2.confirm = true;
37232
- if (flags.onRunning)
37233
- body2.onRunning = flags.onRunning;
37234
- const task = await api.post(`/api/tasks/${encodeURIComponent(id)}/move`, body2);
37235
- if (flags.json)
37236
- ctx.out(JSON.stringify(task, null, 2));
37237
- else
37238
- ctx.out(`Moved ${task.title} to ${task.state}`);
37239
- return task;
37240
- }
37241
- async function automationsList(ctx, flags) {
37242
- const { api } = connect(ctx, flags);
37243
- const list = await api.get("/api/automations");
37244
- 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.");
37245
- }
37246
- async function automationsRun(ctx, id, flags) {
37247
- const { api } = connect(ctx, flags);
37248
- const res = await api.post(`/api/automations/${encodeURIComponent(id)}/run`, {});
37249
- if (flags.json) {
37250
- ctx.out(JSON.stringify(res, null, 2));
37251
- return;
37252
- }
37253
- const o = res.occurrence;
37254
- ctx.out(`Occurrence ${o.id}: ${o.state}${o.reason ? ` (${o.reason})` : ""}${res.task ? `; task ${res.task.id} "${res.task.title}" is ${res.task.state}` : ""}`);
37255
- }
37256
-
37257
- // packages/cli/dist/commands/views.js
37258
- function clientRef(raw, machine = hostname7()) {
37259
- const v = raw.trim();
37260
- if (!/^(herdr|tmux):[^@\s]+(@\S+)?$/.test(v))
37261
- throw new CliError("--client must look like herdr:<session> or tmux:<session>, optionally with @<machine>");
37262
- return v.includes("@") ? v : `${v}@${machine}`;
37263
- }
37264
- async function resolveView(api, ref) {
37265
- const views = await api.get("/api/views");
37266
- const v = findView(views, ref);
37267
- if (v)
37268
- return v;
37269
- const known = views.map((x) => x.name).join(", ") || "none";
37270
- throw new CliError(`Unknown view "${ref}". Views: ${known}`);
37271
- }
37272
- function checkMode(mode) {
37273
- if (mode !== void 0 && mode !== "all" && mode !== "pinned") {
37274
- throw new CliError('--mode must be "all" or "pinned"');
37275
- }
37276
- }
37277
- async function viewsList(ctx, flags) {
37278
- const { api } = connect(ctx, flags);
37279
- const [views, projects, hosts, surfaces] = await Promise.all([
37280
- api.get("/api/views"),
37281
- api.get("/api/projects"),
37282
- api.get("/api/hosts"),
37283
- api.get("/api/surfaces").catch(() => [])
37284
- ]);
37285
- const names = (ids2, all) => ids2 === null ? "any" : ids2.map((i) => all.find((x) => x.id === i)?.name ?? i).join(", ") || "-";
37286
- printList(ctx, flags.json, views, ["NAME", "MODE", "PROJECTS", "HOSTS", "PINNED", "SOURCE", "OPEN IN"], views.map((v) => [
37287
- v.name,
37288
- v.mode,
37289
- names(v.projectIds, projects),
37290
- names(v.hostIds, hosts),
37291
- String(v.sessionIds.length),
37292
- v.clientId ?? "-",
37293
- openSurfaces(surfaces, v.id).map((c) => `${c.kind} ${c.name} (${c.machine})`).join(", ") || "-"
37294
- ]), "No views.");
37295
- }
37296
- async function ids(api, refs, kind) {
37297
- if (!refs || refs.length === 0)
37298
- return void 0;
37299
- const out = [];
37300
- for (const r of refs) {
37301
- out.push((kind === "project" ? await resolveProject(api, r) : await resolveHost(api, r)).id);
37302
- }
37303
- return out;
37304
- }
37305
- async function viewsCreate(ctx, name, flags) {
37306
- checkMode(flags.mode);
37307
- const { api } = connect(ctx, flags);
37308
- const projectIds = await ids(api, flags.project, "project");
37309
- const hostIds = await ids(api, flags.host, "host");
37310
- const v = await api.post("/api/views", {
37311
- name,
37312
- ...flags.mode ? { mode: flags.mode } : {},
37313
- ...projectIds ? { projectIds } : {},
37314
- ...hostIds ? { hostIds } : {},
37315
- ...flags.client ? { clientId: clientRef(flags.client) } : {}
37316
- });
37317
- ctx.out(`Created view ${v.name} (${v.id})`);
37318
- }
37319
- async function viewsEdit(ctx, ref, flags) {
37320
- checkMode(flags.mode);
37321
- const { api } = connect(ctx, flags);
37322
- const v = await resolveView(api, ref);
37323
- const projectIds = flags.anyProject ? null : await ids(api, flags.project, "project");
37324
- const hostIds = flags.anyHost ? null : await ids(api, flags.host, "host");
37325
- const body2 = {
37326
- ...flags.name ? { name: flags.name } : {},
37327
- ...flags.mode ? { mode: flags.mode } : {},
37328
- ...projectIds !== void 0 ? { projectIds } : {},
37329
- ...hostIds !== void 0 ? { hostIds } : {},
37330
- ...flags.noClient ? { clientId: null } : flags.client ? { clientId: clientRef(flags.client) } : {}
37331
- };
37332
- await api.request("PATCH", `/api/views/${encodeURIComponent(v.id)}`, body2);
37333
- ctx.out(`Updated view ${flags.name ?? v.name}`);
37334
- }
37335
- async function viewsDelete(ctx, ref, flags) {
37336
- const { api } = connect(ctx, flags);
37337
- const v = await resolveView(api, ref);
37338
- await api.request("DELETE", `/api/views/${encodeURIComponent(v.id)}`);
37339
- ctx.out(`Deleted view ${v.name}`);
37340
- }
37341
- async function viewsPin(ctx, ref, sessionId, flags, unpin = false) {
37342
- const { api } = connect(ctx, flags);
37343
- const v = await resolveView(api, ref);
37344
- const path3 = `/api/views/${encodeURIComponent(v.id)}/sessions/${encodeURIComponent(sessionId)}`;
37345
- await api.request(unpin ? "DELETE" : "POST", path3);
37346
- ctx.out(`${unpin ? "Unpinned" : "Pinned"} ${sessionId} ${unpin ? "from" : "in"} ${v.name}`);
37347
- }
37348
-
37349
38162
  // packages/cli/dist/main.js
37350
38163
  var CLI_VERSION = JSON.parse(readFileSync17(new URL("../package.json", import.meta.url), "utf8")).version;
37351
38164
  function describeError(err) {
@@ -37442,10 +38255,12 @@ function buildProgram(ctx = defaultCtx()) {
37442
38255
  connectionOptions(herdr.command("status").description("Which herdr tab shows which session")).action(async (o) => {
37443
38256
  await herdrStatus(ctx, connFlags(o));
37444
38257
  });
37445
- 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) => {
37446
38259
  await herdrPair(ctx, {
37447
38260
  session: o.session,
37448
38261
  view: o.view,
38262
+ all: o.all,
38263
+ none: o.none,
37449
38264
  cli: o.cli,
37450
38265
  clientConfig: o.clientConfig,
37451
38266
  force: o.force
@@ -37464,35 +38279,38 @@ function buildProgram(ctx = defaultCtx()) {
37464
38279
  connectionOptions(tmux.command("status").description("Which tmux window shows which session")).action(async (o) => {
37465
38280
  await tmuxStatus(ctx, connFlags(o));
37466
38281
  });
37467
- 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) => {
37468
38283
  await tmuxPair(ctx, {
37469
38284
  session: o.session,
37470
38285
  view: o.view,
38286
+ all: o.all,
38287
+ none: o.none,
37471
38288
  cli: o.cli,
37472
38289
  clientConfig: o.clientConfig,
37473
38290
  force: o.force
37474
38291
  });
37475
38292
  });
37476
- const views = program.command("views").description("Views: named session filters for TUI clients");
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");
37477
38298
  const collect = (v, prev = []) => [...prev, v];
37478
38299
  connectionOptions(views.command("list").description("List views")).option("--json", "JSON output").action((o) => viewsList(ctx, { ...connFlags(o), json: o.json }));
37479
- 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).option("--client <id>", "collect sessions started in this client, e.g. herdr:default").action((name, o) => viewsCreate(ctx, name, {
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, {
37480
38301
  ...connFlags(o),
37481
38302
  mode: o.mode,
37482
38303
  project: o.project,
37483
- host: o.host,
37484
- client: o.client
38304
+ host: o.host
37485
38305
  }));
37486
- connectionOptions(views.command("edit <view>").description("Change a view")).option("--name <name>", "new name").option("--mode <mode>", "all or pinned").option("--project <project>", "limit to a project (repeatable)", collect).option("--host <host>", "limit to a host (repeatable)", collect).option("--any-project", "remove the project limit").option("--any-host", "remove the host limit").option("--client <id>", "collect sessions started in this client, e.g. herdr:default").option("--no-client", "stop collecting sessions from a client").action((ref, o) => viewsEdit(ctx, ref, {
38306
+ connectionOptions(views.command("edit <view>").description("Change a view")).option("--name <name>", "new name").option("--mode <mode>", "all or pinned").option("--project <project>", "limit to a project (repeatable)", collect).option("--host <host>", "limit to a host (repeatable)", collect).option("--any-project", "remove the project limit").option("--any-host", "remove the host limit").action((ref, o) => viewsEdit(ctx, ref, {
37487
38307
  ...connFlags(o),
37488
38308
  name: o.name,
37489
38309
  mode: o.mode,
37490
38310
  project: o.project,
37491
38311
  host: o.host,
37492
38312
  anyProject: o.anyProject,
37493
- anyHost: o.anyHost,
37494
- client: typeof o.client === "string" ? o.client : void 0,
37495
- noClient: o.client === false
38313
+ anyHost: o.anyHost
37496
38314
  }));
37497
38315
  connectionOptions(views.command("delete <view>").description("Delete a view")).action((ref, o) => viewsDelete(ctx, ref, connFlags(o)));
37498
38316
  connectionOptions(views.command("pin <view> <sessionId>").description("Pin a session")).action((ref, id, o) => viewsPin(ctx, ref, id, connFlags(o)));