townmouse 0.2.1 → 0.4.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 (41) hide show
  1. package/CHANGELOG.md +72 -2
  2. package/DESIGN.md +26 -42
  3. package/README.md +286 -54
  4. package/SECURITY.md +3 -0
  5. package/TOWNMOUSE.md +1 -1
  6. package/bin/townmouse +2 -2
  7. package/docs/PACKAGING.md +104 -8
  8. package/docs/browser-workspace.md +62 -9
  9. package/docs/panes.md +199 -9
  10. package/native/TownmouseApp.swift +5 -5
  11. package/npm-shrinkwrap.json +1282 -0
  12. package/package.json +11 -7
  13. package/public/browser-picture.mjs +159 -0
  14. package/public/features/app-version.mjs +35 -0
  15. package/public/features/autosave.mjs +5 -1
  16. package/public/features/multi-window-sync.mjs +3 -1
  17. package/public/features/osc-bridge.mjs +8 -3
  18. package/public/features/session-manager.mjs +202 -100
  19. package/public/features/status-metrics.mjs +23 -0
  20. package/public/features/tab-reorder.mjs +8 -0
  21. package/public/features/window-title.mjs +10 -3
  22. package/public/index.html +617 -78
  23. package/public/input-guard.mjs +10 -2
  24. package/public/panes.css +189 -13
  25. package/public/panes.html +4 -1
  26. package/public/panes.mjs +667 -109
  27. package/public/workspace.css +198 -24
  28. package/public/workspace.mjs +346 -106
  29. package/scripts/install-service.sh +97 -63
  30. package/scripts/panes +134 -5
  31. package/scripts/retire-legacy-service.sh +76 -0
  32. package/scripts/{t1.sh → townmouse.sh} +60 -21
  33. package/scripts/uninstall-service.sh +31 -15
  34. package/src/agent-guide.js +72 -3
  35. package/src/attachments.js +2 -2
  36. package/src/browser-dom.js +5 -2
  37. package/src/browser-workspace.js +549 -62
  38. package/src/owner-page.js +43 -0
  39. package/src/request-boundary.js +1 -1
  40. package/src/server.js +588 -128
  41. package/src/workspace-panes.js +423 -91
@@ -2,41 +2,89 @@
2
2
  #
3
3
  # Townmouse — install the always-on macOS LaunchAgent (launchd).
4
4
  #
5
+ # Townmouse keeps its own service name and port so it can sit beside TerminalOne,
6
+ # the engine it embeds. TerminalOne is `com.floyd.terminalone` on 11001 with the
7
+ # `t1` launcher; none of those are touched here.
8
+ #
5
9
  # EFFECT RADIUS (what this changes on your machine):
6
- # - Writes ~/Library/LaunchAgents/com.floyd.terminalone.plist
7
- # - Registers a per-user LaunchAgent that runs `node src/server.js` on PORT 11001
10
+ # - Writes ~/Library/LaunchAgents/com.floyd.townmouse.plist
11
+ # - Registers a per-user LaunchAgent that runs `node src/server.js` on PORT 11002
8
12
  # - RunAtLoad (starts at login) + KeepAlive (auto-restart on crash)
9
13
  # - KeepAlive is gated on PathState: it only runs while
10
14
  # the installed checkout's `src/server.js` exists (i.e. the app volume is
11
15
  # mounted), and auto-starts when the volume re-appears.
12
- # - Logs to ~/Library/Logs/com.floyd.terminalone.{out,err}.log (INTERNAL disk;
16
+ # - Logs to ~/Library/Logs/com.floyd.townmouse.{out,err}.log (INTERNAL disk;
13
17
  # launchd cannot reliably create log files on the external volume -> EX_CONFIG).
14
- # - Installs a self-contained `t1` binary on the INTERNAL disk (first writable of
15
- # ~/.local/bin, /usr/local/bin, ~/bin) so `t1` works from any shell and does NOT
16
- # dangle when the external volume unmounts (it mount-checks and errors clearly).
17
- # - Creates ~/Applications/Townmouse.app (with brand icon, quarantine cleared) so
18
+ # - Installs a self-contained `townmouse` launcher on the INTERNAL disk (first
19
+ # writable of ~/.local/bin, /usr/local/bin, ~/bin) so `townmouse` works from
20
+ # any shell and does NOT dangle when the external volume unmounts (it
21
+ # mount-checks and errors clearly).
22
+ # - Creates /Applications/Townmouse.app (with brand icon, quarantine cleared) so
18
23
  # it launches with no terminal: Spotlight (Cmd-Space), Launchpad, and the Dock.
24
+ # - Retires the service that Townmouse 0.2.x installed under TerminalOne's name,
25
+ # if this Mac still has one (scripts/retire-legacy-service.sh).
19
26
  # Fully reversible: scripts/uninstall-service.sh
20
27
  #
21
28
  set -euo pipefail
22
29
 
23
30
  SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
24
- LABEL="com.floyd.terminalone"
31
+ LABEL="com.floyd.townmouse"
25
32
  APP_DIR="${TERMINALONE_APP_DIR:-$(cd "$SCRIPT_DIR/.." && pwd -P)}"
