@spencerboucher/switchyard 0.14.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 (67) hide show
  1. package/README.md +1 -1
  2. package/dist/bridge/enroll.js +55 -0
  3. package/dist/bridge/socket-paths.js +57 -0
  4. package/dist/bridge/state-dir.js +17 -0
  5. package/dist/bridge/switchyard-terminal.js +213 -19
  6. package/dist/policies/worker.js +1493 -1332
  7. package/dist/switchyard.mjs +3251 -1851
  8. package/package.json +1 -1
  9. package/web-dist/assets/{AutomationView-CcxKiLxM.js → AutomationView-CMDz-eFh.js} +2 -2
  10. package/web-dist/assets/{AutomationView-CcxKiLxM.js.map → AutomationView-CMDz-eFh.js.map} +1 -1
  11. package/web-dist/assets/{InteractionCard-Bd4Cr_Zi.js → InteractionCard-Bhur-sU9.js} +2 -2
  12. package/web-dist/assets/{InteractionCard-Bd4Cr_Zi.js.map → InteractionCard-Bhur-sU9.js.map} +1 -1
  13. package/web-dist/assets/{Menu-CDIEOsaM.js → Menu-dT22Gwzm.js} +2 -2
  14. package/web-dist/assets/{Menu-CDIEOsaM.js.map → Menu-dT22Gwzm.js.map} +1 -1
  15. package/web-dist/assets/{Overlay-QSBH5woa.js → Overlay-zQBNtPf6.js} +2 -2
  16. package/web-dist/assets/{Overlay-QSBH5woa.js.map → Overlay-zQBNtPf6.js.map} +1 -1
  17. package/web-dist/assets/{Priority-PUuNGK2s.js → Priority-CgO3ns6b.js} +2 -2
  18. package/web-dist/assets/{Priority-PUuNGK2s.js.map → Priority-CgO3ns6b.js.map} +1 -1
  19. package/web-dist/assets/{Tabs-BplxI0Eb.js → Tabs-DZ2T9VBY.js} +2 -2
  20. package/web-dist/assets/{Tabs-BplxI0Eb.js.map → Tabs-DZ2T9VBY.js.map} +1 -1
  21. package/web-dist/assets/{UINodeRenderer-Bxq4kPwg.js → UINodeRenderer-JQy6g7ZB.js} +2 -2
  22. package/web-dist/assets/{UINodeRenderer-Bxq4kPwg.js.map → UINodeRenderer-JQy6g7ZB.js.map} +1 -1
  23. package/web-dist/assets/{attention-BwQ0PjVB.js → attention-DrHtkJHs.js} +2 -2
  24. package/web-dist/assets/{attention-BwQ0PjVB.js.map → attention-DrHtkJHs.js.map} +1 -1
  25. package/web-dist/assets/{automations-BSV9KuSH.js → automations-TOhPm8sF.js} +2 -2
  26. package/web-dist/assets/{automations-BSV9KuSH.js.map → automations-TOhPm8sF.js.map} +1 -1
  27. package/web-dist/assets/{board-C8N8_GS0.js → board-BZWPMk0Z.js} +7 -7
  28. package/web-dist/assets/board-BZWPMk0Z.js.map +1 -0
  29. package/web-dist/assets/{code-BmxcCLin.js → code-DVA5CKfS.js} +4 -4
  30. package/web-dist/assets/code-DVA5CKfS.js.map +1 -0
  31. package/web-dist/assets/{describe-Nw-EGTvb.js → describe-CtmmeUfI.js} +2 -2
  32. package/web-dist/assets/{describe-Nw-EGTvb.js.map → describe-CtmmeUfI.js.map} +1 -1
  33. package/web-dist/assets/{drafts-CbBiiFKw.js → drafts-BP2GMlHS.js} +2 -2
  34. package/web-dist/assets/{drafts-CbBiiFKw.js.map → drafts-BP2GMlHS.js.map} +1 -1
  35. package/web-dist/assets/{enroll-2bd2qhh1.js → enroll-C4m0rxHw.js} +2 -2
  36. package/web-dist/assets/{enroll-2bd2qhh1.js.map → enroll-C4m0rxHw.js.map} +1 -1
  37. package/web-dist/assets/{index-5cSRL594.js → index-LsagdEq-.js} +4 -4
  38. package/web-dist/assets/{index-5cSRL594.js.map → index-LsagdEq-.js.map} +1 -1
  39. package/web-dist/assets/{more-tcGYFcpM.js → more-BonXabXm.js} +2 -2
  40. package/web-dist/assets/{more-tcGYFcpM.js.map → more-BonXabXm.js.map} +1 -1
  41. package/web-dist/assets/{policyLogic-4ByNprLE.js → policyLogic-nqL3E08V.js} +2 -2
  42. package/web-dist/assets/{policyLogic-4ByNprLE.js.map → policyLogic-nqL3E08V.js.map} +1 -1
  43. package/web-dist/assets/{preload-helper-dybNq0aL.js → preload-helper-DOFsWE7_.js} +2 -2
  44. package/web-dist/assets/{preload-helper-dybNq0aL.js.map → preload-helper-DOFsWE7_.js.map} +1 -1
  45. package/web-dist/assets/{queue-BH_AgQ1C.js → queue-p_rnOc-9.js} +2 -2
  46. package/web-dist/assets/{queue-BH_AgQ1C.js.map → queue-p_rnOc-9.js.map} +1 -1
  47. package/web-dist/assets/{repo-Pn-s_Ggk.js → repo-3GZtN4L8.js} +2 -2
  48. package/web-dist/assets/{repo-Pn-s_Ggk.js.map → repo-3GZtN4L8.js.map} +1 -1
  49. package/web-dist/assets/{settings-DjBmhTW8.js → settings-jyGW1LsI.js} +3 -3
  50. package/web-dist/assets/settings-jyGW1LsI.js.map +1 -0
  51. package/web-dist/assets/states-BXOts8eT.js +58 -0
  52. package/web-dist/assets/states-BXOts8eT.js.map +1 -0
  53. package/web-dist/assets/{terminal-login-BSJdzvzq.js → terminal-login-j20zSRZp.js} +2 -2
  54. package/web-dist/assets/{terminal-login-BSJdzvzq.js.map → terminal-login-j20zSRZp.js.map} +1 -1
  55. package/web-dist/assets/useNow-DfER3XvS.js +2 -0
  56. package/web-dist/assets/useNow-DfER3XvS.js.map +1 -0
  57. package/web-dist/assets/{useResource-Bzqxz-K_.js → useResource-DhvWL_9X.js} +2 -2
  58. package/web-dist/assets/{useResource-Bzqxz-K_.js.map → useResource-DhvWL_9X.js.map} +1 -1
  59. package/web-dist/index.html +5 -5
  60. package/web-dist/sw.js +1 -1
  61. package/web-dist/assets/board-C8N8_GS0.js.map +0 -1
  62. package/web-dist/assets/code-BmxcCLin.js.map +0 -1
  63. package/web-dist/assets/settings-DjBmhTW8.js.map +0 -1
  64. package/web-dist/assets/states-f12WE0Zx.js +0 -58
  65. package/web-dist/assets/states-f12WE0Zx.js.map +0 -1
  66. package/web-dist/assets/useNow-Cul-GfCg.js +0 -2
  67. package/web-dist/assets/useNow-Cul-GfCg.js.map +0 -1
