@fnndsc/calypso 0.29.15 → 0.30.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.
- package/dist/calypso.js +19 -8
- package/dist/calypso.js.map +1 -1
- package/dist/daemon/attachFile.d.ts +26 -19
- package/dist/daemon/attachFile.js +42 -51
- package/dist/daemon/attachFile.js.map +1 -1
- package/dist/daemon/attachOrigin.d.ts +69 -0
- package/dist/daemon/attachOrigin.js +125 -0
- package/dist/daemon/attachOrigin.js.map +1 -0
- package/dist/daemon/berth.d.ts +265 -26
- package/dist/daemon/berth.js +521 -158
- package/dist/daemon/berth.js.map +1 -1
- package/dist/daemon/claims.js +19 -9
- package/dist/daemon/claims.js.map +1 -1
- package/dist/daemon/commandLane.d.ts +317 -0
- package/dist/daemon/commandLane.js +409 -0
- package/dist/daemon/commandLane.js.map +1 -0
- package/dist/daemon/console.d.ts +0 -2
- package/dist/daemon/console.js +7 -10
- package/dist/daemon/console.js.map +1 -1
- package/dist/daemon/consoleSession.js +4 -1
- package/dist/daemon/consoleSession.js.map +1 -1
- package/dist/daemon/elevation.d.ts +0 -3
- package/dist/daemon/elevation.js +1 -3
- package/dist/daemon/elevation.js.map +1 -1
- package/dist/daemon/face.d.ts +18 -4
- package/dist/daemon/face.js +77 -32
- package/dist/daemon/face.js.map +1 -1
- package/dist/daemon/hostControl.d.ts +114 -1
- package/dist/daemon/hostControl.js +104 -4
- package/dist/daemon/hostControl.js.map +1 -1
- package/dist/daemon/hostPtyRelay.d.ts +118 -0
- package/dist/daemon/hostPtyRelay.js +186 -0
- package/dist/daemon/hostPtyRelay.js.map +1 -0
- package/dist/daemon/httpRoutes.d.ts +257 -0
- package/dist/daemon/httpRoutes.js +537 -0
- package/dist/daemon/httpRoutes.js.map +1 -0
- package/dist/daemon/instance.d.ts +37 -0
- package/dist/daemon/instance.js +59 -0
- package/dist/daemon/instance.js.map +1 -0
- package/dist/daemon/launch.d.ts +17 -0
- package/dist/daemon/launch.js +198 -194
- package/dist/daemon/launch.js.map +1 -1
- package/dist/daemon/launchBanner.d.ts +76 -0
- package/dist/daemon/launchBanner.js +80 -0
- package/dist/daemon/launchBanner.js.map +1 -0
- package/dist/daemon/rival.d.ts +65 -0
- package/dist/daemon/rival.js +67 -0
- package/dist/daemon/rival.js.map +1 -0
- package/dist/daemon/server.d.ts +104 -190
- package/dist/daemon/server.js +358 -866
- package/dist/daemon/server.js.map +1 -1
- package/dist/daemon/settings.d.ts +42 -0
- package/dist/daemon/settings.js +43 -0
- package/dist/daemon/settings.js.map +1 -0
- package/dist/daemon/surface.d.ts +103 -0
- package/dist/daemon/surface.js +71 -0
- package/dist/daemon/surface.js.map +1 -0
- package/dist/daemon/surfaceReplies.d.ts +109 -0
- package/dist/daemon/surfaceReplies.js +108 -0
- package/dist/daemon/surfaceReplies.js.map +1 -0
- package/dist/daemon/terminals.js +5 -2
- package/dist/daemon/terminals.js.map +1 -1
- package/dist/daemon/token.d.ts +41 -5
- package/dist/daemon/token.js +43 -12
- package/dist/daemon/token.js.map +1 -1
- package/dist/daemon/uploadHold.d.ts +85 -0
- package/dist/daemon/uploadHold.js +205 -0
- package/dist/daemon/uploadHold.js.map +1 -0
- package/dist/daemon/vfsHeaders.d.ts +11 -0
- package/dist/daemon/vfsHeaders.js +60 -0
- package/dist/daemon/vfsHeaders.js.map +1 -0
- package/dist/index.d.ts +5 -5
- package/dist/index.js +3 -4
- package/dist/index.js.map +1 -1
- package/dist/notes.json +1 -1
- package/package.json +9 -4
- package/dist/daemon/discovery.d.ts +0 -23
- package/dist/daemon/discovery.js +0 -57
- package/dist/daemon/discovery.js.map +0 -1
package/dist/daemon/server.js
CHANGED
|
@@ -1,67 +1,61 @@
|
|
|
1
|
-
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
2
|
-
import { randomBytes } from 'node:crypto';
|
|
3
|
-
import { createServer } from 'node:http';
|
|
4
|
-
import { WebSocketServer, WebSocket } from 'ws';
|
|
5
|
-
import { staticRequest_handle, contentDisposition_format, contentType_derive } from './static.js';
|
|
6
|
-
import { token_matches } from './token.js';
|
|
7
|
-
import { RequestBroker } from './broker.js';
|
|
8
|
-
import { CONTRACT_VERSION } from '@fnndsc/menu';
|
|
9
|
-
import { clientMessage_parse, attach_parse } from '@fnndsc/menu';
|
|
10
|
-
import { hostPty_start } from './hostPty.js';
|
|
11
|
-
import { Lane, LOCKS_ALL } from './lane.js';
|
|
12
|
-
import { claim_match, claimCandidates_list } from './claims.js';
|
|
13
|
-
import { DownloadLedger, downloadId_valid } from './downloads.js';
|
|
14
|
-
import { byteStream_normalise, errorFacts_read, vfsBreak_format } from './vfsBreak.js';
|
|
15
1
|
/**
|
|
16
|
-
* The
|
|
2
|
+
* @file The CALYPSO daemon: a WebSocket host over one engine, with a session
|
|
3
|
+
* bus.
|
|
17
4
|
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
*
|
|
34
|
-
*
|
|
35
|
-
*
|
|
36
|
-
*
|
|
5
|
+
* The daemon binds the loopback interface only and hosts a single hosted
|
|
6
|
+
* engine. A surface attaches with the contract version and the attach token
|
|
7
|
+
* (compared in constant time); once attached it drives the engine with
|
|
8
|
+
* `execute` and `complete` messages and receives `result` and completion
|
|
9
|
+
* replies. Command execution takes turns on the session (commandLane.ts) —
|
|
10
|
+
* shell semantics, and what keeps each command's error boundary correct.
|
|
11
|
+
*
|
|
12
|
+
* All attached surfaces share one session. A **session bus** broadcasts every
|
|
13
|
+
* result envelope to the *other* attached surfaces (tagged with the surface
|
|
14
|
+
* that produced it), so a command issued in one surface is immediately
|
|
15
|
+
* visible in the rest. A bounded **scrollback** ring buffer of recent
|
|
16
|
+
* envelopes is replayed to an attaching surface so it does not join blind;
|
|
17
|
+
* scrollback is presentation, not truth — a daemon restart loses it, which is
|
|
18
|
+
* correct, and the durable record is an opt-in transcript materialized to
|
|
19
|
+
* CUBE.
|
|
20
|
+
*
|
|
21
|
+
* CUBE credentials never cross the wire: the engine the daemon hosts holds its
|
|
22
|
+
* own CUBE session, established by the launcher exactly as the CLI does;
|
|
23
|
+
* surfaces authenticate to the daemon, not to CUBE.
|
|
37
24
|
*
|
|
38
|
-
*
|
|
39
|
-
*
|
|
40
|
-
*
|
|
41
|
-
*
|
|
25
|
+
* Key components:
|
|
26
|
+
* - CalypsoDaemon: the daemon: attach, the message routes, the session bus, and the engine's surface seams.
|
|
27
|
+
* - DaemonOptions: what a daemon is made with.
|
|
28
|
+
* - PromptRelay: a question on its way to a surface.
|
|
29
|
+
* - DAEMON_SURFACE: the bus tag of what the daemon itself originates.
|
|
42
30
|
*
|
|
43
|
-
*
|
|
31
|
+
* Typical usage:
|
|
44
32
|
* ```ts
|
|
45
|
-
*
|
|
46
|
-
*
|
|
33
|
+
* const daemon: CalypsoDaemon = new CalypsoDaemon({ engine, token });
|
|
34
|
+
* const port: number = await daemon.start();
|
|
47
35
|
* ```
|
|
48
|
-
*/
|
|
49
|
-
export function lineExit_derive(envelopes, failureReason, lineExit) {
|
|
50
|
-
const failed = failureReason !== undefined || (envelopes?.some((envelope) => envelope.status === 'error') ?? false);
|
|
51
|
-
if (lineExit !== undefined && lineExit !== 0)
|
|
52
|
-
return lineExit;
|
|
53
|
-
return failed ? 1 : 0;
|
|
54
|
-
}
|
|
55
|
-
/**
|
|
56
|
-
* Whether a surface is a browser: it speaks a language of its own (claims)
|
|
57
|
-
* and runs no shell.
|
|
58
36
|
*
|
|
59
|
-
*
|
|
60
|
-
*
|
|
37
|
+
* Dependencies: ws; the wire contract of `@fnndsc/menu`; commandLane.ts (the running lines), httpRoutes.ts (plain
|
|
38
|
+
* HTTP), surfaceReplies.ts (requests open on surfaces), hostPtyRelay.ts, terminals.ts.
|
|
39
|
+
*
|
|
40
|
+
* @module
|
|
61
41
|
*/
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
}
|
|
42
|
+
import { randomBytes } from 'node:crypto';
|
|
43
|
+
import { createServer } from 'node:http';
|
|
44
|
+
import { CONTRACT_VERSION, clientMessage_parse, attach_parse } from '@fnndsc/menu';
|
|
45
|
+
import { WebSocketServer, WebSocket } from 'ws';
|
|
46
|
+
import { attachRequest_refusal, attachOrigins_read } from './attachOrigin.js';
|
|
47
|
+
import { claim_match, claimCandidates_list } from './claims.js';
|
|
48
|
+
import { CommandLane } from './commandLane.js';
|
|
49
|
+
import { HostPtyRelay } from './hostPtyRelay.js';
|
|
50
|
+
import { DaemonHttp } from './httpRoutes.js';
|
|
51
|
+
import { surfaceFromAttach_build, surface_isBrowser } from './surface.js';
|
|
52
|
+
import { SurfaceReplies } from './surfaceReplies.js';
|
|
53
|
+
import { token_matches } from './token.js';
|
|
54
|
+
import { uploadCeiling_read } from './uploadHold.js';
|
|
55
|
+
/** The default number of envelopes retained for scrollback replay. */
|
|
56
|
+
/** The surface tag on session-bus envelopes the daemon itself originates. */
|
|
57
|
+
export const DAEMON_SURFACE = 'daemon';
|
|
58
|
+
const SCROLLBACK_DEFAULT = 200;
|
|
65
59
|
/**
|
|
66
60
|
* A WebSocket daemon hosting one engine for attached surfaces, with a session
|
|
67
61
|
* bus broadcasting activity across them.
|
|
@@ -87,14 +81,14 @@ export class CalypsoDaemon {
|
|
|
87
81
|
stale = false;
|
|
88
82
|
/** The terminals this daemon offers, or null when it offers none (no pty here). */
|
|
89
83
|
terminals = null;
|
|
90
|
-
/**
|
|
91
|
-
|
|
92
|
-
/** The `!` commands running on host ptys, by id, with the surface they draw on. */
|
|
93
|
-
hostPtys = new Map();
|
|
84
|
+
/** The `!` commands running on host ptys of the daemon's own (hostPtyRelay.ts). */
|
|
85
|
+
hostPtyRelay;
|
|
94
86
|
codeCheck;
|
|
95
87
|
/** Where the daemon's own operational lines go. */
|
|
96
88
|
log;
|
|
97
89
|
hostControl;
|
|
90
|
+
/** The words this daemon's engine runs itself, told at attach. */
|
|
91
|
+
engineCommands;
|
|
98
92
|
elevation;
|
|
99
93
|
/** The one session all surfaces share; returned in each attach ack. */
|
|
100
94
|
sessionId = randomBytes(8).toString('hex');
|
|
@@ -106,66 +100,28 @@ export class CalypsoDaemon {
|
|
|
106
100
|
}
|
|
107
101
|
/** Whether a foreground command is executing right now. */
|
|
108
102
|
busy_get() {
|
|
109
|
-
return
|
|
103
|
+
return this.commandLane.busy_get();
|
|
110
104
|
}
|
|
111
|
-
|
|
105
|
+
/** The plain HTTP side: the file route, the session's facts, the web root (httpRoutes.ts). */
|
|
106
|
+
http;
|
|
112
107
|
wss = null;
|
|
113
108
|
httpServer = null;
|
|
114
|
-
/**
|
|
115
|
-
|
|
116
|
-
* works at a time, so a prompt raised mid-command has one unambiguous
|
|
117
|
-
* surface to ask, the one holding the lane. A command waiting on a person
|
|
118
|
-
* gives the lane up until the answer comes (`person_await`).
|
|
119
|
-
*/
|
|
120
|
-
lane = new Lane();
|
|
109
|
+
/** The running lines: their turns, their slots, the waits on a person, and STOP (commandLane.ts). */
|
|
110
|
+
commandLane;
|
|
121
111
|
/** The questions open now, by the surface asked: what, and since when. */
|
|
122
112
|
questionsOpen = new Map();
|
|
123
113
|
/** The session's retained regard: the last indication from any surface. */
|
|
124
114
|
regard = null;
|
|
125
115
|
/** Unsubscribes from the engine's ambient events; null until started. */
|
|
126
116
|
ambientStop = null;
|
|
127
|
-
/**
|
|
128
|
-
|
|
129
|
-
* its own slot, and whatever it raises (output, a question, a pipe
|
|
130
|
-
* segment) goes to its own surface.
|
|
131
|
-
*/
|
|
132
|
-
slotScope = new AsyncLocalStorage();
|
|
133
|
-
/** The lines running now, waiting aside or not, in the order they started. */
|
|
134
|
-
running = new Set();
|
|
135
|
-
/** Names each line for the engine. */
|
|
136
|
-
lineCount = 0;
|
|
137
|
-
/** Surfaces whose STOP found their command still waiting its turn, and when. */
|
|
138
|
-
stopPending = new Map();
|
|
139
|
-
/** The surface of the line the code runs inside, or null outside any. */
|
|
140
|
-
get currentOrigin() {
|
|
141
|
-
return this.slotScope.getStore()?.origin ?? null;
|
|
142
|
-
}
|
|
143
|
-
/** The surface's id for the line the code runs inside, or null outside any. */
|
|
144
|
-
get currentId() {
|
|
145
|
-
return this.slotScope.getStore()?.id ?? null;
|
|
146
|
-
}
|
|
147
|
-
/** Whether the line the code runs inside is surface-internal. */
|
|
148
|
-
get currentInstrument() {
|
|
149
|
-
return this.slotScope.getStore()?.instrument === true;
|
|
150
|
-
}
|
|
151
|
-
// One RequestBroker per surface-delegated request kind. The broker owns the
|
|
152
|
-
// whole correlation lifecycle uniformly: id generation, close-guard,
|
|
153
|
-
// origin-validated settles, listener cleanup. See broker.ts.
|
|
154
|
-
prompts = new RequestBroker('p', 'surface disconnected before answering');
|
|
155
|
-
pipes = new RequestBroker('x', 'surface disconnected before returning pipe output');
|
|
156
|
-
shells = new RequestBroker('h', 'surface disconnected before returning the shell result');
|
|
157
|
-
/** The downloads this daemon is serving, for their progress (downloads.ts). */
|
|
158
|
-
downloads = new DownloadLedger();
|
|
159
|
-
edits = new RequestBroker('e', 'surface disconnected before returning the edit');
|
|
160
|
-
/** Lines run by a surface's own language, by the surface that claims them. */
|
|
161
|
-
surfaceLines = new RequestBroker('l', 'the surface that answers for this line went away before answering');
|
|
117
|
+
/** The requests open on surfaces, and the replies that settle them (surfaceReplies.ts). */
|
|
118
|
+
replies = new SurfaceReplies();
|
|
162
119
|
/** Each surface's terminal viewer: which terminals it draws. */
|
|
163
120
|
viewerOf = new Map();
|
|
164
121
|
/** The browser that last did something: the one a claimed line goes to when no terminal of its own typed it. */
|
|
165
122
|
browserActive = null;
|
|
166
123
|
/** Subjects a surface claimed whole this session, so a line in one is refused by name when none is attached. */
|
|
167
124
|
claimedSeen = new Set();
|
|
168
|
-
deliveries = new RequestBroker('d', 'surface disconnected before the file was delivered');
|
|
169
125
|
/**
|
|
170
126
|
* @param options - The engine to host, the attach token, the bind address,
|
|
171
127
|
* and the scrollback size.
|
|
@@ -180,11 +136,23 @@ export class CalypsoDaemon {
|
|
|
180
136
|
this.telemetryProvider = options.telemetryProvider;
|
|
181
137
|
this.stack = options.stack;
|
|
182
138
|
this.backend = options.backend;
|
|
183
|
-
|
|
139
|
+
const webRoot = options.webRoot;
|
|
140
|
+
const uploadHeld = options.uploadHeld ?? uploadCeiling_read(process.env);
|
|
184
141
|
this.hostControl = options.hostControl ?? [];
|
|
142
|
+
this.engineCommands = options.engineCommands_list;
|
|
185
143
|
this.elevation = options.elevation;
|
|
186
144
|
this.codeCheck = options.codeCheck;
|
|
187
145
|
this.log = options.log ?? ((line) => { console.error(line); });
|
|
146
|
+
// The supplied logger is called as the daemon's own, as it always was.
|
|
147
|
+
const line_log = (line) => { this.log(line); };
|
|
148
|
+
this.http = new DaemonHttp(this.engine, this.token, { webRoot, backend: this.backend, uploadHeld }, line_log);
|
|
149
|
+
this.hostPtyRelay = new HostPtyRelay((socket, message) => { this.send(socket, message); }, line_log);
|
|
150
|
+
this.commandLane = new CommandLane(this.engine, {
|
|
151
|
+
stopper_resolve: (surface) => this.stopper_resolve(surface),
|
|
152
|
+
surface_isAttached: (surface) => this.surfaces.has(surface),
|
|
153
|
+
line_end: (slot, exitCode) => this.line_end(slot, exitCode),
|
|
154
|
+
line_answer: (slot, message, outcome) => { this.line_answer(slot, message, outcome); },
|
|
155
|
+
});
|
|
188
156
|
}
|
|
189
157
|
/**
|
|
190
158
|
* Offers terminals: a surface's console as a chell under a pty
|
|
@@ -204,7 +172,17 @@ export class CalypsoDaemon {
|
|
|
204
172
|
* daemon.ptySpawn_set(await ptySpawn_load());
|
|
205
173
|
*/
|
|
206
174
|
ptySpawn_set(spawn) {
|
|
207
|
-
this.
|
|
175
|
+
this.hostPtyRelay.spawn_set(spawn);
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* Sets the facts this daemon proves itself by at `/instance`, the ones its berth record holds.
|
|
179
|
+
*
|
|
180
|
+
* @param facts - The launch's probe key, identity, pid and boot time.
|
|
181
|
+
* @example
|
|
182
|
+
* daemon.instance_set({ probeKey, identity, pid: process.pid, booted });
|
|
183
|
+
*/
|
|
184
|
+
instance_set(facts) {
|
|
185
|
+
this.http.instance_set(facts);
|
|
208
186
|
}
|
|
209
187
|
/**
|
|
210
188
|
* Records whether the daemon's own code still matches its disk, and tells
|
|
@@ -236,12 +214,12 @@ export class CalypsoDaemon {
|
|
|
236
214
|
const index = { jobs: snapshot.jobs, feeds: snapshot.feeds };
|
|
237
215
|
// The lane rides the heartbeat: which command holds it, for how long,
|
|
238
216
|
// and how many wait behind it. A surface reads it as a gauge.
|
|
239
|
-
const working =
|
|
217
|
+
const working = this.commandLane.foreground_find();
|
|
240
218
|
const lane = {
|
|
241
219
|
running: working !== undefined
|
|
242
220
|
? { line: working.line, sinceMs: Math.round(performance.now() - working.startedAt), surface: working.origin.id }
|
|
243
221
|
: null,
|
|
244
|
-
waiting: this.
|
|
222
|
+
waiting: this.commandLane.waiting,
|
|
245
223
|
// Questions open: each one's command has stepped out of the lane.
|
|
246
224
|
questions: [...this.questionsOpen].map(([surface, open]) => ({ surface: surface.id, message: open.message, sinceMs: Math.round(performance.now() - open.at) })),
|
|
247
225
|
// The joblets running: a restart asked from any surface says it ends them.
|
|
@@ -294,38 +272,21 @@ export class CalypsoDaemon {
|
|
|
294
272
|
*/
|
|
295
273
|
start() {
|
|
296
274
|
return new Promise((resolve, reject) => {
|
|
297
|
-
const httpServer = createServer((request, response) => {
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
return;
|
|
312
|
-
}
|
|
313
|
-
if (requestPath === '/backend') {
|
|
314
|
-
this.backend_serve(request, response);
|
|
315
|
-
return;
|
|
316
|
-
}
|
|
317
|
-
if (requestPath === '/joblets') {
|
|
318
|
-
this.joblets_serve(request, response);
|
|
319
|
-
return;
|
|
320
|
-
}
|
|
321
|
-
if (this.webRoot !== undefined) {
|
|
322
|
-
staticRequest_handle(this.webRoot, request, response);
|
|
323
|
-
return;
|
|
324
|
-
}
|
|
325
|
-
response.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' });
|
|
326
|
-
response.end('not found');
|
|
275
|
+
const httpServer = createServer((request, response) => { this.http.request_route(request, response); });
|
|
276
|
+
// An attach from a browser says which page asked; only this daemon's own page, or one named by its
|
|
277
|
+
// operator, is taken (attachOrigin.ts). A program sends no origin and is asked for its token as ever.
|
|
278
|
+
// The names are read at each attach, so an operator's word is the word at the time it is asked.
|
|
279
|
+
const wss = new WebSocketServer({
|
|
280
|
+
server: httpServer,
|
|
281
|
+
verifyClient: (info) => {
|
|
282
|
+
// Read from the request's own headers, not from what the socket library chose among them: version
|
|
283
|
+
// 13 only, one place for the origin, and two `Origin` lines (joined by a comma) are no origin.
|
|
284
|
+
const refusal = attachRequest_refusal(info.req.headers, attachOrigins_read(process.env));
|
|
285
|
+
if (refusal !== null)
|
|
286
|
+
console.error(`[calypso] refused an attach: ${refusal}`);
|
|
287
|
+
return refusal === null;
|
|
288
|
+
},
|
|
327
289
|
});
|
|
328
|
-
const wss = new WebSocketServer({ server: httpServer });
|
|
329
290
|
wss.on('connection', (socket, request) => this.connection_handle(socket, request));
|
|
330
291
|
httpServer.on('error', reject);
|
|
331
292
|
httpServer.listen(this.port, this.host, () => {
|
|
@@ -346,8 +307,7 @@ export class CalypsoDaemon {
|
|
|
346
307
|
// A terminal's chell is a child of this process: it goes with it, and so
|
|
347
308
|
// does a program running on a host pty.
|
|
348
309
|
this.terminals?.stop();
|
|
349
|
-
|
|
350
|
-
held.run.stop();
|
|
310
|
+
this.hostPtyRelay.ptys_stop();
|
|
351
311
|
if (this.telemetryTimer !== null) {
|
|
352
312
|
clearInterval(this.telemetryTimer);
|
|
353
313
|
this.telemetryTimer = null;
|
|
@@ -373,321 +333,11 @@ export class CalypsoDaemon {
|
|
|
373
333
|
});
|
|
374
334
|
}
|
|
375
335
|
/**
|
|
376
|
-
*
|
|
377
|
-
*
|
|
378
|
-
* the attach answer says the same once it attaches. The attach token gates
|
|
379
|
-
* it as it gates `/vfs` (a wrong one is not found).
|
|
380
|
-
*
|
|
381
|
-
* @param request - The incoming HTTP request.
|
|
382
|
-
* @param response - The response to write.
|
|
383
|
-
*/
|
|
384
|
-
backend_serve(request, response) {
|
|
385
|
-
const query = new URL(request.url ?? '/', 'http://localhost').searchParams;
|
|
386
|
-
if (!token_matches(this.token, query.get('token') ?? '')) {
|
|
387
|
-
response.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' });
|
|
388
|
-
response.end('not found');
|
|
389
|
-
return;
|
|
390
|
-
}
|
|
391
|
-
response.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
|
|
392
|
-
response.end(JSON.stringify({ backend: this.backend ?? null }));
|
|
393
|
-
}
|
|
394
|
-
/**
|
|
395
|
-
* Says which joblets run now (`line &`): `{"joblets": [{number, line,
|
|
396
|
-
* waiting}]}`. A host about to restart the session (porter, for a new
|
|
397
|
-
* release) asks first, since a restart ends them (#1273). Gated by the
|
|
398
|
-
* attach token, as `/backend` is.
|
|
399
|
-
*
|
|
400
|
-
* @param request - The incoming HTTP request.
|
|
401
|
-
* @param response - The response to write.
|
|
402
|
-
*/
|
|
403
|
-
joblets_serve(request, response) {
|
|
404
|
-
const query = new URL(request.url ?? '/', 'http://localhost').searchParams;
|
|
405
|
-
if (!token_matches(this.token, query.get('token') ?? '')) {
|
|
406
|
-
response.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' });
|
|
407
|
-
response.end('not found');
|
|
408
|
-
return;
|
|
409
|
-
}
|
|
410
|
-
response.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
|
|
411
|
-
response.end(JSON.stringify({ joblets: this.engine.joblets_running?.() ?? [] }));
|
|
412
|
-
}
|
|
413
|
-
/**
|
|
414
|
-
* Serves one ChRIS file's bytes over HTTP: `GET /vfs?path=...&token=...`.
|
|
415
|
-
*
|
|
416
|
-
* The route exists so browser surfaces can render file content natively
|
|
417
|
-
* (an image in a panel) instead of through the terminal stream. It is
|
|
418
|
-
* gated by the same attach token as the wire (compared in constant time)
|
|
419
|
-
* and requires the hosted engine to provide `file_read`; refusals and
|
|
420
|
-
* failures answer 404 so the response does not confirm what exists.
|
|
421
|
-
*
|
|
422
|
-
* With `download=1` the same bytes come down as an attachment named for
|
|
423
|
-
* the file, which is how a browser is told to save rather than show: a
|
|
424
|
-
* surface's DOWNLOAD is this URL behind an anchor, so a file reaches the
|
|
425
|
-
* operator's disk the way every other download does.
|
|
426
|
-
*
|
|
427
|
-
* @param request - The incoming HTTP request.
|
|
428
|
-
* @param response - The response to write.
|
|
429
|
-
*/
|
|
430
|
-
async vfs_serve(request, response) {
|
|
431
|
-
const refuse = (status, message) => {
|
|
432
|
-
response.writeHead(status, { 'content-type': 'text/plain; charset=utf-8' });
|
|
433
|
-
response.end(message);
|
|
434
|
-
};
|
|
435
|
-
const query = new URL(request.url ?? '/', 'http://localhost').searchParams;
|
|
436
|
-
if (!token_matches(this.token, query.get('token') ?? '')) {
|
|
437
|
-
refuse(404, 'not found');
|
|
438
|
-
return;
|
|
439
|
-
}
|
|
440
|
-
if (request.method === 'POST') {
|
|
441
|
-
await this.vfs_receive(request, response, query, refuse);
|
|
442
|
-
return;
|
|
443
|
-
}
|
|
444
|
-
if (request.method !== 'GET' && request.method !== 'HEAD') {
|
|
445
|
-
refuse(405, 'method not allowed');
|
|
446
|
-
return;
|
|
447
|
-
}
|
|
448
|
-
// A download's progress, and its stop: the surface asks by its own id.
|
|
449
|
-
const asked = query.get('progress') ?? query.get('cancel');
|
|
450
|
-
if (asked !== null) {
|
|
451
|
-
const id = downloadId_valid(asked) ? asked : null;
|
|
452
|
-
if (id !== null && query.has('cancel'))
|
|
453
|
-
this.downloads.cancel(id);
|
|
454
|
-
const report = id === null ? null : this.downloads.report(id);
|
|
455
|
-
response.writeHead(report === null ? 404 : 200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
|
|
456
|
-
response.end(JSON.stringify(report ?? { reason: 'no such download' }));
|
|
457
|
-
return;
|
|
458
|
-
}
|
|
459
|
-
const filePath = query.get('path');
|
|
460
|
-
const read = this.engine.file_read?.bind(this.engine);
|
|
461
|
-
if (filePath === null || filePath.length === 0 || read === undefined) {
|
|
462
|
-
refuse(404, 'not found');
|
|
463
|
-
return;
|
|
464
|
-
}
|
|
465
|
-
const open = this.engine.file_stream?.bind(this.engine);
|
|
466
|
-
// A download's probe asks by HEAD: the file's headers, its bytes held.
|
|
467
|
-
if (open !== undefined && (request.method === 'GET' || (request.method === 'HEAD' && query.get('probe') === '1'))) {
|
|
468
|
-
await this.vfs_stream(open, filePath, query, response, refuse);
|
|
469
|
-
return;
|
|
470
|
-
}
|
|
471
|
-
try {
|
|
472
|
-
const bytes = await read(filePath);
|
|
473
|
-
const headers = {
|
|
474
|
-
'content-type': contentType_derive(filePath),
|
|
475
|
-
'content-length': bytes.length,
|
|
476
|
-
};
|
|
477
|
-
if (query.get('download') === '1') {
|
|
478
|
-
headers['content-disposition'] = contentDisposition_format(filePath);
|
|
479
|
-
}
|
|
480
|
-
response.writeHead(200, headers);
|
|
481
|
-
response.end(request.method === 'HEAD' ? undefined : bytes);
|
|
482
|
-
}
|
|
483
|
-
catch (error) {
|
|
484
|
-
// The kernel says why it refused (status and a line); the route
|
|
485
|
-
// passes both on. It used to answer 404 for everything, and a
|
|
486
|
-
// surface could only say REFUSED.
|
|
487
|
-
const named = error;
|
|
488
|
-
if (typeof named.status === 'number' && typeof named.reason === 'string') {
|
|
489
|
-
refuse(named.status, named.reason);
|
|
490
|
-
return;
|
|
491
|
-
}
|
|
492
|
-
refuse(404, 'not found');
|
|
493
|
-
}
|
|
494
|
-
}
|
|
495
|
-
/**
|
|
496
|
-
* Serves one file's bytes as they arrive: the length in the header when
|
|
497
|
-
* the store gave one (so a browser draws its own progress), the body
|
|
498
|
-
* piped, nothing held whole. A 3.7 GB DICOM used to be read into one
|
|
499
|
-
* buffer behind a 30 s deadline and answered 404. A failure to open the
|
|
500
|
-
* file answers with the kernel's status and reason. The status waits for
|
|
501
|
-
* CUBE's first byte, so a file whose bytes never start is a 502 that says
|
|
502
|
-
* why. A break after bytes have gone cuts the socket, which the porter and
|
|
503
|
-
* the browser see as a body that stopped rather than a short file. Either
|
|
504
|
-
* break is one line in the daemon's log (vfsBreak.ts): the path, the bytes
|
|
505
|
-
* sent of the size CUBE stated, the time taken and the cause.
|
|
506
|
-
*
|
|
507
|
-
* @param open - The engine's stream seam.
|
|
508
|
-
* @param filePath - The file asked for.
|
|
509
|
-
* @param query - The request's query (`download=1` names an attachment).
|
|
510
|
-
* @param response - The response to write.
|
|
511
|
-
* @param refuse - Answers a refusal before any byte is sent.
|
|
512
|
-
*
|
|
513
|
-
* A download with an id (`dl`) is counted for its progress; its probe
|
|
514
|
-
* (HEAD, `probe=1`) opens the file and answers the headers alone, holding the
|
|
515
|
-
* stream for the save that follows (downloads.ts).
|
|
516
|
-
*/
|
|
517
|
-
async vfs_stream(open, filePath, query, response, refuse) {
|
|
518
|
-
const startedAt = Date.now();
|
|
519
|
-
const dl = downloadId_valid(query.get('dl')) ? query.get('dl') : null;
|
|
520
|
-
const probe = dl !== null && query.get('probe') === '1';
|
|
521
|
-
// The browser's save takes the file its probe opened, when one is held.
|
|
522
|
-
// A cancelled download stays cancelled: its save is refused, not begun again.
|
|
523
|
-
if (dl !== null && this.downloads.cancelled(dl)) {
|
|
524
|
-
refuse(410, 'cancelled');
|
|
525
|
-
return;
|
|
526
|
-
}
|
|
527
|
-
let opened = dl !== null && !probe ? this.downloads.claim(dl) : null;
|
|
528
|
-
if (opened === null) {
|
|
529
|
-
if (dl !== null)
|
|
530
|
-
this.downloads.begin(dl, filePath);
|
|
531
|
-
try {
|
|
532
|
-
opened = await open(filePath);
|
|
533
|
-
}
|
|
534
|
-
catch (error) {
|
|
535
|
-
const named = error;
|
|
536
|
-
const known = typeof named.status === 'number' && typeof named.reason === 'string';
|
|
537
|
-
if (dl !== null)
|
|
538
|
-
this.downloads.fail(dl, known ? String(named.reason) : 'not found');
|
|
539
|
-
if (known)
|
|
540
|
-
refuse(named.status, named.reason);
|
|
541
|
-
else
|
|
542
|
-
refuse(404, 'not found');
|
|
543
|
-
return;
|
|
544
|
-
}
|
|
545
|
-
}
|
|
546
|
-
const headers = { 'content-type': contentType_derive(filePath) };
|
|
547
|
-
if (opened.size !== undefined)
|
|
548
|
-
headers['content-length'] = opened.size;
|
|
549
|
-
if (query.get('download') === '1')
|
|
550
|
-
headers['content-disposition'] = contentDisposition_format(filePath);
|
|
551
|
-
if (probe && dl !== null) {
|
|
552
|
-
// The probe's answer is the file's headers; the bytes wait for the save.
|
|
553
|
-
if (!this.downloads.park(dl, opened)) {
|
|
554
|
-
refuse(410, 'cancelled');
|
|
555
|
-
return;
|
|
556
|
-
}
|
|
557
|
-
response.writeHead(200, headers);
|
|
558
|
-
response.end();
|
|
559
|
-
return;
|
|
560
|
-
}
|
|
561
|
-
let stream;
|
|
562
|
-
try {
|
|
563
|
-
stream = await byteStream_normalise(opened.stream);
|
|
564
|
-
}
|
|
565
|
-
catch (error) {
|
|
566
|
-
const { message } = errorFacts_read(error);
|
|
567
|
-
this.log(`[!] vfs: ${filePath}: ${message}`);
|
|
568
|
-
if (dl !== null)
|
|
569
|
-
this.downloads.fail(dl, message);
|
|
570
|
-
refuse(500, message);
|
|
571
|
-
return;
|
|
572
|
-
}
|
|
573
|
-
const statedBytes = opened.size;
|
|
574
|
-
let browserLeft = false;
|
|
575
|
-
// The browser left (a cancelled download): stop pulling from CUBE.
|
|
576
|
-
response.on('close', () => {
|
|
577
|
-
if (response.writableFinished)
|
|
578
|
-
return;
|
|
579
|
-
browserLeft = true;
|
|
580
|
-
stream.destroy?.();
|
|
581
|
-
});
|
|
582
|
-
const chunks = stream[Symbol.asyncIterator]();
|
|
583
|
-
let sentBytes = 0;
|
|
584
|
-
const break_log = (error) => {
|
|
585
|
-
if (browserLeft)
|
|
586
|
-
return;
|
|
587
|
-
this.log(vfsBreak_format({ path: filePath, sentBytes, statedBytes, elapsedMs: Date.now() - startedAt, ...errorFacts_read(error) }));
|
|
588
|
-
};
|
|
589
|
-
// The status waits for CUBE's first byte: a file that never starts is
|
|
590
|
-
// still a refusal with its reason, not a 200 cut off before its body.
|
|
591
|
-
let first;
|
|
592
|
-
try {
|
|
593
|
-
first = await chunks.next();
|
|
594
|
-
}
|
|
595
|
-
catch (error) {
|
|
596
|
-
break_log(error);
|
|
597
|
-
const { message } = errorFacts_read(error);
|
|
598
|
-
if (dl !== null)
|
|
599
|
-
this.downloads.fail(dl, `the file did not arrive from CUBE: ${message}`);
|
|
600
|
-
if (!browserLeft)
|
|
601
|
-
refuse(502, `the file did not arrive from CUBE: ${message}`);
|
|
602
|
-
return;
|
|
603
|
-
}
|
|
604
|
-
response.writeHead(200, headers);
|
|
605
|
-
const rest = async function* () {
|
|
606
|
-
let step = first;
|
|
607
|
-
while (step.done !== true) {
|
|
608
|
-
const chunk = Buffer.isBuffer(step.value) ? step.value : Buffer.from(step.value);
|
|
609
|
-
sentBytes += chunk.length;
|
|
610
|
-
yield chunk;
|
|
611
|
-
step = await chunks.next();
|
|
612
|
-
}
|
|
613
|
-
};
|
|
614
|
-
try {
|
|
615
|
-
const { pipeline } = await import('node:stream/promises');
|
|
616
|
-
if (dl !== null)
|
|
617
|
-
await pipeline(rest, this.downloads.counter(dl, response), response);
|
|
618
|
-
else
|
|
619
|
-
await pipeline(rest, response);
|
|
620
|
-
}
|
|
621
|
-
catch (error) {
|
|
622
|
-
break_log(error);
|
|
623
|
-
// The status is sent and cannot change: the socket is cut, so the
|
|
624
|
-
// porter and the browser see a body that stopped, never a whole short file.
|
|
625
|
-
if (dl !== null)
|
|
626
|
-
this.downloads.fail(dl, `the file stopped arriving from CUBE: ${errorFacts_read(error).message}`);
|
|
627
|
-
response.destroy();
|
|
628
|
-
}
|
|
629
|
-
}
|
|
630
|
-
/**
|
|
631
|
-
* Takes one file's bytes from a surface: `POST /vfs?path=...&token=...`.
|
|
632
|
-
*
|
|
633
|
-
* A browser cannot reach the machine the daemon runs on, so `upload` is
|
|
634
|
-
* not a verb it can speak: the bytes travel here and the ENGINE puts them
|
|
635
|
-
* in the store, which keeps the write on the kernel's own path rather
|
|
636
|
-
* than letting a surface talk to CUBE.
|
|
637
|
-
*
|
|
638
|
-
* Gated by the same attach token as the read, and capped: a surface that
|
|
639
|
-
* can post unbounded bytes to a loopback port is a surface that can fill
|
|
640
|
-
* the machine.
|
|
641
|
-
*
|
|
642
|
-
* @param request - The incoming request, whose body is the file.
|
|
643
|
-
* @param response - The response to write.
|
|
644
|
-
* @param query - The parsed query string (path and token).
|
|
645
|
-
* @param refuse - How this route says no.
|
|
646
|
-
*/
|
|
647
|
-
async vfs_receive(request, response, query, refuse) {
|
|
648
|
-
const filePath = query.get('path');
|
|
649
|
-
const write = this.engine.file_write?.bind(this.engine);
|
|
650
|
-
if (filePath === null || filePath.length === 0 || write === undefined) {
|
|
651
|
-
refuse(404, 'not found');
|
|
652
|
-
return;
|
|
653
|
-
}
|
|
654
|
-
const chunks = [];
|
|
655
|
-
let received = 0;
|
|
656
|
-
let refused = false;
|
|
657
|
-
try {
|
|
658
|
-
for await (const chunk of request) {
|
|
659
|
-
const part = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
660
|
-
received += part.length;
|
|
661
|
-
if (received > VFS_POST_LIMIT) {
|
|
662
|
-
refused = true;
|
|
663
|
-
break;
|
|
664
|
-
}
|
|
665
|
-
chunks.push(part);
|
|
666
|
-
}
|
|
667
|
-
}
|
|
668
|
-
catch {
|
|
669
|
-
refuse(400, 'could not read the request body');
|
|
670
|
-
return;
|
|
671
|
-
}
|
|
672
|
-
if (refused) {
|
|
673
|
-
refuse(413, `file too large: this route takes at most ${VFS_POST_LIMIT} bytes`);
|
|
674
|
-
return;
|
|
675
|
-
}
|
|
676
|
-
try {
|
|
677
|
-
await write(filePath, Buffer.concat(chunks));
|
|
678
|
-
}
|
|
679
|
-
catch (error) {
|
|
680
|
-
refuse(502, error instanceof Error ? error.message : 'the store refused the write');
|
|
681
|
-
return;
|
|
682
|
-
}
|
|
683
|
-
response.writeHead(200, { 'content-type': 'application/json; charset=utf-8' });
|
|
684
|
-
response.end(JSON.stringify({ path: filePath, bytes: received }));
|
|
685
|
-
}
|
|
686
|
-
/**
|
|
687
|
-
* Handles one surface connection: an attach handshake, then serialized
|
|
688
|
-
* command dispatch, with the surface removed from the bus on close.
|
|
336
|
+
* Handles one surface connection: an attach handshake, then its messages
|
|
337
|
+
* routed, with the surface removed from the bus on close.
|
|
689
338
|
*
|
|
690
339
|
* @param socket - The connected surface.
|
|
340
|
+
* @param request - The upgrade request, whose URL may carry the token.
|
|
691
341
|
*/
|
|
692
342
|
connection_handle(socket, request) {
|
|
693
343
|
let surface = null;
|
|
@@ -722,153 +372,145 @@ export class CalypsoDaemon {
|
|
|
722
372
|
this.send(socket, { type: 'error', reason: message.error ?? 'invalid message' });
|
|
723
373
|
return;
|
|
724
374
|
}
|
|
725
|
-
|
|
726
|
-
const attached = surface;
|
|
727
|
-
if (value.type === 'execute') {
|
|
728
|
-
if (surface_isBrowser(attached))
|
|
729
|
-
this.browserActive = attached;
|
|
730
|
-
// A line in a surface's own language is that surface's to run: it never
|
|
731
|
-
// reaches the engine, and needs no turn on the lane (the session is not
|
|
732
|
-
// touched by it).
|
|
733
|
-
const claimant = value.instrument === true ? null : this.claimant_find(attached, value.line);
|
|
734
|
-
if (claimant !== null) {
|
|
735
|
-
void this.surfaceLine_run(attached, value, claimant);
|
|
736
|
-
return;
|
|
737
|
-
}
|
|
738
|
-
// One lane for every surface: commands take turns, and a command
|
|
739
|
-
// waiting on a person stands aside (person_await), so a pane's own
|
|
740
|
-
// reads, or another surface's command, run while a question is open.
|
|
741
|
-
void this.line_run(attached, value);
|
|
742
|
-
}
|
|
743
|
-
else if (value.type === 'cancel') {
|
|
744
|
-
this.cancel_run(attached, value);
|
|
745
|
-
}
|
|
746
|
-
else if (value.type === 'stop') {
|
|
747
|
-
this.stop_run(attached, value);
|
|
748
|
-
}
|
|
749
|
-
else if (value.type === 'elevate') {
|
|
750
|
-
void this.elevate_run(attached, value);
|
|
751
|
-
}
|
|
752
|
-
else if (value.type === 'complete') {
|
|
753
|
-
void this.complete_run(socket, value);
|
|
754
|
-
}
|
|
755
|
-
else if (value.type === 'promptAnswer') {
|
|
756
|
-
this.prompts.settle(socket, value.promptId, value.answer);
|
|
757
|
-
}
|
|
758
|
-
else if (value.type === 'promptError') {
|
|
759
|
-
this.prompts.fail(socket, value.promptId, value.reason);
|
|
760
|
-
}
|
|
761
|
-
else if (value.type === 'pipeResult') {
|
|
762
|
-
this.pipes.settle(socket, value.pipeId, Buffer.from(value.output, 'base64'));
|
|
763
|
-
}
|
|
764
|
-
else if (value.type === 'pipeError') {
|
|
765
|
-
this.pipes.fail(socket, value.pipeId, value.reason);
|
|
766
|
-
}
|
|
767
|
-
else if (value.type === 'shellResult') {
|
|
768
|
-
this.shells.settle(socket, value.shellId, value.exitCode);
|
|
769
|
-
}
|
|
770
|
-
else if (value.type === 'shellError') {
|
|
771
|
-
this.shells.fail(socket, value.shellId, value.reason);
|
|
772
|
-
}
|
|
773
|
-
else if (value.type === 'editResult') {
|
|
774
|
-
this.edits.settle(socket, value.editId, {
|
|
775
|
-
content: value.content,
|
|
776
|
-
changed: value.changed,
|
|
777
|
-
...(value.opened === undefined ? {} : { opened: value.opened }),
|
|
778
|
-
});
|
|
779
|
-
}
|
|
780
|
-
else if (value.type === 'editError') {
|
|
781
|
-
this.edits.fail(socket, value.editId, value.reason);
|
|
782
|
-
}
|
|
783
|
-
else if (value.type === 'deliverResult') {
|
|
784
|
-
this.deliveries.settle(socket, value.deliverId, { location: value.location, bytes: value.bytes });
|
|
785
|
-
}
|
|
786
|
-
else if (value.type === 'deliverError') {
|
|
787
|
-
this.deliveries.fail(socket, value.deliverId, value.reason);
|
|
788
|
-
}
|
|
789
|
-
else if (value.type === 'regard') {
|
|
790
|
-
this.regard_receive(value.regard);
|
|
791
|
-
}
|
|
792
|
-
else if (value.type === 'watch' || value.type === 'unwatch') {
|
|
793
|
-
this.watch_receive(attached, value.subject, value.type === 'watch');
|
|
794
|
-
}
|
|
795
|
-
else if (value.type === 'terminalOpen') {
|
|
796
|
-
if (this.terminals === null) {
|
|
797
|
-
this.send(socket, { type: 'terminalOpened', terminalId: '', replay: '', refused: 'this daemon offers no terminals (node-pty is not built here)' });
|
|
798
|
-
}
|
|
799
|
-
else {
|
|
800
|
-
const opened = this.terminals.open(viewer, value.cols, value.rows, value.terminalId);
|
|
801
|
-
this.send(socket, { type: 'terminalOpened', terminalId: opened.terminalId, replay: opened.replay });
|
|
802
|
-
}
|
|
803
|
-
}
|
|
804
|
-
else if (value.type === 'terminalInput') {
|
|
805
|
-
this.terminals?.input(viewer, value.terminalId, value.data);
|
|
806
|
-
}
|
|
807
|
-
else if (value.type === 'terminalResize') {
|
|
808
|
-
this.terminals?.resize(viewer, value.terminalId, value.cols, value.rows);
|
|
809
|
-
}
|
|
810
|
-
else if (value.type === 'terminalClose') {
|
|
811
|
-
this.terminals?.close(viewer, value.terminalId);
|
|
812
|
-
}
|
|
813
|
-
else if (value.type === 'hostPtyInput') {
|
|
814
|
-
const held = this.hostPtys.get(value.ptyId);
|
|
815
|
-
if (held !== undefined && held.surface === attached)
|
|
816
|
-
held.run.write(value.data);
|
|
817
|
-
}
|
|
818
|
-
else if (value.type === 'hostPtyResize') {
|
|
819
|
-
// The size a later `!` starts at, and the running one's, when it is this surface's.
|
|
820
|
-
if (attached.capabilities.tty !== undefined)
|
|
821
|
-
attached.capabilities.tty = { ...attached.capabilities.tty, cols: value.cols, rows: value.rows };
|
|
822
|
-
const held = value.ptyId === undefined ? undefined : this.hostPtys.get(value.ptyId);
|
|
823
|
-
if (held !== undefined && held.surface === attached)
|
|
824
|
-
held.run.resize(value.cols, value.rows);
|
|
825
|
-
}
|
|
826
|
-
else if (value.type === 'surfaceLineResult') {
|
|
827
|
-
this.surfaceLines.settle(socket, value.lineId, { rendered: value.rendered, status: value.status });
|
|
828
|
-
}
|
|
829
|
-
else if (value.type === 'surfaceLineError') {
|
|
830
|
-
this.surfaceLines.fail(socket, value.lineId, value.reason);
|
|
831
|
-
}
|
|
832
|
-
else if (value.type === 'note') {
|
|
833
|
-
this.note_relay(viewer, value.text);
|
|
834
|
-
}
|
|
835
|
-
else if (value.type === 'surfaceClaims') {
|
|
836
|
-
attached.capabilities.claims = value.claims;
|
|
837
|
-
for (const claim of value.claims)
|
|
838
|
-
if (claim.verbs === undefined)
|
|
839
|
-
this.claimedSeen.add(claim.subject.toLowerCase());
|
|
840
|
-
}
|
|
841
|
-
else {
|
|
842
|
-
this.send(socket, { type: 'error', reason: 'already attached' });
|
|
843
|
-
}
|
|
375
|
+
this.message_route(surface, viewer, message.value);
|
|
844
376
|
});
|
|
845
377
|
socket.on('close', () => {
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
378
|
+
this.surface_detach(surface, viewer);
|
|
379
|
+
});
|
|
380
|
+
}
|
|
381
|
+
/**
|
|
382
|
+
* Routes one message of an attached surface: a reply settles its request, a line runs, and the rest go to what
|
|
383
|
+
* owns them.
|
|
384
|
+
*
|
|
385
|
+
* @param attached - The surface that sent it.
|
|
386
|
+
* @param viewer - Its socket as a terminal's viewer.
|
|
387
|
+
* @param value - The message.
|
|
388
|
+
*/
|
|
389
|
+
message_route(attached, viewer, value) {
|
|
390
|
+
const socket = attached.socket;
|
|
391
|
+
if (this.replies.reply_settle(socket, value))
|
|
392
|
+
return;
|
|
393
|
+
if (value.type === 'execute') {
|
|
394
|
+
this.execute_route(attached, value);
|
|
395
|
+
}
|
|
396
|
+
else if (value.type === 'cancel') {
|
|
397
|
+
this.cancel_run(attached, value);
|
|
398
|
+
}
|
|
399
|
+
else if (value.type === 'stop') {
|
|
400
|
+
this.stop_run(attached);
|
|
401
|
+
}
|
|
402
|
+
else if (value.type === 'elevate') {
|
|
403
|
+
void this.elevate_run(attached, value);
|
|
404
|
+
}
|
|
405
|
+
else if (value.type === 'complete') {
|
|
406
|
+
void this.complete_run(socket, value);
|
|
407
|
+
}
|
|
408
|
+
else if (value.type === 'regard') {
|
|
409
|
+
this.regard_receive(value.regard);
|
|
410
|
+
}
|
|
411
|
+
else if (value.type === 'watch' || value.type === 'unwatch') {
|
|
412
|
+
this.watch_receive(attached, value.subject, value.type === 'watch');
|
|
413
|
+
}
|
|
414
|
+
else if (this.terminalMessage_route(socket, viewer, value)) {
|
|
415
|
+
return;
|
|
416
|
+
}
|
|
417
|
+
else if (this.hostPtyRelay.message_take(attached, value)) {
|
|
418
|
+
return;
|
|
419
|
+
}
|
|
420
|
+
else if (value.type === 'note') {
|
|
421
|
+
this.note_relay(viewer, value.text);
|
|
422
|
+
}
|
|
423
|
+
else if (value.type === 'surfaceClaims') {
|
|
424
|
+
attached.capabilities.claims = value.claims;
|
|
425
|
+
this.claimedWhole_note(value.claims);
|
|
426
|
+
}
|
|
427
|
+
else {
|
|
428
|
+
this.send(socket, { type: 'error', reason: 'already attached' });
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
/**
|
|
432
|
+
* Routes a line a surface sent: to the surface whose own language it is, or onto the lane.
|
|
433
|
+
*
|
|
434
|
+
* @param attached - The surface that sent it.
|
|
435
|
+
* @param value - The execute request.
|
|
436
|
+
*/
|
|
437
|
+
execute_route(attached, value) {
|
|
438
|
+
if (surface_isBrowser(attached))
|
|
439
|
+
this.browserActive = attached;
|
|
440
|
+
// A line in a surface's own language is that surface's to run: it never
|
|
441
|
+
// reaches the engine, and needs no turn on the lane (the session is not
|
|
442
|
+
// touched by it).
|
|
443
|
+
const claimant = value.instrument === true ? null : this.claimant_find(attached, value.line);
|
|
444
|
+
if (claimant !== null) {
|
|
445
|
+
void this.surfaceLine_run(attached, value, claimant);
|
|
446
|
+
return;
|
|
447
|
+
}
|
|
448
|
+
// One lane for every surface: commands take turns, and a command
|
|
449
|
+
// waiting on a person stands aside (person_await), so a pane's own
|
|
450
|
+
// reads, or another surface's command, run while a question is open.
|
|
451
|
+
void this.commandLane.line_run(attached, value);
|
|
452
|
+
}
|
|
453
|
+
/**
|
|
454
|
+
* Takes a surface's `terminal*` message: it opens, types into, sizes or closes a terminal it draws.
|
|
455
|
+
*
|
|
456
|
+
* @param socket - The surface's socket.
|
|
457
|
+
* @param viewer - Its socket as a terminal's viewer.
|
|
458
|
+
* @param value - The message.
|
|
459
|
+
* @returns False when the message is not a `terminal*` one.
|
|
460
|
+
*/
|
|
461
|
+
terminalMessage_route(socket, viewer, value) {
|
|
462
|
+
if (value.type === 'terminalOpen') {
|
|
463
|
+
if (this.terminals === null) {
|
|
464
|
+
this.send(socket, { type: 'terminalOpened', terminalId: '', replay: '', refused: 'this daemon offers no terminals (node-pty is not built here)' });
|
|
860
465
|
}
|
|
861
|
-
|
|
862
|
-
this.
|
|
863
|
-
this.
|
|
864
|
-
if (this.browserActive === surface)
|
|
865
|
-
this.browserActive = null;
|
|
866
|
-
// A detached surface holds no watches: whatever it kept live is
|
|
867
|
-
// released, and a subject nobody else watches stops being sampled.
|
|
868
|
-
this.engine.watch_release?.(surface.id);
|
|
869
|
-
this.engine.origin_forget?.(surface.id);
|
|
466
|
+
else {
|
|
467
|
+
const opened = this.terminals.open(viewer, value.cols, value.rows, value.terminalId);
|
|
468
|
+
this.send(socket, { type: 'terminalOpened', terminalId: opened.terminalId, replay: opened.replay });
|
|
870
469
|
}
|
|
871
|
-
}
|
|
470
|
+
}
|
|
471
|
+
else if (value.type === 'terminalInput') {
|
|
472
|
+
this.terminals?.input(viewer, value.terminalId, value.data);
|
|
473
|
+
}
|
|
474
|
+
else if (value.type === 'terminalResize') {
|
|
475
|
+
this.terminals?.resize(viewer, value.terminalId, value.cols, value.rows);
|
|
476
|
+
}
|
|
477
|
+
else if (value.type === 'terminalClose') {
|
|
478
|
+
this.terminals?.close(viewer, value.terminalId);
|
|
479
|
+
}
|
|
480
|
+
else {
|
|
481
|
+
return false;
|
|
482
|
+
}
|
|
483
|
+
return true;
|
|
484
|
+
}
|
|
485
|
+
/**
|
|
486
|
+
* Lets a surface go when its socket closes: its terminals keep running, its host programs and (for a shell) its
|
|
487
|
+
* commands hear the hang-up, and it leaves the bus.
|
|
488
|
+
*
|
|
489
|
+
* @param surface - The surface, or null when it never attached.
|
|
490
|
+
* @param viewer - Its socket as a terminal's viewer.
|
|
491
|
+
*/
|
|
492
|
+
surface_detach(surface, viewer) {
|
|
493
|
+
// Its terminals keep running, unwatched, for a reattach.
|
|
494
|
+
this.terminals?.detach(viewer);
|
|
495
|
+
// A program drawing on a terminal that went away hears the hang-up.
|
|
496
|
+
this.hostPtyRelay.surface_hangup(surface);
|
|
497
|
+
// A shell that goes away hangs up on its command, as a terminal's
|
|
498
|
+
// SIGHUP does: one still running is stopped, or nothing could stop it.
|
|
499
|
+
// A browser is not a shell (it reloads and reattaches), and its
|
|
500
|
+
// command runs on (a chell declares a filesystem; a browser does not).
|
|
501
|
+
if (surface && (surface.capabilities.localFilesystem || surface.capabilities.terminal !== undefined)) {
|
|
502
|
+
this.commandLane.surface_hangup(surface);
|
|
503
|
+
}
|
|
504
|
+
if (surface) {
|
|
505
|
+
this.surfaces.delete(surface);
|
|
506
|
+
this.viewerOf.delete(surface);
|
|
507
|
+
if (this.browserActive === surface)
|
|
508
|
+
this.browserActive = null;
|
|
509
|
+
// A detached surface holds no watches: whatever it kept live is
|
|
510
|
+
// released, and a subject nobody else watches stops being sampled.
|
|
511
|
+
this.engine.watch_release?.(surface.id);
|
|
512
|
+
this.engine.origin_forget?.(surface.id);
|
|
513
|
+
}
|
|
872
514
|
}
|
|
873
515
|
/**
|
|
874
516
|
* Whether the running command was typed in a browser's terminal.
|
|
@@ -876,7 +518,7 @@ export class CalypsoDaemon {
|
|
|
876
518
|
* @returns True for a terminal's chell.
|
|
877
519
|
*/
|
|
878
520
|
current_isTerminal() {
|
|
879
|
-
return this.currentOrigin?.capabilities.terminal !== undefined;
|
|
521
|
+
return this.commandLane.currentOrigin?.capabilities.terminal !== undefined;
|
|
880
522
|
}
|
|
881
523
|
/**
|
|
882
524
|
* The surface that acts for the running command: the one that issued it,
|
|
@@ -891,7 +533,7 @@ export class CalypsoDaemon {
|
|
|
891
533
|
* terminal's browser has gone.
|
|
892
534
|
*/
|
|
893
535
|
surfaceActing() {
|
|
894
|
-
const origin = this.currentOrigin;
|
|
536
|
+
const origin = this.commandLane.currentOrigin;
|
|
895
537
|
if (origin === null || origin.capabilities.terminal === undefined)
|
|
896
538
|
return origin;
|
|
897
539
|
const owner = this.terminals?.viewer_get(origin.capabilities.terminal)?.owner?.();
|
|
@@ -943,7 +585,7 @@ export class CalypsoDaemon {
|
|
|
943
585
|
return;
|
|
944
586
|
}
|
|
945
587
|
try {
|
|
946
|
-
const answer = await this.surfaceLines.open(claimant.socket, (lineId) => {
|
|
588
|
+
const answer = await this.replies.surfaceLines.open(claimant.socket, (lineId) => {
|
|
947
589
|
this.send(claimant.socket, { type: 'surfaceLine', lineId, line: message.line, ...(origin.capabilities.terminal !== undefined ? { terminal: origin.capabilities.terminal } : {}) });
|
|
948
590
|
});
|
|
949
591
|
const rendered = answer.rendered === '' || answer.rendered.endsWith('\n') ? answer.rendered : `${answer.rendered}\n`;
|
|
@@ -986,49 +628,22 @@ export class CalypsoDaemon {
|
|
|
986
628
|
*
|
|
987
629
|
* @param origin - Surface asking to cancel a command.
|
|
988
630
|
* @param message - Correlated command identifier to cancel.
|
|
989
|
-
* @returns Nothing. The running command reports its normal final envelope.
|
|
990
631
|
*/
|
|
991
632
|
cancel_run(origin, message) {
|
|
992
|
-
|
|
993
|
-
if (slot === undefined) {
|
|
633
|
+
if (!this.commandLane.foreground_cancel(origin, message.id)) {
|
|
994
634
|
this.send(origin.socket, { type: 'error', reason: 'cancel: no matching foreground command' });
|
|
995
|
-
return;
|
|
996
635
|
}
|
|
997
|
-
// Ctrl-C is a stop: the command is asked to end, and abandoned if it does not.
|
|
998
|
-
this.command_stop(slot);
|
|
999
636
|
}
|
|
1000
637
|
/**
|
|
1001
638
|
* The operator's STOP: ends the command running for this surface, its own
|
|
1002
639
|
* or one typed in a terminal it owns, whatever the command is.
|
|
1003
640
|
*
|
|
1004
641
|
* @param origin - The surface pressing STOP.
|
|
1005
|
-
* @param _message - The request.
|
|
1006
642
|
*/
|
|
1007
|
-
stop_run(origin
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
const stoppable = (slot) => !slot.instrument && (this.stopper_resolve(slot.origin) === origin || !this.surfaces.has(slot.origin));
|
|
1011
|
-
const working = [...this.running].filter((slot) => slot.hold !== null && stoppable(slot));
|
|
1012
|
-
if (working.length > 0) {
|
|
1013
|
-
for (const slot of working)
|
|
1014
|
-
this.command_stop(slot);
|
|
1015
|
-
return;
|
|
1016
|
-
}
|
|
1017
|
-
// Its command may be waiting aside on a task: stopped where it waits,
|
|
1018
|
-
// its own surface's first, else one whose surface has gone.
|
|
1019
|
-
const asides = [...this.running].filter((slot) => slot.hold === null && slot.asideStoppable && stoppable(slot));
|
|
1020
|
-
const aside = asides.find((slot) => this.stopper_resolve(slot.origin) === origin) ?? asides[0];
|
|
1021
|
-
if (aside !== undefined) {
|
|
1022
|
-
this.engine.line_abort?.(aside.key);
|
|
1023
|
-
return;
|
|
643
|
+
stop_run(origin) {
|
|
644
|
+
if (!this.commandLane.stop_press(origin)) {
|
|
645
|
+
this.send(origin.socket, { type: 'error', reason: 'stop: nothing of yours is running' });
|
|
1024
646
|
}
|
|
1025
|
-
// Its command may be waiting its turn behind someone else's: it is
|
|
1026
|
-
// stopped the moment it starts, without running.
|
|
1027
|
-
if (this.lane.waiting > 0) {
|
|
1028
|
-
this.stopPending.set(origin, Date.now());
|
|
1029
|
-
return;
|
|
1030
|
-
}
|
|
1031
|
-
this.send(origin.socket, { type: 'error', reason: 'stop: nothing of yours is running' });
|
|
1032
647
|
}
|
|
1033
648
|
/**
|
|
1034
649
|
* Raises a surface to MANAGE: its password checked at the door, the
|
|
@@ -1068,20 +683,6 @@ export class CalypsoDaemon {
|
|
|
1068
683
|
const owner = surface.capabilities.terminal === undefined ? null : this.terminals?.viewer_get(surface.capabilities.terminal)?.owner?.();
|
|
1069
684
|
return owner !== null && owner !== undefined && this.surfaces.has(owner) ? owner : surface;
|
|
1070
685
|
}
|
|
1071
|
-
/**
|
|
1072
|
-
* Stops the running command: its signal is aborted (a command that checks
|
|
1073
|
-
* it ends, a host process it started is killed), and one still running
|
|
1074
|
-
* after {@link STOP_GRACE_MS} is abandoned, so the session is free again
|
|
1075
|
-
* whatever the command was waiting on.
|
|
1076
|
-
*/
|
|
1077
|
-
command_stop(slot) {
|
|
1078
|
-
this.engine.line_abort?.(slot.key) ?? this.engine.line_cancel?.(slot.key);
|
|
1079
|
-
const timer = setTimeout(() => {
|
|
1080
|
-
if (this.running.has(slot))
|
|
1081
|
-
slot.abandon?.();
|
|
1082
|
-
}, STOP_GRACE_MS);
|
|
1083
|
-
timer.unref?.();
|
|
1084
|
-
}
|
|
1085
686
|
/**
|
|
1086
687
|
* Validates an attach handshake: contract version, then constant-time
|
|
1087
688
|
* token check. On success the surface is acknowledged, registered on the
|
|
@@ -1108,25 +709,9 @@ export class CalypsoDaemon {
|
|
|
1108
709
|
}
|
|
1109
710
|
// Each connection is a distinct surface (its own bus tag); all attach to
|
|
1110
711
|
// the one shared session returned in the ack.
|
|
1111
|
-
const surface =
|
|
1112
|
-
socket,
|
|
1113
|
-
id: randomBytes(8).toString('hex'),
|
|
1114
|
-
capabilities: {
|
|
1115
|
-
shellCommands: attach.value.capabilities?.shellCommands ?? false,
|
|
1116
|
-
hiddenInput: attach.value.capabilities?.hiddenInput ?? false,
|
|
1117
|
-
fileDelivery: attach.value.capabilities?.fileDelivery ?? false,
|
|
1118
|
-
localFilesystem: attach.value.capabilities?.localFilesystem ?? false,
|
|
1119
|
-
color: attach.value.capabilities?.color ?? false,
|
|
1120
|
-
claims: attach.value.capabilities?.claims ?? [],
|
|
1121
|
-
...(attach.value.capabilities?.terminal !== undefined ? { terminal: attach.value.capabilities.terminal } : {}),
|
|
1122
|
-
...(attach.value.capabilities?.tty !== undefined ? { tty: { ...attach.value.capabilities.tty } } : {}),
|
|
1123
|
-
tasksGranted: false,
|
|
1124
|
-
},
|
|
1125
|
-
};
|
|
712
|
+
const surface = surfaceFromAttach_build(socket, attach.value);
|
|
1126
713
|
this.surfaces.add(surface);
|
|
1127
|
-
|
|
1128
|
-
if (claim.verbs === undefined)
|
|
1129
|
-
this.claimedSeen.add(claim.subject.toLowerCase());
|
|
714
|
+
this.claimedWhole_note(surface.capabilities.claims);
|
|
1130
715
|
this.send(socket, {
|
|
1131
716
|
type: 'attached',
|
|
1132
717
|
session: this.sessionId,
|
|
@@ -1138,6 +723,8 @@ export class CalypsoDaemon {
|
|
|
1138
723
|
// Declared state, present from the first frame: a surface's lamp and a
|
|
1139
724
|
// remote shell's banner read it, never infer it.
|
|
1140
725
|
hostControl: this.hostControl,
|
|
726
|
+
// Which words run in the engine, so a surface routes a pipeline as the engine will.
|
|
727
|
+
...(this.engineCommands !== undefined ? { engineCommands: [...this.engineCommands()] } : {}),
|
|
1141
728
|
// Whether this session can be raised to MANAGE with the person's password.
|
|
1142
729
|
elevation: this.elevation !== undefined,
|
|
1143
730
|
// Whether this process still runs the code on its disk; a surface
|
|
@@ -1158,6 +745,17 @@ export class CalypsoDaemon {
|
|
|
1158
745
|
}
|
|
1159
746
|
return surface;
|
|
1160
747
|
}
|
|
748
|
+
/**
|
|
749
|
+
* Remembers the subjects a surface claims whole, so a line in one is refused by name once no surface claiming it
|
|
750
|
+
* is attached.
|
|
751
|
+
*
|
|
752
|
+
* @param claims - What the surface claims.
|
|
753
|
+
*/
|
|
754
|
+
claimedWhole_note(claims) {
|
|
755
|
+
for (const claim of claims)
|
|
756
|
+
if (claim.verbs === undefined)
|
|
757
|
+
this.claimedSeen.add(claim.subject.toLowerCase());
|
|
758
|
+
}
|
|
1161
759
|
/**
|
|
1162
760
|
* Opens or closes a surface's watch on a subject and answers with the
|
|
1163
761
|
* subject's state. A daemon whose engine cannot watch says so rather than
|
|
@@ -1288,129 +886,52 @@ export class CalypsoDaemon {
|
|
|
1288
886
|
}
|
|
1289
887
|
}
|
|
1290
888
|
/**
|
|
1291
|
-
*
|
|
1292
|
-
*
|
|
1293
|
-
*
|
|
889
|
+
* Notes a line that ended, for the prompt context, and refreshes the prompt. A remote REPL draws its next prompt
|
|
890
|
+
* as soon as `result` resolves the command, so the line awaits this before it is answered: the prompt cannot lag
|
|
891
|
+
* one command behind state changes such as `cd`. Returns the push itself, so the line waits on nothing more.
|
|
1294
892
|
*
|
|
1295
|
-
* @param
|
|
1296
|
-
* @
|
|
1297
|
-
|
|
1298
|
-
lineWant_get(line) {
|
|
1299
|
-
let held = 'all';
|
|
1300
|
-
try {
|
|
1301
|
-
held = this.engine.line_holds?.(line) ?? 'all';
|
|
1302
|
-
}
|
|
1303
|
-
catch {
|
|
1304
|
-
// A line the engine cannot read runs alone, as every line once did.
|
|
1305
|
-
}
|
|
1306
|
-
return held === 'all' ? LOCKS_ALL : new Set(held);
|
|
1307
|
-
}
|
|
1308
|
-
/**
|
|
1309
|
-
* Runs one line in its turn: it waits until nothing running holds what it
|
|
1310
|
-
* changes, then runs in a slot of its own.
|
|
1311
|
-
*
|
|
1312
|
-
* @param origin - The surface that submitted the request.
|
|
1313
|
-
* @param message - The execute request.
|
|
893
|
+
* @param slot - The line's slot, holding its turn.
|
|
894
|
+
* @param exitCode - Its exit status.
|
|
895
|
+
* @returns The prompt push.
|
|
1314
896
|
*/
|
|
1315
|
-
|
|
1316
|
-
this.
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
origin,
|
|
1320
|
-
id: message.id,
|
|
1321
|
-
instrument: message.instrument === true,
|
|
1322
|
-
line: message.line,
|
|
1323
|
-
startedAt: performance.now(),
|
|
1324
|
-
want: this.lineWant_get(message.line),
|
|
1325
|
-
hold: null,
|
|
1326
|
-
asideStoppable: false,
|
|
1327
|
-
abandon: null,
|
|
897
|
+
line_end(slot, exitCode) {
|
|
898
|
+
this.lastCommand = {
|
|
899
|
+
durationMs: Math.round(performance.now() - slot.startedAt),
|
|
900
|
+
exitCode,
|
|
1328
901
|
};
|
|
1329
|
-
|
|
1330
|
-
slot.startedAt = performance.now();
|
|
1331
|
-
this.running.add(slot);
|
|
1332
|
-
try {
|
|
1333
|
-
// The command runs inside its own slot, so whatever the engine raises
|
|
1334
|
-
// (a prompt, output, a pipe segment) reaches the surface that
|
|
1335
|
-
// submitted it, whatever else runs meanwhile.
|
|
1336
|
-
await this.slotScope.run(slot, () => this.execute_run(slot, message));
|
|
1337
|
-
}
|
|
1338
|
-
finally {
|
|
1339
|
-
this.running.delete(slot);
|
|
1340
|
-
if (slot.hold !== null)
|
|
1341
|
-
this.lane.release(slot.hold);
|
|
1342
|
-
slot.hold = null;
|
|
1343
|
-
}
|
|
902
|
+
return this.promptline_push();
|
|
1344
903
|
}
|
|
1345
904
|
/**
|
|
1346
|
-
*
|
|
1347
|
-
* publishes each envelope to the session bus.
|
|
905
|
+
* Answers a line that ended: replies to the requester with the result, and
|
|
906
|
+
* publishes each envelope to the session bus. Runs inside the line's slot,
|
|
907
|
+
* while it still holds its turn.
|
|
1348
908
|
*
|
|
1349
909
|
* @param slot - The line's slot, holding its turn.
|
|
1350
910
|
* @param message - The execute request.
|
|
911
|
+
* @param outcome - What the line came to.
|
|
1351
912
|
*/
|
|
1352
|
-
|
|
913
|
+
line_answer(slot, message, outcome) {
|
|
1353
914
|
const origin = slot.origin;
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
//
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
this.stopPending.delete(stopper);
|
|
1365
|
-
if (pendingAt !== undefined && Date.now() - pendingAt < STOP_PENDING_MS) {
|
|
1366
|
-
envelopes = [{ status: 'error', rendered: '', renderedErr: `stopped: \`${message.line}\` was stopped before it ran\n` }];
|
|
1367
|
-
}
|
|
1368
|
-
else
|
|
1369
|
-
try {
|
|
1370
|
-
// A stopped command that does not end is abandoned: the session
|
|
1371
|
-
// stops waiting, and whatever it does later is no one's.
|
|
1372
|
-
const abandoned = new Promise((resolve) => {
|
|
1373
|
-
slot.abandon = () => resolve([{ status: 'error', rendered: '', renderedErr: `stopped: \`${message.line}\` did not end when asked and was abandoned\n` }]);
|
|
1374
|
-
});
|
|
1375
|
-
// The line counts against its surface's own last answer: a terminal
|
|
1376
|
-
// a surface shows is that surface (#1273).
|
|
1377
|
-
envelopes = await Promise.race([this.engine.line_execute(message.line, { origin: stopper.id, id: slot.key, ended: (code) => { lineExit = code; } }), abandoned]);
|
|
1378
|
-
}
|
|
1379
|
-
catch (err) {
|
|
1380
|
-
failureReason = err instanceof Error ? err.message : String(err);
|
|
915
|
+
const { envelopes, failureReason, exitCode } = outcome;
|
|
916
|
+
if (envelopes !== undefined) {
|
|
917
|
+
this.send(origin.socket, { type: 'result', id: message.id, envelopes, exitCode });
|
|
918
|
+
// Instrument traffic (a panel's silent refresh, an ambient cycler)
|
|
919
|
+
// is surface-internal: it never enters the session bus or the
|
|
920
|
+
// scrollback, so siblings and reattach replays carry only what the
|
|
921
|
+
// operator actually did.
|
|
922
|
+
if (message.instrument !== true) {
|
|
923
|
+
for (const envelope of envelopes) {
|
|
924
|
+
this.bus_publish(origin, envelope, message.mirrored === true);
|
|
1381
925
|
}
|
|
1382
|
-
finally {
|
|
1383
|
-
slot.abandon = null;
|
|
1384
|
-
}
|
|
1385
|
-
const exitCode = lineExit_derive(envelopes, failureReason, lineExit);
|
|
1386
|
-
this.lastCommand = {
|
|
1387
|
-
durationMs: Math.round(performance.now() - startedAt),
|
|
1388
|
-
exitCode,
|
|
1389
|
-
};
|
|
1390
|
-
// A remote REPL draws its next prompt as soon as `result` resolves the
|
|
1391
|
-
// command. Push the refreshed context first so that prompt cannot lag
|
|
1392
|
-
// one command behind state changes such as `cd`.
|
|
1393
|
-
await this.promptline_push();
|
|
1394
|
-
if (envelopes !== undefined) {
|
|
1395
|
-
this.send(origin.socket, { type: 'result', id: message.id, envelopes, exitCode });
|
|
1396
|
-
// Instrument traffic (a panel's silent refresh, an ambient cycler)
|
|
1397
|
-
// is surface-internal: it never enters the session bus or the
|
|
1398
|
-
// scrollback, so siblings and reattach replays carry only what the
|
|
1399
|
-
// operator actually did.
|
|
1400
|
-
if (message.instrument !== true) {
|
|
1401
|
-
for (const envelope of envelopes) {
|
|
1402
|
-
this.bus_publish(origin, envelope, message.mirrored === true);
|
|
1403
|
-
}
|
|
1404
|
-
}
|
|
1405
|
-
}
|
|
1406
|
-
else {
|
|
1407
|
-
this.send(origin.socket, {
|
|
1408
|
-
type: 'error',
|
|
1409
|
-
id: message.id,
|
|
1410
|
-
reason: failureReason ?? 'engine execution failed',
|
|
1411
|
-
});
|
|
1412
926
|
}
|
|
1413
927
|
}
|
|
928
|
+
else {
|
|
929
|
+
this.send(origin.socket, {
|
|
930
|
+
type: 'error',
|
|
931
|
+
id: message.id,
|
|
932
|
+
reason: failureReason ?? 'engine execution failed',
|
|
933
|
+
});
|
|
934
|
+
}
|
|
1414
935
|
}
|
|
1415
936
|
/**
|
|
1416
937
|
* Takes a hold for work no line of a surface runs (a joblet): it waits in
|
|
@@ -1420,46 +941,8 @@ export class CalypsoDaemon {
|
|
|
1420
941
|
* @param holds - What the work changes, or 'all'.
|
|
1421
942
|
* @returns Gives the hold back; a second call does nothing.
|
|
1422
943
|
*/
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
let given = false;
|
|
1426
|
-
return () => {
|
|
1427
|
-
if (given)
|
|
1428
|
-
return;
|
|
1429
|
-
given = true;
|
|
1430
|
-
this.lane.release(hold);
|
|
1431
|
-
};
|
|
1432
|
-
}
|
|
1433
|
-
/**
|
|
1434
|
-
* Waits on a person without holding the session: the request is sent and
|
|
1435
|
-
* what the line holds given up, so other lines run; when the person
|
|
1436
|
-
* answers, the line queues for its turn again.
|
|
1437
|
-
*
|
|
1438
|
-
* @param ask - Sends the request (under the asking command's slot) and
|
|
1439
|
-
* resolves with the person's answer.
|
|
1440
|
-
* @returns The answer.
|
|
1441
|
-
*/
|
|
1442
|
-
async person_await(ask, stoppable = false) {
|
|
1443
|
-
const answered = ask();
|
|
1444
|
-
const mine = this.slotScope.getStore();
|
|
1445
|
-
if (mine === undefined || mine.hold === null)
|
|
1446
|
-
return await answered;
|
|
1447
|
-
// What the line holds is given up while it waits, and its slot stays
|
|
1448
|
-
// its own: the engine keeps its per-line state (its exit code, a pipe's
|
|
1449
|
-
// untaken input, its cancellation) per line, so nothing is handed over.
|
|
1450
|
-
// A line waiting aside on a task stays the operator's to stop, and
|
|
1451
|
-
// stays so while it waits for its turn again behind another's line: a
|
|
1452
|
-
// STOP in that moment would otherwise find nothing of theirs running.
|
|
1453
|
-
mine.asideStoppable = stoppable && !mine.instrument;
|
|
1454
|
-
this.lane.release(mine.hold);
|
|
1455
|
-
mine.hold = null;
|
|
1456
|
-
try {
|
|
1457
|
-
return await answered;
|
|
1458
|
-
}
|
|
1459
|
-
finally {
|
|
1460
|
-
mine.hold = await this.lane.acquire(mine.want);
|
|
1461
|
-
mine.asideStoppable = false;
|
|
1462
|
-
}
|
|
944
|
+
hold_take(holds) {
|
|
945
|
+
return this.commandLane.hold_take(holds);
|
|
1463
946
|
}
|
|
1464
947
|
/**
|
|
1465
948
|
* Waits aside: the running command steps out of the lane while it waits
|
|
@@ -1471,9 +954,7 @@ export class CalypsoDaemon {
|
|
|
1471
954
|
* @returns What that resolved with.
|
|
1472
955
|
*/
|
|
1473
956
|
aside_current(waiting) {
|
|
1474
|
-
|
|
1475
|
-
return waiting;
|
|
1476
|
-
return this.person_await(() => waiting, true);
|
|
957
|
+
return this.commandLane.aside_await(waiting);
|
|
1477
958
|
}
|
|
1478
959
|
/**
|
|
1479
960
|
* Raises a prompt on the surface running the current command, returning its
|
|
@@ -1491,11 +972,11 @@ export class CalypsoDaemon {
|
|
|
1491
972
|
// A stopped command may not ask anyone anything.
|
|
1492
973
|
if (this.engine.command_stopped?.() === true)
|
|
1493
974
|
return Promise.reject(new Error('the command was stopped'));
|
|
1494
|
-
const origin = this.currentOrigin;
|
|
975
|
+
const origin = this.commandLane.currentOrigin;
|
|
1495
976
|
if (!origin) {
|
|
1496
977
|
return Promise.reject(new Error('no active command to prompt for'));
|
|
1497
978
|
}
|
|
1498
|
-
if (this.currentInstrument) {
|
|
979
|
+
if (this.commandLane.currentInstrument) {
|
|
1499
980
|
// A surface's own housekeeping asked the operator a question. It is
|
|
1500
981
|
// refused here rather than shown, because the operator did not issue
|
|
1501
982
|
// the command that raised it and cannot be expected to answer for it.
|
|
@@ -1504,7 +985,7 @@ export class CalypsoDaemon {
|
|
|
1504
985
|
if (request.hidden && !origin.capabilities.hiddenInput) {
|
|
1505
986
|
return Promise.reject(new Error('this surface cannot securely collect hidden input'));
|
|
1506
987
|
}
|
|
1507
|
-
if (this.prompts.pending_has(origin.socket)) {
|
|
988
|
+
if (this.replies.prompts.pending_has(origin.socket)) {
|
|
1508
989
|
// One question at a time. Queuing them invisibly hands an operator a
|
|
1509
990
|
// question whose command they have forgotten issuing.
|
|
1510
991
|
return Promise.reject(new Error('another question is already open on this surface'));
|
|
@@ -1517,7 +998,9 @@ export class CalypsoDaemon {
|
|
|
1517
998
|
this.questionsOpen.delete(origin);
|
|
1518
999
|
void this.promptline_push();
|
|
1519
1000
|
};
|
|
1520
|
-
|
|
1001
|
+
// The command that asks, by the id its surface gave it: read now, while it is the one running.
|
|
1002
|
+
const executeId = this.commandLane.currentId;
|
|
1003
|
+
return this.commandLane.person_await(() => this.replies.prompts.open(origin.socket, (promptId) => {
|
|
1521
1004
|
this.send(origin.socket, {
|
|
1522
1005
|
type: 'prompt',
|
|
1523
1006
|
promptId,
|
|
@@ -1526,6 +1009,9 @@ export class CalypsoDaemon {
|
|
|
1526
1009
|
...(request.wants === undefined ? {} : { wants: request.wants }),
|
|
1527
1010
|
...(request.path === undefined ? {} : { path: request.path }),
|
|
1528
1011
|
...(request.commit === undefined ? {} : { commit: request.commit }),
|
|
1012
|
+
...(executeId === null ? {} : { executeId }),
|
|
1013
|
+
...(request.purpose === undefined ? {} : { purpose: request.purpose }),
|
|
1014
|
+
...(request.subject === undefined ? {} : { subject: request.subject }),
|
|
1529
1015
|
});
|
|
1530
1016
|
}).finally(settled));
|
|
1531
1017
|
}
|
|
@@ -1538,8 +1024,8 @@ export class CalypsoDaemon {
|
|
|
1538
1024
|
* @returns True when the event was sent to a surface.
|
|
1539
1025
|
*/
|
|
1540
1026
|
progress_current(event) {
|
|
1541
|
-
const origin = this.currentOrigin;
|
|
1542
|
-
const id = this.currentId;
|
|
1027
|
+
const origin = this.commandLane.currentOrigin;
|
|
1028
|
+
const id = this.commandLane.currentId;
|
|
1543
1029
|
if (!origin || !id || origin.socket.readyState !== WebSocket.OPEN) {
|
|
1544
1030
|
return false;
|
|
1545
1031
|
}
|
|
@@ -1558,8 +1044,8 @@ export class CalypsoDaemon {
|
|
|
1558
1044
|
event_current(kind, data) {
|
|
1559
1045
|
if (this.engine.command_stopped?.() === true)
|
|
1560
1046
|
return false;
|
|
1561
|
-
const origin = this.currentOrigin;
|
|
1562
|
-
const id = this.currentId;
|
|
1047
|
+
const origin = this.commandLane.currentOrigin;
|
|
1048
|
+
const id = this.commandLane.currentId;
|
|
1563
1049
|
if (!origin || !id || origin.socket.readyState !== WebSocket.OPEN) {
|
|
1564
1050
|
return false;
|
|
1565
1051
|
}
|
|
@@ -1579,8 +1065,8 @@ export class CalypsoDaemon {
|
|
|
1579
1065
|
// An abandoned command's late output belongs to no one.
|
|
1580
1066
|
if (this.engine.command_stopped?.() === true)
|
|
1581
1067
|
return false;
|
|
1582
|
-
const origin = this.currentOrigin;
|
|
1583
|
-
const id = this.currentId;
|
|
1068
|
+
const origin = this.commandLane.currentOrigin;
|
|
1069
|
+
const id = this.commandLane.currentId;
|
|
1584
1070
|
if (!origin || !id || origin.socket.readyState !== WebSocket.OPEN) {
|
|
1585
1071
|
return false;
|
|
1586
1072
|
}
|
|
@@ -1603,10 +1089,29 @@ export class CalypsoDaemon {
|
|
|
1603
1089
|
if (!origin) {
|
|
1604
1090
|
return Promise.reject(new Error('no active command to run a pipe segment for'));
|
|
1605
1091
|
}
|
|
1606
|
-
|
|
1607
|
-
|
|
1092
|
+
const elsewhere = this.elsewhere_refusal(origin, 'a pipeline segment');
|
|
1093
|
+
if (elsewhere !== null)
|
|
1094
|
+
return Promise.reject(new Error(elsewhere));
|
|
1095
|
+
const lineId = this.commandLane.currentId;
|
|
1096
|
+
return this.replies.pipes.open(origin.socket, (pipeId) => {
|
|
1097
|
+
this.send(origin.socket, { type: 'pipe', pipeId, command, input: input.toString('base64'), ...(lineId === null ? {} : { lineId }) });
|
|
1608
1098
|
});
|
|
1609
1099
|
}
|
|
1100
|
+
/**
|
|
1101
|
+
* Why a request for a program on a surface's machine may not go where it would: to a surface other than the one
|
|
1102
|
+
* that sent the running line (a browser holding the terminal that typed it). That surface did not send the line
|
|
1103
|
+
* and has nothing to run it against, so the daemon refuses here, before anything is sent, and the line says why.
|
|
1104
|
+
*
|
|
1105
|
+
* @param acting - The surface the request would go to.
|
|
1106
|
+
* @param what - What would run, for the words.
|
|
1107
|
+
* @returns The refusal, or null when it goes to the line's own surface.
|
|
1108
|
+
*/
|
|
1109
|
+
elsewhere_refusal(acting, what) {
|
|
1110
|
+
const origin = this.commandLane.currentOrigin;
|
|
1111
|
+
if (origin === null || origin === acting)
|
|
1112
|
+
return null;
|
|
1113
|
+
return `${what} for this line would run on another surface than the one that sent it; nothing ran`;
|
|
1114
|
+
}
|
|
1610
1115
|
/**
|
|
1611
1116
|
* Runs a host-shell command on the surface running the current command.
|
|
1612
1117
|
* The daemon never spawns the process itself.
|
|
@@ -1618,15 +1123,19 @@ export class CalypsoDaemon {
|
|
|
1618
1123
|
shell_current(command, toIssuer = false) {
|
|
1619
1124
|
// Under host control a terminal's own chell runs it, in its pty: it is
|
|
1620
1125
|
// on this host already, and a full-screen program gets a terminal.
|
|
1621
|
-
const origin = toIssuer ? this.currentOrigin : this.surfaceActing();
|
|
1126
|
+
const origin = toIssuer ? this.commandLane.currentOrigin : this.surfaceActing();
|
|
1622
1127
|
if (!origin) {
|
|
1623
1128
|
return Promise.reject(new Error('no active command to run a shell command for'));
|
|
1624
1129
|
}
|
|
1625
1130
|
if (!origin.capabilities.shellCommands) {
|
|
1626
1131
|
return Promise.reject(new Error('this surface has no shell, and the daemon was not started with --host-control'));
|
|
1627
1132
|
}
|
|
1628
|
-
|
|
1629
|
-
|
|
1133
|
+
const elsewhere = this.elsewhere_refusal(origin, 'a host command');
|
|
1134
|
+
if (elsewhere !== null)
|
|
1135
|
+
return Promise.reject(new Error(elsewhere));
|
|
1136
|
+
const lineId = this.commandLane.currentId;
|
|
1137
|
+
return this.replies.shells.open(origin.socket, (shellId) => {
|
|
1138
|
+
this.send(origin.socket, { type: 'shell', shellId, command, ...(lineId === null ? {} : { lineId }) });
|
|
1630
1139
|
});
|
|
1631
1140
|
}
|
|
1632
1141
|
/**
|
|
@@ -1645,34 +1154,7 @@ export class CalypsoDaemon {
|
|
|
1645
1154
|
* const code: number | null = await daemon.hostPty_current('nvim notes.txt', signal);
|
|
1646
1155
|
*/
|
|
1647
1156
|
hostPty_current(command, signal) {
|
|
1648
|
-
|
|
1649
|
-
if (origin === null || origin.capabilities.tty === undefined || this.ptySpawn === null)
|
|
1650
|
-
return null;
|
|
1651
|
-
if (origin.socket.readyState !== WebSocket.OPEN)
|
|
1652
|
-
return null;
|
|
1653
|
-
const ptyId = randomBytes(8).toString('hex');
|
|
1654
|
-
// The surface takes its terminal over to the program before any byte arrives.
|
|
1655
|
-
this.send(origin.socket, { type: 'hostPtyStart', ptyId });
|
|
1656
|
-
let run;
|
|
1657
|
-
try {
|
|
1658
|
-
run = hostPty_start(this.ptySpawn, command, {
|
|
1659
|
-
terminal: origin.capabilities.tty,
|
|
1660
|
-
cwd: process.cwd(),
|
|
1661
|
-
env: process.env,
|
|
1662
|
-
data: (data) => this.send(origin.socket, { type: 'hostPtyData', ptyId, data }),
|
|
1663
|
-
...(signal !== undefined ? { signal } : {}),
|
|
1664
|
-
});
|
|
1665
|
-
}
|
|
1666
|
-
catch (error) {
|
|
1667
|
-
this.send(origin.socket, { type: 'hostPtyExit', ptyId, code: 1 });
|
|
1668
|
-
return Promise.reject(error instanceof Error ? error : new Error(String(error)));
|
|
1669
|
-
}
|
|
1670
|
-
this.hostPtys.set(ptyId, { surface: origin, run });
|
|
1671
|
-
return run.done.then((code) => {
|
|
1672
|
-
this.hostPtys.delete(ptyId);
|
|
1673
|
-
this.send(origin.socket, { type: 'hostPtyExit', ptyId, code });
|
|
1674
|
-
return code;
|
|
1675
|
-
});
|
|
1157
|
+
return this.hostPtyRelay.pty_run(this.commandLane.currentOrigin, this.commandLane.currentId, command, signal);
|
|
1676
1158
|
}
|
|
1677
1159
|
/**
|
|
1678
1160
|
* Opens content in the editor of the surface running the current command
|
|
@@ -1684,18 +1166,23 @@ export class CalypsoDaemon {
|
|
|
1684
1166
|
* @param extension - An optional filename extension for syntax mode.
|
|
1685
1167
|
* @param path - The file being edited, for an editor that stays open and
|
|
1686
1168
|
* saves back to it (a browser's editor pane).
|
|
1169
|
+
* @param named - The file as the line typed it, so a surface on another
|
|
1170
|
+
* machine holds the edit to its own line's operand.
|
|
1687
1171
|
* @returns The edited content and whether it changed, or that an editor
|
|
1688
1172
|
* which stays open took it.
|
|
1689
1173
|
* @throws {Error} When no command is executing or the surface disconnects.
|
|
1690
1174
|
*/
|
|
1691
|
-
edit_current(content, extension, path) {
|
|
1175
|
+
edit_current(content, extension, path, named) {
|
|
1692
1176
|
const origin = this.surfaceActing();
|
|
1693
1177
|
if (!origin) {
|
|
1694
1178
|
return Promise.reject(new Error('no active command to edit for'));
|
|
1695
1179
|
}
|
|
1180
|
+
// The asking line's id goes only to the surface that sent the line; a browser holding a terminal's line edits
|
|
1181
|
+
// by its own route and needs none.
|
|
1182
|
+
const lineId = origin === this.commandLane.currentOrigin ? this.commandLane.currentId : null;
|
|
1696
1183
|
// Someone is editing: the session is free meanwhile.
|
|
1697
|
-
return this.person_await(() => this.edits.open(origin.socket, (editId) => {
|
|
1698
|
-
this.send(origin.socket, { type: 'edit', editId, content, extension, ...(path === undefined ? {} : { path }) });
|
|
1184
|
+
return this.commandLane.person_await(() => this.replies.edits.open(origin.socket, (editId) => {
|
|
1185
|
+
this.send(origin.socket, { type: 'edit', editId, content, extension, ...(path === undefined ? {} : { path }), ...(named === undefined ? {} : { named }), ...(lineId === null ? {} : { lineId }) });
|
|
1699
1186
|
}));
|
|
1700
1187
|
}
|
|
1701
1188
|
/**
|
|
@@ -1716,7 +1203,7 @@ export class CalypsoDaemon {
|
|
|
1716
1203
|
return [...this.surfaces].map((each) => ({
|
|
1717
1204
|
id: each.id,
|
|
1718
1205
|
kind: each.capabilities.shellCommands ? 'chell' : 'browser',
|
|
1719
|
-
you: each === this.currentOrigin,
|
|
1206
|
+
you: each === this.commandLane.currentOrigin,
|
|
1720
1207
|
...(this.questionsOpen.has(each) ? { asking: this.questionsOpen.get(each).message } : {}),
|
|
1721
1208
|
}));
|
|
1722
1209
|
}
|
|
@@ -1729,7 +1216,7 @@ export class CalypsoDaemon {
|
|
|
1729
1216
|
tasks: origin.capabilities.tasksGranted,
|
|
1730
1217
|
// A surface that runs shell commands (a chell) runs pipe segments too.
|
|
1731
1218
|
pipeSegments: origin.capabilities.shellCommands,
|
|
1732
|
-
color: this.currentOrigin?.capabilities.color ?? origin.capabilities.color,
|
|
1219
|
+
color: this.commandLane.currentOrigin?.capabilities.color ?? origin.capabilities.color,
|
|
1733
1220
|
} : null;
|
|
1734
1221
|
}
|
|
1735
1222
|
/**
|
|
@@ -1754,15 +1241,20 @@ export class CalypsoDaemon {
|
|
|
1754
1241
|
if (!origin.capabilities.fileDelivery) {
|
|
1755
1242
|
return Promise.reject(new Error('this surface cannot receive a file'));
|
|
1756
1243
|
}
|
|
1757
|
-
|
|
1244
|
+
// The surface's own id for the line that is asking: it binds the delivery to that line. Only the surface that
|
|
1245
|
+
// sent the line is told it; a browser holding a terminal's line delivers by its own route, with no line of its own.
|
|
1246
|
+
const line = origin === this.commandLane.currentOrigin ? this.commandLane.currentId : null;
|
|
1247
|
+
return this.replies.deliveries.open(origin.socket, (deliverId) => {
|
|
1758
1248
|
this.send(origin.socket, {
|
|
1759
1249
|
type: 'deliver',
|
|
1760
1250
|
deliverId,
|
|
1251
|
+
...(line !== null ? { id: line } : {}),
|
|
1761
1252
|
path: request.path,
|
|
1762
1253
|
filename: request.filename,
|
|
1763
1254
|
...(request.destination !== undefined ? { destination: request.destination } : {}),
|
|
1764
1255
|
...(request.size !== undefined ? { size: request.size } : {}),
|
|
1765
1256
|
...(request.contentType !== undefined ? { contentType: request.contentType } : {}),
|
|
1257
|
+
...(request.source !== undefined ? { source: request.source } : {}),
|
|
1766
1258
|
});
|
|
1767
1259
|
});
|
|
1768
1260
|
}
|