@spencerboucher/switchyard 0.13.0 → 0.15.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 (183) hide show
  1. package/README.md +4 -3
  2. package/dist/bridge/agent-channel.js +26 -0
  3. package/dist/bridge/enroll.js +55 -0
  4. package/dist/bridge/resource-snapshot.js +47 -0
  5. package/dist/bridge/socket-paths.js +57 -0
  6. package/dist/bridge/state-dir.js +17 -0
  7. package/dist/bridge/switchyard-bridge.js +11 -0
  8. package/dist/bridge/switchyard-terminal.js +251 -23
  9. package/dist/policies/worker.js +1951 -1431
  10. package/dist/switchyard.mjs +5108 -2426
  11. package/package.json +1 -1
  12. package/web-dist/assets/AutomationView-CMDz-eFh.js +2 -0
  13. package/web-dist/assets/{AutomationView-Cg7yk8nb.js.map → AutomationView-CMDz-eFh.js.map} +1 -1
  14. package/web-dist/assets/{jsx-runtime-D13aM9HY.js → Button-BKQW9doW.js} +2 -2
  15. package/web-dist/assets/Button-BKQW9doW.js.map +1 -0
  16. package/web-dist/assets/Card-WONLvqGM.js +2 -0
  17. package/web-dist/assets/{Card-sHm0eI2Q.js.map → Card-WONLvqGM.js.map} +1 -1
  18. package/web-dist/assets/Checkbox-D18Ch0n4.js +2 -0
  19. package/web-dist/assets/{Checkbox-CEvKyfJz.js.map → Checkbox-D18Ch0n4.js.map} +1 -1
  20. package/web-dist/assets/Copy-D6U5ewFc.js +2 -0
  21. package/web-dist/assets/{Copy-BHOLVthK.js.map → Copy-D6U5ewFc.js.map} +1 -1
  22. package/web-dist/assets/{DangerZone-og55TRug.js → DangerZone-Ch2KNmob.js} +2 -2
  23. package/web-dist/assets/{DangerZone-og55TRug.js.map → DangerZone-Ch2KNmob.js.map} +1 -1
  24. package/web-dist/assets/InteractionCard-Bhur-sU9.js +4 -0
  25. package/web-dist/assets/InteractionCard-Bhur-sU9.js.map +1 -0
  26. package/web-dist/assets/Menu-dT22Gwzm.js +2 -0
  27. package/web-dist/assets/Menu-dT22Gwzm.js.map +1 -0
  28. package/web-dist/assets/Overlay-zQBNtPf6.js +2 -0
  29. package/web-dist/assets/Overlay-zQBNtPf6.js.map +1 -0
  30. package/web-dist/assets/Priority-CgO3ns6b.js +2 -0
  31. package/web-dist/assets/{Priority-xSUsxoXm.js.map → Priority-CgO3ns6b.js.map} +1 -1
  32. package/web-dist/assets/SegmentedControl-D2kj3j7u.js +2 -0
  33. package/web-dist/assets/SegmentedControl-D2kj3j7u.js.map +1 -0
  34. package/web-dist/assets/Select-CpWLZnId.js +2 -0
  35. package/web-dist/assets/{Select-C5xlhWYb.js.map → Select-CpWLZnId.js.map} +1 -1
  36. package/web-dist/assets/Switch-DHX-YYPr.js +2 -0
  37. package/web-dist/assets/{Switch-dVcf-7Je.js.map → Switch-DHX-YYPr.js.map} +1 -1
  38. package/web-dist/assets/Tabs-DZ2T9VBY.js +184 -0
  39. package/web-dist/assets/Tabs-DZ2T9VBY.js.map +1 -0
  40. package/web-dist/assets/TextArea-BQPdfjO_.js +2 -0
  41. package/web-dist/assets/{TextArea-D8WB5GD8.js.map → TextArea-BQPdfjO_.js.map} +1 -1
  42. package/web-dist/assets/TextLink-CCc3WEdm.js +2 -0
  43. package/web-dist/assets/{TextLink-CrfA8AeH.js.map → TextLink-CCc3WEdm.js.map} +1 -1
  44. package/web-dist/assets/UINodeRenderer-JQy6g7ZB.js +4 -0
  45. package/web-dist/assets/UINodeRenderer-JQy6g7ZB.js.map +1 -0
  46. package/web-dist/assets/arrow-down-YwTzxo-r.js +2 -0
  47. package/web-dist/assets/{arrow-down-C-iLrN8I.js.map → arrow-down-YwTzxo-r.js.map} +1 -1
  48. package/web-dist/assets/arrow-up-Bzh112dp.js +2 -0
  49. package/web-dist/assets/{arrow-up-Dj-VTKx4.js.map → arrow-up-Bzh112dp.js.map} +1 -1
  50. package/web-dist/assets/attention-DrHtkJHs.js +2 -0
  51. package/web-dist/assets/attention-DrHtkJHs.js.map +1 -0
  52. package/web-dist/assets/automations-TOhPm8sF.js +2 -0
  53. package/web-dist/assets/automations-TOhPm8sF.js.map +1 -0
  54. package/web-dist/assets/board-BZWPMk0Z.js +10 -0
  55. package/web-dist/assets/board-BZWPMk0Z.js.map +1 -0
  56. package/web-dist/assets/calendar-clock-CwOgyN2z.js +2 -0
  57. package/web-dist/assets/{calendar-clock-B8zE4JsX.js.map → calendar-clock-CwOgyN2z.js.map} +1 -1
  58. package/web-dist/assets/chevron-right-aaHL5Igi.js +2 -0
  59. package/web-dist/assets/{chevron-right-evVLS6hq.js.map → chevron-right-aaHL5Igi.js.map} +1 -1
  60. package/web-dist/assets/code-DVA5CKfS.js +25 -0
  61. package/web-dist/assets/code-DVA5CKfS.js.map +1 -0
  62. package/web-dist/assets/{describe-w4KmQFfU.js → describe-CtmmeUfI.js} +3 -3
  63. package/web-dist/assets/{describe-w4KmQFfU.js.map → describe-CtmmeUfI.js.map} +1 -1
  64. package/web-dist/assets/drafts-BP2GMlHS.js +13 -0
  65. package/web-dist/assets/drafts-BP2GMlHS.js.map +1 -0
  66. package/web-dist/assets/enroll-C4m0rxHw.js +2 -0
  67. package/web-dist/assets/{enroll-DPKdD0en.js.map → enroll-C4m0rxHw.js.map} +1 -1
  68. package/web-dist/assets/external-link-CI-Uzhfh.js +2 -0
  69. package/web-dist/assets/{external-link-3jjTxo92.js.map → external-link-CI-Uzhfh.js.map} +1 -1
  70. package/web-dist/assets/hand-HCdmhGph.js +2 -0
  71. package/web-dist/assets/{hand-UPoHamrn.js.map → hand-HCdmhGph.js.map} +1 -1
  72. package/web-dist/assets/index-LsagdEq-.js +11 -0
  73. package/web-dist/assets/index-LsagdEq-.js.map +1 -0
  74. package/web-dist/assets/index-f4tQ91xN.css +2 -0
  75. package/web-dist/assets/key-round-DIA3lje5.js +2 -0
  76. package/web-dist/assets/{key-round-VDbE9E4X.js.map → key-round-DIA3lje5.js.map} +1 -1
  77. package/web-dist/assets/link-2-D6l0YZ-8.js +2 -0
  78. package/web-dist/assets/{link-2-CaMlUDRG.js.map → link-2-D6l0YZ-8.js.map} +1 -1
  79. package/web-dist/assets/logic-CzU-NdeO.js +2 -0
  80. package/web-dist/assets/{logic-B46fwD-8.js.map → logic-CzU-NdeO.js.map} +1 -1
  81. package/web-dist/assets/more-BonXabXm.js +2 -0
  82. package/web-dist/assets/more-BonXabXm.js.map +1 -0
  83. package/web-dist/assets/pencil-BtK08_f_.js +2 -0
  84. package/web-dist/assets/{pencil-DI8QbCN8.js.map → pencil-BtK08_f_.js.map} +1 -1
  85. package/web-dist/assets/play-j138GLHB.js +2 -0
  86. package/web-dist/assets/{play-CjoDg3ws.js.map → play-j138GLHB.js.map} +1 -1
  87. package/web-dist/assets/plus-D935l0Os.js +2 -0
  88. package/web-dist/assets/{plus-BLP-wIYD.js.map → plus-D935l0Os.js.map} +1 -1
  89. package/web-dist/assets/{policyLogic-7OOzM_xa.js → policyLogic-nqL3E08V.js} +2 -2
  90. package/web-dist/assets/{policyLogic-7OOzM_xa.js.map → policyLogic-nqL3E08V.js.map} +1 -1
  91. package/web-dist/assets/preload-helper-DOFsWE7_.js +3 -0
  92. package/web-dist/assets/preload-helper-DOFsWE7_.js.map +1 -0
  93. package/web-dist/assets/presence-BnGwJNSq.js +2 -0
  94. package/web-dist/assets/{presence-05bJD5G3.js.map → presence-BnGwJNSq.js.map} +1 -1
  95. package/web-dist/assets/queue-p_rnOc-9.js +2 -0
  96. package/web-dist/assets/queue-p_rnOc-9.js.map +1 -0
  97. package/web-dist/assets/registry-D8Ph1G2W.js +2 -0
  98. package/web-dist/assets/registry-D8Ph1G2W.js.map +1 -0
  99. package/web-dist/assets/{repo-BA_bnCvu.js → repo-3GZtN4L8.js} +2 -2
  100. package/web-dist/assets/{repo-BA_bnCvu.js.map → repo-3GZtN4L8.js.map} +1 -1
  101. package/web-dist/assets/settings-jyGW1LsI.js +9 -0
  102. package/web-dist/assets/settings-jyGW1LsI.js.map +1 -0
  103. package/web-dist/assets/states-BXOts8eT.js +58 -0
  104. package/web-dist/assets/states-BXOts8eT.js.map +1 -0
  105. package/web-dist/assets/terminal-DKqo1lis.js +2 -0
  106. package/web-dist/assets/{terminal-BOV_MXPZ.js.map → terminal-DKqo1lis.js.map} +1 -1
  107. package/web-dist/assets/terminal-login-j20zSRZp.js +2 -0
  108. package/web-dist/assets/{terminal-login-C0n8cXqn.js.map → terminal-login-j20zSRZp.js.map} +1 -1
  109. package/web-dist/assets/timer-CyFp7DQs.js +2 -0
  110. package/web-dist/assets/{timer-BCIucSXh.js.map → timer-CyFp7DQs.js.map} +1 -1
  111. package/web-dist/assets/useBreakpoint-kT0J1Dnk.js +2 -0
  112. package/web-dist/assets/{useBreakpoint-CYDIV-KM.js.map → useBreakpoint-kT0J1Dnk.js.map} +1 -1
  113. package/web-dist/assets/useNow-DfER3XvS.js +2 -0
  114. package/web-dist/assets/useNow-DfER3XvS.js.map +1 -0
  115. package/web-dist/assets/useResource-DhvWL_9X.js +2 -0
  116. package/web-dist/assets/{useResource-DHtFcID5.js.map → useResource-DhvWL_9X.js.map} +1 -1
  117. package/web-dist/index.html +13 -12
  118. package/web-dist/sw.js +1 -1
  119. package/web-dist/sw.js.map +1 -1
  120. package/web-dist/assets/AutomationView-Cg7yk8nb.js +0 -2
  121. package/web-dist/assets/Card-sHm0eI2Q.js +0 -2
  122. package/web-dist/assets/Checkbox-CEvKyfJz.js +0 -2
  123. package/web-dist/assets/Copy-BHOLVthK.js +0 -2
  124. package/web-dist/assets/InteractionCard-B-yhxwKs.js +0 -6
  125. package/web-dist/assets/InteractionCard-B-yhxwKs.js.map +0 -1
  126. package/web-dist/assets/Menu-Cyt18mF2.js +0 -2
  127. package/web-dist/assets/Menu-Cyt18mF2.js.map +0 -1
  128. package/web-dist/assets/Overlay-BPNYBq3V.js +0 -2
  129. package/web-dist/assets/Overlay-BPNYBq3V.js.map +0 -1
  130. package/web-dist/assets/Priority-xSUsxoXm.js +0 -2
  131. package/web-dist/assets/SegmentedControl-DaBwumC0.js +0 -2
  132. package/web-dist/assets/SegmentedControl-DaBwumC0.js.map +0 -1
  133. package/web-dist/assets/Select-C5xlhWYb.js +0 -2
  134. package/web-dist/assets/Switch-dVcf-7Je.js +0 -2
  135. package/web-dist/assets/Tabs-93APobOB.js +0 -184
  136. package/web-dist/assets/Tabs-93APobOB.js.map +0 -1
  137. package/web-dist/assets/TextArea-D8WB5GD8.js +0 -2
  138. package/web-dist/assets/TextLink-CrfA8AeH.js +0 -2
  139. package/web-dist/assets/arrow-down-C-iLrN8I.js +0 -2
  140. package/web-dist/assets/arrow-up-Dj-VTKx4.js +0 -2
  141. package/web-dist/assets/attention-C8rfu6Uw.js +0 -2
  142. package/web-dist/assets/attention-C8rfu6Uw.js.map +0 -1
  143. package/web-dist/assets/automations-DQxUzi5Q.js +0 -2
  144. package/web-dist/assets/automations-DQxUzi5Q.js.map +0 -1
  145. package/web-dist/assets/board-aS6ooJpx.js +0 -10
  146. package/web-dist/assets/board-aS6ooJpx.js.map +0 -1
  147. package/web-dist/assets/calendar-clock-B8zE4JsX.js +0 -2
  148. package/web-dist/assets/chevron-right-evVLS6hq.js +0 -2
  149. package/web-dist/assets/code-Zr5DqwWI.js +0 -25
  150. package/web-dist/assets/code-Zr5DqwWI.js.map +0 -1
  151. package/web-dist/assets/enroll-DPKdD0en.js +0 -2
  152. package/web-dist/assets/external-link-3jjTxo92.js +0 -2
  153. package/web-dist/assets/hand-UPoHamrn.js +0 -2
  154. package/web-dist/assets/index-DFNY2EUd.css +0 -2
  155. package/web-dist/assets/index-DPScWz2I.js +0 -11
  156. package/web-dist/assets/index-DPScWz2I.js.map +0 -1
  157. package/web-dist/assets/jsx-runtime-D13aM9HY.js.map +0 -1
  158. package/web-dist/assets/key-round-VDbE9E4X.js +0 -2
  159. package/web-dist/assets/link-2-CaMlUDRG.js +0 -2
  160. package/web-dist/assets/logic-B46fwD-8.js +0 -2
  161. package/web-dist/assets/more-CiyGP5GD.js +0 -2
  162. package/web-dist/assets/more-CiyGP5GD.js.map +0 -1
  163. package/web-dist/assets/pencil-DI8QbCN8.js +0 -2
  164. package/web-dist/assets/play-CjoDg3ws.js +0 -2
  165. package/web-dist/assets/plus-BLP-wIYD.js +0 -2
  166. package/web-dist/assets/preload-helper-B2m1UyXR.js +0 -13
  167. package/web-dist/assets/preload-helper-B2m1UyXR.js.map +0 -1
  168. package/web-dist/assets/presence-05bJD5G3.js +0 -2
  169. package/web-dist/assets/queue-BcbJqzTY.js +0 -2
  170. package/web-dist/assets/queue-BcbJqzTY.js.map +0 -1
  171. package/web-dist/assets/settings-D03MF_Kx.js +0 -7
  172. package/web-dist/assets/settings-D03MF_Kx.js.map +0 -1
  173. package/web-dist/assets/shared-Bxc2JM1K.js +0 -3
  174. package/web-dist/assets/shared-Bxc2JM1K.js.map +0 -1
  175. package/web-dist/assets/states-DynH8-o6.js +0 -58
  176. package/web-dist/assets/states-DynH8-o6.js.map +0 -1
  177. package/web-dist/assets/terminal-BOV_MXPZ.js +0 -2
  178. package/web-dist/assets/terminal-login-C0n8cXqn.js +0 -2
  179. package/web-dist/assets/timer-BCIucSXh.js +0 -2
  180. package/web-dist/assets/useBreakpoint-CYDIV-KM.js +0 -2
  181. package/web-dist/assets/useNow-0tMsLHnB.js +0 -2
  182. package/web-dist/assets/useNow-0tMsLHnB.js.map +0 -1
  183. package/web-dist/assets/useResource-DHtFcID5.js +0 -2