package/README.md CHANGED
@@ -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.14.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
 
@@ -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,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,19 +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";
26
35
  import { resourceSnapshot } from "./resource-snapshot.js";
36
+ import { shortSocketPath } from "./socket-paths.js";
27
37
  const PATCHED = Symbol.for("switchyard.terminal");
28
38
  const WRAPPED = Symbol.for("switchyard.terminal.wrapped");
29
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;
30
44
  function messageText(message) {
31
45
  const content = message?.content;
32
46
  if (typeof content === "string")
@@ -81,10 +95,33 @@ export function sessionTotals(entries) {
81
95
  }
82
96
  return totals;
83
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
+ }
84
109
  export default function switchyardTerminal(pi) {
110
+ const g = globalThis;
111
+ if (g[LOADED])
112
+ return;
85
113
  const socketPath = process.env.SWITCHYARD_CONTROL_SOCKET;
86
- if (!socketPath)
114
+ // Inside a holder, only the copy the holder loaded with -e runs.
115
+ if (socketPath && !isCopy(process.env.SWITCHYARD_TERMINAL_EXTENSION))
116
+ return;
117
+ const enrollDir = socketPath
118
+ ? null
119
+ : enrollRuntimeDir(process.env, process.stdin.isTTY === true && process.stdout.isTTY === true);
120
+ if (!socketPath && !enrollDir)
87
121
  return;
122
+ g[LOADED] = true;
123
+ /** Started by the user, not inside a Switchyard holder. */
124
+ const enrolled = !socketPath;
88
125
  let ctx = null;
89
126
  let completer = null;
90
127
  // Work that needs a command context (reload, plugin web views) runs inside a hidden command.
@@ -135,8 +172,8 @@ export default function switchyardTerminal(pi) {
135
172
  appendEntry: (customType, data) => pi.appendEntry(customType, data),
136
173
  mode: "terminal",
137
174
  getCapabilities: () => ({
138
- agentTools: true,
139
- messageDelivery: true,
175
+ agentTools: !enrolled,
176
+ messageDelivery: !enrolled,
140
177
  editorDraftGuard: (() => {
141
178
  try {
142
179
  return typeof ctx?.ui?.getEditorText?.() === "string";
@@ -156,18 +193,33 @@ export default function switchyardTerminal(pi) {
156
193
  return resourceSnapshot(pi, ctx, nativeDialogs + pending.size);
157
194
  });
158
195
  snapshotRegistered = true;
159
- toolPolicy = installPolicyHooks(pi, channel);
160
- registerAgentTools(pi, channel);
161
- const delivery = createMessageDelivery(pi, {
162
- channel,
163
- getContext: () => ctx,
164
- isDialogOpen: () => nativeDialogs > 0 || pending.size > 0,
165
- mode: "terminal",
166
- });
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;
167
210
  const send = (obj) => {
168
211
  try {
169
- 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
+ }
170
221
  return;
222
+ }
171
223
  socket.write(`${JSON.stringify(obj)}\n`);
172
224
  }
173
225
  catch {
@@ -387,7 +439,8 @@ export default function switchyardTerminal(pi) {
387
439
  ui[method] = wrap((title, second, opts) => race(ui, method, orig, title, second, opts));
388
440
  }
389
441
  const origEditor = ui.editor;
390
- 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) {
391
444
  ui.editor = wrap((title, prefill) => raceEditor(ui, origEditor, title, prefill));
392
445
  }
393
446
  const origNotify = ui.notify;
@@ -621,6 +674,9 @@ export default function switchyardTerminal(pi) {
621
674
  return;
622
675
  case "shutdown":
623
676
  respond(id, type);
677
+ // Never quit a Pi the user started.
678
+ if (enrolled)
679
+ return;
624
680
  setImmediate(() => {
625
681
  try {
626
682
  ctx.shutdown();
@@ -781,10 +837,10 @@ export default function switchyardTerminal(pi) {
781
837
  // The holder listens before it starts Pi, but retry a few times anyway (a slow or restarting holder).
782
838
  const CONNECT_ATTEMPTS = 5;
783
839
  const CONNECT_RETRY_MS = 200;
784
- const connect = (attempt) => {
840
+ const connect = (path, attempt) => {
785
841
  let s;
786
842
  try {
787
- s = createConnection(socketPath);
843
+ s = createConnection(path);
788
844
  }
789
845
  catch {
790
846
  socket = null;
@@ -813,13 +869,138 @@ export default function switchyardTerminal(pi) {
813
869
  socket = null;
814
870
  }
815
871
  if (!connected && attempt < CONNECT_ATTEMPTS) {
816
- setTimeout(() => connect(attempt + 1), CONNECT_RETRY_MS).unref();
872
+ setTimeout(() => connect(path, attempt + 1), CONNECT_RETRY_MS).unref();
817
873
  }
818
874
  });
819
875
  s.unref();
820
876
  s.write(`${JSON.stringify({ role: "extension" })}\n`);
821
877
  };
822
- 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
+ };
823
1004
  try {
824
1005
  pi.events?.on?.(REMOTE_UI_CHANNEL, (data) => {
825
1006
  const r = data;
@@ -870,7 +1051,10 @@ export default function switchyardTerminal(pi) {
870
1051
  channel.announce();
871
1052
  if (event?.reason && event.reason !== "startup") {
872
1053
  send({ type: "switchyard_native", sessionId, sessionFile });
1054
+ writeMeta();
873
1055
  }
1056
+ if (enrolled && sessionFile)
1057
+ listen();
874
1058
  for (const cmd of early.splice(0))
875
1059
  handleCommand(cmd);
876
1060
  });
@@ -950,8 +1134,18 @@ export default function switchyardTerminal(pi) {
950
1134
  on("session_shutdown", () => {
951
1135
  snapshotRegistered = false;
952
1136
  removeSnapshot();
953
- delivery.close();
1137
+ delivery?.close();
954
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
+ }
955
1149
  });
956
1150
  on("input", (event) => {
957
1151
  if (event?.source !== "interactive")