@fnndsc/calypso 0.21.4 → 0.23.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.
@@ -32,6 +32,8 @@ import { token_matches } from './token.js';
32
32
  import { RequestBroker } from './broker.js';
33
33
  import { CONTRACT_VERSION } from '@fnndsc/menu';
34
34
  import { clientMessage_parse, attach_parse } from '@fnndsc/menu';
35
+ import { Lane } from './lane.js';
36
+ import { claim_match, claimCandidates_of } from './claims.js';
35
37
  import { DownloadLedger, downloadId_valid } from './downloads.js';
36
38
  /**
37
39
  * The largest file `POST /vfs` will take, in bytes.
@@ -46,6 +48,8 @@ const VFS_POST_LIMIT = 256 * 1024 * 1024;
46
48
  /** The surface tag on session-bus envelopes the daemon itself originates. */
47
49
  export const DAEMON_SURFACE = 'daemon';
48
50
  const SCROLLBACK_DEFAULT = 200;
51
+ /** The slot while nobody holds the lane. */
52
+ const SLOT_EMPTY = { origin: null, id: null, instrument: false, line: null, startedAt: 0 };
49
53
  /**
50
54
  * A WebSocket daemon hosting one engine for attached surfaces, with a session
51
55
  * bus broadcasting activity across them.
@@ -60,8 +64,6 @@ export class CalypsoDaemon {
60
64
  /** The last executed command's measured facts, sticky across pushes. */
61
65
  lastCommand;
62
66
  telemetryProvider;
63
- /** Commands queued behind the one running: the lane's depth. */
64
- queueWaiting = 0;
65
67
  /** The line holding the lane, and since when; null while the lane is idle. */
66
68
  currentLine = null;
67
69
  currentStartedAt = 0;