package/README.md CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  A coding agent has to run where your repositories, toolchains and logins are: your laptop, a workstation, a home server. You, on the other hand, are not always sitting in front of that machine. Switchyard keeps the agents where the work is and lets you follow along from anywhere: start a session from your phone, answer the question it asks while you are on your laptop, take over from a terminal, and get a notification when the result is ready for review. Every client looks at the same live session, and closing one never stops the work.
6
6
 
7
- On top of interactive sessions it adds tasks, a board, scheduled automations and a review flow, so an agent can work through a backlog while you are away and hand everything back for you to accept.
7
+ On top of interactive sessions it adds tasks, a board, scheduled automations and a review flow, so an agent can work through a backlog while you are away and hand everything back for you to accept. Switchyard aims to preserve continuity with your evolving Pi setup: plugins own their workflows and optional adapters translate supported interactions, not arbitrary custom terminal UIs. See [plugin ownership](docs/plugin-boundaries.md).
8
8
 
9
9
  ## How it fits together
10
10
 
@@ -118,7 +118,7 @@ switchyard up
118
118
  ```sh
119
119
  docker run -d --name switchyard -p 127.0.0.1:7400:7400 -v switchyard-data:/data \
120
120
  -e SWITCHYARD_PUBLIC_URL=https://switchyard.example.com \
121
- ghcr.io/justmytwospence/switchyard:0.12.0
121
+ ghcr.io/justmytwospence/switchyard:0.15.0
122
122
  # Single sign-on is required off localhost: see docs/auth.md
123
123
  ```
