townmouse 0.0.0-stage → 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 (108) hide show
  1. package/CHANGELOG.md +196 -0
  2. package/DESIGN.md +153 -0
  3. package/LICENSE +661 -0
  4. package/README.md +600 -2
  5. package/SECURITY.md +60 -0
  6. package/TOWNMOUSE.md +91 -0
  7. package/assets/brand/mascot/README.md +23 -0
  8. package/assets/brand/mascot/townmouse-aristocrat.png +0 -0
  9. package/assets/brand/mascot/townmouse-icon.svg +1 -0
  10. package/assets/brand/mascot/townmouse-monocled.png +0 -0
  11. package/bin/townmouse +68 -0
  12. package/docs/PACKAGING.md +371 -0
  13. package/docs/browser-workspace.md +237 -0
  14. package/docs/panes.md +442 -0
  15. package/native/TownmouseApp.swift +108 -0
  16. package/npm-shrinkwrap.json +1282 -0
  17. package/package.json +93 -4
  18. package/public/apple-touch-icon.png +0 -0
  19. package/public/brand/floydslabs-credit.png +0 -0
  20. package/public/brand/floydslabs-credit.webp +0 -0
  21. package/public/brand/townmouse-aristocrat.webp +0 -0
  22. package/public/brand/townmouse-monocled.webp +0 -0
  23. package/public/browser-picture.mjs +159 -0
  24. package/public/clipboard-text.mjs +5 -0
  25. package/public/favicon-16x16.png +0 -0
  26. package/public/favicon-32x32.png +0 -0
  27. package/public/favicon.ico +0 -0
  28. package/public/favicon.svg +1 -0
  29. package/public/features/app-version.mjs +35 -0
  30. package/public/features/autosave.mjs +80 -0
  31. package/public/features/clipboard.mjs +69 -0
  32. package/public/features/command-palette.mjs +181 -0
  33. package/public/features/desktop-palette.mjs +19 -0
  34. package/public/features/export.mjs +37 -0
  35. package/public/features/file-drop.mjs +77 -0
  36. package/public/features/floating-palette.mjs +113 -0
  37. package/public/features/fontsize.mjs +72 -0
  38. package/public/features/haptic-keys.mjs +42 -0
  39. package/public/features/history-undo.mjs +102 -0
  40. package/public/features/keepalive.mjs +36 -0
  41. package/public/features/keybar-config.mjs +70 -0
  42. package/public/features/keyboard-shortcuts.mjs +74 -0
  43. package/public/features/links.mjs +139 -0
  44. package/public/features/multi-window-sync.mjs +76 -0
  45. package/public/features/osc-bridge.mjs +64 -0
  46. package/public/features/phone-landscape-focus.mjs +157 -0
  47. package/public/features/recent-commands.mjs +100 -0
  48. package/public/features/search.mjs +134 -0
  49. package/public/features/session-lock.mjs +96 -0
  50. package/public/features/session-manager.mjs +251 -0
  51. package/public/features/settings-sync.mjs +77 -0
  52. package/public/features/shortcut-help.mjs +85 -0
  53. package/public/features/smart-completions.mjs +101 -0
  54. package/public/features/smart-suggest.mjs +124 -0
  55. package/public/features/snippets.mjs +85 -0
  56. package/public/features/split-view.mjs +102 -0
  57. package/public/features/status-metrics.mjs +137 -0
  58. package/public/features/stylus-support.mjs +124 -0
  59. package/public/features/swipe-history.mjs +141 -0
  60. package/public/features/swipe-sessions.mjs +85 -0
  61. package/public/features/tab-reorder.mjs +70 -0
  62. package/public/features/theme-system.mjs +51 -0
  63. package/public/features/toast-status.mjs +118 -0
  64. package/public/features/two-finger-menu.mjs +87 -0
  65. package/public/features/voice-input.mjs +244 -0
  66. package/public/features/wake-fullscreen.mjs +67 -0
  67. package/public/features/window-title.mjs +47 -0
  68. package/public/features/zoom.mjs +80 -0
  69. package/public/icon-128.png +0 -0
  70. package/public/icon-180.png +0 -0
  71. package/public/icon-192.png +0 -0
  72. package/public/icon-48.png +0 -0
  73. package/public/icon-512-maskable.png +0 -0
  74. package/public/icon-512.png +0 -0
  75. package/public/icon.svg +1 -0
  76. package/public/index.html +2304 -0
  77. package/public/input-chunks.mjs +22 -0
  78. package/public/input-guard.mjs +218 -0
  79. package/public/manifest.json +56 -0
  80. package/public/panes.css +1433 -0
  81. package/public/panes.html +211 -0
  82. package/public/panes.mjs +3183 -0
  83. package/public/service-worker.js +67 -0
  84. package/public/workspace.css +1621 -0
  85. package/public/workspace.mjs +1715 -0
  86. package/scripts/install-service.sh +303 -0
  87. package/scripts/node-runtime.sh +138 -0
  88. package/scripts/panes +568 -0
  89. package/scripts/prepare-native.sh +35 -0
  90. package/scripts/retire-legacy-service.sh +76 -0
  91. package/scripts/run-hooks +69 -0
  92. package/scripts/townmouse.sh +152 -0
  93. package/scripts/uninstall-service.sh +65 -0
  94. package/src/agent-guide.js +329 -0
  95. package/src/attachments.js +128 -0
  96. package/src/browser-dom.js +548 -0
  97. package/src/browser-workspace.js +1733 -0
  98. package/src/chrome-resolve.js +80 -0
  99. package/src/owner-page.js +43 -0
  100. package/src/pty-permissions.js +99 -0
  101. package/src/regex-worker.js +13 -0
  102. package/src/replay-text.js +189 -0
  103. package/src/request-boundary.js +58 -0
  104. package/src/safe-regex.js +87 -0
  105. package/src/server.js +1582 -0
  106. package/src/shell-resolve.js +42 -0
  107. package/src/static-deps.js +61 -0
  108. package/src/workspace-panes.js +1431 -0