@@ -74,6 +76,8 @@ export class CalypsoDaemon {
74
76
  backend;
75
77
  /** Whether the daemon's own code on disk has moved on since it started. */
76
78
  stale = false;
79
+ /** The terminals this daemon offers, or null when it offers none (no pty here). */
80
+ terminals = null;
77
81
  codeCheck;
78
82
  hostControl;
79
83
  /** The one session all surfaces share; returned in each attach ack. */
@@ -92,11 +96,14 @@ export class CalypsoDaemon {
92
96
  wss = null;
93
97
  httpServer = null;
94
98
  /**
95
- * Execution is serialized across the whole session (one foreground command
96
- * at a time), so a prompt raised mid-command has one unambiguous surface to
97
- * ask — the one running the current command.
99
+ * Execution takes turns across the whole session (lane.ts): one command
100
+ * works at a time, so a prompt raised mid-command has one unambiguous
101
+ * surface to ask, the one holding the lane. A command waiting on a person
102
+ * gives the lane up until the answer comes (`person_await`).
98
103
  */
99
- queue = Promise.resolve();
104
+ lane = new Lane();
105
+ /** The questions open now, by the surface asked: what, and since when. */
106
+ questionsOpen = new Map();
100
107
  /** The session's retained regard: the last indication from any surface. */
101
108
  regard = null;
102
109
  /** Unsubscribes from the engine's ambient events; null until started. */
@@ -120,6 +127,14 @@ export class CalypsoDaemon {
120
127
  /** The downloads this daemon is serving, for their progress (downloads.ts). */
121
128
  downloads = new DownloadLedger();
122
129
  edits = new RequestBroker('e', 'surface disconnected before returning the edit');
130
+ /** Lines run by a surface's own language, by the surface that claims them. */
131
+ surfaceLines = new RequestBroker('l', 'the surface that answers for this line went away before answering');
132
+ /** Each surface's terminal viewer: which terminals it draws. */
133
+ viewerOf = new Map();
134
+ /** The browser that last did something: the one a claimed line goes to when no terminal of its own typed it. */
135
+ browserActive = null;
136
+ /** Subjects a surface claimed whole this session, so a line in one is refused by name when none is attached. */
137
+ claimedSeen = new Set();
123
138
  deliveries = new RequestBroker('d', 'surface disconnected before the file was delivered');
124
139
  /**
125
140
  * @param options - The engine to host, the attach token, the bind address,
@@ -139,6 +154,15 @@ export class CalypsoDaemon {
139
154
  this.hostControl = options.hostControl ?? [];
140
155
  this.codeCheck = options.codeCheck;
141
156
  }
157
+ /**
158
+ * Offers terminals: a surface's console as a chell under a pty
159
+ * (terminals.ts). Set once the daemon knows its own address.
160
+ *
161
+ * @param terminals - The terminals, or null to offer none.
162
+ */
163
+ terminals_set(terminals) {
164
+ this.terminals = terminals;
165
+ }
142
166
  /**
143
167
  * Records whether the daemon's own code still matches its disk, and tells
144
168
  * every attached surface when that changes.
@@ -173,7 +197,9 @@ export class CalypsoDaemon {
173
197
  running: this.currentLine !== null && !this.currentInstrument
174
198
  ? { line: this.currentLine, sinceMs: Math.round(performance.now() - this.currentStartedAt), surface: this.currentOrigin?.id ?? '' }
175
199
  : null,
176
- waiting: this.queueWaiting,
200
+ waiting: this.lane.waiting,
201
+ // Questions open: each one's command has stepped out of the lane.
202
+ questions: [...this.questionsOpen].map(([surface, open]) => ({ surface: surface.id, message: open.message, sinceMs: Math.round(performance.now() - open.at) })),
177
203
  };
178
204
  // Who else is here: a restart asked from one surface names the rest.
179
205
  // A surface that runs host shells is a terminal; one that does not, a browser.
@@ -257,6 +283,8 @@ export class CalypsoDaemon {
257
283
  * @returns A promise resolving when the server has closed.
258
284
  */
259
285
  stop() {
286
+ // A terminal's chell is a child of this process: it goes with it.
287
+ this.terminals?.stop();
260
288
  if (this.telemetryTimer !== null) {
261
289
  clearInterval(this.telemetryTimer);
262
290
  this.telemetryTimer = null;
@@ -529,6 +557,12 @@ export class CalypsoDaemon {
529
557
  */
530
558
  connection_handle(socket, request) {
531
559
  let surface = null;
560
+ // This socket as a terminal's viewer: output and exits go back down it.
561
+ const viewer = {
562
+ data: (terminalId, data) => this.send(socket, { type: 'terminalData', terminalId, data }),
563
+ exit: (terminalId, code) => this.send(socket, { type: 'terminalExit', terminalId, code }),
564
+ owner: () => surface,
565
+ };
532
566
  // A front that holds the token for a browser — the porter — puts it on
533
567
  // the upgrade URL it proxies, the way `/vfs?token=` already travels; the
534
568
  // page then attaches with an empty token and is judged by the URL's.
@@ -545,6 +579,8 @@ export class CalypsoDaemon {
545
579
  }
546
580
  if (!surface) {
547
581
  surface = this.attach_handle(socket, parsed, urlToken);
582
+ if (surface !== null)
583
+ this.viewerOf.set(surface, viewer);
548
584
  return;
549
585
  }
550
586
  const message = clientMessage_parse(parsed);
@@ -555,26 +591,20 @@ export class CalypsoDaemon {
555
591
  const value = message.value;
556
592
  const attached = surface;
557
593
  if (value.type === 'execute') {
558
- if (value.instrument === true && this.prompts.pending_has(socket)) {
559
- // An instrument command runs BESIDE a question, not behind it.
560
- // The errand that answers a question browses with instrument
561
- // reads, and the command that asked is waiting on that answer —
562
- // so queuing them behind it would deadlock: the answer waits on
563
- // the browsing, the browsing waits on the answer.
564
- //
565
- // Safe because of what an instrument is: a pane's own read, which
566
- // never asks (refused above) and never moves the session. A
567
- // command that changes state is never instrument traffic.
568
- void this.execute_run(attached, value);
569
- }
570
- else {
571
- // One shared queue: commands from every surface run one at a time.
572
- this.queueWaiting += 1;
573
- this.queue = this.queue.then(() => {
574
- this.queueWaiting -= 1;
575
- return this.execute_run(attached, value);
576
- });
594
+ if (!attached.capabilities.shellCommands && attached.capabilities.claims.length > 0)
595
+ this.browserActive = attached;
596
+ // A line in a surface's own language is that surface's to run: it never
597
+ // reaches the engine, and needs no turn on the lane (the session is not
598
+ // touched by it).
599
+ const claimant = value.instrument === true ? null : this.claimant_for(attached, value.line);
600
+ if (claimant !== null) {
601
+ void this.surfaceLine_run(attached, value, claimant);
602
+ return;
577
603
  }
604
+ // One lane for every surface: commands take turns, and a command
605
+ // waiting on a person stands aside (person_await), so a pane's own
606
+ // reads, or another surface's command, run while a question is open.
607
+ void this.lane.run(() => this.execute_run(attached, value));
578
608
  }
579
609
  else if (value.type === 'cancel') {
580
610
  this.cancel_run(attached, value);
@@ -622,19 +652,156 @@ export class CalypsoDaemon {
622
652
  else if (value.type === 'watch' || value.type === 'unwatch') {
623
653
  this.watch_receive(attached, value.subject, value.type === 'watch');
624
654
  }
655
+ else if (value.type === 'terminalOpen') {
656
+ if (this.terminals === null) {
657
+ this.send(socket, { type: 'terminalOpened', terminalId: '', replay: '', refused: 'this daemon offers no terminals (node-pty is not built here)' });
658
+ }
659
+ else {
660
+ const opened = this.terminals.open(viewer, value.cols, value.rows, value.terminalId);
661
+ this.send(socket, { type: 'terminalOpened', terminalId: opened.terminalId, replay: opened.replay });
662
+ }
663
+ }
664
+ else if (value.type === 'terminalInput') {
665
+ this.terminals?.input(viewer, value.terminalId, value.data);
666
+ }
667
+ else if (value.type === 'terminalResize') {
668
+ this.terminals?.resize(viewer, value.terminalId, value.cols, value.rows);
669
+ }
670
+ else if (value.type === 'terminalClose') {
671
+ this.terminals?.close(viewer, value.terminalId);
672
+ }
673
+ else if (value.type === 'surfaceLineResult') {
674
+ this.surfaceLines.settle(socket, value.lineId, { rendered: value.rendered, status: value.status });
675
+ }
676
+ else if (value.type === 'surfaceLineError') {
677
+ this.surfaceLines.fail(socket, value.lineId, value.reason);
678
+ }
679
+ else if (value.type === 'note') {
680
+ this.note_relay(viewer, value.text);
681
+ }
682
+ else if (value.type === 'surfaceClaims') {
683
+ attached.capabilities.claims = value.claims;
684
+ for (const claim of value.claims)
685
+ if (claim.verbs === undefined)
686
+ this.claimedSeen.add(claim.subject.toLowerCase());
687
+ }
625
688
  else {
626
689
  this.send(socket, { type: 'error', reason: 'already attached' });
627
690
  }
628
691
  });
629
692
  socket.on('close', () => {
693
+ // Its terminals keep running, unwatched, for a reattach.
694
+ this.terminals?.detach(viewer);
630
695
  if (surface) {
631
696
  this.surfaces.delete(surface);
697
+ this.viewerOf.delete(surface);
698
+ if (this.browserActive === surface)
699
+ this.browserActive = null;
632
700
  // A detached surface holds no watches: whatever it kept live is
633
701
  // released, and a subject nobody else watches stops being sampled.
634
702
  this.engine.watch_release?.(surface.id);
635
703
  }
636
704
  });
637
705
  }
706
+ /**
707
+ * The surface that acts for the running command: the one that issued it,
708
+ * except a browser's terminal, whose chell runs on this daemon's host. A
709
+ * shell, a pipe segment, an editor or a delivered file asked of a
710
+ * terminal's chell would happen on the daemon host (a browser handed a
711
+ * host shell, a download written to the host's disk), so they go to the
712
+ * browser that owns the terminal, which does them its own way or refuses
713
+ * by name. Its questions stay with the chell, answered in the terminal.
714
+ *
715
+ * @returns The acting surface, or null when no command runs or the
716
+ * terminal's browser has gone.
717
+ */
718
+ surfaceActing() {
719
+ const origin = this.currentOrigin;
720
+ if (origin === null || origin.capabilities.terminal === undefined)
721
+ return origin;
722
+ const owner = this.terminals?.viewer_get(origin.capabilities.terminal)?.owner?.();
723
+ return owner !== null && owner !== undefined && this.surfaces.has(owner) ? owner : null;
724
+ }
725
+ /**
726
+ * The surface that runs a line in its own language: the browser whose
727
+ * terminal typed it, else the browser that last did something, else any
728
+ * that claims the subject. 'absent' when the subject is a surface's but no
729
+ * surface that claims it is attached; null when the session owns the line.
730
+ *
731
+ * @param origin - The surface the line came from.
732
+ * @param line - The line.
733
+ * @returns The claimant, 'absent', or null.
734
+ */
735
+ claimant_for(origin, line) {
736
+ const claiming = (surface) => surface !== null && surface !== undefined && surface !== origin && this.surfaces.has(surface) && claim_match(surface.capabilities.claims, line) !== null;
737
+ const owner = origin.capabilities.terminal === undefined ? null : this.terminals?.viewer_get(origin.capabilities.terminal)?.owner?.();
738
+ if (claiming(owner))
739
+ return owner;
740
+ if (claiming(this.browserActive))
741
+ return this.browserActive;
742
+ const any = [...this.surfaces].find((surface) => claiming(surface));
743
+ if (any !== undefined)
744
+ return any;
745
+ // A subject a surface claimed whole is no command of the session's: with
746
+ // no such surface attached, the line is refused by name, not run.
747
+ const subject = (line.trim().split(/\s+/)[0] ?? '').toLowerCase();
748
+ if (this.claimedSeen.has(subject) && claim_match([{ subject }], line) !== null)
749
+ return 'absent';
750
+ return null;
751
+ }
752
+ /**
753
+ * Runs a line in a surface's own language, and answers the surface that
754
+ * typed it with what the language said.
755
+ *
756
+ * @param origin - The surface that typed the line.
757
+ * @param message - The execute request.
758
+ * @param claimant - The surface that runs it, or 'absent'.
759
+ */
760
+ async surfaceLine_run(origin, message, claimant) {
761
+ const subject = (message.line.trim().split(/\s+/)[0] ?? '').toLowerCase();
762
+ if (claimant === 'absent') {
763
+ this.send(origin.socket, { type: 'result', id: message.id, envelopes: [{ status: 'error', rendered: '', renderedErr: `${subject}: an ARGUS word; no ARGUS is attached to this session\n` }] });
764
+ return;
765
+ }
766
+ try {
767
+ const answer = await this.surfaceLines.open(claimant.socket, (lineId) => {
768
+ this.send(claimant.socket, { type: 'surfaceLine', lineId, line: message.line, ...(origin.capabilities.terminal !== undefined ? { terminal: origin.capabilities.terminal } : {}) });
769
+ });
770
+ const rendered = answer.rendered === '' || answer.rendered.endsWith('\n') ? answer.rendered : `${answer.rendered}\n`;
771
+ this.send(origin.socket, { type: 'result', id: message.id, envelopes: [answer.status === 'ok' ? { status: 'ok', rendered } : { status: 'error', rendered: '', renderedErr: rendered }] });
772
+ }
773
+ catch (err) {
774
+ const reason = err instanceof Error ? err.message : String(err);
775
+ this.send(origin.socket, { type: 'result', id: message.id, envelopes: [{ status: 'error', rendered: '', renderedErr: `${subject}: ${reason}\n` }] });
776
+ }
777
+ }
778
+ /**
779
+ * The terminals a surface draws.
780
+ *
781
+ * @param surface - The surface.
782
+ * @returns Their ids; none for a surface that draws no terminal.
783
+ */
784
+ terminalsOf(surface) {
785
+ const viewer = this.viewerOf.get(surface);
786
+ return viewer === undefined ? [] : this.terminals?.ids_of(viewer) ?? [];
787
+ }
788
+ /**
789
+ * Carries a browser's note to its consoles: the chell of every terminal it
790
+ * draws prints it above the line being typed.
791
+ *
792
+ * @param viewer - The browser's terminal viewer.
793
+ * @param text - The note.
794
+ */
795
+ note_relay(viewer, text) {
796
+ const owned = this.terminals?.ids_of(viewer) ?? [];
797
+ if (owned.length === 0)
798
+ return;
799
+ for (const surface of this.surfaces) {
800
+ if (surface.capabilities.terminal !== undefined && owned.includes(surface.capabilities.terminal)) {
801
+ this.send(surface.socket, { type: 'consoleNote', text });
802
+ }
803
+ }
804
+ }
638
805
  /**
639
806
  * Relays a cancellation request only to the surface's own foreground command.
640
807
  *
@@ -686,9 +853,14 @@ export class CalypsoDaemon {
686
853
  fileDelivery: attach.value.capabilities?.fileDelivery ?? false,
687
854
  localFilesystem: attach.value.capabilities?.localFilesystem ?? false,
688
855
  color: attach.value.capabilities?.color ?? false,
856
+ claims: attach.value.capabilities?.claims ?? [],
857
+ ...(attach.value.capabilities?.terminal !== undefined ? { terminal: attach.value.capabilities.terminal } : {}),
689
858
  },
690
859
  };
691
860
  this.surfaces.add(surface);
861
+ for (const claim of surface.capabilities.claims)
862
+ if (claim.verbs === undefined)
863
+ this.claimedSeen.add(claim.subject.toLowerCase());
692
864
  this.send(socket, {
693
865
  type: 'attached',
694
866
  session: this.sessionId,
@@ -704,6 +876,7 @@ export class CalypsoDaemon {
704
876
  // says CALYPSO DAEMON OUT OF DATE only on this, never on its own
705
877
  // build alone (an ARGUS-only release changes no daemon code).
706
878
  stale: this.stale,
879
+ terminals: this.terminals !== null,
707
880
  });
708
881
  this.codeCheck?.();
709
882
  this.scrollback_replay(socket);
@@ -791,7 +964,9 @@ export class CalypsoDaemon {
791
964
  if (!this.promptProvider) {
792
965
  return;
793
966
  }
794
- const context = await this.promptProvider(this.lastCommand);
967
+ const provided = await this.promptProvider(this.lastCommand);
968
+ // The session's open questions are the daemon's to count, not the backend's.
969
+ const context = this.questionsOpen.size > 0 ? { ...provided, questions: this.questionsOpen.size } : provided;
795
970
  this.promptWarmupActive = context.procWarmup !== undefined;
796
971
  if (target) {
797
972
  this.send(target.socket, { type: 'promptline', context });
@@ -820,14 +995,19 @@ export class CalypsoDaemon {
820
995
  * @param origin - The surface that produced the envelope.
821
996
  * @param envelope - The envelope to publish.
822
997
  */
823
- bus_publish(origin, envelope) {
998
+ bus_publish(origin, envelope, mirrored = false) {
824
999
  this.scrollback.push({ surface: origin.id, envelope });
825
1000
  if (this.scrollback.length > this.scrollbackSize) {
826
1001
  this.scrollback.splice(0, this.scrollback.length - this.scrollbackSize);
827
1002
  }
1003
+ // A browser that mirrors a command into its own consoles has shown it
1004
+ // there already: their chells are skipped, every other surface hears it.
1005
+ const shown = mirrored ? this.terminalsOf(origin) : [];
828
1006
  for (const surface of this.surfaces) {
1007
+ if (surface.capabilities.terminal !== undefined && shown.includes(surface.capabilities.terminal))
1008
+ continue;
829
1009
  if (surface !== origin) {
830
- this.send(surface.socket, { type: 'session', surface: origin.id, envelope });
1010
+ this.send(surface.socket, { type: 'session', surface: origin.id, envelope, ...(origin.capabilities.terminal !== undefined ? { terminal: origin.capabilities.terminal } : {}) });
831
1011
  }
832
1012
  }
833
1013
  }
@@ -841,15 +1021,8 @@ export class CalypsoDaemon {
841
1021
  async execute_run(origin, message) {
842
1022
  // The command runs with this surface as the prompt target, so any prompt
843
1023
  // the engine raises is asked of the surface that submitted the command.
844
- // Saved and restored rather than set and cleared: an instrument command
845
- // may run beside a command that is waiting on a question, and the outer
846
- // command's output must still find its way home when the inner one
847
- // finishes.
848
- const outerOrigin = this.currentOrigin;
849
- const outerId = this.currentId;
850
- const outerInstrument = this.currentInstrument;
851
- const outerLine = this.currentLine;
852
- const outerStartedAt = this.currentStartedAt;
1024
+ // The slot is the lane holder's: set when the command takes its turn,
1025
+ // put aside while it waits on a person, and cleared when it finishes.
853
1026
  this.currentOrigin = origin;
854
1027
  this.currentId = message.id;
855
1028
  this.currentInstrument = message.instrument === true;
@@ -884,7 +1057,7 @@ export class CalypsoDaemon {
884
1057
  // operator actually did.
885
1058
  if (message.instrument !== true) {
886
1059
  for (const envelope of envelopes) {
887
- this.bus_publish(origin, envelope);
1060
+ this.bus_publish(origin, envelope, message.mirrored === true);
888
1061
  }
889
1062
  }
890
1063
  }
@@ -897,11 +1070,56 @@ export class CalypsoDaemon {
897
1070
  }
898
1071
  }
899
1072
  finally {
900
- this.currentOrigin = outerOrigin;
901
- this.currentId = outerId;
902
- this.currentInstrument = outerInstrument;
903
- this.currentLine = outerLine;
904
- this.currentStartedAt = outerStartedAt;
1073
+ this.slot_restore(SLOT_EMPTY);
1074
+ }
1075
+ }
1076
+ /**
1077
+ * The current-command slot, as it stands.
1078
+ *
1079
+ * @returns Who holds the lane, for which command.
1080
+ */
1081
+ slot_take() {
1082
+ return { origin: this.currentOrigin, id: this.currentId, instrument: this.currentInstrument, line: this.currentLine, startedAt: this.currentStartedAt };
1083
+ }
1084
+ /**
1085
+ * Puts a slot back.
1086
+ *
1087
+ * @param slot - The slot.
1088
+ */
1089
+ slot_restore(slot) {
1090
+ this.currentOrigin = slot.origin;
1091
+ this.currentId = slot.id;
1092
+ this.currentInstrument = slot.instrument;
1093
+ this.currentLine = slot.line;
1094
+ this.currentStartedAt = slot.startedAt;
1095
+ }
1096
+ /**
1097
+ * Waits on a person without holding the session: the request is sent, the
1098
+ * lane given up and the slot put aside, so the next command takes its
1099
+ * turn; when the person answers, the command queues for the lane again
1100
+ * and resumes with its own slot.
1101
+ *
1102
+ * @param ask - Sends the request (under the asking command's slot) and
1103
+ * resolves with the person's answer.
1104
+ * @returns The answer.
1105
+ */
1106
+ async person_await(ask) {
1107
+ const answered = ask();
1108
+ const mine = this.slot_take();
1109
+ // The engine's per-command state goes with the command (its exit code,
1110
+ // a pipe's untaken input, its cancellation), so the next command starts
1111
+ // clean and this one finds its own on return.
1112
+ const engineTurn = this.engine.turn_leave?.();
1113
+ this.slot_restore(SLOT_EMPTY);
1114
+ this.lane.release();
1115
+ try {
1116
+ return await answered;
1117
+ }
1118
+ finally {
1119
+ await this.lane.acquire();
1120
+ this.slot_restore(mine);
1121
+ if (engineTurn !== undefined)
1122
+ this.engine.turn_resume?.(engineTurn);
905
1123
  }
906
1124
  }
907
1125
  /**
@@ -935,7 +1153,15 @@ export class CalypsoDaemon {
935
1153
  // question whose command they have forgotten issuing.
936
1154
  return Promise.reject(new Error('another question is already open on this surface'));
937
1155
  }
938
- return this.prompts.open(origin.socket, (promptId) => {
1156
+ // An open question is the session's to show: every surface's prompt
1157
+ // context counts it, and `who` says who asked what.
1158
+ this.questionsOpen.set(origin, { message: request.message, at: performance.now() });
1159
+ void this.promptline_push();
1160
+ const settled = () => {
1161
+ this.questionsOpen.delete(origin);
1162
+ void this.promptline_push();
1163
+ };
1164
+ return this.person_await(() => this.prompts.open(origin.socket, (promptId) => {
939
1165
  this.send(origin.socket, {
940
1166
  type: 'prompt',
941
1167
  promptId,
@@ -945,7 +1171,7 @@ export class CalypsoDaemon {
945
1171
  ...(request.path === undefined ? {} : { path: request.path }),
946
1172
  ...(request.commit === undefined ? {} : { commit: request.commit }),
947
1173
  });
948
- });
1174
+ }).finally(settled));
949
1175
  }
950
1176
  /**
951
1177
  * Streams structured progress from the executing command to its origin
@@ -994,7 +1220,7 @@ export class CalypsoDaemon {
994
1220
  * @throws {Error} When no command is executing or the surface disconnects.
995
1221
  */
996
1222
  pipe_current(command, input) {
997
- const origin = this.currentOrigin;
1223
+ const origin = this.surfaceActing();
998
1224
  if (!origin) {
999
1225
  return Promise.reject(new Error('no active command to run a pipe segment for'));
1000
1226
  }
@@ -1011,7 +1237,7 @@ export class CalypsoDaemon {
1011
1237
  * @throws {Error} When no command is executing or the surface disconnects.
1012
1238
  */
1013
1239
  shell_current(command) {
1014
- const origin = this.currentOrigin;
1240
+ const origin = this.surfaceActing();
1015
1241
  if (!origin) {
1016
1242
  return Promise.reject(new Error('no active command to run a shell command for'));
1017
1243
  }
@@ -1037,13 +1263,14 @@ export class CalypsoDaemon {
1037
1263
  * @throws {Error} When no command is executing or the surface disconnects.
1038
1264
  */
1039
1265
  edit_current(content, extension, path) {
1040
- const origin = this.currentOrigin;
1266
+ const origin = this.surfaceActing();
1041
1267
  if (!origin) {
1042
1268
  return Promise.reject(new Error('no active command to edit for'));
1043
1269
  }
1044
- return this.edits.open(origin.socket, (editId) => {
1270
+ // Someone is editing: the session is free meanwhile.
1271
+ return this.person_await(() => this.edits.open(origin.socket, (editId) => {
1045
1272
  this.send(origin.socket, { type: 'edit', editId, content, extension, ...(path === undefined ? {} : { path }) });
1046
- });
1273
+ }));
1047
1274
  }
1048
1275
  /**
1049
1276
  * Reports what the surface running the current command can do on its own
@@ -1064,14 +1291,15 @@ export class CalypsoDaemon {
1064
1291
  id: each.id,
1065
1292
  kind: each.capabilities.shellCommands ? 'chell' : 'browser',
1066
1293
  you: each === this.currentOrigin,
1294
+ ...(this.questionsOpen.has(each) ? { asking: this.questionsOpen.get(each).message } : {}),
1067
1295
  }));
1068
1296
  }
1069
1297
  capabilities_current() {
1070
- const origin = this.currentOrigin;
1298
+ const origin = this.surfaceActing();
1071
1299
  return origin ? {
1072
1300
  fileDelivery: origin.capabilities.fileDelivery,
1073
1301
  localFilesystem: origin.capabilities.localFilesystem,
1074
- color: origin.capabilities.color,
1302
+ color: this.currentOrigin?.capabilities.color ?? origin.capabilities.color,
1075
1303
  } : null;
1076
1304
  }
1077
1305
  /**
@@ -1089,7 +1317,7 @@ export class CalypsoDaemon {
1089
1317
  * @throws {Error} When no command is executing or the surface disconnects.
1090
1318
  */
1091
1319
  deliver_current(request) {
1092
- const origin = this.currentOrigin;
1320
+ const origin = this.surfaceActing();
1093
1321
  if (!origin) {
1094
1322
  return Promise.reject(new Error('no active command to deliver a file for'));
1095
1323
  }
@@ -1118,11 +1346,14 @@ export class CalypsoDaemon {
1118
1346
  async complete_run(socket, message) {
1119
1347
  try {
1120
1348
  const result = await this.engine.line_complete(message.prefix);
1349
+ // The surfaces' own subjects and claimed verbs complete like any command.
1350
+ const claims = [...this.surfaces].flatMap((each) => each.capabilities.claims);
1351
+ const offered = claimCandidates_of(claims, message.prefix).filter((word) => !result.candidates.includes(word));
1121
1352
  this.send(socket, {
1122
1353
  type: 'complete',
1123
1354
  id: message.id,
1124
1355
  prefix: result.prefix,
1125
- candidates: result.candidates,
1356
+ candidates: [...result.candidates, ...offered],
1126
1357
  });
1127
1358
  }
1128
1359
  catch (err) {