townmouse 0.0.0-stage → 0.2.1
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.
- package/CHANGELOG.md +126 -0
- package/DESIGN.md +169 -0
- package/LICENSE +661 -0
- package/README.md +368 -2
- package/SECURITY.md +57 -0
- package/TOWNMOUSE.md +91 -0
- package/assets/brand/mascot/README.md +23 -0
- package/assets/brand/mascot/townmouse-aristocrat.png +0 -0
- package/assets/brand/mascot/townmouse-icon.svg +1 -0
- package/assets/brand/mascot/townmouse-monocled.png +0 -0
- package/bin/townmouse +68 -0
- package/docs/PACKAGING.md +275 -0
- package/docs/browser-workspace.md +184 -0
- package/docs/panes.md +252 -0
- package/native/TownmouseApp.swift +108 -0
- package/package.json +89 -4
- package/public/apple-touch-icon.png +0 -0
- package/public/brand/floydslabs-credit.png +0 -0
- package/public/brand/floydslabs-credit.webp +0 -0
- package/public/brand/townmouse-aristocrat.webp +0 -0
- package/public/brand/townmouse-monocled.webp +0 -0
- package/public/clipboard-text.mjs +5 -0
- package/public/favicon-16x16.png +0 -0
- package/public/favicon-32x32.png +0 -0
- package/public/favicon.ico +0 -0
- package/public/favicon.svg +1 -0
- package/public/features/autosave.mjs +76 -0
- package/public/features/clipboard.mjs +69 -0
- package/public/features/command-palette.mjs +181 -0
- package/public/features/desktop-palette.mjs +19 -0
- package/public/features/export.mjs +37 -0
- package/public/features/file-drop.mjs +77 -0
- package/public/features/floating-palette.mjs +113 -0
- package/public/features/fontsize.mjs +72 -0
- package/public/features/haptic-keys.mjs +42 -0
- package/public/features/history-undo.mjs +102 -0
- package/public/features/keepalive.mjs +36 -0
- package/public/features/keybar-config.mjs +70 -0
- package/public/features/keyboard-shortcuts.mjs +74 -0
- package/public/features/links.mjs +139 -0
- package/public/features/multi-window-sync.mjs +74 -0
- package/public/features/osc-bridge.mjs +59 -0
- package/public/features/phone-landscape-focus.mjs +157 -0
- package/public/features/recent-commands.mjs +100 -0
- package/public/features/search.mjs +134 -0
- package/public/features/session-lock.mjs +96 -0
- package/public/features/session-manager.mjs +149 -0
- package/public/features/settings-sync.mjs +77 -0
- package/public/features/shortcut-help.mjs +85 -0
- package/public/features/smart-completions.mjs +101 -0
- package/public/features/smart-suggest.mjs +124 -0
- package/public/features/snippets.mjs +85 -0
- package/public/features/split-view.mjs +102 -0
- package/public/features/status-metrics.mjs +114 -0
- package/public/features/stylus-support.mjs +124 -0
- package/public/features/swipe-history.mjs +141 -0
- package/public/features/swipe-sessions.mjs +85 -0
- package/public/features/tab-reorder.mjs +62 -0
- package/public/features/theme-system.mjs +51 -0
- package/public/features/toast-status.mjs +118 -0
- package/public/features/two-finger-menu.mjs +87 -0
- package/public/features/voice-input.mjs +244 -0
- package/public/features/wake-fullscreen.mjs +67 -0
- package/public/features/window-title.mjs +40 -0
- package/public/features/zoom.mjs +80 -0
- package/public/icon-128.png +0 -0
- package/public/icon-180.png +0 -0
- package/public/icon-192.png +0 -0
- package/public/icon-48.png +0 -0
- package/public/icon-512-maskable.png +0 -0
- package/public/icon-512.png +0 -0
- package/public/icon.svg +1 -0
- package/public/index.html +1765 -0
- package/public/input-chunks.mjs +22 -0
- package/public/input-guard.mjs +210 -0
- package/public/manifest.json +56 -0
- package/public/panes.css +1257 -0
- package/public/panes.html +208 -0
- package/public/panes.mjs +2625 -0
- package/public/service-worker.js +67 -0
- package/public/workspace.css +1447 -0
- package/public/workspace.mjs +1475 -0
- package/scripts/install-service.sh +269 -0
- package/scripts/node-runtime.sh +138 -0
- package/scripts/panes +439 -0
- package/scripts/prepare-native.sh +35 -0
- package/scripts/run-hooks +69 -0
- package/scripts/t1.sh +113 -0
- package/scripts/uninstall-service.sh +49 -0
- package/src/agent-guide.js +260 -0
- package/src/attachments.js +128 -0
- package/src/browser-dom.js +545 -0
- package/src/browser-workspace.js +1246 -0
- package/src/chrome-resolve.js +80 -0
- package/src/pty-permissions.js +99 -0
- package/src/regex-worker.js +13 -0
- package/src/replay-text.js +189 -0
- package/src/request-boundary.js +58 -0
- package/src/safe-regex.js +87 -0
- package/src/server.js +1122 -0
- package/src/shell-resolve.js +42 -0
- package/src/static-deps.js +61 -0
- package/src/workspace-panes.js +1099 -0
package/scripts/panes
ADDED
|
@@ -0,0 +1,439 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
// Native pane control for the Townmouse workspace.
|
|
4
|
+
// Terminal panes are spawned with TOWNMOUSE_API / TOWNMOUSE_TOKEN / TOWNMOUSE_PANE_ID
|
|
5
|
+
// already in the environment, so an agent never copies a connection code.
|
|
6
|
+
const fs = require('fs');
|
|
7
|
+
const os = require('os');
|
|
8
|
+
const path = require('path');
|
|
9
|
+
|
|
10
|
+
const api = (process.env.TOWNMOUSE_API || 'http://127.0.0.1:11001/api/panes').replace(/\/$/, '');
|
|
11
|
+
let token = process.env.TOWNMOUSE_TOKEN || '';
|
|
12
|
+
if (!token) {
|
|
13
|
+
try { token = fs.readFileSync(path.join(os.homedir(), '.townmouse', 'pane-token'), 'utf8').trim(); } catch (_) { /* reported below */ }
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
async function call(method, suffix, body) {
|
|
17
|
+
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, {
|
|
19
|
+
method,
|
|
20
|
+
headers: { 'Content-Type': 'application/json', 'X-Townmouse-Token': token },
|
|
21
|
+
// A hung server must not hang the agent. Long enough for a 120s bounded
|
|
22
|
+
// wait plus the round trip.
|
|
23
|
+
signal: AbortSignal.timeout(Number(process.env.TOWNMOUSE_CLI_TIMEOUT_MS) || 135000),
|
|
24
|
+
...(body ? { body: JSON.stringify(body) } : {})
|
|
25
|
+
});
|
|
26
|
+
const data = await res.json().catch(() => ({}));
|
|
27
|
+
if (!res.ok) {
|
|
28
|
+
// Keep the structured body: a refused action (stale target, missing
|
|
29
|
+
// element) explains itself better than the bare error string.
|
|
30
|
+
throw Object.assign(new Error(data.error || data.message || `HTTP ${res.status}`), { data, status: res.status });
|
|
31
|
+
}
|
|
32
|
+
return data;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// Options that never take a value. Without this list, `--replace "text"` would
|
|
36
|
+
// consume the text as the flag's value and clear the field instead of filling
|
|
37
|
+
// it.
|
|
38
|
+
const BOOLEAN_FLAGS = new Set(['replace', 'elements', 'activate', 'accept', 'dismiss', 'force', 'help']);
|
|
39
|
+
|
|
40
|
+
function args(list) {
|
|
41
|
+
const out = { _: [] };
|
|
42
|
+
for (let i = 0; i < list.length; i++) {
|
|
43
|
+
const value = list[i];
|
|
44
|
+
if (value.startsWith('--')) {
|
|
45
|
+
const key = value.slice(2);
|
|
46
|
+
if (BOOLEAN_FLAGS.has(key)) { out[key] = true; continue; }
|
|
47
|
+
const next = list[i + 1];
|
|
48
|
+
if (next && !next.startsWith('--')) { out[key] = next; i++; }
|
|
49
|
+
else out[key] = true;
|
|
50
|
+
} else out._.push(value);
|
|
51
|
+
}
|
|
52
|
+
return out;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function print(value) { console.log(JSON.stringify(value, null, 2)); }
|
|
56
|
+
|
|
57
|
+
// How many leading tokens are `pane exec` options rather than the command.
|
|
58
|
+
function leadingOptionCount(list) {
|
|
59
|
+
let count = 0;
|
|
60
|
+
while (count < list.length) {
|
|
61
|
+
const value = list[count];
|
|
62
|
+
if (value === '--no-wait') { count += 1; continue; }
|
|
63
|
+
if (value === '--wait-ms' || value === '--timeout') { count += 2; continue; }
|
|
64
|
+
break;
|
|
65
|
+
}
|
|
66
|
+
return count;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const MIME_BY_EXT = {
|
|
70
|
+
'.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif',
|
|
71
|
+
'.webp': 'image/webp', '.svg': 'image/svg+xml', '.pdf': 'application/pdf',
|
|
72
|
+
'.txt': 'text/plain', '.md': 'text/markdown', '.json': 'application/json',
|
|
73
|
+
'.zip': 'application/zip'
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
function shellQuote(value) {
|
|
77
|
+
return `'${String(value).replace(/'/g, `'\\''`)}'`;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// Pane ids look like `p_1a2b3c4d5e6f`. Inside a pane the id can be omitted
|
|
81
|
+
// entirely, and then the remaining arguments are the whole command — so the id
|
|
82
|
+
// has to be recognised by shape, not by position.
|
|
83
|
+
function paneTarget(list, verb) {
|
|
84
|
+
if (list.length && /^p_[0-9a-f]+$/i.test(list[0])) {
|
|
85
|
+
return { paneId: list[0], rest: list.slice(1) };
|
|
86
|
+
}
|
|
87
|
+
const paneId = process.env.TOWNMOUSE_PANE_ID || '';
|
|
88
|
+
if (!paneId) throw new Error(`${verb} requires a pane id, or TOWNMOUSE_PANE_ID (run inside a Townmouse pane).`);
|
|
89
|
+
return { paneId, rest: list };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
async function main() {
|
|
93
|
+
const [scope, action, ...rest] = process.argv.slice(2);
|
|
94
|
+
if (scope === 'pane' && (action === 'run' || action === 'input')) {
|
|
95
|
+
const target = paneTarget(rest, `pane ${action}`);
|
|
96
|
+
const payload = target.rest.join(' ');
|
|
97
|
+
if (action === 'run') {
|
|
98
|
+
print(await call('POST', `/panes/${target.paneId}/command`, { command: payload }));
|
|
99
|
+
} else {
|
|
100
|
+
print(await call('POST', `/panes/${target.paneId}/input`, { data: payload }));
|
|
101
|
+
}
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
if (scope === 'pane' && action === 'send-text') {
|
|
105
|
+
// paneTarget already removed an explicit id. Slicing the original list as
|
|
106
|
+
// though one was always present dropped the first word of the text when the
|
|
107
|
+
// pane came from the environment.
|
|
108
|
+
const target = paneTarget(rest, 'pane send-text');
|
|
109
|
+
const paneId = target.paneId;
|
|
110
|
+
let textParts = [...target.rest];
|
|
111
|
+
let bracketed = true;
|
|
112
|
+
if (textParts[0] === '--raw') { bracketed = false; textParts = textParts.slice(1); }
|
|
113
|
+
let text = textParts.join(' ');
|
|
114
|
+
if (bracketed) text = '\x1b[200~' + text + '\x1b[201~';
|
|
115
|
+
print(await call('POST', `/panes/${paneId}/input`, { data: text }));
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
if (scope === 'pane' && action === 'keys') {
|
|
119
|
+
const { paneId, rest: keys } = paneTarget(rest, 'pane keys');
|
|
120
|
+
if (!keys.length) throw new Error('pane keys requires at least one key name.');
|
|
121
|
+
print(await call('POST', `/panes/${paneId}/keys`, { keys }));
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
if (scope === 'pane' && action === 'status') {
|
|
125
|
+
const { paneId, rest: remaining } = paneTarget(rest, 'pane status');
|
|
126
|
+
const options = args(remaining);
|
|
127
|
+
const state = options.state || options._[0];
|
|
128
|
+
if (!state) throw new Error('pane status requires --state working|blocked|idle|done|unknown.');
|
|
129
|
+
print(await call('POST', `/panes/${paneId}/status`, { state, message: options.message }));
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
if (scope === 'pane' && action === 'dialog') {
|
|
133
|
+
const { paneId, rest: remaining } = paneTarget(rest, 'pane dialog');
|
|
134
|
+
const options = args(remaining);
|
|
135
|
+
const dialogAction = options.accept ? 'accept' : options.dismiss ? 'dismiss' : '';
|
|
136
|
+
if (!dialogAction) throw new Error('pane dialog requires --accept or --dismiss.');
|
|
137
|
+
print(await call('POST', `/panes/${paneId}/browser/dialog`, {
|
|
138
|
+
action: dialogAction,
|
|
139
|
+
text: options.text
|
|
140
|
+
}));
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
if (scope === 'pane' && action === 'wait') {
|
|
144
|
+
const { paneId, rest: remaining } = paneTarget(rest, 'pane wait');
|
|
145
|
+
const options = args(remaining);
|
|
146
|
+
const query = new URLSearchParams();
|
|
147
|
+
if (options.match !== undefined) query.set('match', String(options.match));
|
|
148
|
+
if (options.regex !== undefined) query.set('regex', String(options.regex));
|
|
149
|
+
if (options.idle !== undefined) query.set('idleMs', String(options.idle));
|
|
150
|
+
if (options.state !== undefined) query.set('state', String(options.state));
|
|
151
|
+
if (options.timeout !== undefined) query.set('timeout', String(options.timeout));
|
|
152
|
+
if (options.since !== undefined) query.set('since', String(options.since));
|
|
153
|
+
if (!query.toString()) throw new Error('pane wait requires --match, --regex, --idle, or --state.');
|
|
154
|
+
print(await call('GET', `/panes/${paneId}/wait?${query.toString()}`));
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
if (scope === 'guide') {
|
|
158
|
+
print(await call('GET', '/guide'));
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
if (scope === 'pane' && action === 'exec') {
|
|
162
|
+
const { paneId, rest: parts } = paneTarget(rest, 'pane exec');
|
|
163
|
+
let wait = true;
|
|
164
|
+
let timeoutMs;
|
|
165
|
+
// Everything after the first `--` is the command, verbatim. Without a
|
|
166
|
+
// separator, only leading options are consumed; the rest is the command.
|
|
167
|
+
const separator = parts.indexOf('--');
|
|
168
|
+
const optionPart = separator >= 0 ? parts.slice(0, separator) : parts.slice(0, leadingOptionCount(parts));
|
|
169
|
+
const commandPart = separator >= 0 ? parts.slice(separator + 1) : parts.slice(optionPart.length);
|
|
170
|
+
for (let i = 0; i < optionPart.length; i++) {
|
|
171
|
+
const value = optionPart[i];
|
|
172
|
+
if (value === '--no-wait') { wait = false; continue; }
|
|
173
|
+
if (value === '--wait-ms' || value === '--timeout') { timeoutMs = Number(optionPart[++i]); continue; }
|
|
174
|
+
throw new Error(`Unknown pane exec option: ${value}. Put the command after --.`);
|
|
175
|
+
}
|
|
176
|
+
const command = commandPart.join(' ');
|
|
177
|
+
if (!command) throw new Error('pane exec requires a command.');
|
|
178
|
+
const result = await call('POST', `/panes/${paneId}/jobs`, { command, wait, timeoutMs });
|
|
179
|
+
print(result);
|
|
180
|
+
if (result.status === 'running') process.exitCode = 3;
|
|
181
|
+
else if (result.status !== 'completed') process.exitCode = 1;
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
if (scope === 'pane' && action === 'job') {
|
|
185
|
+
// `panes pane job <job-id>` works inside a pane; otherwise supply both.
|
|
186
|
+
const hasPaneId = rest.length > 1 && /^p_[0-9a-f]+$/i.test(rest[0]);
|
|
187
|
+
const paneId = hasPaneId ? rest[0] : (process.env.TOWNMOUSE_PANE_ID || '');
|
|
188
|
+
const jobId = hasPaneId ? rest[1] : rest[0];
|
|
189
|
+
if (!paneId || !jobId) throw new Error('pane job requires a job id, or a pane id and a job id.');
|
|
190
|
+
const result = await call('GET', `/panes/${paneId}/jobs/${jobId}`);
|
|
191
|
+
print(result);
|
|
192
|
+
if (result.status === 'running') process.exitCode = 3;
|
|
193
|
+
else if (result.status !== 'completed') process.exitCode = 1;
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
if (scope === 'pane' && action === 'browser') {
|
|
197
|
+
// Accept the documented `browser <verb> <pane-id> ...`, the id-first
|
|
198
|
+
// `browser <pane-id> <verb> ...`, and `browser <verb> ...` inside a pane.
|
|
199
|
+
const parts = [...rest];
|
|
200
|
+
let paneId = '';
|
|
201
|
+
if (parts.length > 1 && /^p_[0-9a-f]+$/i.test(parts[0])) paneId = parts.shift();
|
|
202
|
+
const verb = parts.shift();
|
|
203
|
+
if (!paneId && parts.length && /^p_[0-9a-f]+$/i.test(parts[0])) paneId = parts.shift();
|
|
204
|
+
if (!paneId) paneId = process.env.TOWNMOUSE_PANE_ID || '';
|
|
205
|
+
const options = args(parts);
|
|
206
|
+
if (!paneId || !verb) throw new Error('pane browser requires an action (run inside a Townmouse pane, or pass a pane id).');
|
|
207
|
+
const base = `/panes/${paneId}/browser`;
|
|
208
|
+
const number = (value) => (value === undefined ? undefined : Number(value));
|
|
209
|
+
const finish = (value) => {
|
|
210
|
+
print(value);
|
|
211
|
+
if (value && value.ok === false) process.exitCode = value.status === 'stale' ? 4 : 1;
|
|
212
|
+
return value;
|
|
213
|
+
};
|
|
214
|
+
switch (verb) {
|
|
215
|
+
case 'observe': {
|
|
216
|
+
const query = [];
|
|
217
|
+
if (options.elements) query.push('elements=1');
|
|
218
|
+
if (options.max) query.push(`max=${encodeURIComponent(options.max)}`);
|
|
219
|
+
const result = await call('GET', `${base}/observe${query.length ? '?' + query.join('&') : ''}`);
|
|
220
|
+
if (options['image-file'] && result.image) {
|
|
221
|
+
fs.writeFileSync(String(options['image-file']), Buffer.from(result.image, 'base64'));
|
|
222
|
+
result.imageFile = String(options['image-file']);
|
|
223
|
+
delete result.image;
|
|
224
|
+
}
|
|
225
|
+
print(result);
|
|
226
|
+
return;
|
|
227
|
+
}
|
|
228
|
+
case 'elements': {
|
|
229
|
+
const query = options.max ? `?max=${encodeURIComponent(options.max)}` : '';
|
|
230
|
+
print(await call('GET', `${base}/elements${query}`));
|
|
231
|
+
return;
|
|
232
|
+
}
|
|
233
|
+
case 'click':
|
|
234
|
+
case 'hover': {
|
|
235
|
+
const body = { action: verb };
|
|
236
|
+
if (options.ref) body.ref = String(options.ref);
|
|
237
|
+
else { body.x = number(options.x); body.y = number(options.y); }
|
|
238
|
+
if (options.observation !== undefined) body.observationId = Number(options.observation);
|
|
239
|
+
if (options.force) body.force = true;
|
|
240
|
+
finish(await call('POST', `${base}/action`, body));
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
case 'type': {
|
|
244
|
+
const body = { action: 'type', text: options._.join(' ') };
|
|
245
|
+
if (options.ref) body.ref = String(options.ref);
|
|
246
|
+
if (options.replace) body.replace = true;
|
|
247
|
+
finish(await call('POST', `${base}/action`, body));
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
case 'key': {
|
|
251
|
+
const keys = options._.slice(0).map(String);
|
|
252
|
+
if (!keys.length) throw new Error('pane browser key requires at least one key.');
|
|
253
|
+
finish(await call('POST', `${base}/action`, { action: 'key', keys }));
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
case 'drag': {
|
|
257
|
+
finish(await call('POST', `${base}/action`, {
|
|
258
|
+
action: 'drag',
|
|
259
|
+
fromRef: options['from-ref'],
|
|
260
|
+
toRef: options['to-ref'],
|
|
261
|
+
fromX: number(options['from-x']),
|
|
262
|
+
fromY: number(options['from-y']),
|
|
263
|
+
toX: number(options['to-x']),
|
|
264
|
+
toY: number(options['to-y'])
|
|
265
|
+
}));
|
|
266
|
+
return;
|
|
267
|
+
}
|
|
268
|
+
case 'scroll': {
|
|
269
|
+
finish(await call('POST', `${base}/action`, {
|
|
270
|
+
action: 'scroll',
|
|
271
|
+
ref: options.ref,
|
|
272
|
+
selector: options.selector,
|
|
273
|
+
dx: number(options.dx),
|
|
274
|
+
dy: number(options.dy ?? options.amount)
|
|
275
|
+
}));
|
|
276
|
+
return;
|
|
277
|
+
}
|
|
278
|
+
case 'select': {
|
|
279
|
+
if (!options.ref) throw new Error('pane browser select requires --ref.');
|
|
280
|
+
finish(await call('POST', `${base}/action`, { action: 'select', ref: String(options.ref), value: options.value }));
|
|
281
|
+
return;
|
|
282
|
+
}
|
|
283
|
+
case 'navigate': {
|
|
284
|
+
const url = options._[0];
|
|
285
|
+
if (!url) throw new Error('pane browser navigate requires a URL.');
|
|
286
|
+
print(await call('POST', `${base}/action`, { action: 'navigate', url }));
|
|
287
|
+
return;
|
|
288
|
+
}
|
|
289
|
+
case 'back':
|
|
290
|
+
case 'forward':
|
|
291
|
+
case 'reload':
|
|
292
|
+
print(await call('POST', `${base}/action`, { action: verb }));
|
|
293
|
+
return;
|
|
294
|
+
case 'wait': {
|
|
295
|
+
print(await call('POST', `${base}/wait`, {
|
|
296
|
+
url: options.url,
|
|
297
|
+
title: options.title,
|
|
298
|
+
text: options.text,
|
|
299
|
+
selector: options.selector,
|
|
300
|
+
value: options.value,
|
|
301
|
+
ref: options.ref,
|
|
302
|
+
timeout: number(options.timeout)
|
|
303
|
+
}));
|
|
304
|
+
return;
|
|
305
|
+
}
|
|
306
|
+
case 'text': {
|
|
307
|
+
print(await call('GET', `${base}/content`));
|
|
308
|
+
return;
|
|
309
|
+
}
|
|
310
|
+
case 'sizing': {
|
|
311
|
+
const mode = options._[0];
|
|
312
|
+
if (!['fit', 'fixed'].includes(mode)) throw new Error('pane browser sizing requires fit or fixed.');
|
|
313
|
+
print(await call('POST', `${base}/sizing`, { mode, width: number(options.width), height: number(options.height) }));
|
|
314
|
+
return;
|
|
315
|
+
}
|
|
316
|
+
default:
|
|
317
|
+
throw new Error(`Unknown browser action: ${verb}`);
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
const a = args(rest);
|
|
321
|
+
if (scope === 'attach') {
|
|
322
|
+
const attachArgs = args([action, ...rest].filter((value) => value !== undefined));
|
|
323
|
+
const file = attachArgs._[0];
|
|
324
|
+
if (!file) throw new Error('attach requires a file path.');
|
|
325
|
+
if (!token) throw new Error('No workspace token. Run from a Townmouse terminal pane or set TOWNMOUSE_TOKEN.');
|
|
326
|
+
const stat = fs.statSync(file);
|
|
327
|
+
if (stat.size > 25 * 1024 * 1024) throw new Error('Attachment exceeds the 25 MB limit.');
|
|
328
|
+
const root = api.replace(/\/api\/panes\/?$/, '');
|
|
329
|
+
const type = attachArgs.type || MIME_BY_EXT[path.extname(file).toLowerCase()] || 'application/octet-stream';
|
|
330
|
+
const response = await fetch(root + '/api/attachments', {
|
|
331
|
+
method: 'POST',
|
|
332
|
+
headers: {
|
|
333
|
+
'Content-Type': type,
|
|
334
|
+
'X-Filename': encodeURIComponent(path.basename(file)),
|
|
335
|
+
'X-Townmouse-Token': token
|
|
336
|
+
},
|
|
337
|
+
body: fs.readFileSync(file)
|
|
338
|
+
});
|
|
339
|
+
const attachment = await response.json().catch(() => ({}));
|
|
340
|
+
if (!response.ok) throw new Error(attachment.error || `Upload failed (${response.status}).`);
|
|
341
|
+
if (attachArgs.pane) {
|
|
342
|
+
await call('POST', `/panes/${attachArgs.pane}/input`, { data: shellQuote(attachment.path) + ' ' });
|
|
343
|
+
attachment.insertedPane = attachArgs.pane;
|
|
344
|
+
}
|
|
345
|
+
print(attachment);
|
|
346
|
+
return;
|
|
347
|
+
}
|
|
348
|
+
if (!scope || scope === 'help' || scope === '--help') {
|
|
349
|
+
console.log(`Usage:
|
|
350
|
+
panes guide Print the agent instruction sheet.
|
|
351
|
+
panes state
|
|
352
|
+
panes tab list
|
|
353
|
+
panes tab create [--title TEXT] [--activate]
|
|
354
|
+
panes tab close <tab-id>
|
|
355
|
+
panes pane create --tab <tab-id> --kind terminal|browser [--url URL] [--cwd PATH] [--title TEXT]
|
|
356
|
+
panes pane url <pane-id> <url>
|
|
357
|
+
panes pane exec <pane-id> -- <command...> [--wait-ms N] [--no-wait]
|
|
358
|
+
Tracked job: exit code + output.
|
|
359
|
+
panes pane job <pane-id> <job-id> Re-read a tracked job.
|
|
360
|
+
panes pane run <pane-id> <command...> Type into the interactive terminal (unconfirmed).
|
|
361
|
+
panes pane read <pane-id> [--lines N] [--raw]
|
|
362
|
+
panes pane text <pane-id> Browser page text.
|
|
363
|
+
panes pane input <pane-id> <text...>
|
|
364
|
+
panes pane send-text <pane-id> [--raw] <text...>
|
|
365
|
+
panes pane keys <pane-id> <key...> (enter, esc, tab, ctrl+c, alt+x, arrows)
|
|
366
|
+
panes pane wait <pane-id> [--match TEXT | --regex PATTERN | --idle MS | --state STATE]
|
|
367
|
+
[--since OFFSET] [--timeout MS]
|
|
368
|
+
panes pane status <pane-id> --state working|blocked|idle|done|unknown [--message TEXT]
|
|
369
|
+
panes pane dialog <pane-id> --accept|--dismiss [--text VALUE]
|
|
370
|
+
|
|
371
|
+
Browser control (pane ids may be omitted inside a Townmouse pane):
|
|
372
|
+
panes pane browser observe <pane-id> [--elements] [--max N] [--image-file PATH]
|
|
373
|
+
panes pane browser elements <pane-id> [--max N]
|
|
374
|
+
panes pane browser click <pane-id> [--ref e12 | --x N --y N [--observation N]]
|
|
375
|
+
panes pane browser hover <pane-id> [--ref e12 | --x N --y N]
|
|
376
|
+
panes pane browser drag <pane-id> --from-ref e12 --to-ref e15
|
|
377
|
+
panes pane browser type <pane-id> <text...> [--ref e12] [--replace]
|
|
378
|
+
panes pane browser key <pane-id> <key...> (Alt+M, Control+Shift+Tab, arrows)
|
|
379
|
+
panes pane browser scroll <pane-id> [--ref e12 | --selector CSS] [--dy N] [--dx N]
|
|
380
|
+
panes pane browser select <pane-id> --ref e12 --value V
|
|
381
|
+
panes pane browser navigate <pane-id> <url>
|
|
382
|
+
panes pane browser back|forward|reload <pane-id>
|
|
383
|
+
panes pane browser wait <pane-id> [--url U | --text T | --selector S | --value V --ref e12]
|
|
384
|
+
[--timeout MS]
|
|
385
|
+
panes pane browser sizing <pane-id> fit|fixed [--width N] [--height N]
|
|
386
|
+
panes pane close <pane-id>
|
|
387
|
+
panes attach <file> [--pane <pane-id>] [--type MIME]
|
|
388
|
+
panes active --tab <tab-id> [--pane <pane-id>]
|
|
389
|
+
|
|
390
|
+
Exit codes: 0 done, 1 failed/missing, 3 still running, 4 stale target.
|
|
391
|
+
Environment: TOWNMOUSE_API, TOWNMOUSE_TOKEN, TOWNMOUSE_TAB_ID, TOWNMOUSE_PANE_ID.`);
|
|
392
|
+
return;
|
|
393
|
+
}
|
|
394
|
+
if (scope === 'state') { print(await call('GET', '/state')); return; }
|
|
395
|
+
if (scope === 'active') {
|
|
396
|
+
const activeArgs = args([action, ...rest].filter((value) => value !== undefined));
|
|
397
|
+
print(await call('POST', '/active', { tabId: activeArgs.tab, paneId: activeArgs.pane }));
|
|
398
|
+
return;
|
|
399
|
+
}
|
|
400
|
+
if (scope === 'tab') {
|
|
401
|
+
if (action === 'list') { const s = await call('GET', '/state'); print(s.tabs); return; }
|
|
402
|
+
if (action === 'create') { print(await call('POST', '/tabs', { title: a.title, activate: a.activate === true, createdBy: 'agent' })); return; }
|
|
403
|
+
if (action === 'close') { print(await call('DELETE', `/tabs/${a._[0]}`)); return; }
|
|
404
|
+
}
|
|
405
|
+
if (scope === 'pane') {
|
|
406
|
+
const hasPaneId = a._.length > 0 && /^p_[0-9a-f]+$/i.test(a._[0]);
|
|
407
|
+
const paneId = hasPaneId ? a._[0] : (process.env.TOWNMOUSE_PANE_ID || '');
|
|
408
|
+
const positional = hasPaneId ? a._.slice(1) : a._;
|
|
409
|
+
if (action === 'create') {
|
|
410
|
+
const tab = a.tab || process.env.TOWNMOUSE_TAB_ID;
|
|
411
|
+
if (!tab) throw new Error('--tab is required (or run inside a Townmouse pane).');
|
|
412
|
+
print(await call('POST', `/tabs/${tab}/panes`, { kind: a.kind || 'terminal', url: a.url, cwd: a.cwd, title: a.title, createdBy: 'agent' }));
|
|
413
|
+
return;
|
|
414
|
+
}
|
|
415
|
+
if (action === 'url') { print(await call('POST', `/panes/${paneId}/url`, { url: positional[0] })); return; }
|
|
416
|
+
if (action === 'run') { print(await call('POST', `/panes/${paneId}/command`, { command: positional.join(' ') })); return; }
|
|
417
|
+
if (action === 'input') { print(await call('POST', `/panes/${paneId}/input`, { data: positional.join(' ') })); return; }
|
|
418
|
+
if (action === 'text') { print(await call('GET', `/panes/${paneId}/browser/content`)); return; }
|
|
419
|
+
if (action === 'read') {
|
|
420
|
+
if (!paneId) throw new Error('pane read requires a pane id (or run inside a Townmouse pane).');
|
|
421
|
+
// Clean screen text by default; --raw keeps the original escape data.
|
|
422
|
+
const mode = a.raw === true ? 'raw' : 'clean';
|
|
423
|
+
const data = await call('GET', `/panes/${paneId}/text?mode=${mode}`);
|
|
424
|
+
const lines = Number(a.lines || 80);
|
|
425
|
+
const text = String(data.text || '').split('\n').slice(-lines).join('\n');
|
|
426
|
+
print({ ...data, text, data: text });
|
|
427
|
+
return;
|
|
428
|
+
}
|
|
429
|
+
if (action === 'close') {
|
|
430
|
+
if (!paneId) throw new Error('pane close requires a pane id (or run inside a Townmouse pane).');
|
|
431
|
+
print(await call('DELETE', `/panes/${paneId}`));
|
|
432
|
+
return;
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
console.error('Unknown command. Run: panes help');
|
|
436
|
+
process.exitCode = 2;
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
main().catch((error) => { console.error(error.message); process.exitCode = 1; });
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
#!/bin/sh
|
|
2
|
+
# Mark node-pty's macOS spawn helpers executable wherever npm placed them.
|
|
3
|
+
#
|
|
4
|
+
# npm hoists dependencies for a normal install (`npm install townmouse`, `npx`)
|
|
5
|
+
# and nests them for a global install, so the old package-local
|
|
6
|
+
# `$ROOT/node_modules/node-pty` path silently matched nothing and every terminal
|
|
7
|
+
# pane failed with "posix_spawnp failed". Resolve the real directory through
|
|
8
|
+
# Node instead, then fix the helpers there.
|
|
9
|
+
set -eu
|
|
10
|
+
ROOT=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd)
|
|
11
|
+
NODE="${TERMINALONE_NODE:-$(command -v node 2>/dev/null || true)}"
|
|
12
|
+
|
|
13
|
+
node_pty_dir() {
|
|
14
|
+
[ -n "$NODE" ] || return 1
|
|
15
|
+
(
|
|
16
|
+
cd "$ROOT" || exit 1
|
|
17
|
+
"$NODE" -e '
|
|
18
|
+
const path = require("path");
|
|
19
|
+
const fs = require("fs");
|
|
20
|
+
let dir = path.dirname(require.resolve("node-pty"));
|
|
21
|
+
while (dir !== path.dirname(dir) && !fs.existsSync(path.join(dir, "package.json"))) {
|
|
22
|
+
dir = path.dirname(dir);
|
|
23
|
+
}
|
|
24
|
+
process.stdout.write(dir);
|
|
25
|
+
' 2>/dev/null
|
|
26
|
+
)
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
PTY_DIR=$(node_pty_dir || true)
|
|
30
|
+
[ -n "$PTY_DIR" ] || PTY_DIR="$ROOT/node_modules/node-pty"
|
|
31
|
+
[ -d "$PTY_DIR" ] || exit 0
|
|
32
|
+
|
|
33
|
+
for helper in "$PTY_DIR"/prebuilds/darwin-*/spawn-helper; do
|
|
34
|
+
[ ! -f "$helper" ] || chmod +x "$helper"
|
|
35
|
+
done
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Run ordered Terminal Workspace lifecycle hooks with bounded execution."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import subprocess
|
|
9
|
+
import sys
|
|
10
|
+
from datetime import datetime, timezone
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def main() -> int:
|
|
15
|
+
if len(sys.argv) < 2:
|
|
16
|
+
print(f"usage: {sys.argv[0]} EVENT [--best-effort]", file=sys.stderr)
|
|
17
|
+
return 64
|
|
18
|
+
event = sys.argv[1]
|
|
19
|
+
if not event.replace("-", "").replace("_", "").isalnum():
|
|
20
|
+
print(f"invalid hook event: {event}", file=sys.stderr)
|
|
21
|
+
return 64
|
|
22
|
+
best_effort = "--best-effort" in sys.argv[2:]
|
|
23
|
+
root = Path(__file__).resolve().parent.parent
|
|
24
|
+
product = "terminalone"
|
|
25
|
+
timeout = float(os.environ.get("TERMINAL_HOOK_TIMEOUT", "30"))
|
|
26
|
+
hook_roots = [
|
|
27
|
+
root / ".terminal-hooks" / f"{event}.d",
|
|
28
|
+
Path.home() / ".config" / "terminal-workspace" / "hooks" / product / f"{event}.d",
|
|
29
|
+
]
|
|
30
|
+
context = json.dumps({
|
|
31
|
+
"schemaVersion": 1,
|
|
32
|
+
"product": product,
|
|
33
|
+
"event": event,
|
|
34
|
+
"root": str(root),
|
|
35
|
+
"pid": os.getpid(),
|
|
36
|
+
"timestamp": datetime.now(timezone.utc).isoformat(),
|
|
37
|
+
}) + "\n"
|
|
38
|
+
env = os.environ | {
|
|
39
|
+
"TERMINAL_HOOK_EVENT": event,
|
|
40
|
+
"TERMINAL_PRODUCT": product,
|
|
41
|
+
"TERMINAL_PRODUCT_ROOT": str(root),
|
|
42
|
+
}
|
|
43
|
+
failures = 0
|
|
44
|
+
for directory in hook_roots:
|
|
45
|
+
if not directory.is_dir():
|
|
46
|
+
continue
|
|
47
|
+
for hook in sorted(directory.iterdir()):
|
|
48
|
+
if hook.name.startswith(".") or not hook.is_file():
|
|
49
|
+
continue
|
|
50
|
+
if not os.access(hook, os.X_OK):
|
|
51
|
+
print(f"hook skipped (not executable): {hook}", file=sys.stderr)
|
|
52
|
+
continue
|
|
53
|
+
try:
|
|
54
|
+
result = subprocess.run(
|
|
55
|
+
[str(hook)], input=context, text=True, env=env, timeout=timeout, check=False
|
|
56
|
+
)
|
|
57
|
+
if result.returncode:
|
|
58
|
+
failures += 1
|
|
59
|
+
print(f"hook failed ({result.returncode}): {hook}", file=sys.stderr)
|
|
60
|
+
except subprocess.TimeoutExpired:
|
|
61
|
+
failures += 1
|
|
62
|
+
print(f"hook timed out after {timeout:g}s: {hook}", file=sys.stderr)
|
|
63
|
+
if failures and not best_effort:
|
|
64
|
+
return 70
|
|
65
|
+
return 0 if not failures or best_effort else 70
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
if __name__ == "__main__":
|
|
69
|
+
raise SystemExit(main())
|
package/scripts/t1.sh
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
#!/bin/bash
|
|
2
|
+
#
|
|
3
|
+
# t1 — open Townmouse. Ensures the always-on service is running, waits for it to
|
|
4
|
+
# be healthy, then opens the UI as a chrome-less app window (falls back to the
|
|
5
|
+
# default browser). This is the volume-resident implementation; install-service.sh
|
|
6
|
+
# generates a self-contained `t1` binary on the internal disk that delegates here,
|
|
7
|
+
# plus ~/Applications/Townmouse.app. Run install once, then use `t1` or Spotlight.
|
|
8
|
+
#
|
|
9
|
+
set -euo pipefail
|
|
10
|
+
|
|
11
|
+
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
|
|
12
|
+
PORT="${PORT:-11001}"
|
|
13
|
+
APP_DIR="${TERMINALONE_APP_DIR:-$(cd "$SCRIPT_DIR/.." && pwd -P)}"
|
|
14
|
+
LOG_DIR="${TERMINALONE_LOG_DIR:-$HOME/Library/Logs/Townmouse}"
|
|
15
|
+
URL="${TERMINALONE_URL:-http://localhost:$PORT}"
|
|
16
|
+
HEALTH_URL="${TERMINALONE_HEALTH_URL:-$URL/health}"
|
|
17
|
+
LABEL="com.floyd.terminalone"
|
|
18
|
+
DOMAIN="gui/$(id -u)"
|
|
19
|
+
SERVE_ONLY=false
|
|
20
|
+
[ "${1:-}" = "--serve-only" ] && SERVE_ONLY=true
|
|
21
|
+
|
|
22
|
+
show_usage() {
|
|
23
|
+
cat <<'EOF'
|
|
24
|
+
Usage: t1 [--serve-only]
|
|
25
|
+
|
|
26
|
+
Open Townmouse, or ensure its service is healthy without opening a browser.
|
|
27
|
+
|
|
28
|
+
Options:
|
|
29
|
+
--serve-only Start or verify the service, then exit
|
|
30
|
+
-h, --help Show this help and exit
|
|
31
|
+
EOF
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
case "${1:-}" in
|
|
35
|
+
help|-h|--help)
|
|
36
|
+
show_usage
|
|
37
|
+
exit 0
|
|
38
|
+
;;
|
|
39
|
+
esac
|
|
40
|
+
|
|
41
|
+
show_error() {
|
|
42
|
+
local msg="$1"
|
|
43
|
+
printf 't1: %s\n' "$msg" >&2
|
|
44
|
+
if [ ! -t 2 ] && command -v osascript >/dev/null 2>&1; then
|
|
45
|
+
osascript -e "display dialog \"$msg\" with title \"Townmouse\" buttons {\"OK\"} default button \"OK\" with icon caution" >/dev/null 2>&1 || true
|
|
46
|
+
fi
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
wait_for_health() {
|
|
50
|
+
local tries="${1:-32}"
|
|
51
|
+
for _ in $(seq 1 "$tries"); do
|
|
52
|
+
if curl -sf "$HEALTH_URL" >/dev/null 2>&1; then
|
|
53
|
+
return 0
|
|
54
|
+
fi
|
|
55
|
+
sleep 0.25
|
|
56
|
+
done
|
|
57
|
+
return 1
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
start_direct_backend() {
|
|
61
|
+
mkdir -p "$LOG_DIR"
|
|
62
|
+
"$APP_DIR/scripts/run-hooks" pre-start
|
|
63
|
+
nohup env PORT="$PORT" "$APP_DIR/scripts/node-runtime.sh" exec "$APP_DIR/src/server.js" >>"$LOG_DIR/local-launch.out.log" 2>>"$LOG_DIR/local-launch.err.log" &
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
if ! wait_for_health 1; then
|
|
67
|
+
# Nudge the service (no-op if it isn't installed / already running).
|
|
68
|
+
launchctl kickstart "$DOMAIN/$LABEL" 2>/dev/null || true
|
|
69
|
+
|
|
70
|
+
if ! wait_for_health 16; then
|
|
71
|
+
# lsof's first line is a column header, not a listener. Inspect command
|
|
72
|
+
# names only on real listener rows so a starting Node service is not
|
|
73
|
+
# mistaken for a foreign process.
|
|
74
|
+
if lsof -nP -iTCP:"$PORT" -sTCP:LISTEN 2>/dev/null \
|
|
75
|
+
| awk 'NR > 1 && tolower($1) !~ /node/ { foreign = 1 } END { exit !foreign }'; then
|
|
76
|
+
show_error "Port $PORT is already in use by another process. Free the port or change Townmouse's port."
|
|
77
|
+
exit 1
|
|
78
|
+
fi
|
|
79
|
+
|
|
80
|
+
if ! "$APP_DIR/scripts/node-runtime.sh" doctor >/dev/null 2>&1; then
|
|
81
|
+
show_error "Townmouse runtime is not ready. Run: t1 repair"
|
|
82
|
+
exit 1
|
|
83
|
+
fi
|
|
84
|
+
|
|
85
|
+
if [ ! -f "$APP_DIR/src/server.js" ]; then
|
|
86
|
+
show_error "Townmouse files are missing at $APP_DIR."
|
|
87
|
+
exit 1
|
|
88
|
+
fi
|
|
89
|
+
|
|
90
|
+
start_direct_backend
|
|
91
|
+
|
|
92
|
+
if ! wait_for_health 32; then
|
|
93
|
+
"$APP_DIR/scripts/run-hooks" start-error --best-effort
|
|
94
|
+
show_error "Townmouse failed to start. Logs: $LOG_DIR/local-launch.err.log"
|
|
95
|
+
exit 1
|
|
96
|
+
fi
|
|
97
|
+
"$APP_DIR/scripts/run-hooks" post-start --best-effort
|
|
98
|
+
fi
|
|
99
|
+
fi
|
|
100
|
+
|
|
101
|
+
if $SERVE_ONLY; then
|
|
102
|
+
echo "Townmouse service ready -> $URL"
|
|
103
|
+
exit 0
|
|
104
|
+
fi
|
|
105
|
+
|
|
106
|
+
if [ -d "/Applications/Google Chrome.app" ]; then
|
|
107
|
+
open -na "Google Chrome" --args --app="$URL"
|
|
108
|
+
elif [ -d "/Applications/Google Chrome Beta.app" ]; then
|
|
109
|
+
open -na "Google Chrome Beta" --args --app="$URL"
|
|
110
|
+
else
|
|
111
|
+
open "$URL"
|
|
112
|
+
fi
|
|
113
|
+
echo "Townmouse -> $URL"
|