124
124
 
@@ -132,7 +132,7 @@ switchyard host install-service # launchd on macOS, a systemd user service on
132
132
 
133
133
  Settings › Hosts › Add host shows these three commands with your token filled in. To build from source instead, see [docs/development.md](docs/development.md).
134
134
 
135
- [docs/deployment.md](docs/deployment.md) has recipes for Caddy, Traefik, nginx and Tailscale, a compose file, and every setting. A typed Node client for scripts and CI is in development for the next release; see [docs/client-sdk.md](docs/client-sdk.md) for its API and limitations.
135
+ [docs/deployment.md](docs/deployment.md) has recipes for Caddy, Traefik, nginx and Tailscale, a compose file, and every setting. A typed Node client for scripts and CI accompanies the release; see [docs/client-sdk.md](docs/client-sdk.md) for its API and limitations.
136
136
 
137
137
  ## Security model
138
138
 
@@ -157,6 +157,7 @@ Switchyard is young and moving quickly. It is tested against Pi `>=1.4.0 <1.6.0`
157
157
  | [Deployment](docs/deployment.md) | Single machine, server, reverse proxies, VPNs, hosts, environment reference, privilege model |
158
158
  | [Sign-in and devices](docs/auth.md) | The owner model, single sign-on, passkeys, terminal approval, single sign-on, host enrollment, revocation |