26
- PORT="${PORT:-11001}"
27
- NODE="${TERMINALONE_NODE:-$($APP_DIR/scripts/node-runtime.sh path 2>/dev/null || true)}"
33
+ PORT="${PORT:-11002}"
34
+ NODE="${TERMINALONE_NODE:-$("$APP_DIR/scripts/node-runtime.sh" path 2>/dev/null || true)}"
28
35
  PLIST_DIR="${TERMINALONE_PLIST_DIR:-$HOME/Library/LaunchAgents}"
29
36
  PLIST="$PLIST_DIR/$LABEL.plist"
30
37
  LOG_DIR="${TERMINALONE_SYSTEM_LOG_DIR:-$HOME/Library/Logs}"
31
38
  DOMAIN="gui/$(id -u)"
32
39
  APP_PARENT_OVERRIDE="${TERMINALONE_APPLICATIONS_DIR:-}"
33
- T1_BIN_DIR_OVERRIDE="${TERMINALONE_BIN_DIR:-}"
40
+ BIN_DIR_OVERRIDE="${TERMINALONE_BIN_DIR:-}"
34
41
 
35
42
  [ -n "$NODE" ] || { echo "ERROR: Townmouse requires Node 22.x; run scripts/node-runtime.sh doctor"; exit 1; }
36
43
  [ -f "$APP_DIR/src/server.js" ] || { echo "ERROR: $APP_DIR/src/server.js not found (is the volume mounted?)"; exit 1; }