package/docs/panes.md ADDED
@@ -0,0 +1,442 @@
1
+ # Pane Workspace
2
+
3
+ ## Or: Four Panes, One Token, Zero Connection Codes To Copy
4
+
5
+ ---
6
+
7
+ - **DOCUMENT CLASSIFICATION:** Technical / Moderate Chaos
8
+ - **DATE RECORDED:** 2026-11-15 — Late Enough To Be Useful
9
+ - **LOCATION:** The Garage, Brown County, Indiana
10
+ - **BEVERAGE:** Coffee that tastes like motor oil (fresh pot)
11
+ - **CURRENT STATE:** Four panes open, one agent asking for a fifth
12
+
13
+ ---
14
+
15
+ Open `/panes.html`, `/panes`, or **Panes** in the workspace sidebar. This is the
16
+ agent-first surface: a workspace tab holds one to four panes, and each pane is
17
+ either a live PTY terminal or a live headless-browser page. Tabs are created by
18
+ the human or by the orchestrator, and every tab can hold a different mix.
19
+
20
+ On first start, with no saved workspace, the pane surface seeds one tab with a
21
+ terminal pane titled **Orchestrator**. That is a real PTY of its own — a second
22
+ shell alongside the standard terminal view — created by the same server process,
23
+ not a second application instance. It is intentional: the workspace opens with a
24
+ place for the orchestrator to work. Keep it. It is an agent's pane: an agent can
25
+ report and run from inside it from the first moment.
26
+
27
+ The terminal panes are real PTYs from the embedded TerminalOne engine. The
28
+ browser panes are real Chromium pages rendered by the server. Neither one is a
29
+ screenshot pretending to be a workspace.
30
+
31
+ The server caps the workspace at 24 tabs, four panes per tab, and 24 terminal
32
+ panes. The browser runtime caps open browser contexts at 32. The state response
33
+ carries `maxTabs`, `maxPanesPerTab`, and `maxTerminalPanes`. The caps exist so a
34
+ runaway agent runs out of room before it runs the machine out of memory.
35
+
36
+ ## Human
37
+
38
+ - **Tabs** button in the bottom bar: list, switch, create, and close workspace
39
+ tabs.
40
+ - **Menu**: add a terminal or browser pane to the active tab, or create a tab.
41
+ - **Keyboard**: focus the active terminal; in a browser pane it focuses the
42
+ page-type field.
43
+ - Drag a divider to resize panes, use Arrow/Home/End while a divider is focused,
44
+ or double-click it to reset. Ratios are remembered per tab.
45
+ - The phone key bar above the bottom navigation provides Esc, Tab, sticky
46
+ Ctrl/Alt, C, arrows, Home/End, PgUp/PgDn. Ctrl then C sends SIGINT.
47
+ - Right-click or long-press a terminal for Copy, Paste, Select all, Clear, and
48
+ Reader. Reader is a word-wrapped transcript; the live pane remains a cell
49
+ grid. Menu also has smaller/larger text, and a shortcut sheet.
50
+ - Closing a pane or tab asks first. An answerable `alert`/`confirm`/`prompt`
51
+ appears as a card; a forgotten dialog is dismissed after 30 seconds.
52
+ - **Agent access** is in the header of every pane you open: **Private**,
53
+ **View only**, or **Allow control**. These are the browser tab's three levels,
54
+ in the same words. Yours start Private. Change it there when you want an agent
55
+ to look at a pane or to drive it; setting it back to Private ends what an
56
+ agent was doing on that pane at once: its view of the output closes and a
57
+ command it was waiting on stops. An agent's ask appears under the header of
58
+ the pane it is about, with its reason, and is answered there: Not now, View
59
+ only, Allow control. An ask waits five minutes and then clears itself. A pane
60
+ an agent opened carries its "agent" mark instead and has no control; anything
61
+ typed into one of those is readable by agents.
62
+ - Browser panes accept clicks, wheel scrolling, typing, Back, Forward, Reload,
63
+ and an address. The browser is a real Chromium page rendered by the server,
64
+ and its viewport reflows to the pane's actual size.
65
+ - Drop or paste files/images onto a terminal pane. The file is uploaded once
66
+ into the state directory's `attachments/<YYYYMMDD>/` tree (25 MB per request,
67
+ 2,000 files / 512 MB per day) and a shell-quoted absolute path is inserted
68
+ into the PTY. The terminal never receives a base64 stream. An attachment card
69
+ shows the path and URL with Copy/Open actions; dropping onto a browser pane
70
+ opens the loopback URL instead. Buckets older than
71
+ `TOWNMOUSE_ATTACHMENT_RETENTION_DAYS` (default 30) move to
72
+ `attachments-archive` instead of being deleted.
73
+
74
+ ## Agent
75
+
76
+ Each terminal pane is spawned with:
77
+
78
+ ```text
79
+ TOWNMOUSE_API=http://127.0.0.1:<port>/api/panes
80
+ TOWNMOUSE_TOKEN=<workspace token>
81
+ TOWNMOUSE_TAB_ID=<this tab>
82
+ TOWNMOUSE_PANE_ID=<this pane>
83
+ TOWNMOUSE_PANES_CLI=<repo>/scripts/panes
84
+ ```
85
+
86
+ No code is copied between the browser and the terminal. Run the CLI directly:
87
+
88
+ ```sh
89
+ "$TOWNMOUSE_PANES_CLI" state
90
+ "$TOWNMOUSE_PANES_CLI" tab list
91
+ "$TOWNMOUSE_PANES_CLI" tab create --title "Second workspace"
92
+ "$TOWNMOUSE_PANES_CLI" tab close <tab-id>
93
+ "$TOWNMOUSE_PANES_CLI" pane create --tab <tab-id> --kind terminal
94
+ "$TOWNMOUSE_PANES_CLI" pane create --kind browser --url https://example.com
95
+ "$TOWNMOUSE_PANES_CLI" pane url <pane-id> https://example.com
96
+ "$TOWNMOUSE_PANES_CLI" pane run <pane-id> "npm test"
97
+ "$TOWNMOUSE_PANES_CLI" pane input <pane-id> "echo hello"
98
+ "$TOWNMOUSE_PANES_CLI" pane send-text <pane-id> "multi-line prompt"
99
+ "$TOWNMOUSE_PANES_CLI" pane keys <pane-id> ctrl+c
100
+ "$TOWNMOUSE_PANES_CLI" pane wait <pane-id> --match "PASS" --timeout 60000
101
+ "$TOWNMOUSE_PANES_CLI" pane status <pane-id> --state blocked --message "approval?"
102
+ "$TOWNMOUSE_PANES_CLI" pane dialog <pane-id> --accept
103
+ "$TOWNMOUSE_PANES_CLI" pane read <pane-id> --lines 120
104
+ "$TOWNMOUSE_PANES_CLI" pane close <pane-id>
105
+ "$TOWNMOUSE_PANES_CLI" pane request <pane-id> --level control --message "why"
106
+ "$TOWNMOUSE_PANES_CLI" attach ./screenshot.png --pane <pane-id>
107
+ "$TOWNMOUSE_PANES_CLI" active --tab <tab-id> --pane <pane-id>
108
+ ```
109
+
110
+ ### Whose pane is whose
111
+
112
+ The server decides whose pane or tab it is from the key that asks, and never
113
+ from a field in the request. A pane you open through the CLI or the API, with
114
+ the workspace token, is an agent's pane: every agent can read and drive it. So
115
+ is the seeded Orchestrator pane. A pane the owner opens from the page is the
116
+ owner's, and to you it is exactly what the owner has given:
117
+
118
+ | The owner gives | You can |
119
+ |---|---|
120
+ | **Private** (always at first) | See only that the pane exists and what you have on it. Its title, address, folder and output are not sent to you. |
121
+ | **View only** | Read it: the terminal's text and output stream, a job's result, the page's picture, controls and text, and waits. |
122
+ | **Allow control** | View only, and also type, press keys, run commands and jobs, report a status, open an address, act on the page, answer a page dialog and set the page's size. |
123
+
124
+ On the owner's pane, whatever you were given, you cannot close it, resize it,
125
+ move it, bring it forward, close a tab that holds it, or change what an agent
126
+ may do on it. Those stay the owner's.
127
+
128
+ Every pane in `panes state` carries `createdBy` (whose it is: `human` or
129
+ `agent`), `agentAccess` (what you have: `level` and `label`), and
130
+ `accessRequest` (an ask of yours that is waiting). A Private pane of the
131
+ owner's appears as an empty shape with `redacted: true`. A refusal is a 403
132
+ with a `code` (`PANE_PRIVATE`, `PANE_VIEW_ONLY` or `OWNER_ONLY`) and a message
133
+ that names the command to ask for more:
134
+
135
+ ```sh
136
+ "$TOWNMOUSE_PANES_CLI" pane request <pane-id> --level view|control [--message TEXT] [--timeout MS] [--no-wait]
137
+ "$TOWNMOUSE_PANES_CLI" pane request <pane-id> --cancel
138
+ ```
139
+
140
+ The ask is shown on that pane with your message. The command waits for the
141
+ answer, two minutes unless `--timeout` says otherwise: exit 0 when the owner
142
+ gives access, 3 while it is still waiting (run it again to keep waiting), 5
143
+ when the owner says Not now. `--no-wait` returns at once and prints the waiting
144
+ ask; `--cancel` withdraws it. One ask waits per pane; an unanswered ask clears
145
+ after five minutes; after Not now the pane cannot be asked about for five
146
+ minutes. Asking for a level the owner has already given is answered
147
+ `ALREADY_GRANTED`: there is nothing to ask for.
148
+
149
+ To show the owner one of your own panes, report it with `pane status` and bring
150
+ that pane forward with `panes active --tab <tab-id> --pane <pane-id>`.
151
+
152
+ The owner's key is never handed to you. It goes only to the owner's page,
153
+ opened in a browser, and only to that page's own request; a program making
154
+ ordinary requests is refused and told the steps above. These levels hold
155
+ against an agent's own key: the `panes` command, and the token in a pane's
156
+ environment. They do not hold against a program on the same Mac that presents
157
+ itself as the owner's page, by sending a browser's navigation details on
158
+ purpose. That is what the next stage, agents separated from the owner, is for.
159
+
160
+ No password field's value ever reaches you. A catalog, the result of a click or
161
+ of typing, and the report of the focused element all return `null` with
162
+ `redacted: true` for one, on the pane workspace and on the single-browser
163
+ workspace alike, and `pane browser wait --value` on a password field is refused.
164
+ Typing into the field works; only what comes back is withheld.
165
+
166
+ ### Instruction sheet
167
+
168
+ `panes guide` (or `GET /api/panes/guide`) prints the sheet an agent receives on
169
+ connect: every tool, what it needs, what it returns, and — separately — which
170
+ capabilities this connection has and has not been granted. It describes
171
+ permissions; it does not enlarge them.
172
+
173
+ ### Pane ids default to the current pane
174
+
175
+ Inside a pane, the pane id can be omitted. The CLI recognises a real id by shape
176
+ (`p_…`) and otherwise falls back to `TOWNMOUSE_PANE_ID`, so `panes pane read` and
177
+ `panes pane browser click` work with no argument.
178
+
179
+ ### Tracked commands
180
+
181
+ `pane run` types a line into the interactive terminal and returns recent output.
182
+ That does **not** prove the command finished. For ordinary, non-interactive
183
+ commands use a tracked job:
184
+
185
+ ```sh
186
+ "$TOWNMOUSE_PANES_CLI" pane exec -- "npm test" # waits, returns exit code
187
+ "$TOWNMOUSE_PANES_CLI" pane exec --no-wait -- "make" # returns a job id
188
+ "$TOWNMOUSE_PANES_CLI" pane job <job-id> # poll it
189
+ ```
190
+
191
+ A job reports `status` (`running` | `completed` | `failed`), `exitCode`,
192
+ `signal`, `stdout`, `stderr`, and truncation flags. Keep the interactive
193
+ terminal for programs such as `dlaude` that stay open and wait for input.
194
+
195
+ ### Clean and raw terminal text
196
+
197
+ `pane read` renders screen text (`replayTranscript`) so escape codes do not
198
+ clutter the output, and `--raw` returns the original terminal data. Both modes
199
+ report `offset`, `bufferStart`, and a `truncated` flag.
200
+
201
+ ### Browser control
202
+
203
+ ```sh
204
+ "$TOWNMOUSE_PANES_CLI" pane browser observe --elements # labelled screenshot + controls
205
+ "$TOWNMOUSE_PANES_CLI" pane browser elements # controls only
206
+ "$TOWNMOUSE_PANES_CLI" pane browser click --ref e12
207
+ "$TOWNMOUSE_PANES_CLI" pane browser click --x 300 --y 200 --observation 42
208
+ "$TOWNMOUSE_PANES_CLI" pane browser type --ref e12 --replace "café 東京"
209
+ "$TOWNMOUSE_PANES_CLI" pane browser key Alt+M
210
+ "$TOWNMOUSE_PANES_CLI" pane browser hover --ref e12
211
+ "$TOWNMOUSE_PANES_CLI" pane browser drag --from-ref e12 --to-ref e15
212
+ "$TOWNMOUSE_PANES_CLI" pane browser scroll --ref e12 --dy 400
213
+ "$TOWNMOUSE_PANES_CLI" pane browser select --ref e12 --value blue
214
+ "$TOWNMOUSE_PANES_CLI" pane browser navigate https://example.com
215
+ "$TOWNMOUSE_PANES_CLI" pane browser wait --text "Saved" --timeout 10000
216
+ "$TOWNMOUSE_PANES_CLI" pane browser sizing fixed --width 1280 --height 800
217
+ ```
218
+
219
+ Controls are identified by role and name, including inside cross-origin frames
220
+ and open shadow roots. Each action returns a `status` (`completed`, `missing`,
221
+ `wrong-kind`, `failed`, `stale`, `unconfirmed`); a coordinate used with a stale
222
+ `--observation` is refused with exit code 4 and a message to look again. Every
223
+ wait is bounded. In `fixed` sizing the owner's viewer scales the picture instead
224
+ of rearranging the page.
225
+
226
+ None of this depends on whether anyone is looking at the pane. The owner's view
227
+ of a browser pane is pictured up to 30 times a second while the pane is on
228
+ screen and the page is changing, and not at all while it cannot be seen; that
229
+ is described under "Pictures" in
230
+ [browser-workspace.md](browser-workspace.md). An agent's `observe` is its own
231
+ capture: it does not start that stream, it is not made to wait behind it, and
232
+ an agent at work is never taken for a viewer.
233
+
234
+ `pane create` defaults to `TOWNMOUSE_TAB_ID` when `--tab` is omitted. It also
235
+ accepts `--cwd` and `--title`. `tab create` accepts `--activate` when the new
236
+ tab should become active; without it, the CLI creates the tab without moving the
237
+ active tab. The orchestrator can create as many tabs as the server allows; each
238
+ tab holds up to four panes. A single tab can be all terminals, all browsers, or
239
+ any mix.
240
+
241
+ `pane url` requires a browser pane. `pane run` writes the command with a newline
242
+ and returns the last 4,000 characters of output after its wait, flagged
243
+ `confirmed: false` because typing a line is not proof the command finished; use
244
+ `pane exec` for a tracked job. `pane input` writes raw text and does not append a
245
+ newline. Both `pane run` and `pane input` require a terminal pane.
246
+
247
+ `pane send-text` preserves literal text and wraps it in bracketed-paste markers
248
+ by default; pass `--raw` to opt out. `pane keys` accepts logical names including
249
+ `enter`, `esc`, `tab`, `ctrl+c`, `alt+x`, and arrows. `pane wait` long-polls for
250
+ plain text, a regex, an idle interval, or an agent-reported state, and returns
251
+ the matching output with `offset` and `elapsedMs`; the server caps a wait at 120
252
+ seconds. Regex patterns run in a worker thread with a 500 ms deadline, so a
253
+ pattern that backtracks pathologically is terminated and refused instead of
254
+ stalling the server; patterns are capped at 200 characters. `pane status` records
255
+ `working`, `blocked`, `idle`, `done`, or `unknown`
256
+ with an optional message; the pane header colors the badge and state responses
257
+ carry `lastOutputAt`, `idleMs`, `exitCode`, and `exitSignal`. `pane dialog`
258
+ answers a waiting page dialog. `attach` uploads a file with the scoped pane token
259
+ and prints `path`, `url`, `localUrl`, and `relativeUrl`; use `--pane` to insert
260
+ the quoted path as well. Pane order is changed with
261
+ `POST /api/panes/tabs/<tab-id>/reorder` (`paneId`, `index`), or on the client by
262
+ dragging a pane header or Alt+Shift+Arrow.
263
+
264
+ The CLI reads `TOWNMOUSE_API` and `TOWNMOUSE_TOKEN` from the environment and
265
+ falls back to `~/.townmouse/pane-token` when the token is absent. It sends the
266
+ token in `X-Townmouse-Token`; the API also accepts `Authorization: Bearer
267
+ <token>`. The owner's page sends a key of its own in `X-Townmouse-Owner`
268
+ instead. The server reads who is asking from the key alone: the workspace token
269
+ is an agent, the page key is the owner, and anything else is a 403 with the code
270
+ `UNKNOWN_KEY`. `createdBy` in a request body is ignored; older clients still
271
+ send it, and a current server reaches the same answer from the key.
272
+
273
+ ### Shell sessions
274
+
275
+ The shells in the owner's terminal row (`/`, the terminal screen) answer under
276
+ `/api/sessions`, with the same token:
277
+
278
+ ```sh
279
+ "$TOWNMOUSE_PANES_CLI" session list
280
+ "$TOWNMOUSE_PANES_CLI" session create [--name TEXT] [--cwd PATH] [--activate]
281
+ "$TOWNMOUSE_PANES_CLI" session rename <session> --name TEXT
282
+ "$TOWNMOUSE_PANES_CLI" session activate <session>
283
+ "$TOWNMOUSE_PANES_CLI" session close <session>
284
+ ```
285
+
286
+ A shell belongs to whoever started it, as a pane does. These commands reach
287
+ the shells agents started. A `<session>` is its name, its full id, or the
288
+ first eight or more characters of its id, among the shells `session list`
289
+ shows you. A start of an id that matches more than one of them is refused,
290
+ and so is a name that is not among them: one of the owner's shells comes back
291
+ as not found.
292
+
293
+ `session list` returns the shells agents started, in the owner's row order:
294
+ its `id`, `name`, `command`, `cwd`, when it was started and last viewed, how
295
+ many windows are viewing it (`viewers`), and whether it is the one the owner
296
+ is viewing (`active`). Of the owner's own shells it says only how many there
297
+ are: `ownerStarted`, beside the limit (`max`). `activeSessionId` names the
298
+ shell the owner looked at last when that is one of yours; while the owner is
299
+ looking at one of their own it is null, and so is `activation`.
300
+
301
+ `session create` starts a shell nobody is viewing. The key that asks decides
302
+ whose it is: an agent's key makes it an agent's shell, and `createdBy` in the
303
+ request is ignored. It appears in the owner's row at once and does not change
304
+ which shell the owner is looking at, unless `--activate` is passed. `--cwd`
305
+ must be an existing directory; `--name` is at most 40 characters and no two
306
+ shells share one. `session rename` gives one of your shells a name the owner
307
+ can read. `session close` ends one of your shells and anything running in it;
308
+ a window that was viewing it moves to another shell and says so. It cannot be
309
+ undone. On a shell the owner started, renaming, showing and closing are the
310
+ owner's alone: an agent is refused with 403 `OWNER_ONLY` and the shell is left
311
+ as it was.
312
+
313
+ `session activate` is the one action that moves the owner's view: every open
314
+ Townmouse terminal window shows that shell, when it is one of yours. The
315
+ ground rule applies: use it when the owner asked to see that shell.
316
+
317
+ A shell keeps running after you stop looking at it, until it is closed or the
318
+ app stops, and at most ten run at once. When you hold a shell you may close, a
319
+ refused `create` says to close one first. When you hold none, it says that
320
+ every session is in use and how many of them the owner started. Close the
321
+ shells you start.
322
+
323
+ ## Wire facts
324
+
325
+ - Terminal output is an SSE stream at
326
+ `GET /api/panes/panes/<pane-id>/stream?since=<offset>` with
327
+ `Content-Type: text/event-stream`. Each event's JSON payload carries `data` and
328
+ `offset`; the initial replay also reports `exited`. The server keeps the last
329
+ 200,000 characters of output and replays from `since`. It sends a `: ping`
330
+ comment every 15 seconds.
331
+ - If the stream drops, the client falls back to polling
332
+ `GET /api/panes/panes/<pane-id>/read?since=<offset>` every 180 ms. A dropped
333
+ stream is not a dead terminal.
334
+ - Terminal input is batched by the client: keystrokes and pastes are coalesced
335
+ for 12 ms, and at most one `POST /api/panes/panes/<pane-id>/input` is in
336
+ flight. Payloads over 24,000 characters are split into sequential chunks so
337
+ each request stays under the JSON body limit; order is preserved. A burst of
338
+ typing arrives as one ordered request, which is the difference between smooth
339
+ and jittery when the agent is also producing output.
340
+ - Resize is `POST /api/panes/panes/<pane-id>/resize`. Terminal columns are
341
+ clamped to 20-400 and rows to 5-200. Browser panes set a viewport clamped to
342
+ 320-1920 by 240-1200.
343
+ - A browser pane's picture is `GET /api/panes/panes/<pane-id>/browser/snapshot`.
344
+ Without query parameters a picture is taken for the caller there and then
345
+ (an agent's `observe` takes its own, separately). The owner's page sends
346
+ `watch=1&since=<seq>&wait=<ms>` while the pane is on screen (the request waits
347
+ up to `wait` ms for the next picture; the answer carries `changed` and `seq`,
348
+ and a picture only when there is a new one) and `watch=0` while the pane
349
+ cannot be seen (title, address and page prompt only, no picture).
350
+ - `POST /api/panes/panes/<pane-id>/start` spawns a deferred terminal at the
351
+ measured cols/rows; the UI creates terminals with `start:false` so the first
352
+ prompt is laid out at the visible width.
353
+ - At most four terminal SSE streams are open at once; additional panes use the
354
+ polling fallback so input and state requests keep an HTTP connection. If a
355
+ reader stops draining, the server ends its stream instead of buffering output
356
+ without limit.
357
+ - `POST /api/panes/panes/<pane-id>/keys` writes named keys; `GET .../wait`
358
+ supports `match`, `regex`, `idleMs`, and `state`; `POST .../status` records
359
+ agent lifecycle; `POST .../browser/dialog` answers a page dialog.
360
+ - State includes an `epoch` minted per server boot and `restored`. After a
361
+ restart the client keeps tabs, pane kinds, titles, cwd, and browser URLs but
362
+ warns that terminal scrollback and running jobs are gone.
363
+ - Owner bootstrap (`GET /api/panes/bootstrap`) answers only the owner's page.
364
+ It takes the HttpOnly owner cookie, which is minted only when an owner page
365
+ is reached by a navigation (`Sec-Fetch-Mode: navigate`, which a browser sets
366
+ and a plain HTTP client does not), and requires the mark of the page's own
367
+ request (`Sec-Fetch-Site: same-origin`; an absent value is refused). Anything
368
+ else is a 403 with a code: `OWNER_PAGE_REQUIRED`, `NOT_FROM_OWNER_PAGE` or
369
+ `AGENT_TOKEN`, each with a message that names what an agent does instead. A
370
+ pane token receives 403 there; the token is accepted by the pane API, by
371
+ attachment uploads and by the shell-session API. The single-browser workspace's bootstrap
372
+ (`GET /api/browser/bootstrap`) is guarded the same way. The bootstrap hands
373
+ the page its key (`ownerKey`), which lives for one server run and is never
374
+ written to disk. When the server restarts the page's key stops working; the
375
+ page sees `UNKNOWN_KEY`, renews its key through the cookie, and reloads once
376
+ if the cookie has gone too.
377
+ - Every state answer is numbered (`seq`). The page ignores an answer older
378
+ than the one it has, so a change the person just made cannot flash back.
379
+ - Grants are held in memory. A saved workspace records whose pane is whose, so
380
+ an agent's pane is still the agent's after a restart, while one of the
381
+ owner's comes back Private.
382
+ - Shell sessions: `GET /api/sessions` returns `{ epoch, sessions, activeSessionId,
383
+ max, activation }` to the owner. An agent gets the same shape holding only
384
+ the shells agents started, plus `ownerStarted`, the count of the owner's.
385
+ `POST /api/sessions` takes `{ name?, cwd?, activate? }` and answers 200 with
386
+ the session, 409 `SESSION_LIMIT` at the cap or `NAME_IN_USE` for a name in
387
+ use, 400 for a name or folder that cannot be used. Who started it is read
388
+ from the key; `createdBy` in the body is ignored.
389
+ `PATCH /api/sessions/<id>` takes `{ name }`. `POST /api/sessions/<id>/activate`
390
+ answers `{ activated, windows }`. `DELETE /api/sessions/<id>` answers
391
+ `{ closed, ...state }`. For an agent, those three on a shell the owner
392
+ started are 403 `OWNER_ONLY`. An unknown session is 404 `SESSION_NOT_FOUND`. `epoch` is minted per app
393
+ run; a different one means the app was restarted. The owner's page drives the
394
+ same actions over its own WebSocket and is sent the list on every change, so
395
+ the row, the list and this API are one list. `GET /health` counts the same
396
+ shells in `sessions`.
397
+
398
+ ### What an agent may call on one of the owner's panes
399
+
400
+ Every route under `/api/panes` is open to the owner. For an agent:
401
+
402
+ | Route | Private | View only | Allow control |
403
+ |---|---|---|---|
404
+ | `GET /state`, `GET /guide` | Yes (the owner's Private panes as empty shapes) | Yes | Yes |
405
+ | `POST /tabs`, `POST /tabs/:id/panes` (opening a pane of the agent's own) | Yes | Yes | Yes |
406
+ | `GET /panes/:id/text`, `/read`, `/stream`, `/wait`, `/jobs/:jobId` | 403 `PANE_PRIVATE` | Yes | Yes |
407
+ | `GET /panes/:id/browser/snapshot`, `/observe`, `/elements`, `/content`; `POST /panes/:id/browser/wait` | 403 `PANE_PRIVATE` | Yes | Yes |
408
+ | `POST /panes/:id/input`, `/keys`, `/command`, `/jobs`, `/status`, `/start`, `/url` | 403 `PANE_PRIVATE` | 403 `PANE_VIEW_ONLY` | Yes |
409
+ | `POST /panes/:id/browser/action`, `/reopen`, `/dialog`, `/sizing`; `DELETE /panes/:id/jobs/:jobId` | 403 `PANE_PRIVATE` | 403 `PANE_VIEW_ONLY` | Yes |
410
+ | `POST /panes/:id/resize`, `DELETE /panes/:id` | 403 `OWNER_ONLY` | 403 `OWNER_ONLY` | 403 `OWNER_ONLY` |
411
+ | `POST /tabs/:id/reorder` moving it; `POST /active` bringing it, or a tab of only the owner's panes, forward; `DELETE /tabs/:id` for a tab holding one | 403 `OWNER_ONLY` | 403 `OWNER_ONLY` | 403 `OWNER_ONLY` |
412
+ | `POST /panes/:id/permission` | 403 `OWNER_ONLY` | 403 `OWNER_ONLY` | 403 `OWNER_ONLY` |
413
+ | `POST /panes/:id/request-access` | Asks | Asks, for what is missing | 409 `ALREADY_GRANTED` |
414
+ | `DELETE /panes/:id/request-access` | Withdraws the agent's ask | Withdraws the agent's ask | Withdraws the agent's ask |
415
+
416
+ On a pane an agent opened, every route above answers the agent. Each check is
417
+ made before the work and again after it, and a level lowered while a stream,
418
+ a wait or a queued action is in flight ends it. On the owner's pane the owner
419
+ sets the level with `POST /api/panes/panes/<id>/permission` (`private`,
420
+ `view` or `control`), and answers or dismisses an ask by setting a level or
421
+ with `DELETE /api/panes/panes/<id>/request-access`.
422
+
423
+ The workspace limits are real. The token is real. The panes are real. The old
424
+ way copied a connection string between the browser and the terminal; this one
425
+ hands the agent the environment and gets out of the way.
426
+
427
+ ```text
428
+ ┌──────────────────────────────────────────────────────────┐
429
+ │ DOCUMENT METADATA │
430
+ ├──────────────────────────────────────────────────────────┤
431
+ │ Classification: Technical / Pane Workspace │
432
+ │ Cat Supervision: Bowser, monitoring the pane count │
433
+ │ "I Don't Suck": PASS │
434
+ │ Corporate Feelings: HURT (intended) │
435
+ └──────────────────────────────────────────────────────────┘
436
+ ```
437
+
438
+ **DOCUMENT ENDS**
439
+
440
+ *— Workspace, Floyd's Labs*
441
+ *The Garage — Brown County, Indiana*
442
+ *"Four panes is a workspace. Five is an incident report."*
@@ -0,0 +1,108 @@
1
+ import AppKit
2
+ import Foundation
3
+ import WebKit
4
+
5
+ @main
6
+ @MainActor
7
+ final class TownmouseApp: NSObject, NSApplicationDelegate {
8
+ private var window: NSWindow!
9
+ private var webView: WKWebView!
10
+ private let serviceURL = URL(string: ProcessInfo.processInfo.environment["TOWNMOUSE_URL"] ?? ProcessInfo.processInfo.environment["TERMINALONE_URL"] ?? "http://127.0.0.1:11002")!
11
+
12
+ static func main() {
13
+ let app = NSApplication.shared
14
+ let delegate = TownmouseApp()
15
+ app.delegate = delegate
16
+ app.setActivationPolicy(.regular)
17
+ app.run()
18
+ }
19
+
20
+ func applicationDidFinishLaunching(_ notification: Notification) {
21
+ let configuration = WKWebViewConfiguration()
22
+ configuration.websiteDataStore = .default()
23
+ webView = WKWebView(frame: .zero, configuration: configuration)
24
+ window = NSWindow(
25
+ contentRect: NSRect(x: 0, y: 0, width: 1280, height: 820),
26
+ styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],
27
+ backing: .buffered,
28
+ defer: false
29
+ )
30
+ window.title = "Townmouse"
31
+ window.setFrameAutosaveName("TownmouseMainWindow")
32
+ window.contentView = webView
33
+ window.center()
34
+ window.makeKeyAndOrderFront(nil)
35
+ NSApp.activate(ignoringOtherApps: true)
36
+ ensureBackendAndLoad()
37
+ }
38
+
39
+ func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { true }
40
+
41
+ private func ensureBackendAndLoad() {
42
+ DispatchQueue.global(qos: .userInitiated).async { [serviceURL, weak self] in
43
+ if !Self.isHealthy(serviceURL) {
44
+ Self.startBackend()
45
+ }
46
+ let deadline = Date().addingTimeInterval(12)
47
+ while Date() < deadline && !Self.isHealthy(serviceURL) {
48
+ Thread.sleep(forTimeInterval: 0.25)
49
+ }
50
+ let healthy = Self.isHealthy(serviceURL)
51
+ DispatchQueue.main.async { [weak self] in
52
+ guard let self else { return }
53
+ if healthy {
54
+ self.webView.load(URLRequest(url: serviceURL))
55
+ } else {
56
+ self.presentStartupError()
57
+ }
58
+ }
59
+ }
60
+ }
61
+
62
+ nonisolated private static func isHealthy(_ baseURL: URL) -> Bool {
63
+ let healthURL = baseURL.appendingPathComponent("health")
64
+ var request = URLRequest(url: healthURL)
65
+ request.timeoutInterval = 1
66
+ let semaphore = DispatchSemaphore(value: 0)
67
+ var ok = false
68
+ URLSession.shared.dataTask(with: request) { _, response, _ in
69
+ ok = (response as? HTTPURLResponse)?.statusCode == 200
70
+ semaphore.signal()
71
+ }.resume()
72
+ _ = semaphore.wait(timeout: .now() + 1.5)
73
+ return ok
74
+ }
75
+
76
+ nonisolated private static func startBackend() {
77
+ var candidates: [String] = []
78
+ if let configured = ProcessInfo.processInfo.environment["TERMINALONE_T1"] {
79
+ candidates.append(configured)
80
+ }
81
+ if let resource = Bundle.main.path(forResource: "launcher-path", ofType: "txt"),
82
+ let path = try? String(contentsOfFile: resource, encoding: .utf8).trimmingCharacters(in: .whitespacesAndNewlines) {
83
+ candidates.append(path)
84
+ }
85
+ candidates += [
86
+ NSString(string: "~/.local/bin/townmouse").expandingTildeInPath,
87
+ "/usr/local/bin/townmouse",
88
+ NSString(string: "~/bin/townmouse").expandingTildeInPath,
89
+ ]
90
+ guard let launcher = candidates.first(where: { FileManager.default.isExecutableFile(atPath: $0) }) else { return }
91
+ let process = Process()
92
+ process.executableURL = URL(fileURLWithPath: launcher)
93
+ process.arguments = ["--serve-only"]
94
+ process.standardOutput = FileHandle.nullDevice
95
+ process.standardError = FileHandle.nullDevice
96
+ try? process.run()
97
+ }
98
+
99
+ private func presentStartupError() {
100
+ let alert = NSAlert()
101
+ alert.messageText = "Townmouse could not start"
102
+ alert.informativeText = "Run ‘townmouse doctor’ in a terminal for the exact cause and repair command."
103
+ alert.alertStyle = .critical
104
+ alert.addButton(withTitle: "OK")
105
+ alert.runModal()
106
+ NSApp.terminate(nil)
107
+ }
108
+ }