159
159
  | [CLI](docs/cli.md) | Every `switchyard` command and credentials |
160
+ | [Keyboard shortcuts](docs/keyboard-shortcuts.md) | Vim-style app navigation, palette controls and the `?` help sheet |
160
161
  | [Terminal sessions](docs/terminal-sessions.md) | Pi's own TUI for every session, from any terminal, and the herdr integration |
161
162
  | [Operations](docs/operations.md) | Backup, restore, migrations, retention, logs, health, diagnostics |
162
163
  | [Policies](docs/policies.md) | Agent tools, guardrails, approvals and budgets |
@@ -309,6 +309,32 @@ export function createAgentChannel(options) {
309
309
  noteHumanInput(r.args.humanInputId);
310
310
  receipt(r, { humanInputId: r.args.humanInputId });
311
311
  }
312
+ else if (r.method === "resources.snapshot") {
313
+ const handler = handlers.get(r.method);
314
+ if (!handler || !options.getCapabilities().resourceSnapshot)
315
+ throw channelError("unsupported_capability", "Resource inspection is unavailable");
316
+ if (!r.args ||
317
+ typeof r.args !== "object" ||
318
+ Array.isArray(r.args) ||
319
+ Object.keys(r.args).length !== 0)
320
+ throw channelError("invalid_request", "Resource inspection expects empty arguments");
321
+ const binding = configuration;
322
+ const result = await handler(r.args, r);
323
+ if (configuration !== binding || r.nativeSessionId !== syncNative())
324
+ throw channelError("conflict", "Bridge binding changed during resource inspection");
325
+ const frame = {
326
+ type: "bridge.receipt",
327
+ requestId: r.requestId,
328
+ runtimeId: r.runtimeId,
329
+ nativeSessionId: r.nativeSessionId,
330
+ bindingId: r.bindingId,
331
+ ok: true,
332
+ result,
333
+ };
334
+ if (Buffer.byteLength(JSON.stringify(frame), "utf8") > 128 * 1024)
335
+ throw channelError("invalid_request", "Resource snapshot exceeds bridge frame limit");
336
+ receipt(r, result);
337
+ }
312
338
  else {
313
339
  const handler = handlers.get(r.method);
314
340
  if (!handler)
@@ -0,0 +1,55 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { hostname } from "node:os";
3
+ import { join } from "node:path";
4
+ import { defaultStateDir } from "./state-dir.js";
5
+ /** The client this Pi runs in, as a view client id (`herdr:<session>@<machine>`), or null. */
6
+ export function clientId(env, host = hostname()) {
7
+ if (env.HERDR_ENV !== "1")
8
+ return null;
9
+ const fromSocket = /\/sessions\/([^/]+)\/herdr\.sock$/.exec(env.HERDR_SOCKET_PATH ?? "")?.[1];
10
+ const name = fromSocket || env.HERDR_SESSION?.trim() || "default";
11
+ return `herdr:${name}@${host}`;
12
+ }
13
+ /**
14
+ * The runtime directory to enrol in, or null when this Pi must not enrol: Switchyard started it,
15
+ * the user opted out (`SWITCHYARD_ENROLL=0`), it has no terminal, or no host agent runs here.
16
+ */
17
+ export function enrollRuntimeDir(env, tty) {
18
+ if (env.SWITCHYARD_CONTROL_SOCKET || env.SWITCHYARD_BRIDGE_SOCKET)
19
+ return null;
20
+ if (env.SWITCHYARD_ENROLL === "0" || !tty)
21
+ return null;
22
+ const stateDir = env.SWITCHYARD_ENROLL_STATE_DIR?.trim() || defaultStateDir(env);
23
+ const dir = join(stateDir, "runtime");
24
+ return existsSync(dir) ? dir : null;
25
+ }
26
+ export function metaPath(socketPath) {
27
+ return `${socketPath}.json`;
28
+ }
29
+ export function isEnrollMeta(v) {
30
+ if (!v || typeof v !== "object")
31
+ return false;
32
+ const m = v;
33
+ return (typeof m.pid === "number" &&
34
+ Number.isInteger(m.pid) &&
35
+ m.pid > 0 &&
36
+ typeof m.cwd === "string" &&
37
+ m.cwd.startsWith("/") &&
38
+ (m.client === null || typeof m.client === "string") &&
39
+ typeof m.sessionId === "string" &&
40
+ m.sessionId.length > 0 &&
41
+ typeof m.sessionFile === "string" &&
42
+ m.sessionFile.length > 0 &&
43
+ typeof m.startedAt === "string");
44
+ }
45
+ /** The meta file of an enrolment socket, or null when missing or invalid. */
46
+ export function readEnrollMeta(socketPath) {
47
+ try {
48
+ const parsed = JSON.parse(readFileSync(metaPath(socketPath), "utf8"));
49
+ return isEnrollMeta(parsed) ? parsed : null;
50
+ }
51
+ catch {
52
+ return null;
53
+ }
54
+ }
55
+ //# sourceMappingURL=enroll.js.map
@@ -0,0 +1,47 @@
1
+ import { isAbsolute } from "node:path";
2
+ /** Only provenance and guard booleans cross the bridge; never settings or draft contents. */
3
+ export function resourceSnapshot(pi, ctx, pendingDialogs = 0) {
4
+ const paths = new Set();
5
+ const add = (source) => {
6
+ const path = source.sourceInfo?.path;
7
+ if (typeof path === "string" && !path.startsWith("builtin:") && isAbsolute(path)) {
8
+ if (path.length > 4096)
9
+ throw new Error("Resource path exceeds 4096 characters");
10
+ paths.add(path);
11
+ if (paths.size > 2048)
12
+ throw new Error("Resource snapshot exceeds 2048 paths");
13
+ }
14
+ };
15
+ for (const tool of pi.getAllTools?.() ?? [])
16
+ add(tool);
17
+ for (const command of pi.getCommands?.() ?? []) {
18
+ if (command.source === "extension")
19
+ add(command);
20
+ }
21
+ let projectTrusted = null;
22
+ try {
23
+ const trust = ctx.isProjectTrusted?.();
24
+ if (typeof trust === "boolean")
25
+ projectTrusted = trust;
26
+ }
27
+ catch {
28
+ // Unknown trust must never authorize project discovery.
29
+ }
30
+ let hasEditorDraft = true;
31
+ try {
32
+ const text = ctx.ui?.getEditorText?.();
33
+ if (typeof text === "string")
34
+ hasEditorDraft = text.length > 0;
35
+ }
36
+ catch {
37
+ // Inspection remains available; a full reload must fail closed without a draft guard.
38
+ }
39
+ return {
40
+ cwd: ctx.cwd,
41
+ projectTrusted,
42
+ reportedExtensionPaths: [...paths].sort(),
43
+ hasEditorDraft,
44
+ pendingDialogs,
45
+ };
46
+ }
47
+ //# sourceMappingURL=resource-snapshot.js.map
@@ -0,0 +1,57 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { chmodSync, lstatSync, mkdirSync } from "node:fs";
3
+ import { dirname, join, resolve } from "node:path";
4
+ /*
5
+ * Private Unix socket paths for the host agent's runtime directory. In bridge/ so the Pi
6
+ * extension (which may only import its siblings) can use them too.
7
+ */
8
+ export const MAX_SOCKET_PATH = 100;
9
+ /** Short fallback for long runtime dirs: one private subdirectory per runtime dir, so agents never share it. */
10
+ export function fallbackSocketDir(runtimeDir) {
11
+ const hash = createHash("sha256").update(resolve(runtimeDir)).digest("hex").slice(0, 8);
12
+ return join("/tmp", `switchyard-${process.getuid?.() ?? "u"}`, hash);
13
+ }
14
+ /** Directories a runtime dir's sockets can live in (for sweeps). */
15
+ export function socketDirs(runtimeDir) {
16
+ return [runtimeDir, fallbackSocketDir(runtimeDir)];
17
+ }
18
+ /** Pure check: "ok", "chmod" (ours but looser than 0700), or throws. */
19
+ export function checkPrivateDir(dir, st, uid) {
20
+ if (st.isSymbolicLink())
21
+ throw new Error(`Socket directory ${dir} is a symlink; remove it so Switchyard can create a private directory`);
22
+ if (!st.isDirectory())
23
+ throw new Error(`Socket directory ${dir} is not a directory; remove it so Switchyard can create a private directory`);
24
+ if (uid !== undefined && st.uid !== uid)
25
+ throw new Error(`Socket directory ${dir} belongs to uid ${st.uid}, not ${uid}; remove it or use a shorter SWITCHYARD_STATE_DIR`);
26
+ return (st.mode & 0o077) !== 0 ? "chmod" : "ok";
27
+ }
28
+ /** Create `dir` (0700) if missing, then require: not a symlink, a directory, ours, mode 0700 (tightened if looser). */
29
+ export function ensurePrivateDir(dir) {
30
+ let st = null;
31
+ try {
32
+ st = lstatSync(dir);
33
+ }
34
+ catch {
35
+ /* missing */
36
+ }
37
+ if (!st) {
38
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
39
+ st = lstatSync(dir);
40
+ }
41
+ if (checkPrivateDir(dir, st, process.getuid?.()) === "chmod")
42
+ chmodSync(dir, 0o700);
43
+ }
44
+ /** A fresh Unix socket path in `runtimeDir`, or in a short private `/tmp` directory when that is too long. */
45
+ export function shortSocketPath(runtimeDir, prefix) {
46
+ const name = `${prefix}-${randomUUID().slice(0, 8)}.sock`;
47
+ if (join(runtimeDir, name).length <= MAX_SOCKET_PATH) {
48
+ ensurePrivateDir(runtimeDir);
49
+ return join(runtimeDir, name);
50
+ }
51
+ // Unix socket paths are limited (104 bytes on macOS); fall back to a short directory.
52
+ const dir = fallbackSocketDir(runtimeDir);
53
+ ensurePrivateDir(dirname(dir)); // /tmp/switchyard-<uid>
54
+ ensurePrivateDir(dir);
55
+ return join(dir, name);
56
+ }
57
+ //# sourceMappingURL=socket-paths.js.map
@@ -0,0 +1,17 @@
1
+ import { homedir } from "node:os";
2
+ import { join } from "node:path";
3
+ /**
4
+ * The host agent's state directory: `SWITCHYARD_STATE_DIR`, else
5
+ * `~/Library/Application Support/switchyard` on macOS and
6
+ * `${XDG_STATE_HOME:-~/.local/state}/switchyard` elsewhere.
7
+ */
8
+ export function defaultStateDir(env = process.env, platform = process.platform, home = homedir()) {
9
+ const fromEnv = env.SWITCHYARD_STATE_DIR?.trim();
10
+ if (fromEnv)
11
+ return fromEnv;
12
+ if (platform === "darwin")
13
+ return join(home, "Library", "Application Support", "switchyard");
14
+ const xdg = env.XDG_STATE_HOME?.trim();
15
+ return join(xdg || join(home, ".local", "state"), "switchyard");
16
+ }
17
+ //# sourceMappingURL=state-dir.js.map
@@ -14,6 +14,7 @@ import { LineSplitter } from "./lines.js";
14
14
  import { createMessageDelivery } from "./message-delivery.js";
15
15
  import { modelInfo } from "./pi-model.js";
16
16
  import { installPolicyHooks } from "./policy.js";
17
+ import { resourceSnapshot } from "./resource-snapshot.js";
17
18
  export default function switchyardBridge(pi) {
18
19
  const socketPath = process.env.SWITCHYARD_BRIDGE_SOCKET;
19
20
  if (!socketPath)
@@ -24,6 +25,7 @@ export default function switchyardBridge(pi) {
24
25
  let ctx = null;
25
26
  let dialogs = 0;
26
27
  let toolPolicy = false;
28
+ let snapshotRegistered = false;
27
29
  const channel = createAgentChannel({
28
30
  send: (record) => {
29
31
  try {
@@ -44,9 +46,16 @@ export default function switchyardBridge(pi) {
44
46
  messageDelivery: true,
45
47
  editorDraftGuard: true,
46
48
  toolPolicy,
49
+ resourceSnapshot: snapshotRegistered,
47
50
  }),
48
51
  policyRequired: process.env.SWITCHYARD_POLICY_REQUIRED === "1",
49
52
  });
53
+ const removeSnapshot = channel.registerCommand("resources.snapshot", () => {
54
+ if (!ctx)
55
+ throw new Error("Session is not ready");
56
+ return resourceSnapshot(pi, ctx, dialogs);
57
+ });
58
+ snapshotRegistered = true;
50
59
  toolPolicy = installPolicyHooks(pi, channel);
51
60
  registerAgentTools(pi, channel);
52
61
  const delivery = createMessageDelivery(pi, {
@@ -179,6 +188,8 @@ export default function switchyardBridge(pi) {
179
188
  channel.noteHumanInput();
180
189
  });
181
190
  pi.on("session_shutdown", () => {
191
+ snapshotRegistered = false;
192
+ removeSnapshot();
182
193
  delivery.close();
183
194
  channel.close();
184
195
  try {
@@ -14,18 +14,33 @@
14
14
  *
15
15
  * Other extensions that draw a custom terminal dialog can also ask the same question as a
16
16
  * web-only dialog through `switchyard.remote-ui.v1` on `pi.events`; the first answer wins.
17
+ *
18
+ * Enrolled mode: loaded into a Pi the user started themselves (no `SWITCHYARD_CONTROL_SOCKET`),
19
+ * the extension plays the holder's part instead. It listens on an `ext-*.sock` in the host
20
+ * agent's runtime directory, and the host attaches to it like to a holder. The terminal stays the
21
+ * user's: no agent tools or policy hooks, no remote answers to the editor, and `shutdown` never
22
+ * quits Pi. See `enroll.ts`.
17
23
  */
18
24
  import { randomUUID } from "node:crypto";
19
- import { createConnection } from "node:net";
25
+ import { chmodSync, realpathSync, rmSync, writeFileSync } from "node:fs";
26
+ import { createConnection, createServer } from "node:net";
27
+ import { fileURLToPath } from "node:url";
20
28
  import { createAgentChannel } from "./agent-channel.js";
21
29
  import { registerAgentTools } from "./agent-tools.js";
30
+ import { clientId, enrollRuntimeDir, metaPath } from "./enroll.js";
22
31
  import { LineSplitter } from "./lines.js";
23
32
  import { createMessageDelivery } from "./message-delivery.js";
24
33
  import { modelInfo } from "./pi-model.js";
25
34
  import { installPolicyHooks } from "./policy.js";
35
+ import { resourceSnapshot } from "./resource-snapshot.js";
36
+ import { shortSocketPath } from "./socket-paths.js";
26
37
  const PATCHED = Symbol.for("switchyard.terminal");
27
38
  const WRAPPED = Symbol.for("switchyard.terminal.wrapped");
28
39
  const REMOTE_UI_CHANNEL = "switchyard.remote-ui.v1";
40
+ /** Set while one copy of this extension is active in the process (a global shim plus `-e`). */
41
+ const LOADED = Symbol.for("switchyard.terminal.loaded");
42
+ /** Records kept for the host while no controller is attached (enrolled mode). */
43
+ const BACKLOG_MAX = 5000;
29
44
  function messageText(message) {
30
45
  const content = message?.content;
31
46
  if (typeof content === "string")
@@ -80,10 +95,33 @@ export function sessionTotals(entries) {
80
95
  }
81
96
  return totals;
82
97
  }
98
+ /** Whether this module is the copy at `path` (symlinks resolved); unknown counts as yes. */
99
+ function isCopy(path) {
100
+ if (!path)
101
+ return true;
102
+ try {
103
+ return realpathSync(fileURLToPath(import.meta.url)) === realpathSync(path);
104
+ }
105
+ catch {
106
+ return true;
107
+ }
108
+ }
83
109
  export default function switchyardTerminal(pi) {
110
+ const g = globalThis;
111
+ if (g[LOADED])
112
+ return;
84
113
  const socketPath = process.env.SWITCHYARD_CONTROL_SOCKET;
85
- if (!socketPath)
114
+ // Inside a holder, only the copy the holder loaded with -e runs.
115
+ if (socketPath && !isCopy(process.env.SWITCHYARD_TERMINAL_EXTENSION))
86
116
  return;
117
+ const enrollDir = socketPath
118
+ ? null
119
+ : enrollRuntimeDir(process.env, process.stdin.isTTY === true && process.stdout.isTTY === true);
120
+ if (!socketPath && !enrollDir)
121
+ return;
122
+ g[LOADED] = true;
123
+ /** Started by the user, not inside a Switchyard holder. */
124
+ const enrolled = !socketPath;
87
125
  let ctx = null;
88
126
  let completer = null;
89
127
  // Work that needs a command context (reload, plugin web views) runs inside a hidden command.
@@ -117,6 +155,7 @@ export default function switchyardTerminal(pi) {
117
155
  let remoteBacked = 0;
118
156
  let nativeDialogs = 0;
119
157
  let toolPolicy = false;
158
+ let snapshotRegistered = false;
120
159
  const channel = createAgentChannel({
121
160
  send: (record) => {
122
161
  try {
@@ -133,8 +172,8 @@ export default function switchyardTerminal(pi) {
133
172
  appendEntry: (customType, data) => pi.appendEntry(customType, data),
134
173
  mode: "terminal",
135
174
  getCapabilities: () => ({
136
- agentTools: true,
137
- messageDelivery: true,
175
+ agentTools: !enrolled,
176
+ messageDelivery: !enrolled,
138
177
  editorDraftGuard: (() => {
139
178
  try {
140
179
  return typeof ctx?.ui?.getEditorText?.() === "string";
@@ -144,21 +183,43 @@ export default function switchyardTerminal(pi) {
144
183
  }
145
184
  })(),
146
185
  toolPolicy,
186
+ resourceSnapshot: snapshotRegistered,
147
187
  }),
148
188
  policyRequired: process.env.SWITCHYARD_POLICY_REQUIRED === "1",
149
189
  });
150
- toolPolicy = installPolicyHooks(pi, channel);
151
- registerAgentTools(pi, channel);
152
- const delivery = createMessageDelivery(pi, {
153
- channel,
154
- getContext: () => ctx,
155
- isDialogOpen: () => nativeDialogs > 0 || pending.size > 0,
156
- mode: "terminal",
190
+ const removeSnapshot = channel.registerCommand("resources.snapshot", () => {
191
+ if (!ctx)
192
+ throw new Error("Session is not ready");
193
+ return resourceSnapshot(pi, ctx, nativeDialogs + pending.size);
157
194
  });
195
+ snapshotRegistered = true;
196
+ // A Pi the user started is theirs: no Switchyard tools, policy hooks or message delivery.
197
+ toolPolicy = enrolled ? false : installPolicyHooks(pi, channel);
198
+ if (!enrolled)
199
+ registerAgentTools(pi, channel);
200
+ const delivery = enrolled
201
+ ? null
202
+ : createMessageDelivery(pi, {
203
+ channel,
204
+ getContext: () => ctx,
205
+ isDialogOpen: () => nativeDialogs > 0 || pending.size > 0,
206
+ mode: "terminal",
207
+ });
208
+ const backlog = [];
209
+ let gap = false;
158
210
  const send = (obj) => {
159
211
  try {
160
- if (!socket || socket.destroyed)
212
+ if (!socket || socket.destroyed) {
213
+ // Enrolled: keep records for the host agent until it attaches, like a holder does.
214
+ if (enrolled) {
215
+ backlog.push(JSON.stringify(obj));
216
+ if (backlog.length > BACKLOG_MAX) {
217
+ backlog.shift();
218
+ gap = true;
219
+ }
220
+ }
161
221
  return;
222
+ }
162
223
  socket.write(`${JSON.stringify(obj)}\n`);
163
224
  }
164
225
  catch {
@@ -378,7 +439,8 @@ export default function switchyardTerminal(pi) {
378
439
  ui[method] = wrap((title, second, opts) => race(ui, method, orig, title, second, opts));
379
440
  }
380
441
  const origEditor = ui.editor;
381
- if (typeof origEditor === "function") {
442
+ // Enrolled: nothing can dismiss the editor remotely (no pty), so it stays terminal-only.
443
+ if (typeof origEditor === "function" && !enrolled) {
382
444
  ui.editor = wrap((title, prefill) => raceEditor(ui, origEditor, title, prefill));
383
445
  }
384
446
  const origNotify = ui.notify;
@@ -612,6 +674,9 @@ export default function switchyardTerminal(pi) {
612
674
  return;
613
675
  case "shutdown":
614
676
  respond(id, type);
677
+ // Never quit a Pi the user started.
678
+ if (enrolled)
679
+ return;
615
680
  setImmediate(() => {
616
681
  try {
617
682
  ctx.shutdown();
@@ -668,14 +733,37 @@ export default function switchyardTerminal(pi) {
668
733
  });
669
734
  return;
670
735
  }
671
- case "reload":
672
- if (!ctx) {
673
- respond(id, type, undefined, "Session is not ready");
736
+ case "reload": {
737
+ const guard = (c) => {
738
+ if (!c)
739
+ return "Session is not ready";
740
+ if (!c.isIdle() || c.hasPendingMessages?.())
741
+ return "Wait for Pi to become idle";
742
+ const snapshot = resourceSnapshot(pi, c, nativeDialogs + pending.size);
743
+ if (snapshot.pendingDialogs > 0)
744
+ return "Answer the open dialog first";
745
+ if (snapshot.hasEditorDraft)
746
+ return "Clear the terminal editor draft before reloading";
747
+ return null;
748
+ };
749
+ const error = guard(ctx);
750
+ if (error) {
751
+ respond(id, type, undefined, error);
674
752
  return;
675
753
  }
676
- respond(id, type);
677
- runInternal((c) => c.reload());
754
+ runInternal(async (c) => {
755
+ // Recheck at the actual command boundary, not just when queued by the host.
756
+ const error = guard(c);
757
+ if (error || typeof c.reload !== "function") {
758
+ respond(id, type, undefined, error ?? "This Pi cannot reload extensions");
759
+ return;
760
+ }
761
+ respond(id, type);
762
+ await c.reload();
763
+ return;
764
+ });
678
765
  return;
766
+ }
679
767
  case "complete": {
680
768
  const text = String(cmd.text ?? "");
681
769
  if (!completer?.getSuggestions || !/^\/\S+ /.test(text) || text.includes("\n")) {
@@ -749,10 +837,10 @@ export default function switchyardTerminal(pi) {
749
837
  // The holder listens before it starts Pi, but retry a few times anyway (a slow or restarting holder).
750
838
  const CONNECT_ATTEMPTS = 5;
751
839
  const CONNECT_RETRY_MS = 200;
752
- const connect = (attempt) => {
840
+ const connect = (path, attempt) => {
753
841
  let s;
754
842
  try {
755
- s = createConnection(socketPath);
843
+ s = createConnection(path);
756
844
  }
757
845
  catch {
758
846
  socket = null;
@@ -781,13 +869,138 @@ export default function switchyardTerminal(pi) {
781
869
  socket = null;
782
870
  }
783
871
  if (!connected && attempt < CONNECT_ATTEMPTS) {
784
- setTimeout(() => connect(attempt + 1), CONNECT_RETRY_MS).unref();
872
+ setTimeout(() => connect(path, attempt + 1), CONNECT_RETRY_MS).unref();
785
873
  }
786
874
  });
787
875
  s.unref();
788
876
  s.write(`${JSON.stringify({ role: "extension" })}\n`);
789
877
  };
790
- connect(1);
878
+ if (socketPath)
879
+ connect(socketPath, 1);
880
+ // ---- enrolled: listen like a holder ----
881
+ let server = null;
882
+ let enrollSocket = null;
883
+ let attachedBefore = false;
884
+ const startedAt = new Date().toISOString();
885
+ const writeMeta = () => {
886
+ if (!enrollSocket || !ctx)
887
+ return;
888
+ const file = ctx.sessionManager.getSessionFile?.();
889
+ if (!file)
890
+ return;
891
+ const meta = {
892
+ pid: process.pid,
893
+ cwd: ctx.cwd ?? process.cwd(),
894
+ client: clientId(process.env),
895
+ sessionId: ctx.sessionManager.getSessionId(),
896
+ sessionFile: file,
897
+ startedAt,
898
+ };
899
+ try {
900
+ writeFileSync(metaPath(enrollSocket), JSON.stringify(meta), { mode: 0o600 });
901
+ }
902
+ catch {
903
+ // never throw into Pi
904
+ }
905
+ };
906
+ const removeEnrollFiles = () => {
907
+ if (!enrollSocket)
908
+ return;
909
+ for (const f of [enrollSocket, metaPath(enrollSocket)]) {
910
+ try {
911
+ rmSync(f, { force: true });
912
+ }
913
+ catch {
914
+ // ignore
915
+ }
916
+ }
917
+ };
918
+ /** A host agent attached: replay what it missed, then announce like a fresh holder attach. */
919
+ const attachControl = (s) => {
920
+ if (socket && socket !== s)
921
+ socket.destroy();
922
+ socket = s;
923
+ s.write(`${JSON.stringify({ type: "holder_status", piPid: process.pid })}\n`);
924
+ if (gap)
925
+ s.write(`${JSON.stringify({ type: "holder_gap" })}\n`);
926
+ for (const line of backlog.splice(0))
927
+ s.write(`${line}\n`);
928
+ gap = false;
929
+ announce();
930
+ if (attachedBefore)
931
+ channel.onControlAttached();
932
+ else
933
+ channel.onConnect();
934
+ attachedBefore = true;
935
+ };
936
+ const listen = () => {
937
+ if (!enrollDir || server)
938
+ return;
939
+ try {
940
+ const path = shortSocketPath(enrollDir, "ext");
941
+ const srv = createServer((s) => {
942
+ let role = null;
943
+ const lines = new LineSplitter((line) => {
944
+ if (role === "control") {
945
+ if (socket !== s)
946
+ return;
947
+ try {
948
+ if (JSON.parse(line)?.type === "holder_kill")
949
+ return; // the user's Pi is not killed
950
+ }
951
+ catch {
952
+ return;
953
+ }
954
+ onLine(line);
955
+ return;
956
+ }
957
+ try {
958
+ role = String(JSON.parse(line)?.role ?? "");
959
+ }
960
+ catch {
961
+ role = "";
962
+ }
963
+ if (role === "control")
964
+ attachControl(s);
965
+ else
966
+ s.destroy(); // no viewers: the terminal is the user's
967
+ });
968
+ s.setEncoding("utf8");
969
+ s.on("data", (chunk) => lines.push(chunk));
970
+ s.on("error", () => { });
971
+ s.on("close", () => {
972
+ if (socket === s) {
973
+ channel.onDisconnect();
974
+ socket = null;
975
+ }
976
+ });
977
+ s.unref();
978
+ });
979
+ srv.on("error", () => { });
980
+ const old = process.umask(0o077);
981
+ try {
982
+ srv.listen(path, () => {
983
+ try {
984
+ chmodSync(path, 0o600);
985
+ }
986
+ catch {
987
+ // ignore
988
+ }
989
+ writeMeta();
990
+ });
991
+ }
992
+ finally {
993
+ process.umask(old);
994
+ }
995
+ srv.unref();
996
+ server = srv;
997
+ enrollSocket = path;
998
+ process.once("exit", removeEnrollFiles);
999
+ }
1000
+ catch {
1001
+ // No socket, no enrolment; Pi works as usual.
1002
+ }
1003
+ };
791
1004
  try {
792
1005
  pi.events?.on?.(REMOTE_UI_CHANNEL, (data) => {
793
1006
  const r = data;
@@ -838,7 +1051,10 @@ export default function switchyardTerminal(pi) {
838
1051
  channel.announce();
839
1052
  if (event?.reason && event.reason !== "startup") {
840
1053
  send({ type: "switchyard_native", sessionId, sessionFile });
1054
+ writeMeta();
841
1055
  }
1056
+ if (enrolled && sessionFile)
1057
+ listen();
842
1058
  for (const cmd of early.splice(0))
843
1059
  handleCommand(cmd);
844
1060
  });
@@ -916,8 +1132,20 @@ export default function switchyardTerminal(pi) {
916
1132
  send({ type: "ui_prompt", event: event.type, kind: event.kind, title: event.title ?? null });
917
1133
  });
918
1134
  on("session_shutdown", () => {
919
- delivery.close();
1135
+ snapshotRegistered = false;
1136
+ removeSnapshot();
1137
+ delivery?.close();
920
1138
  channel.close();
1139
+ delete g[LOADED];
1140
+ if (enrolled) {
1141
+ // Like a holder whose Pi quit: the host marks the session stopped.
1142
+ send({ type: "holder_exit", code: 0, signal: null, screen: [] });
1143
+ socket?.end();
1144
+ server?.close();
1145
+ server = null;
1146
+ removeEnrollFiles();
1147
+ process.removeListener("exit", removeEnrollFiles);
1148
+ }
921
1149
  });
922
1150
  on("input", (event) => {
923
1151
  if (event?.source !== "interactive")