44
+ # Pick the directory for the `townmouse` launcher before anything is changed, so
45
+ # an unusable choice stops the install with nothing half-done. The directory must
46
+ # be on the INTERNAL disk: macOS keeps writable paths on the Data volume, and a
47
+ # launcher on a volume that unmounts would dangle. A `townmouse` that this
48
+ # installer did not write (npm's own command for the package, or someone else's)
49
+ # is never overwritten; such a directory is passed over.
50
+ INTERNAL_DEV="$(df /System/Volumes/Data 2>/dev/null | tail -1 | awk '{print $1}')"
51
+ [ -n "$INTERNAL_DEV" ] || INTERNAL_DEV="$(df / | tail -1 | awk '{print $1}')"
52
+ is_internal() { case "$1" in /Volumes/*) return 1;; esac; [ "$(df "$1" 2>/dev/null | tail -1 | awk '{print $1}')" = "$INTERNAL_DEV" ]; }
53
+ launcher_slot_is_free() {
54
+ local launcher="$1/townmouse"
55
+ { [ -e "$launcher" ] || [ -L "$launcher" ]; } || return 0
56
+ [ -f "$launcher" ] && [ ! -L "$launcher" ] && grep -q 'Townmouse launcher' "$launcher" 2>/dev/null
57
+ }
58
+ BIN_DIR_SELECTED=""
59
+ if [ -n "$BIN_DIR_OVERRIDE" ]; then
60
+ if [ -e "$BIN_DIR_OVERRIDE/townmouse" ] && ! launcher_slot_is_free "$BIN_DIR_OVERRIDE"; then
61
+ echo "ERROR: $BIN_DIR_OVERRIDE/townmouse exists and was not written by this installer, so it will not be overwritten. Remove it, or point TERMINALONE_BIN_DIR at another directory on the internal disk." >&2
62
+ exit 1
63
+ fi
64
+ mkdir -p "$BIN_DIR_OVERRIDE"
65
+ BIN_DIR_SELECTED="$BIN_DIR_OVERRIDE"
66
+ else
67
+ for d in "$HOME/.local/bin" /usr/local/bin "$HOME/bin"; do
68
+ if [ -d "$d" ] && [ -w "$d" ] && is_internal "$d" && launcher_slot_is_free "$d"; then BIN_DIR_SELECTED="$d"; break; fi
69
+ done
70
+ if [ -z "$BIN_DIR_SELECTED" ]; then
71
+ # Nothing writable, internal and free of a foreign `townmouse`: create ~/bin on the internal disk.
72
+ if mkdir -p "$HOME/bin" 2>/dev/null && is_internal "$HOME/bin" && launcher_slot_is_free "$HOME/bin"; then
73
+ BIN_DIR_SELECTED="$HOME/bin"
74
+ else
75
+ BIN_DIR_SELECTED="$HOME/.local/bin"
76
+ if ! launcher_slot_is_free "$BIN_DIR_SELECTED"; then
77
+ echo "ERROR: $BIN_DIR_SELECTED/townmouse exists and was not written by this installer, so it will not be overwritten. Remove it, or set TERMINALONE_BIN_DIR to a directory on the internal disk." >&2
78
+ exit 1
79
+ fi
80
+ mkdir -p "$BIN_DIR_SELECTED"
81
+ echo " WARN : no internal-disk bin dir found; townmouse placed on $BIN_DIR_SELECTED (may be external)."
82
+ fi
83
+ fi
84
+ fi
37
85
  # A package tarball can lose execute bits on helper scripts. Restore the ones
38
86
  # this installer calls before it calls them.
39
- chmod +x "$APP_DIR/scripts/run-hooks" "$APP_DIR/scripts/t1.sh" "$APP_DIR/scripts/node-runtime.sh" 2>/dev/null || true
87
+ chmod +x "$APP_DIR/scripts/run-hooks" "$APP_DIR/scripts/townmouse.sh" "$APP_DIR/scripts/node-runtime.sh" 2>/dev/null || true
40
88
  if [ "${TERMINALONE_SKIP_RUNTIME_CHECK:-0}" != "1" ]; then
41
89
  "$APP_DIR/scripts/node-runtime.sh" doctor >/dev/null || {
42
90
  echo "Repairing Townmouse native modules for $($NODE -v)..."
@@ -46,6 +94,10 @@ fi
46
94
  "$APP_DIR/scripts/run-hooks" pre-install
47
95
  mkdir -p "$PLIST_DIR" "$LOG_DIR"
48
96
 
97
+ # 0.2.x installed this app under TerminalOne's launchd label and port. Take that
98
+ # service out of TerminalOne's way before starting ours.
99
+ bash "$SCRIPT_DIR/retire-legacy-service.sh"
100
+
49
101
  # NOTE: no WorkingDirectory key — the server resolves all paths via __dirname, and a
50
102
  # chdir into the external volume from the launchd context can itself trigger EX_CONFIG.
51
103
  cat > "$PLIST" <<PLISTEOF
@@ -114,48 +166,23 @@ else
114
166
  launchctl kickstart -k "$DOMAIN/$LABEL" || true
115
167
  fi
116
168
 
117
- # --- Install `t1` as a REAL self-contained binary on the INTERNAL disk.
169
+ # --- Install `townmouse` as a REAL self-contained launcher on the INTERNAL disk.
118
170
  # Not a symlink into the external volume: a symlink would dangle ("no such file")
119
171
  # the moment the app volume unmounts. This generated stub lives on the internal disk,
120
172
  # bakes in the app path, checks the mount, and fails LOUDLY (stderr + GUI dialog)
121
173
  # instead of cryptically when the volume is gone.
122
- chmod +x "$APP_DIR/scripts/t1.sh" 2>/dev/null || true
123
- # Pick a bin dir on the INTERNAL disk. macOS: / is a sealed snapshot but writable
124
- # paths live on the Data volume (same physical internal container); we match that
125
- # device and reject any /Volumes/* external mount so `t1` can't live on a disk that
126
- # unmounts. Prefer dirs already on PATH.
127
- INTERNAL_DEV="$(df /System/Volumes/Data 2>/dev/null | tail -1 | awk '{print $1}')"
128
- [ -n "$INTERNAL_DEV" ] || INTERNAL_DEV="$(df / | tail -1 | awk '{print $1}')"
129
- is_internal() { case "$1" in /Volumes/*) return 1;; esac; [ "$(df "$1" 2>/dev/null | tail -1 | awk '{print $1}')" = "$INTERNAL_DEV" ]; }
130
- T1_BIN_DIR=""
131
- if [ -n "$T1_BIN_DIR_OVERRIDE" ]; then
132
- mkdir -p "$T1_BIN_DIR_OVERRIDE"
133
- T1_BIN_DIR="$T1_BIN_DIR_OVERRIDE"
134
- else
135
- for d in "$HOME/.local/bin" /usr/local/bin "$HOME/bin"; do
136
- if [ -d "$d" ] && [ -w "$d" ] && is_internal "$d"; then T1_BIN_DIR="$d"; break; fi
137
- done
138
- if [ -z "$T1_BIN_DIR" ]; then
139
- # Nothing writable+internal+existing; create ~/bin on the internal disk.
140
- if mkdir -p "$HOME/bin" 2>/dev/null && is_internal "$HOME/bin"; then
141
- T1_BIN_DIR="$HOME/bin"
142
- else
143
- T1_BIN_DIR="$HOME/.local/bin"; mkdir -p "$T1_BIN_DIR"
144
- echo " WARN : no internal-disk bin dir found; t1 placed on $T1_BIN_DIR (may be external)."
145
- fi
146
- fi
147
- fi
148
- T1_LINK="$T1_BIN_DIR/t1"
149
- T1_TMP="$(mktemp "$T1_BIN_DIR/.t1.XXXXXX")"
150
- cat > "$T1_TMP" <<T1EOF
174
+ chmod +x "$APP_DIR/scripts/townmouse.sh" 2>/dev/null || true
175
+ LAUNCHER_LINK="$BIN_DIR_SELECTED/townmouse"
176
+ LAUNCHER_TMP="$(mktemp "$BIN_DIR_SELECTED/.townmouse.XXXXXX")"
177
+ cat > "$LAUNCHER_TMP" <<LAUNCHEREOF
151
178
  #!/bin/bash
152
179
  # Townmouse launcher — generated by install-service.sh. Self-contained; lives on
153
180
  # the internal disk so it survives "$APP_DIR" unmounting. Regenerate via reinstall.
154
181
  set -euo pipefail
155
- T1_APP="$APP_DIR/scripts/t1.sh"
156
- if [ ! -f "\$T1_APP" ]; then
182
+ TOWNMOUSE_APP="$APP_DIR/scripts/townmouse.sh"
183
+ if [ ! -f "\$TOWNMOUSE_APP" ]; then
157
184
  MSG="Townmouse is unavailable: its volume is not mounted (expected at $APP_DIR). Reconnect the drive, then try again."
158
- printf '\\033[31mt1: %s\\033[0m\\n' "\$MSG" >&2
185
+ printf '\\033[31mtownmouse: %s\\033[0m\\n' "\$MSG" >&2
159
186
  # If launched without a terminal (Finder/Spotlight/Dock), surface a GUI dialog too.
160
187
  if [ ! -t 2 ] && command -v osascript >/dev/null 2>&1; then
161
188
  osascript -e "display dialog \"\$MSG\" with title \"Townmouse\" buttons {\"OK\"} default button \"OK\" with icon caution" >/dev/null 2>&1 || true
@@ -165,12 +192,12 @@ fi
165
192
  case "\${1:-}" in
166
193
  doctor) exec "$APP_DIR/scripts/node-runtime.sh" doctor ;;
167
194
  repair) exec "$APP_DIR/scripts/node-runtime.sh" repair ;;
168
- hooks) for d in "$APP_DIR/.terminal-hooks" "$HOME/.config/terminal-workspace/hooks/terminalone"; do [ ! -d "\$d" ] || find "\$d" -maxdepth 2 -type f; done | sort ; exit 0 ;;
195
+ hooks) for d in "$APP_DIR/.terminal-hooks" "\$HOME/.config/terminal-workspace/hooks/terminalone"; do [ ! -d "\$d" ] || find "\$d" -maxdepth 2 -type f; done | sort ; exit 0 ;;
169
196
  esac
170
- exec /bin/bash "\$T1_APP" "\$@"
171
- T1EOF
172
- chmod +x "$T1_TMP"
173
- mv -f "$T1_TMP" "$T1_LINK"
197
+ exec /bin/bash "\$TOWNMOUSE_APP" "\$@"
198
+ LAUNCHEREOF
199
+ chmod +x "$LAUNCHER_TMP"
200
+ mv -f "$LAUNCHER_TMP" "$LAUNCHER_LINK"
174
201
 
175
202
  # --- Make Townmouse launchable from anywhere WITHOUT a terminal:
176
203
  # a tiny .app bundle -> shows in Spotlight, Launchpad, and Dock. Prefer /Applications
@@ -193,7 +220,7 @@ cat > "$APP_BUNDLE/Contents/Info.plist" <<APPEOF
193
220
  <dict>
194
221
  <key>CFBundleName</key><string>Townmouse</string>
195
222
  <key>CFBundleDisplayName</key><string>Townmouse</string>
196
- <key>CFBundleIdentifier</key><string>com.floyd.terminalone</string>
223
+ <key>CFBundleIdentifier</key><string>com.floyd.townmouse</string>
197
224
  <key>CFBundleVersion</key><string>1.0</string>
198
225
  <key>CFBundlePackageType</key><string>APPL</string>
199
226
  <key>CFBundleExecutable</key><string>Townmouse</string>
@@ -203,16 +230,21 @@ cat > "$APP_BUNDLE/Contents/Info.plist" <<APPEOF
203
230
  </dict>
204
231
  </plist>
205
232
  APPEOF
233
+ # Say which macOS versions the wrapper runs on, matching LSMinimumSystemVersion in
234
+ # the bundle. Without a target the compiler stamps its own default, which can be
235
+ # newer than the Mac it is built on; Launch Services then refuses the icon with
236
+ # kLSIncompatibleSystemVersionErr even though the program itself would run.
237
+ SWIFT_TARGET="$(uname -m)-apple-macosx13.0"
206
238
  if [ -n "${TERMINALONE_SWIFTC:-}" ]; then
207
239
  [ -x "$TERMINALONE_SWIFTC" ] || { echo "ERROR: TERMINALONE_SWIFTC is not executable." >&2; exit 1; }
208
- "$TERMINALONE_SWIFTC" -parse-as-library -O -framework AppKit -framework WebKit \
240
+ "$TERMINALONE_SWIFTC" -parse-as-library -O -target "$SWIFT_TARGET" -framework AppKit -framework WebKit \
209
241
  "$APP_DIR/native/TownmouseApp.swift" -o "$APP_BUNDLE/Contents/MacOS/Townmouse"
210
242
  else
211
243
  xcrun --find swiftc >/dev/null 2>&1 || { echo "ERROR: Swift compiler unavailable; install Apple Command Line Tools." >&2; exit 1; }
212
- xcrun swiftc -parse-as-library -O -framework AppKit -framework WebKit \
244
+ xcrun swiftc -parse-as-library -O -target "$SWIFT_TARGET" -framework AppKit -framework WebKit \
213
245
  "$APP_DIR/native/TownmouseApp.swift" -o "$APP_BUNDLE/Contents/MacOS/Townmouse"
214
246
  fi
215
- printf '%s\n' "$T1_LINK" > "$APP_BUNDLE/Contents/Resources/launcher-path.txt"
247
+ printf '%s\n' "$LAUNCHER_LINK" > "$APP_BUNDLE/Contents/Resources/launcher-path.txt"
216
248
  # Build the .icns from the brand icon so it shows in Spotlight/Launchpad/Dock.
217
249
  RES_DIR="$APP_BUNDLE/Contents/Resources"
218
250
  mkdir -p "$RES_DIR"
@@ -232,22 +264,24 @@ fi
232
264
  # prompt on first Finder/Spotlight launch. Safe no-op if no flag is present.
233
265
  xattr -dr com.apple.quarantine "$APP_BUNDLE" 2>/dev/null || true
234
266
  # Register with Launch Services so Spotlight/Launchpad index it promptly.
235
- /System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister -f "$APP_BUNDLE" 2>/dev/null || true
267
+ if [ "${TERMINALONE_SKIP_LSREGISTER:-0}" != "1" ]; then
268
+ /System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister -f "$APP_BUNDLE" 2>/dev/null || true
269
+ fi
236
270
  "$APP_DIR/scripts/run-hooks" post-install --best-effort
237
271
  # Ensure the chosen bin dir is actually on PATH. If not, add a marked line to the
238
272
  # user's shell rc (idempotent — only once). Covers zsh (default) and bash.
239
- T1_PATH_ADDED=""
273
+ LAUNCHER_PATH_ADDED=""
240
274
  case ":$PATH:" in
241
- *":$T1_BIN_DIR:"*) : ;; # already on PATH this session
275
+ *":$BIN_DIR_SELECTED:"*) : ;; # already on PATH this session
242
276
  *)
243
277
  MARK="# added by Townmouse install-service.sh"
244
- LINE="export PATH=\"$T1_BIN_DIR:\$PATH\" $MARK"
278
+ LINE="export PATH=\"$BIN_DIR_SELECTED:\$PATH\" $MARK"
245
279
  for rc in "$HOME/.zshrc" "$HOME/.bash_profile"; do
246
280
  if [ ! -e "$rc" ]; then
247
281
  if [ "$rc" = "$HOME/.zshrc" ]; then touch "$rc"; else continue; fi
248
282
  fi
249
283
  if ! grep -qF "$MARK" "$rc" 2>/dev/null; then
250
- printf '\n%s\n' "$LINE" >> "$rc" && T1_PATH_ADDED="$rc"
284
+ printf '\n%s\n' "$LINE" >> "$rc" && LAUNCHER_PATH_ADDED="$rc"
251
285
  fi
252
286
  done
253
287
  ;;
@@ -258,12 +292,12 @@ echo " plist : $PLIST"
258
292
  echo " node : $NODE"
259
293
  echo " logs : $LOG_DIR/$LABEL.{out,err}.log and $LOG_DIR/Townmouse/local-launch.err.log"
260
294
  echo " url : http://localhost:$PORT"
261
- echo " t1 : ${T1_LINK:-(failed to link)}"
295
+ echo " townmouse : ${LAUNCHER_LINK:-(failed to link)}"
262
296
  echo " app : $APP_BUNDLE (Spotlight: Cmd-Space -> Townmouse)"
263
297
  echo " app : opens the UI only after health is confirmed; falls back to direct local startup if launchd is unavailable."
264
298
  echo "Manage: launchctl print $DOMAIN/$LABEL | stop: scripts/uninstall-service.sh"
265
- if [ -n "$T1_PATH_ADDED" ]; then
266
- echo " PATH : added $T1_BIN_DIR to $T1_PATH_ADDED — run 'source $T1_PATH_ADDED' or open a new shell, then 't1'."
299
+ if [ -n "$LAUNCHER_PATH_ADDED" ]; then
300
+ echo " PATH : added $BIN_DIR_SELECTED to $LAUNCHER_PATH_ADDED — run 'source $LAUNCHER_PATH_ADDED' or open a new shell, then 'townmouse'."
267
301
  else
268
- echo " PATH : $T1_BIN_DIR already on PATH — run 't1' now."
302
+ echo " PATH : $BIN_DIR_SELECTED already on PATH — run 'townmouse' now."
269
303
  fi
package/scripts/panes CHANGED
@@ -7,15 +7,18 @@ const fs = require('fs');
7
7
  const os = require('os');
8
8
  const path = require('path');
9
9
 
10
- const api = (process.env.TOWNMOUSE_API || 'http://127.0.0.1:11001/api/panes').replace(/\/$/, '');
10
+ const api = (process.env.TOWNMOUSE_API || 'http://127.0.0.1:11002/api/panes').replace(/\/$/, '');
11
+ // The shells in the owner's terminal row answer beside the pane API, with the
12
+ // same token.
13
+ const sessionApi = api.replace(/\/api\/panes$/, '') + '/api/sessions';
11
14
  let token = process.env.TOWNMOUSE_TOKEN || '';
12
15
  if (!token) {
13
16
  try { token = fs.readFileSync(path.join(os.homedir(), '.townmouse', 'pane-token'), 'utf8').trim(); } catch (_) { /* reported below */ }
