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
@@ -10,6 +10,7 @@ const { resolveShell } = require('./shell-resolve');
10
10
  const { replayTranscript } = require('./replay-text');
11
11
  const { buildGuide } = require('./agent-guide');
12
12
  const { createPatternMatcher } = require('./safe-regex');
13
+ const { ownerPageRefusal } = require('./owner-page');
13
14
 
14
15
  const MAX_PANES_PER_TAB = 4;
15
16
  const MAX_TABS = 24;
@@ -75,6 +76,23 @@ function installWorkspacePanes(app, browserWorkspace, options = {}) {
75
76
  // Attachment uploads are owner-gated at the page boundary, but a terminal
76
77
  // agent inside the workspace presents this scoped pane token instead.
77
78
  app.locals.townmousePaneToken = token;
79
+
80
+ // Two keys, two callers. The workspace token is the agents' key: one per
81
+ // machine, kept on disk, handed to every terminal pane and to the CLI. The
82
+ // page key is the owner's: minted per server run, never written anywhere,
83
+ // and handed once, by the cookie-proven bootstrap route, to the person's
84
+ // page. Who is asking is read from the key a request presents, never from a
85
+ // field in its body, so an agent that sends createdBy: "human" stays an agent.
86
+ const pageKey = crypto.randomBytes(32).toString('hex');
87
+ // What an agent has on a pane, lowest first. The words are the terminal
88
+ // surface's: Private, View only, Allow control.
89
+ const ACCESS = { private: 0, view: 1, control: 2 };
90
+ const ACCESS_LABEL = { private: 'Private', view: 'View only', control: 'Allow control' };
91
+ // An unanswered ask clears itself, and one the owner declined may not be
92
+ // repeated at once, so a person who was away does not find a pile of prompts.
93
+ const ACCESS_REQUEST_TTL_MS = 5 * 60 * 1000;
94
+ const ACCESS_DECLINE_TTL_MS = 5 * 60 * 1000;
95
+
78
96
  const stateDir = process.env.TOWNMOUSE_STATE_DIR || path.join(os.homedir(), '.townmouse');
79
97
  const stateFile = path.join(stateDir, 'workspace.json');
80
98
 
@@ -84,10 +102,15 @@ function installWorkspacePanes(app, browserWorkspace, options = {}) {
84
102
  let activePaneId = null;
85
103
  let restored = false;
86
104
  let savedWorkspace = false;
105
+ let olderWorkspace = false;
87
106
  let restorePromise = null;
88
107
  let saveTimer = null;
89
108
  let shuttingDown = false;
90
109
  let activeStreams = 0;
110
+ // Each state answer is numbered as it is built. A page that has a newer
111
+ // answer ignores an older one still on the wire, so what the person just
112
+ // changed cannot flash back for a moment.
113
+ let stateSeq = 0;
91
114
 
92
115
  const id = (prefix) => prefix + '_' + crypto.randomBytes(6).toString('hex');
93
116
  const route = (fn) => async (req, res) => {
@@ -103,13 +126,129 @@ function installWorkspacePanes(app, browserWorkspace, options = {}) {
103
126
  if (req.body == null) req.body = {};
104
127
  next();
105
128
  });
106
- const auth = (req, res, next) => {
129
+ // Length is compared first so a wrong-length guess cannot throw inside the
130
+ // constant-time comparison; both keys are fixed-length hex.
131
+ const sameSecret = (supplied, secret) => {
132
+ if (typeof supplied !== 'string') return false;
133
+ const given = Buffer.from(supplied);
134
+ const held = Buffer.from(secret);
135
+ return given.length === held.length && crypto.timingSafeEqual(given, held);
136
+ };
137
+ // 'owner' is the person's page. 'agent' is anything holding the workspace token.
138
+ const callerOf = (req) => {
139
+ if (sameSecret(req.get('X-Townmouse-Owner'), pageKey)) return 'owner';
107
140
  const supplied = req.get('X-Townmouse-Token') || (req.get('Authorization') || '').replace(/^Bearer\s+/i, '');
108
- if (supplied !== token) { res.status(403).json({ error: 'Workspace token required.' }); return; }
141
+ return sameSecret(supplied, token) ? 'agent' : null;
142
+ };
143
+ const auth = (req, res, next) => {
144
+ const caller = callerOf(req);
145
+ // The code lets the page tell a stale key (the server restarted) from any
146
+ // other refusal, and renew its session without bothering the person.
147
+ if (!caller) { res.status(403).json({ error: 'Workspace token required.', code: 'UNKNOWN_KEY' }); return; }
148
+ req.caller = caller;
109
149
  next();
110
150
  };
111
151
  const tabOf = (pane) => tabs.get(pane.tabId) || null;
112
152
 
153
+ // ── Who may do what on a pane ─────────────────────────────────────────────
154
+ //
155
+ // A pane belongs to whoever asked for it: the owner's page, or an agent
156
+ // through the CLI or the API. The owner may do anything. An agent has
157
+ // control of a pane an agent opened, and exactly the grant the owner has
158
+ // given on one of the owner's own panes: nothing (Private), reading (View
159
+ // only), or reading and driving (Allow control). Everything below is
160
+ // enforced here, in the routes, so hiding a control in a page changes
161
+ // nothing about what a request can do.
162
+
163
+ function refuse(status, code, message, extra = {}) {
164
+ throw Object.assign(new Error(message), { status, body: { error: message, code, ...extra } });
165
+ }
166
+
167
+ // What an agent currently has on a pane. The same object is put on every
168
+ // pane in every state response, so the page and the CLI cannot disagree
169
+ // with the routes.
170
+ function agentAccess(pane) {
171
+ const level = pane.createdBy === 'agent' ? 'control' : pane.grant;
172
+ return { level, label: ACCESS_LABEL[level] };
173
+ }
174
+
175
+ function hasAccess(pane, caller, need) {
176
+ if (!pane) return false;
177
+ if (caller === 'owner') return true;
178
+ return ACCESS[agentAccess(pane).level] >= ACCESS[need];
179
+ }
180
+
181
+ // A refusal names the pane's level and the one command that asks the owner
182
+ // for more, so an agent's next step is never a guess.
183
+ function requireAccess(pane, caller, need) {
184
+ if (hasAccess(pane, caller, need)) return;
185
+ const access = agentAccess(pane);
186
+ const ask = `panes pane request ${pane.id} --level ${need}`;
187
+ if (access.level === 'private') {
188
+ refuse(403, 'PANE_PRIVATE',
189
+ `This pane is Private: the owner has not given an agent access. Ask for it: ${ask}`, { paneId: pane.id, agentAccess: access });
190
+ }
191
+ refuse(403, 'PANE_VIEW_ONLY',
192
+ `The owner gave an agent View only on this pane. Ask for control: ${ask}`, { paneId: pane.id, agentAccess: access });
193
+ }
194
+
195
+ // Some things are the owner's alone on the owner's own panes, whatever an
196
+ // agent has been given: ending the pane, resizing it, and changing the grant.
197
+ function requireOwner(pane, caller, verb) {
198
+ if (caller === 'owner' || pane.createdBy === 'agent') return;
199
+ refuse(403, 'OWNER_ONLY', `Only the owner can ${verb} one of the owner's panes.`, { paneId: pane.id, agentAccess: agentAccess(pane) });
200
+ }
201
+
202
+ function paneOr404(paneId) {
203
+ const pane = panes.get(paneId);
204
+ if (!pane) refuse(404, 'PANE_NOT_FOUND', 'Pane not found.');
205
+ return pane;
206
+ }
207
+
208
+ function tabOr404(tabId) {
209
+ const tab = tabs.get(tabId);
210
+ if (!tab) refuse(404, 'TAB_NOT_FOUND', 'Workspace tab not found.');
211
+ return tab;
212
+ }
213
+
214
+ // A pending ask, or null once it has waited long enough for an answer.
215
+ function currentRequest(pane) {
216
+ const request = pane.accessRequest;
217
+ if (!request) return null;
218
+ if (Date.now() - request.at > ACCESS_REQUEST_TTL_MS) {
219
+ pane.accessRequest = null;
220
+ return null;
221
+ }
222
+ return {
223
+ level: request.level,
224
+ label: ACCESS_LABEL[request.level],
225
+ message: request.message,
226
+ at: request.at,
227
+ expiresAt: request.at + ACCESS_REQUEST_TTL_MS
228
+ };
229
+ }
230
+
231
+ // "Not now" means the owner does not want to be asked about this pane for a
232
+ // while, whatever the level: a smaller or a larger ask both wait.
233
+ function recentlyDeclined(pane) {
234
+ const declined = pane.accessDeclined;
235
+ return Boolean(declined && Date.now() - declined.at <= ACCESS_DECLINE_TTL_MS);
236
+ }
237
+
238
+ // Changing the grant ends what an agent already holds on the pane, the way
239
+ // the terminal surface rotates a connection token: an output stream an agent
240
+ // is reading closes, and the long routes (waits, a queued action, a job that
241
+ // is being waited on) look again before they answer.
242
+ function setGrant(pane, level) {
243
+ const wasControl = ACCESS[agentAccess(pane).level];
244
+ pane.grant = level;
245
+ pane.accessRequest = null;
246
+ if (pane.kind === 'browser' && pane.browserId) browserWorkspace.grant(pane.browserId, level);
247
+ if (ACCESS[level] < wasControl) {
248
+ for (const stream of [...pane.streams]) if (stream.paneViewer === 'agent') stream.endPaneStream?.();
249
+ }
250
+ }
251
+
113
252
  function createTab(title, createdBy = 'human') {
114
253
  if (tabs.size >= MAX_TABS) {
115
254
  throw Object.assign(new Error('Close a workspace tab before opening another.'), { status: 409 });
@@ -193,6 +332,10 @@ function installWorkspacePanes(app, browserWorkspace, options = {}) {
193
332
  pane.exitCode = null;
194
333
  pane.exitSignal = null;
195
334
  pane.startedAt = Date.now();
335
+ // The widest the shell has been. What it printed was laid out for that many
336
+ // columns, and a viewer that is narrower must be told, so it can show the
337
+ // output at that width first (see the terminal mounting in public/panes.mjs).
338
+ pane.maxCols = Math.max(pane.maxCols || 0, pane.cols);
196
339
  const child = pty.spawn(shell, ['-l'], {
197
340
  name: 'xterm-256color', cols: pane.cols, rows: pane.rows,
198
341
  cwd: pane.cwd, env
@@ -227,19 +370,27 @@ function installWorkspacePanes(app, browserWorkspace, options = {}) {
227
370
  if (kind !== 'browser' && [...panes.values()].filter((pane) => pane.kind === 'terminal').length >= MAX_TERMINAL_PANES) {
228
371
  throw Object.assign(new Error('Close a terminal pane before opening another.'), { status: 409 });
229
372
  }
373
+ // createdBy is decided by the caller of this function from who asked, and
374
+ // is never taken from a request body: the routes pass the key's owner.
230
375
  const pane = {
231
376
  id: id('p'), tabId, kind: kind === 'browser' ? 'browser' : 'terminal',
232
377
  title: opts.title || '', titleLocked: Boolean(opts.title), url: '', browserId: null, pty: null,
233
378
  createdBy: opts.createdBy === 'agent' ? 'agent' : 'human',
379
+ // The owner's panes start Private. A grant lives in memory only: after a
380
+ // restart the panes come back empty, so an agent asks again rather than
381
+ // inheriting access given to something that no longer exists.
382
+ grant: 'private', accessRequest: null, accessDeclined: null,
234
383
  cwd: opts.cwd || null,
235
384
  buffer: '', bufferStart: 0, totalOffset: 0, streams: new Set(),
236
- cols: clampCols(opts.cols), rows: clampRows(opts.rows), exited: false,
385
+ cols: clampCols(opts.cols), rows: clampRows(opts.rows), maxCols: 0, exited: false,
237
386
  exitCode: null, exitSignal: null, lastOutputAt: Date.now(), createdAt: Date.now(),
238
387
  startedAt: null, exitedAt: null, jobs: [], liveJobs: 0,
239
388
  agentState: null, agentMessage: '', agentStateAt: null
240
389
  };
241
390
  if (pane.kind === 'browser') {
242
- const browser = await browserWorkspace.create('agent', opts.url);
391
+ // The page session records the same truth: an agent's pane is an agent
392
+ // context; one of the owner's panes is the owner's, and takes the grant.
393
+ const browser = await browserWorkspace.create(pane.createdBy === 'agent' ? 'agent' : 'human', opts.url);
243
394
  tab = tabs.get(tabId);
244
395
  if (!tab) {
245
396
  await browserWorkspace.close(browser.id).catch(() => {});
@@ -282,7 +433,9 @@ function installWorkspacePanes(app, browserWorkspace, options = {}) {
282
433
  ? Math.max(0, activeTab.panes.findIndex((pane) => pane.id === activePaneId))
283
434
  : 0;
284
435
  const payload = {
285
- version: 1,
436
+ // Version 2 is the first that can be trusted for ownership: it records
437
+ // who asked for each pane, as the server decided it.
438
+ version: 2,
286
439
  savedAt: new Date().toISOString(),
287
440
  activeTabIndex: activeIndex,
288
441
  activePaneIndex,
@@ -312,6 +465,9 @@ function installWorkspacePanes(app, browserWorkspace, options = {}) {
312
465
  catch (_) { return; }
313
466
  if (!saved || !Array.isArray(saved.tabs)) return;
314
467
  savedWorkspace = true;
468
+ // Written before ownership could be trusted; it is saved again in the
469
+ // current form once it has been read, so the migration happens once.
470
+ olderWorkspace = Number(saved.version || 1) < 2;
315
471
  for (const savedTab of saved.tabs.slice(0, MAX_TABS)) {
316
472
  const tab = createTab(
317
473
  typeof savedTab.title === 'string' ? savedTab.title : 'Workspace',
@@ -325,12 +481,22 @@ function installWorkspacePanes(app, browserWorkspace, options = {}) {
325
481
  const savedUrl = typeof savedPane.url === 'string' && savedPane.url !== 'about:blank'
326
482
  ? savedPane.url
327
483
  : undefined;
484
+ // Whose pane it is comes back with it. An agent's pane stays the
485
+ // agents' to use after a restart; one of the owner's comes back
486
+ // Private, because its grant was given to a pane that no longer
487
+ // exists. Before version 2 the seeded Orchestrator pane was recorded
488
+ // as the owner's, since nothing told the two apart: it is the place
489
+ // the agents work in, so an older workspace gets it back as theirs.
490
+ const legacyOrchestrator = Number(saved.version || 1) < 2 &&
491
+ savedPane.title === 'Orchestrator' && savedPane.kind !== 'browser' &&
492
+ savedPane.createdBy !== 'agent';
328
493
  await createPane(tab.id, savedPane.kind === 'browser' ? 'browser' : 'terminal', {
329
494
  title: typeof savedPane.title === 'string' ? savedPane.title : undefined,
330
495
  url: savedUrl,
331
496
  cwd: typeof savedPane.cwd === 'string' ? savedPane.cwd : undefined,
332
497
  cols: savedPane.cols,
333
- rows: savedPane.rows
498
+ rows: savedPane.rows,
499
+ createdBy: legacyOrchestrator || savedPane.createdBy === 'agent' ? 'agent' : 'human'
334
500
  });
335
501
  } catch (_) { /* one bad pane must not lose the rest of the workspace */ }
336
502
  }
@@ -344,7 +510,20 @@ function installWorkspacePanes(app, browserWorkspace, options = {}) {
344
510
  activePaneId = pane ? pane.id : (active.panes[0]?.id || null);
345
511
  }
346
512
 
347
- function serializePane(pane) {
513
+ // A pane as a caller may see it. The owner sees everything. An agent is
514
+ // shown the shape of a Private pane, and nothing in it: no title, address,
515
+ // working directory or status, only what an agent has and whether an ask of
516
+ // its own is waiting. So the agent can count the panes and ask about one,
517
+ // and cannot learn what the person is doing there.
518
+ function serializePane(pane, viewer = 'owner') {
519
+ const access = agentAccess(pane);
520
+ const request = currentRequest(pane);
521
+ if (viewer === 'agent' && pane.createdBy === 'human' && access.level === 'private') {
522
+ return {
523
+ id: pane.id, tabId: pane.tabId, kind: pane.kind, createdBy: 'human',
524
+ agentAccess: access, accessRequest: request, redacted: true
525
+ };
526
+ }
348
527
  if (pane.kind === 'browser' && pane.browserId) {
349
528
  const browser = browserWorkspace.get(pane.browserId);
350
529
  if (browser) {
@@ -365,6 +544,8 @@ function installWorkspacePanes(app, browserWorkspace, options = {}) {
365
544
  sizing: pane.kind === 'browser' ? pane.sizing : undefined,
366
545
  cwd: pane.kind === 'terminal' ? pane.cwd : undefined,
367
546
  cols: pane.cols, rows: pane.rows,
547
+ // The widest the shell has been; its output was laid out for at most this.
548
+ maxCols: pane.kind === 'terminal' ? Math.max(pane.maxCols || 0, pane.cols) : undefined,
368
549
  // Kept flat for existing callers; the three meanings are also exposed
369
550
  // separately below so they cannot be confused with one another.
370
551
  status: programStatus,
@@ -399,7 +580,11 @@ function installWorkspacePanes(app, browserWorkspace, options = {}) {
399
580
  startedAt: latestJob.startedAt,
400
581
  endedAt: latestJob.endedAt
401
582
  } : null,
583
+ // createdBy says whose pane it is; agentAccess says what an agent has on
584
+ // it now; accessRequest is an agent's unanswered ask.
402
585
  createdBy: pane.createdBy,
586
+ agentAccess: access,
587
+ accessRequest: request,
403
588
  active: pane.id === activePaneId
404
589
  };
405
590
  }
@@ -425,15 +610,20 @@ function installWorkspacePanes(app, browserWorkspace, options = {}) {
425
610
  }
426
611
  return payload;
427
612
  }
428
- function serializeTab(tab) {
429
- return { id: tab.id, title: tab.title, createdBy: tab.createdBy || 'human', active: tab.id === activeTabId, panes: tab.panes.map(serializePane) };
613
+ function serializeTab(tab, viewer = 'owner') {
614
+ return { id: tab.id, title: tab.title, createdBy: tab.createdBy || 'human', active: tab.id === activeTabId, panes: tab.panes.map((pane) => serializePane(pane, viewer)) };
430
615
  }
431
- function state() {
616
+ // viewer tells the caller how the server sees it, so a page whose key has
617
+ // gone stale (the server restarted) knows to renew it instead of quietly
618
+ // drawing an agent's view of the person's own panes.
619
+ function state(viewer = 'owner') {
432
620
  return {
433
621
  host: os.hostname().replace(/\.local$/i, '').toLowerCase(),
434
622
  epoch,
623
+ seq: ++stateSeq,
435
624
  restored,
436
- tabs: [...tabs.values()].map(serializeTab),
625
+ viewer,
626
+ tabs: [...tabs.values()].map((tab) => serializeTab(tab, viewer)),
437
627
  activeTabId, activePaneId,
438
628
  limits: { maxTabs: MAX_TABS, maxPanesPerTab: MAX_PANES_PER_TAB, maxTerminalPanes: MAX_TERMINAL_PANES }
439
629
  };
@@ -446,9 +636,17 @@ function installWorkspacePanes(app, browserWorkspace, options = {}) {
446
636
  .catch(() => { /* corrupt state is not fatal */ })
447
637
  .then(async () => {
448
638
  restored = true;
639
+ if (olderWorkspace) {
640
+ olderWorkspace = false;
641
+ await saveState().catch(() => { /* the next change retries */ });
642
+ }
449
643
  if (savedWorkspace || tabs.size) return;
450
644
  const tab = createTab('Workspace 1');
451
- const pane = await createPane(tab.id, 'terminal', { title: 'Orchestrator' });
645
+ // The Orchestrator pane is the place an agent works in: the person
646
+ // starts one there, and it reports and runs from inside it. It is
647
+ // the agents' pane from the first moment; what the person adds is
648
+ // theirs.
649
+ const pane = await createPane(tab.id, 'terminal', { title: 'Orchestrator', createdBy: 'agent' });
452
650
  activeTabId = tab.id;
453
651
  activePaneId = pane.id;
454
652
  });
@@ -629,15 +827,17 @@ function installWorkspacePanes(app, browserWorkspace, options = {}) {
629
827
  };
630
828
  }
631
829
 
830
+ // The owner's key leaves only with the owner's page. The proof and its
831
+ // refusals are shared with the single-browser workspace's bootstrap.
632
832
  app.get('/api/panes/bootstrap', route(async (req, res) => {
633
- if (req.get('Authorization')) throw Object.assign(new Error('Agent tokens cannot bootstrap the owner workspace.'), { status: 403 });
634
- if (!req.isOwner) throw Object.assign(new Error('Owner page required.'), { status: 403 });
635
- const site = req.get('Sec-Fetch-Site');
636
- if (site && site !== 'same-origin' && site !== 'none') throw Object.assign(new Error('Owner page required.'), { status: 403 });
833
+ const refused = ownerPageRefusal(req);
834
+ if (refused) throw Object.assign(new Error(refused.body.error), { status: refused.status, body: refused.body });
637
835
  await ensureInitial();
638
- res.json({ token, state: state(), api: apiUrl });
836
+ // ownerKey is the page's own key for this server run. The page sends it
837
+ // from here on; it never needs the agents' token.
838
+ res.json({ token, ownerKey: pageKey, state: state('owner'), api: apiUrl });
639
839
  }));
640
- app.get('/api/panes/state', auth, route(async (req, res) => { await ensureInitial(); res.json(state()); }));
840
+ app.get('/api/panes/state', auth, route(async (req, res) => { await ensureInitial(); res.json(state(req.caller)); }));
641
841
 
642
842
  // The instruction sheet an agent gets when it connects. It describes the
643
843
  // tools and this connection's permissions; it never enlarges them.
@@ -656,7 +856,10 @@ function installWorkspacePanes(app, browserWorkspace, options = {}) {
656
856
  }));
657
857
  app.post('/api/panes/tabs', auth, route(async (req, res) => {
658
858
  await ensureInitial();
659
- const createdBy = req.body.createdBy === 'agent' ? 'agent' : 'human';
859
+ // The key that asks decides whose tab it is. createdBy in the body is
860
+ // ignored: it was how a client described itself, and trusting it let an
861
+ // agent label a tab as the owner's.
862
+ const createdBy = req.caller === 'owner' ? 'human' : 'agent';
660
863
  const tab = createTab(typeof req.body.title === 'string' ? req.body.title.slice(0, 80) : '', createdBy);
661
864
  const activate = req.body.activate === true || (createdBy === 'human' && req.body.activate !== false);
662
865
  if (activate) {
@@ -664,11 +867,15 @@ function installWorkspacePanes(app, browserWorkspace, options = {}) {
664
867
  activePaneId = tab.panes[0]?.id || null;
665
868
  scheduleSave();
666
869
  }
667
- res.json(serializeTab(tab));
870
+ res.json(serializeTab(tab, req.caller));
668
871
  }));
669
872
  app.delete('/api/panes/tabs/:id', auth, route(async (req, res) => {
670
- const tab = tabs.get(req.params.id);
671
- if (!tab) { res.status(404).json({ error: 'Workspace tab not found.' }); return; }
873
+ const tab = tabOr404(req.params.id);
874
+ // Closing a tab ends every pane in it, and one of the owner's panes is
875
+ // the owner's to end however much an agent has been given on it.
876
+ if (req.caller !== 'owner' && tab.panes.some((pane) => pane.createdBy === 'human')) {
877
+ refuse(403, 'OWNER_ONLY', "This tab holds one of the owner's panes, so only the owner can close it.", { tabId: tab.id });
878
+ }
672
879
  for (const pane of [...tab.panes]) closePane(pane);
673
880
  tabs.delete(tab.id);
674
881
  if (activeTabId === tab.id) {
@@ -677,20 +884,22 @@ function installWorkspacePanes(app, browserWorkspace, options = {}) {
677
884
  activePaneId = next?.panes[0]?.id || null;
678
885
  }
679
886
  scheduleSave();
680
- res.json({ closed: true, state: state() });
887
+ res.json({ closed: true, state: state(req.caller) });
681
888
  }));
682
889
  app.post('/api/panes/tabs/:id/panes', auth, route(async (req, res) => {
683
890
  await ensureInitial();
891
+ // A pane belongs to whoever opens it: the owner's page or an agent's key.
892
+ // An agent may add a pane of its own beside the owner's; it reads nothing
893
+ // by doing so.
684
894
  const pane = await createPane(req.params.id, req.body.kind, {
685
895
  url: req.body.url, cwd: req.body.cwd, title: req.body.title,
686
896
  cols: req.body.cols, rows: req.body.rows, start: req.body.start,
687
- createdBy: req.body.createdBy
897
+ createdBy: req.caller === 'owner' ? 'human' : 'agent'
688
898
  });
689
- res.json(serializePane(pane));
899
+ res.json(serializePane(pane, req.caller));
690
900
  }));
691
901
  app.post('/api/panes/panes/:id/status', auth, route(async (req, res) => {
692
- const pane = panes.get(req.params.id);
693
- if (!pane || pane.kind !== 'terminal') { res.status(400).json({ error: 'Terminal pane required.' }); return; }
902
+ const pane = terminalPane(req.params.id, req.caller, 'control');
694
903
  const state = String(req.body.state || '').toLowerCase();
695
904
  if (!['working', 'blocked', 'idle', 'done', 'unknown'].includes(state)) {
696
905
  res.status(400).json({ error: 'State must be working, blocked, idle, done, or unknown.' });
@@ -700,11 +909,10 @@ function installWorkspacePanes(app, browserWorkspace, options = {}) {
700
909
  pane.agentMessage = String(req.body.message || '').slice(0, 1000);
701
910
  pane.agentStateAt = Date.now();
702
911
  scheduleSave();
703
- res.json(serializePane(pane));
912
+ res.json(serializePane(pane, req.caller));
704
913
  }));
705
914
  app.post('/api/panes/panes/:id/start', auth, route(async (req, res) => {
706
- const pane = panes.get(req.params.id);
707
- if (!pane || pane.kind !== 'terminal') { res.status(400).json({ error: 'Terminal pane required.' }); return; }
915
+ const pane = terminalPane(req.params.id, req.caller, 'control');
708
916
  if (pane.exited) { res.status(409).json({ error: 'Terminal pane has exited.' }); return; }
709
917
  if (!pane.pty) {
710
918
  pane.cols = clampCols(req.body.cols);
@@ -712,52 +920,144 @@ function installWorkspacePanes(app, browserWorkspace, options = {}) {
712
920
  startPanePty(pane);
713
921
  scheduleSave();
714
922
  }
715
- res.json(serializePane(pane));
923
+ res.json(serializePane(pane, req.caller));
716
924
  }));
717
925
  app.post('/api/panes/tabs/:id/reorder', auth, route(async (req, res) => {
718
- const tab = tabs.get(req.params.id);
719
- if (!tab) { res.status(404).json({ error: 'Workspace tab not found.' }); return; }
926
+ const tab = tabOr404(req.params.id);
720
927
  const from = tab.panes.findIndex((pane) => pane.id === req.body.paneId);
721
928
  if (from < 0) { res.status(404).json({ error: 'Pane not found in this tab.' }); return; }
929
+ // An agent may arrange its own panes, not the owner's.
930
+ requireOwner(tab.panes[from], req.caller, 'move');
722
931
  const to = Math.max(0, Math.min(tab.panes.length - 1, Math.round(Number(req.body.index))));
723
- if (!Number.isFinite(to) || to === from) { res.json(state()); return; }
932
+ if (!Number.isFinite(to) || to === from) { res.json(state(req.caller)); return; }
724
933
  const [pane] = tab.panes.splice(from, 1);
725
934
  tab.panes.splice(to, 0, pane);
726
935
  scheduleSave();
727
- res.json(state());
936
+ res.json(state(req.caller));
728
937
  }));
729
938
  app.delete('/api/panes/panes/:id', auth, route(async (req, res) => {
730
- const pane = panes.get(req.params.id);
731
- if (!pane) { res.status(404).json({ error: 'Pane not found.' }); return; }
939
+ const pane = paneOr404(req.params.id);
940
+ requireOwner(pane, req.caller, 'close');
732
941
  closePane(pane);
733
- res.json({ closed: true, state: state() });
942
+ res.json({ closed: true, state: state(req.caller) });
734
943
  }));
735
944
  app.post('/api/panes/active', auth, route(async (req, res) => {
945
+ // What is active is what the person is looking at and typing into. An
946
+ // agent may bring one of its own panes forward to show it; it may not
947
+ // move the person onto one of the owner's panes.
948
+ const pane = req.body.paneId ? panes.get(req.body.paneId) : null;
949
+ const tab = req.body.tabId ? tabs.get(req.body.tabId) : null;
950
+ if (req.caller !== 'owner') {
951
+ if (pane && pane.createdBy === 'human') requireOwner(pane, req.caller, 'bring');
952
+ if (tab && !tab.panes.some((candidate) => candidate.createdBy === 'agent')) {
953
+ refuse(403, 'OWNER_ONLY', "This tab holds only the owner's panes, so only the owner can switch to it.", { tabId: tab.id });
954
+ }
955
+ }
736
956
  if (req.body.tabId && tabs.has(req.body.tabId)) activeTabId = req.body.tabId;
737
957
  if (req.body.paneId && panes.has(req.body.paneId)) activePaneId = req.body.paneId;
738
958
  scheduleSave();
739
- res.json(state());
959
+ res.json(state(req.caller));
740
960
  }));
961
+
962
+ // ── The grant, and the one way an agent asks for it ──────────────────────
963
+
964
+ // Only the owner changes what an agent may do on one of the owner's panes.
965
+ // Setting a level also answers any pending ask, and lowering one ends what
966
+ // agents already hold on the pane (see setGrant).
967
+ app.post('/api/panes/panes/:id/permission', auth, route(async (req, res) => {
968
+ const pane = paneOr404(req.params.id);
969
+ if (req.caller !== 'owner') refuse(403, 'OWNER_ONLY', 'Only the owner can change what an agent may do on a pane.', { paneId: pane.id, agentAccess: agentAccess(pane) });
970
+ if (pane.createdBy === 'agent') refuse(409, 'AGENT_PANE', 'An agent opened this pane, so agents always have control of it. To keep a pane private, open one of your own.', { paneId: pane.id });
971
+ const level = String(req.body.permission || '');
972
+ if (!Object.hasOwn(ACCESS, level)) { res.status(400).json({ error: 'Agent access must be private, view, or control.' }); return; }
973
+ setGrant(pane, level);
974
+ res.json(state(req.caller));
975
+ }));
976
+
977
+ // An agent asks for access to one of the owner's panes. The ask appears on
978
+ // that pane for the owner to answer. It clears itself unanswered, and a pane
979
+ // the owner just said not now to cannot be asked about for a while.
980
+ app.post('/api/panes/panes/:id/request-access', auth, route(async (req, res) => {
981
+ const pane = paneOr404(req.params.id);
982
+ if (req.caller === 'owner') refuse(403, 'AGENT_ONLY', 'The owner does not ask: set the pane\'s agent access instead.', { paneId: pane.id });
983
+ if (pane.createdBy === 'agent') refuse(409, 'AGENT_PANE', 'Agents already have control of this pane; there is nothing to ask for.', { paneId: pane.id });
984
+ const level = String(req.body.level || '');
985
+ if (!Object.hasOwn(ACCESS, level) || level === 'private') { res.status(400).json({ error: 'Ask for view or control.' }); return; }
986
+ const access = agentAccess(pane);
987
+ if (ACCESS[access.level] >= ACCESS[level]) {
988
+ refuse(409, 'ALREADY_GRANTED', `Agents already have ${access.label} on this pane; there is nothing to ask for.`, { paneId: pane.id, agentAccess: access });
989
+ }
990
+ const pending = currentRequest(pane);
991
+ if (pending && ACCESS[pending.level] >= ACCESS[level]) {
992
+ // The same ask, or a smaller one, is already waiting: one prompt per pane.
993
+ res.json(serializePane(pane, req.caller));
994
+ return;
995
+ }
996
+ if (recentlyDeclined(pane)) {
997
+ refuse(409, 'DECLINED', `The owner said not now to ${ACCESS_LABEL[pane.accessDeclined.level]} on this pane a moment ago, so this pane cannot be asked about yet. Finish without it, or wait for the owner to change what an agent may do there.`, { paneId: pane.id, agentAccess: access });
998
+ }
999
+ const message = String(req.body.message || '').replace(/\s+/g, ' ').trim().slice(0, 300);
1000
+ pane.accessRequest = { level, message, at: Date.now() };
1001
+ res.json(serializePane(pane, req.caller));
1002
+ }));
1003
+
1004
+ // The owner dismisses an ask ("not now": the grant is left as it is), or an
1005
+ // agent withdraws its own.
1006
+ app.delete('/api/panes/panes/:id/request-access', auth, route(async (req, res) => {
1007
+ const pane = paneOr404(req.params.id);
1008
+ if (req.caller === 'owner' && pane.accessRequest) {
1009
+ pane.accessDeclined = { level: pane.accessRequest.level, at: Date.now() };
1010
+ }
1011
+ pane.accessRequest = null;
1012
+ res.json(serializePane(pane, req.caller));
1013
+ }));
1014
+
1015
+ // ── Browser panes ────────────────────────────────────────────────────────
1016
+ //
1017
+ // Reading a page (the picture, the catalog, the text, a wait) needs View
1018
+ // only. Moving it (an address, an action, a dialog, its size) needs Allow
1019
+ // control. Each route checks before the work and again after it, because a
1020
+ // grant can be lowered while a capture or a wait is running.
1021
+
1022
+ // Lookup in the order that tells an agent least: a missing pane, then
1023
+ // whether this caller may use it, and only then whether it is a browser.
1024
+ function browserPane(paneId, caller, need) {
1025
+ const pane = paneOr404(paneId);
1026
+ requireAccess(pane, caller, need);
1027
+ if (pane.kind !== 'browser') throw Object.assign(new Error('Browser pane required.'), { status: 400 });
1028
+ return pane;
1029
+ }
1030
+ function terminalPane(paneId, caller, need) {
1031
+ const pane = paneOr404(paneId);
1032
+ requireAccess(pane, caller, need);
1033
+ if (pane.kind !== 'terminal') throw Object.assign(new Error('Terminal pane required.'), { status: 400 });
1034
+ return pane;
1035
+ }
1036
+
741
1037
  app.post('/api/panes/panes/:id/url', auth, route(async (req, res) => {
742
- const pane = panes.get(req.params.id);
743
- if (!pane || pane.kind !== 'browser') { res.status(400).json({ error: 'Browser pane required.' }); return; }
1038
+ const pane = browserPane(req.params.id, req.caller, 'control');
744
1039
  const browser = await browserWorkspace.navigate(pane.browserId, req.body.url);
1040
+ requireAccess(pane, req.caller, 'control');
745
1041
  pane.url = browser.url;
746
1042
  if (!pane.titleLocked) pane.title = browser.title || pane.title;
747
1043
  scheduleSave();
748
- res.json(serializePane(pane));
1044
+ res.json(serializePane(pane, req.caller));
749
1045
  }));
750
1046
  app.post('/api/panes/panes/:id/browser/action', auth, route(async (req, res) => {
751
- const pane = panes.get(req.params.id);
752
- if (!pane || pane.kind !== 'browser') { res.status(400).json({ error: 'Browser pane required.' }); return; }
753
- const outcome = await browserWorkspace.action(pane.browserId, req.body.action, req.body);
1047
+ const pane = browserPane(req.params.id, req.caller, 'control');
1048
+ const outcome = await browserWorkspace.action(pane.browserId, req.body.action, req.body, {
1049
+ // Actions queue behind captures and navigations. This is checked again
1050
+ // inside the queue, so a grant lowered a moment ago stops the action.
1051
+ authorize: () => requireAccess(pane, req.caller, 'control')
1052
+ });
1053
+ requireAccess(pane, req.caller, 'control');
754
1054
  pane.url = outcome.url;
755
1055
  if (!pane.titleLocked) pane.title = outcome.title || pane.title;
756
1056
  if (!['click', 'type', 'key', 'scroll', 'select', 'setValue', 'selectAt', 'setValueAt', 'hover', 'drag'].includes(req.body.action)) scheduleSave();
757
1057
  // The action result is nested so it cannot be mistaken for the pane's
758
1058
  // program status; those are three different meanings of "status".
759
1059
  res.status(outcome.httpStatus || 200).json({
760
- ...serializePane(pane),
1060
+ ...serializePane(pane, req.caller),
761
1061
  // Flat `control` stays for the human viewer's picker overlay.
762
1062
  control: outcome.control || null,
763
1063
  action: {
@@ -772,67 +1072,75 @@ function installWorkspacePanes(app, browserWorkspace, options = {}) {
772
1072
  });
773
1073
  }));
774
1074
  app.post('/api/panes/panes/:id/browser/reopen', auth, route(async (req, res) => {
775
- const pane = panes.get(req.params.id);
776
- if (!pane || pane.kind !== 'browser') { res.status(400).json({ error: 'Browser pane required.' }); return; }
1075
+ const pane = browserPane(req.params.id, req.caller, 'control');
777
1076
  const previous = pane.browserId;
778
- const browser = await browserWorkspace.create('agent', req.body.url);
1077
+ const browser = await browserWorkspace.create(pane.createdBy === 'agent' ? 'agent' : 'human', req.body.url);
1078
+ browserWorkspace.grant(browser.id, agentAccess(pane).level);
779
1079
  pane.browserId = browser.id;
780
1080
  pane.url = browser.url && browser.url !== 'about:blank' ? browser.url : 'about:blank';
781
1081
  if (!pane.titleLocked) pane.title = browser.title || 'Browser';
782
1082
  if (previous) await browserWorkspace.close(previous).catch(() => {});
783
1083
  scheduleSave();
784
- res.json(serializePane(pane));
1084
+ res.json(serializePane(pane, req.caller));
785
1085
  }));
786
1086
  app.post('/api/panes/panes/:id/browser/dialog', auth, route(async (req, res) => {
787
- const pane = panes.get(req.params.id);
788
- if (!pane || pane.kind !== 'browser') { res.status(400).json({ error: 'Browser pane required.' }); return; }
1087
+ const pane = browserPane(req.params.id, req.caller, 'control');
789
1088
  const browser = await browserWorkspace.respondDialog(pane.browserId, req.body.action, req.body.text);
1089
+ requireAccess(pane, req.caller, 'view');
790
1090
  res.json(browser);
791
1091
  }));
1092
+ // A viewer sends `watch`: `watch=1` while its pane is on screen (the request
1093
+ // waits for the next picture, up to `wait` ms), `watch=0` for its title,
1094
+ // address and page prompt only. Without `watch` a picture is taken for the
1095
+ // caller there and then; an agent's `observe` takes its own, separately.
792
1096
  app.get('/api/panes/panes/:id/browser/snapshot', auth, route(async (req, res) => {
793
- const pane = panes.get(req.params.id);
794
- if (!pane || pane.kind !== 'browser') { res.status(400).json({ error: 'Browser pane required.' }); return; }
795
- const snap = await browserWorkspace.snapshot(pane.browserId);
1097
+ const pane = browserPane(req.params.id, req.caller, 'view');
1098
+ const snap = await browserWorkspace.snapshot(pane.browserId, browserWorkspace.viewerRequest(req, res));
1099
+ if (!snap) return; // The viewer went away while its request waited.
1100
+ requireAccess(pane, req.caller, 'view');
796
1101
  pane.url = snap.url;
797
1102
  if (!pane.titleLocked) pane.title = snap.title || pane.title;
798
1103
  res.json(snap);
799
1104
  }));
800
1105
  app.get('/api/panes/panes/:id/browser/observe', auth, route(async (req, res) => {
801
- const pane = panes.get(req.params.id);
802
- if (!pane || pane.kind !== 'browser') { res.status(400).json({ error: 'Browser pane required.' }); return; }
1106
+ const pane = browserPane(req.params.id, req.caller, 'view');
803
1107
  const observed = await browserWorkspace.observe(pane.browserId, {
804
1108
  elements: req.query.elements === '1' || req.query.elements === 'true',
805
1109
  max: req.query.max
806
1110
  });
1111
+ requireAccess(pane, req.caller, 'view');
807
1112
  pane.url = observed.url;
808
1113
  if (!pane.titleLocked) pane.title = observed.title || pane.title;
809
1114
  res.json(observed);
810
1115
  }));
811
1116
  app.get('/api/panes/panes/:id/browser/elements', auth, route(async (req, res) => {
812
- const pane = panes.get(req.params.id);
813
- if (!pane || pane.kind !== 'browser') { res.status(400).json({ error: 'Browser pane required.' }); return; }
1117
+ const pane = browserPane(req.params.id, req.caller, 'view');
814
1118
  const catalogued = await browserWorkspace.elements(pane.browserId, { max: req.query.max });
1119
+ requireAccess(pane, req.caller, 'view');
815
1120
  pane.url = catalogued.url;
816
1121
  if (!pane.titleLocked) pane.title = catalogued.title || pane.title;
817
1122
  res.json(catalogued);
818
1123
  }));
819
1124
  app.post('/api/panes/panes/:id/browser/wait', auth, route(async (req, res) => {
820
- const pane = panes.get(req.params.id);
821
- if (!pane || pane.kind !== 'browser') { res.status(400).json({ error: 'Browser pane required.' }); return; }
822
- res.json(await browserWorkspace.wait(pane.browserId, req.body || {}));
1125
+ const pane = browserPane(req.params.id, req.caller, 'view');
1126
+ const waited = await browserWorkspace.wait(pane.browserId, req.body || {}, {
1127
+ interrupted: () => !hasAccess(pane, req.caller, 'view')
1128
+ });
1129
+ requireAccess(pane, req.caller, 'view');
1130
+ res.json(waited);
823
1131
  }));
824
1132
  app.post('/api/panes/panes/:id/browser/sizing', auth, route(async (req, res) => {
825
- const pane = panes.get(req.params.id);
826
- if (!pane || pane.kind !== 'browser') { res.status(400).json({ error: 'Browser pane required.' }); return; }
1133
+ const pane = browserPane(req.params.id, req.caller, 'control');
827
1134
  const size = await browserWorkspace.sizing(pane.browserId, req.body.mode, req.body);
1135
+ requireAccess(pane, req.caller, 'view');
828
1136
  res.json(size);
829
1137
  }));
830
1138
  app.get('/api/panes/panes/:id/browser/content', auth, route(async (req, res) => {
831
- const pane = panes.get(req.params.id);
832
- if (!pane || pane.kind !== 'browser') { res.status(400).json({ error: 'Browser pane required.' }); return; }
1139
+ const pane = browserPane(req.params.id, req.caller, 'view');
833
1140
  const browser = browserWorkspace.get(pane.browserId);
834
1141
  if (!browser) { res.status(404).json({ error: 'Browser pane no longer exists.' }); return; }
835
1142
  const info = await browserWorkspace.content(pane.browserId, { limit: req.query.limit });
1143
+ requireAccess(pane, req.caller, 'view');
836
1144
  res.json({
837
1145
  url: info.url,
838
1146
  title: info.title || browser.title || pane.title,
@@ -843,10 +1151,18 @@ function installWorkspacePanes(app, browserWorkspace, options = {}) {
843
1151
  frames: info.frames
844
1152
  });
845
1153
  }));
1154
+ // ── Terminal panes ────────────────────────────────────────────────────────
1155
+ //
1156
+ // Reading a terminal (the stream, the buffer, screen text, a wait, a job's
1157
+ // output) needs View only. Writing to it (input, keys, a typed line, a job,
1158
+ // a status) needs Allow control. Resizing and closing stay the owner's.
1159
+
846
1160
  app.get('/api/panes/panes/:id/stream', auth, (req, res) => {
847
- const pane = panes.get(req.params.id);
848
- if (!pane || pane.kind !== 'terminal') {
849
- res.status(400).json({ error: 'Terminal pane required.' });
1161
+ let pane;
1162
+ try { pane = terminalPane(req.params.id, req.caller, 'view'); }
1163
+ catch (error) {
1164
+ // This route writes its own response, so the refusal is written here.
1165
+ res.status(error.status || 400).json(error.body || { error: error.message });
850
1166
  return;
851
1167
  }
852
1168
  if (activeStreams >= MAX_ACTIVE_STREAMS) {
@@ -867,6 +1183,9 @@ function installWorkspacePanes(app, browserWorkspace, options = {}) {
867
1183
  // the handshake cannot leak a stream slot forever.
868
1184
  req.on('close', end);
869
1185
  res.on('close', end);
1186
+ // Lowering the grant ends the streams agents are reading on this pane.
1187
+ res.paneViewer = req.caller;
1188
+ res.endPaneStream = () => { try { res.end(); } catch (_) { /* already gone */ } end(); };
870
1189
  res.writeHead(200, {
871
1190
  'Content-Type': 'text/event-stream',
872
1191
  'Cache-Control': 'no-store',
@@ -885,21 +1204,20 @@ function installWorkspacePanes(app, browserWorkspace, options = {}) {
885
1204
  ping.unref?.();
886
1205
  });
887
1206
  app.get('/api/panes/panes/:id/read', auth, route(async (req, res) => {
888
- const pane = panes.get(req.params.id);
889
- if (!pane || pane.kind !== 'terminal') { res.status(400).json({ error: 'Terminal pane required.' }); return; }
1207
+ const pane = terminalPane(req.params.id, req.caller, 'view');
890
1208
  let since = Math.max(0, Number(req.query.since) || 0);
891
1209
  if (since < pane.bufferStart) since = pane.bufferStart;
892
1210
  res.json({ data: pane.buffer.slice(since - pane.bufferStart), offset: pane.totalOffset, exited: pane.exited });
893
1211
  }));
894
1212
  app.post('/api/panes/panes/:id/input', auth, route(async (req, res) => {
895
- const pane = panes.get(req.params.id);
896
- if (!pane || pane.kind !== 'terminal' || !pane.pty) { res.status(400).json({ error: 'Terminal pane required.' }); return; }
1213
+ const pane = terminalPane(req.params.id, req.caller, 'control');
1214
+ if (!pane.pty) { res.status(400).json({ error: 'Terminal pane required.' }); return; }
897
1215
  pane.pty.write(String(req.body.data ?? ''));
898
1216
  res.json({ ok: true });
899
1217
  }));
900
1218
  app.post('/api/panes/panes/:id/keys', auth, route(async (req, res) => {
901
- const pane = panes.get(req.params.id);
902
- if (!pane || pane.kind !== 'terminal' || !pane.pty) { res.status(400).json({ error: 'Terminal pane required.' }); return; }
1219
+ const pane = terminalPane(req.params.id, req.caller, 'control');
1220
+ if (!pane.pty) { res.status(400).json({ error: 'Terminal pane required.' }); return; }
903
1221
  const keys = Array.isArray(req.body.keys) ? req.body.keys : [req.body.key];
904
1222
  if (!keys.length || keys.length > 32) { res.status(400).json({ error: 'Send between 1 and 32 keys.' }); return; }
905
1223
  const sequence = keys.map(keySequence).join('');
@@ -908,8 +1226,7 @@ function installWorkspacePanes(app, browserWorkspace, options = {}) {
908
1226
  res.json({ ok: true, bytes: sequence.length });
909
1227
  }));
910
1228
  app.get('/api/panes/panes/:id/wait', auth, route(async (req, res) => {
911
- const pane = panes.get(req.params.id);
912
- if (!pane || pane.kind !== 'terminal') { res.status(400).json({ error: 'Terminal pane required.' }); return; }
1229
+ const pane = terminalPane(req.params.id, req.caller, 'view');
913
1230
  const timeout = Math.max(100, Math.min(120000, Number(req.query.timeout) || 30000));
914
1231
  const since = req.query.since === undefined ? pane.totalOffset : Math.max(0, Number(req.query.since) || 0);
915
1232
  const match = typeof req.query.match === 'string' ? req.query.match : '';
@@ -958,6 +1275,10 @@ function installWorkspacePanes(app, browserWorkspace, options = {}) {
958
1275
  res.on('close', () => finish({ aborted: true }));
959
1276
  const run = async () => {
960
1277
  while (!finished) {
1278
+ // A wait can hold a caller for two minutes. If the owner takes
1279
+ // the pane back in that time, the wait ends with nothing rather
1280
+ // than answering a question about a pane it may no longer read.
1281
+ if (!hasAccess(pane, req.caller, 'view')) return finish({ aborted: true });
961
1282
  const data = pane.buffer.slice(Math.max(0, since - pane.bufferStart));
962
1283
  if (state && pane.agentState === (state === 'unknown' ? null : state)) return snapshot(true, 'state');
963
1284
  if (match && data.includes(match)) return snapshot(true, 'match');
@@ -982,11 +1303,14 @@ function installWorkspacePanes(app, browserWorkspace, options = {}) {
982
1303
  if (!res.writableEnded) res.status(result.status || 400).json({ error: result.error });
983
1304
  return;
984
1305
  }
1306
+ requireAccess(pane, req.caller, 'view');
985
1307
  if (!res.writableEnded) res.json(result);
986
1308
  }));
987
1309
  app.post('/api/panes/panes/:id/resize', auth, route(async (req, res) => {
988
- const pane = panes.get(req.params.id);
989
- if (!pane) { res.status(400).json({ error: 'Pane required.' }); return; }
1310
+ // A pane's size is how the owner's viewer lays it out; an agent does not
1311
+ // rearrange what the person is looking at.
1312
+ const pane = paneOr404(req.params.id);
1313
+ requireOwner(pane, req.caller, 'resize');
990
1314
  if (pane.kind === 'browser') {
991
1315
  const size = await browserWorkspace.setViewport(pane.browserId, req.body.width, req.body.height);
992
1316
  res.json(size);
@@ -999,12 +1323,17 @@ function installWorkspacePanes(app, browserWorkspace, options = {}) {
999
1323
  res.json({ cols: pane.cols, rows: pane.rows });
1000
1324
  return;
1001
1325
  }
1326
+ // Let output the shell wrote before this request be read first, so that the
1327
+ // point named below is exact. A viewer shows what came before that point at
1328
+ // the width the shell had (see public/panes.mjs, a terminal that opened at
1329
+ // the shell's width), and is fitted to its pane afterwards.
1330
+ await new Promise((resolve) => setImmediate(resolve));
1331
+ pane.maxCols = Math.max(pane.maxCols || 0, pane.cols);
1002
1332
  pane.pty.resize(pane.cols, pane.rows);
1003
- res.json({ cols: pane.cols, rows: pane.rows });
1333
+ res.json({ cols: pane.cols, rows: pane.rows, offset: pane.totalOffset });
1004
1334
  }));
1005
1335
  app.get('/api/panes/panes/:id/text', auth, route(async (req, res) => {
1006
- const pane = panes.get(req.params.id);
1007
- if (!pane || pane.kind !== 'terminal') { res.status(400).json({ error: 'Terminal pane required.' }); return; }
1336
+ const pane = terminalPane(req.params.id, req.caller, 'view');
1008
1337
  const mode = req.query.mode === 'raw' ? 'raw' : 'clean';
1009
1338
  const since = req.query.since === undefined ? pane.bufferStart : Number(req.query.since);
1010
1339
  if (mode === 'raw') {
@@ -1030,29 +1359,29 @@ function installWorkspacePanes(app, browserWorkspace, options = {}) {
1030
1359
  }));
1031
1360
 
1032
1361
  app.post('/api/panes/panes/:id/jobs', auth, route(async (req, res) => {
1033
- const pane = panes.get(req.params.id);
1034
- if (!pane || pane.kind !== 'terminal') { res.status(400).json({ error: 'Terminal pane required.' }); return; }
1362
+ const pane = terminalPane(req.params.id, req.caller, 'control');
1035
1363
  const command = String(req.body.command || '').replace(/\r?\n$/, '');
1036
1364
  if (!command.trim()) { res.status(400).json({ error: 'command must not be empty.' }); return; }
1037
1365
  if (command.length > 10000) { res.status(400).json({ error: 'command is too long.' }); return; }
1038
1366
  const job = startJob(pane, command);
1039
1367
  const wait = req.body.wait !== false;
1040
1368
  if (wait) await waitForJob(job, req.body.timeoutMs);
1369
+ // The wait can last two minutes. The command was started with the grant
1370
+ // the agent had; its output leaves only if the agent may still read.
1371
+ requireAccess(pane, req.caller, 'view');
1041
1372
  scheduleSave();
1042
1373
  res.status(202).json(serializeJob(job));
1043
1374
  }));
1044
1375
 
1045
1376
  app.get('/api/panes/panes/:id/jobs/:jobId', auth, route(async (req, res) => {
1046
- const pane = panes.get(req.params.id);
1047
- if (!pane || pane.kind !== 'terminal') { res.status(400).json({ error: 'Terminal pane required.' }); return; }
1377
+ const pane = terminalPane(req.params.id, req.caller, 'view');
1048
1378
  const job = pane.jobs.find((candidate) => candidate.id === req.params.jobId);
1049
1379
  if (!job) { res.status(404).json({ error: 'Job not found.' }); return; }
1050
1380
  res.json(serializeJob(job));
1051
1381
  }));
1052
1382
 
1053
1383
  app.delete('/api/panes/panes/:id/jobs/:jobId', auth, route(async (req, res) => {
1054
- const pane = panes.get(req.params.id);
1055
- if (!pane || pane.kind !== 'terminal') { res.status(400).json({ error: 'Terminal pane required.' }); return; }
1384
+ const pane = terminalPane(req.params.id, req.caller, 'control');
1056
1385
  const job = pane.jobs.find((candidate) => candidate.id === req.params.jobId);
1057
1386
  if (!job) { res.status(404).json({ error: 'Job not found.' }); return; }
1058
1387
  const cancelled = cancelJob(job);
@@ -1060,11 +1389,12 @@ function installWorkspacePanes(app, browserWorkspace, options = {}) {
1060
1389
  }));
1061
1390
 
1062
1391
  app.post('/api/panes/panes/:id/command', auth, route(async (req, res) => {
1063
- const pane = panes.get(req.params.id);
1064
- if (!pane || pane.kind !== 'terminal' || !pane.pty) { res.status(400).json({ error: 'Terminal pane required.' }); return; }
1392
+ const pane = terminalPane(req.params.id, req.caller, 'control');
1393
+ if (!pane.pty) { res.status(400).json({ error: 'Terminal pane required.' }); return; }
1065
1394
  const command = String(req.body.command || '').replace(/\r?\n$/, '');
1066
1395
  pane.pty.write(command + '\n');
1067
1396
  await new Promise((resolve) => setTimeout(resolve, Number(req.body.waitMs) || 300));
1397
+ requireAccess(pane, req.caller, 'view');
1068
1398
  // This proves the line was written and shows recent output. It does not
1069
1399
  // prove the command finished; use POST /jobs for that.
1070
1400
  res.json({
@@ -1093,7 +1423,9 @@ function installWorkspacePanes(app, browserWorkspace, options = {}) {
1093
1423
  tabs.clear();
1094
1424
  }
1095
1425
 
1096
- return { closeAll, state };
1426
+ // auth and route are shared with the shell-session API in server.js, so
1427
+ // every workspace route has one definition of "who may call" and of errors.
1428
+ return { closeAll, state, auth, route };
1097
1429
  }
1098
1430
 
1099
1431
  module.exports = { installWorkspacePanes };