14
17
  }
15
18
 
16
- async function call(method, suffix, body) {
19
+ async function call(method, suffix, body, base = api) {
17
20
  if (!token) throw new Error('No workspace token. Run from a Townmouse terminal pane or set TOWNMOUSE_TOKEN.');
18
- const res = await fetch(api + suffix, {
21
+ const res = await fetch(base + suffix, {
19
22
  method,
20
23
  headers: { 'Content-Type': 'application/json', 'X-Townmouse-Token': token },
21
24
  // A hung server must not hang the agent. Long enough for a 120s bounded
@@ -35,7 +38,7 @@ async function call(method, suffix, body) {
35
38
  // Options that never take a value. Without this list, `--replace "text"` would
36
39
  // consume the text as the flag's value and clear the field instead of filling
37
40
  // it.
38
- const BOOLEAN_FLAGS = new Set(['replace', 'elements', 'activate', 'accept', 'dismiss', 'force', 'help']);
41
+ const BOOLEAN_FLAGS = new Set(['replace', 'elements', 'activate', 'accept', 'dismiss', 'force', 'help', 'no-wait', 'cancel']);
39
42
 
40
43
  function args(list) {
41
44
  const out = { _: [] };
@@ -89,6 +92,23 @@ function paneTarget(list, verb) {
89
92
  return { paneId, rest: list };
90
93
  }
91
94
 
95
+ // A shell session is named by its id, by the first 8 or more characters of
96
+ // its id, or by its name when no other session has the same one. Names are
97
+ // looked up in the list the server shows this caller, which for an agent is
98
+ // the shells agents started: one of the owner's comes back as not found.
99
+ async function sessionTarget(reference, verb) {
100
+ const wanted = String(reference || '').trim();
101
+ if (!wanted) throw new Error(`${verb} requires a session: its name, its id, or the start of its id.`);
102
+ const state = await call('GET', '', undefined, sessionApi);
103
+ const sessions = Array.isArray(state.sessions) ? state.sessions : [];
104
+ const exact = sessions.find((session) => session.id === wanted || session.name === wanted);
105
+ if (exact) return exact;
106
+ const partial = /^[0-9a-f-]{8,}$/i.test(wanted) ? sessions.filter((session) => session.id.startsWith(wanted)) : [];
107
+ if (partial.length > 1) throw new Error(`“${wanted}” matches ${partial.length} sessions; use more of the id.`);
108
+ if (partial.length === 1) return partial[0];
109
+ throw new Error(`No session is named “${wanted}”. Run: panes session list`);
110
+ }
111
+
92
112
  async function main() {
93
113
  const [scope, action, ...rest] = process.argv.slice(2);
94
114
  if (scope === 'pane' && (action === 'run' || action === 'input')) {
@@ -154,6 +174,55 @@ async function main() {
154
174
  print(await call('GET', `/panes/${paneId}/wait?${query.toString()}`));
155
175
  return;
156
176
  }
177
+ if (scope === 'pane' && action === 'request') {
178
+ // The one way an agent gets at one of the owner's panes: ask, and wait for
179
+ // the answer. The answer is the pane's own state, so this reads the same
180
+ // truth the owner's page shows.
181
+ const target = paneTarget(rest, 'pane request');
182
+ const paneId = target.paneId;
183
+ const options = args(target.rest);
184
+ if (options.cancel) {
185
+ print(await call('DELETE', `/panes/${paneId}/request-access`));
186
+ return;
187
+ }
188
+ const level = options.level || 'control';
189
+ if (!['view', 'control'].includes(level)) throw new Error('pane request requires --level view or control.');
190
+ await call('POST', `/panes/${paneId}/request-access`, { level, message: options.message });
191
+ const rank = { private: 0, view: 1, control: 2 };
192
+ const readPane = async () => {
193
+ const state = await call('GET', '/state');
194
+ for (const tab of state.tabs || []) {
195
+ const pane = (tab.panes || []).find((candidate) => candidate.id === paneId);
196
+ if (pane) return pane;
197
+ }
198
+ return null;
199
+ };
200
+ const deadline = Date.now() + Math.max(0, Number(options.timeout) || 120000);
201
+ let answered = 'waiting';
202
+ let pane = await readPane();
203
+ for (;;) {
204
+ const has = pane && pane.agentAccess ? rank[pane.agentAccess.level] || 0 : 0;
205
+ if (pane && has >= rank[level]) { answered = 'granted'; break; }
206
+ if (!pane || !pane.accessRequest) { answered = 'declined'; break; }
207
+ if (options['no-wait'] || Date.now() >= deadline) break;
208
+ await new Promise((resolve) => setTimeout(resolve, 1000));
209
+ pane = await readPane();
210
+ }
211
+ print({
212
+ paneId,
213
+ requested: level,
214
+ answered,
215
+ agentAccess: pane ? pane.agentAccess : null,
216
+ // While the ask waits, this says until when.
217
+ accessRequest: pane && pane.accessRequest ? pane.accessRequest : null,
218
+ note: answered === 'granted' ? 'The owner gave access. It lasts until the owner changes it or the server restarts.'
219
+ : answered === 'declined' ? 'The owner dismissed the ask, or it expired unanswered. Finish without this pane; do not ask again at once.'
220
+ : 'The owner has not answered yet. Run the command again to keep waiting.'
221
+ });
222
+ if (answered === 'waiting') process.exitCode = 3;
223
+ else if (answered === 'declined') process.exitCode = 5;
224
+ return;
225
+ }
157
226
  if (scope === 'guide') {
158
227
  print(await call('GET', '/guide'));
159
228
  return;
@@ -317,6 +386,44 @@ async function main() {
317
386
  throw new Error(`Unknown browser action: ${verb}`);
318
387
  }
319
388
  }
389
+ // Shell sessions: the shells in the owner's terminal row. A session is named
390
+ // by its name, its id, or the start of its id.
391
+ if (scope === 'session') {
392
+ const options = args(rest);
393
+ if (action === 'list') {
394
+ print(await call('GET', '', undefined, sessionApi));
395
+ return;
396
+ }
397
+ if (action === 'create') {
398
+ // createdBy is what older servers read to learn who was asking. A current
399
+ // server ignores it and decides from the key: the token makes this an
400
+ // agent's shell either way.
401
+ print(await call('POST', '', {
402
+ name: options.name,
403
+ cwd: options.cwd,
404
+ activate: options.activate === true,
405
+ createdBy: 'agent'
406
+ }, sessionApi));
407
+ return;
408
+ }
409
+ if (action === 'rename') {
410
+ const target = await sessionTarget(options._[0], 'session rename');
411
+ if (!options.name) throw new Error('session rename requires --name TEXT.');
412
+ print(await call('PATCH', `/${target.id}`, { name: options.name }, sessionApi));
413
+ return;
414
+ }
415
+ if (action === 'activate') {
416
+ const target = await sessionTarget(options._[0], 'session activate');
417
+ print(await call('POST', `/${target.id}/activate`, {}, sessionApi));
418
+ return;
419
+ }
420
+ if (action === 'close') {
421
+ const target = await sessionTarget(options._[0], 'session close');
422
+ print(await call('DELETE', `/${target.id}`, undefined, sessionApi));
423
+ return;
424
+ }
425
+ throw new Error(`Unknown session action: ${action}. Run: panes help`);
426
+ }
320
427
  const a = args(rest);
321
428
  if (scope === 'attach') {
322
429
  const attachArgs = args([action, ...rest].filter((value) => value !== undefined));
@@ -367,6 +474,9 @@ async function main() {
367
474
  [--since OFFSET] [--timeout MS]
368
475
  panes pane status <pane-id> --state working|blocked|idle|done|unknown [--message TEXT]
369
476
  panes pane dialog <pane-id> --accept|--dismiss [--text VALUE]
477
+ panes pane request <pane-id> [--level view|control] [--message TEXT] [--timeout MS] [--no-wait]
478
+ Ask the owner for access to one of their panes, and wait
479
+ for the answer. --cancel withdraws the ask.
370
480
 
371
481
  Browser control (pane ids may be omitted inside a Townmouse pane):
372
482
  panes pane browser observe <pane-id> [--elements] [--max N] [--image-file PATH]
@@ -387,7 +497,23 @@ async function main() {
387
497
  panes attach <file> [--pane <pane-id>] [--type MIME]
388
498
  panes active --tab <tab-id> [--pane <pane-id>]
389
499
 
390
- Exit codes: 0 done, 1 failed/missing, 3 still running, 4 stale target.
500
+ Shell sessions (shells in the owner's terminal row). These commands reach the shells agents
501
+ started, which 'session list' shows; the owner's shells are only counted there, as ownerStarted.
502
+ <session> is a name, an id, or the start of an id from that list.
503
+ panes session list
504
+ panes session create [--name TEXT] [--cwd PATH] [--activate]
505
+ panes session rename <session> --name TEXT
506
+ panes session activate <session> Moves the owner's view; only when they asked.
507
+ panes session close <session> Ends the shell. It cannot be undone.
508
+
509
+ Exit codes: 0 done, 1 failed/missing, 3 still running or still waiting, 4 stale target,
510
+ 5 the owner declined the request.
511
+ Who may do what: a pane you open is every agent's to use, and so is the Orchestrator pane.
512
+ A pane the owner opened is Private until the owner gives View only (you can read it) or
513
+ Allow control (you can read and drive it). 'panes state' says what you have on each pane
514
+ under agentAccess. A password field takes your typing and never returns its value.
515
+ A shell you start is any agent's to rename, show and close; a shell the owner started is the
516
+ owner's, so you cannot rename, show or close it, and 'session list' only counts it.
391
517
  Environment: TOWNMOUSE_API, TOWNMOUSE_TOKEN, TOWNMOUSE_TAB_ID, TOWNMOUSE_PANE_ID.`);
392
518
  return;
393
519
  }
@@ -399,6 +525,9 @@ Environment: TOWNMOUSE_API, TOWNMOUSE_TOKEN, TOWNMOUSE_TAB_ID, TOWNMOUSE_PANE_ID
399
525
  }
400
526
  if (scope === 'tab') {
401
527
  if (action === 'list') { const s = await call('GET', '/state'); print(s.tabs); return; }
528
+ // createdBy is what older servers read to learn who was asking. A current
529
+ // server ignores it and decides from the key: the token makes this the
530
+ // agent's tab either way.
402
531
  if (action === 'create') { print(await call('POST', '/tabs', { title: a.title, activate: a.activate === true, createdBy: 'agent' })); return; }
403
532
  if (action === 'close') { print(await call('DELETE', `/tabs/${a._[0]}`)); return; }
404
533
  }
@@ -0,0 +1,76 @@
1
+ #!/bin/bash
2
+ #
3
+ # Retire what Townmouse 0.2.x left under TerminalOne's name. Those versions
4
+ # installed the service as `com.floyd.terminalone` on port 11001 and wrote their
5
+ # launcher as `t1`, so Townmouse displaced TerminalOne on any Mac that had both.
6
+ # Only artifacts that are provably Townmouse's are removed: a plist under the
7
+ # TerminalOne label whose program is a Townmouse server, and a `t1` launcher that
8
+ # names itself a Townmouse launcher. TerminalOne's own service and launcher are
9
+ # never touched.
10
+ #
11
+ set -euo pipefail
12
+
13
+ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
14
+ APP_DIR="${TERMINALONE_APP_DIR:-$(cd "$SCRIPT_DIR/.." && pwd -P)}"
15
+ LEGACY_LABEL="com.floyd.terminalone"
16
+ DOMAIN="gui/$(id -u)"
17
+ PLIST_DIR="${TERMINALONE_PLIST_DIR:-$HOME/Library/LaunchAgents}"
18
+ LEGACY_PLIST="$PLIST_DIR/$LEGACY_LABEL.plist"
19
+ LEGACY_STUB_MARKER='# Townmouse launcher — generated by install-service.sh'
20
+
21
+ legacy_server_path() {
22
+ sed -n 's/.*<string>\([^<]*\/src\/server\.js\)<\/string>.*/\1/p' "$LEGACY_PLIST" | head -n 1
23
+ }
24
+
25
+ # Says whether the launch agent under TerminalOne's label runs Townmouse.
26
+ # 0 it runs Townmouse: this installation's server, or a server that belongs
27
+ # to a package named townmouse
28
+ # 1 it runs another product: a package beside the server is named something else
29
+ # 2 it cannot be told: no package beside the server, and the folder is not
30
+ # literally named townmouse
31
+ # The folder name is the last resort, because an engine vendored at
32
+ # .../townmouse/terminalone/src/server.js belongs to TerminalOne.
33
+ is_townmouse_plist() {
34
+ local server package
35
+ grep -Fq "<string>$APP_DIR/src/server.js</string>" "$LEGACY_PLIST" && return 0
36
+ server="$(legacy_server_path)"
37
+ [ -n "$server" ] || return 2
38
+ package="$(dirname "$server")/../package.json"
39
+ if [ -f "$package" ]; then
40
+ if grep -Eq '"name"[[:space:]]*:[[:space:]]*"townmouse"' "$package"; then return 0; fi
41
+ return 1
42
+ fi
43
+ if printf '%s\n' "$server" | grep -Eiq '(^|/)townmouse/src/server\.js$'; then return 0; fi
44
+ return 2
45
+ }
46
+
47
+ if [ -f "$LEGACY_PLIST" ]; then
48
+ verdict=0
49
+ is_townmouse_plist || verdict=$?
50
+ case "$verdict" in
51
+ 0)
52
+ launchctl bootout "$DOMAIN/$LEGACY_LABEL" 2>/dev/null || true
53
+ rm -f "$LEGACY_PLIST"
54
+ echo " legacy: removed the Townmouse service that 0.2.x installed as $LEGACY_LABEL."
55
+ echo " legacy: TerminalOne's own service, if you use it, comes back by running its scripts/install-service.sh."
56
+ ;;
57
+ 2)
58
+ echo " legacy: a launch agent named $LEGACY_LABEL exists and could not be told from Townmouse's, so it was left alone."
59
+ echo " legacy: if it runs Townmouse 0.2.x, stop it by hand: launchctl bootout $DOMAIN/$LEGACY_LABEL"
60
+ ;;
61
+ esac
62
+ fi
63
+
64
+ if [ -n "${TERMINALONE_BIN_DIR:-}" ]; then
65
+ LAUNCHER_DIRS=("$TERMINALONE_BIN_DIR")
66
+ else
67
+ LAUNCHER_DIRS=(/usr/local/bin "$HOME/.local/bin" "$HOME/bin")
68
+ fi
69
+ for dir in "${LAUNCHER_DIRS[@]}"; do
70
+ [ -n "$dir" ] || continue
71
+ stub="$dir/t1"
72
+ if [ -f "$stub" ] && [ ! -L "$stub" ] && grep -qF "$LEGACY_STUB_MARKER" "$stub" 2>/dev/null; then
73
+ rm -f "$stub"
74
+ echo " legacy: removed $stub, the t1 launcher that 0.2.x wrote for Townmouse."
75
+ fi
76
+ done