pi-studio 0.10.4 → 0.11.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.
@@ -1,15 +1,17 @@
1
1
  import { createHash } from "node:crypto";
2
2
 
3
3
  export const REPL_SUBMISSION_DISPLAY_VERSION = 1;
4
- export const DEFAULT_REPL_SUBMISSION_ECHO_MODE = "off";
4
+ export const DEFAULT_REPL_SUBMISSION_ECHO_MODE = "summary";
5
5
  export const REPL_SUBMISSION_ECHO_MODES = Object.freeze(["off", "summary", "full"]);
6
- export const REPL_SUBMISSION_SUMMARY_MAX_CHARS = 600;
7
- export const REPL_SUBMISSION_SUMMARY_MAX_LINES = 6;
6
+ export const REPL_SUBMISSION_SUMMARY_MAX_CHARS = 2_000;
7
+ export const REPL_SUBMISSION_SUMMARY_MAX_LINES = 20;
8
8
  export const REPL_SUBMISSION_FULL_MAX_CHARS = 4_000;
9
9
  export const REPL_SUBMISSION_FULL_MAX_LINES = 40;
10
10
 
11
11
  const UNSAFE_UNICODE_PATTERN = /[\u2028\u2029\u202a-\u202e\u2066-\u2069]/g;
12
12
  const OTHER_CONTROL_PATTERN = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/g;
13
+ const LABELLED_BEGIN_MARKER_PATTERN = /^── ([a-z0-9][a-z0-9-]{0,31}) · input · ([1-9]\d*) (line|lines) · id: ([a-f0-9]{12}) ──$/;
14
+ const LABELLED_END_MARKER_PATTERN = /^── done · id: ([a-f0-9]{12}) ──$/;
13
15
  const COMPACT_BEGIN_MARKER_PATTERN = /^── ([a-z0-9][a-z0-9-]{0,31}) · ([a-f0-9]{12}) · ([1-9]\d*) (line|lines) ──$/;
14
16
  const COMPACT_OUTPUT_MARKER = "── output ──";
15
17
  const COMPACT_END_MARKER_PATTERN = /^── done · ([a-f0-9]{12}) ──$/;
@@ -53,10 +55,6 @@ function normalizeDisplayCode(code) {
53
55
  return sanitized || "(empty submission)";
54
56
  }
55
57
 
56
- function formatPreviewLine(line) {
57
- return line ? `│ ${line}` : "│";
58
- }
59
-
60
58
  function buildBoundedPreviewLines(codeLines, maxLines, maxChars) {
61
59
  const shown = [];
62
60
  let usedChars = 0;
@@ -73,7 +71,7 @@ function buildBoundedPreviewLines(codeLines, maxLines, maxChars) {
73
71
  break;
74
72
  }
75
73
  const clipped = truncateCodePoints(line, remaining);
76
- shown.push(formatPreviewLine(clipped.text));
74
+ shown.push(clipped.text);
77
75
  usedChars += Array.from(clipped.text).length + 1;
78
76
  if (clipped.truncated) {
79
77
  truncated = true;
@@ -81,7 +79,7 @@ function buildBoundedPreviewLines(codeLines, maxLines, maxChars) {
81
79
  }
82
80
  }
83
81
  if (shown.length < codeLines.length) truncated = true;
84
- if (truncated) shown.push(`│ … preview truncated; ${codeLines.length} ${codeLines.length === 1 ? "line" : "lines"} total`);
82
+ if (truncated) shown.push(`… preview truncated; ${codeLines.length} ${codeLines.length === 1 ? "line" : "lines"} total`);
85
83
  return shown;
86
84
  }
87
85
 
@@ -101,9 +99,9 @@ export function createReplSubmissionDisplay(details = {}) {
101
99
  const displayCode = normalizeDisplayCode(details.code);
102
100
  const codeLines = displayCode.split("\n");
103
101
  const lineLabel = `${codeLines.length} ${codeLines.length === 1 ? "line" : "lines"}`;
104
- const beginMarker = `── ${origin} · ${anchorId} · ${lineLabel} ──`;
102
+ const beginMarker = `── ${origin} · input · ${lineLabel} · id: ${anchorId} ──`;
105
103
  const outputMarker = COMPACT_OUTPUT_MARKER;
106
- const endMarker = `── done · ${anchorId} ──`;
104
+ const endMarker = `── done · id: ${anchorId} ──`;
107
105
  const enabled = mode !== "off";
108
106
  const previewLines = !enabled
109
107
  ? []
@@ -121,7 +119,8 @@ export function createReplSubmissionDisplay(details = {}) {
121
119
  outputMarker,
122
120
  endMarker,
123
121
  previewLines,
124
- prefixLines: enabled ? [beginMarker, ...previewLines, outputMarker] : [],
122
+ prefixLines: enabled ? ["", beginMarker, ...previewLines, outputMarker] : [],
123
+ suffixLines: enabled ? [endMarker, ""] : [],
125
124
  };
126
125
  }
127
126
 
@@ -134,6 +133,15 @@ function parseLineCount(countText, countLabel) {
134
133
 
135
134
  export function parseReplSubmissionDisplayMarker(line) {
136
135
  const normalized = String(line || "").replace(/\r$/, "");
136
+ const labelledBegin = normalized.match(LABELLED_BEGIN_MARKER_PATTERN);
137
+ if (labelledBegin) {
138
+ const [, origin, countText, countLabel, anchorId] = labelledBegin;
139
+ const lineCount = parseLineCount(countText, countLabel);
140
+ return lineCount === null
141
+ ? null
142
+ : { version: REPL_SUBMISSION_DISPLAY_VERSION, origin, phase: "submitted", anchorId, lineCount };
143
+ }
144
+ // Keep the earlier compact form readable without changing its parse result.
137
145
  const compactBegin = normalized.match(COMPACT_BEGIN_MARKER_PATTERN);
138
146
  if (compactBegin) {
139
147
  const [, origin, anchorId, countText, countLabel] = compactBegin;
@@ -145,7 +153,7 @@ export function parseReplSubmissionDisplayMarker(line) {
145
153
  if (normalized === COMPACT_OUTPUT_MARKER) {
146
154
  return { version: REPL_SUBMISSION_DISPLAY_VERSION, phase: "output" };
147
155
  }
148
- const compactEnd = normalized.match(COMPACT_END_MARKER_PATTERN);
156
+ const compactEnd = normalized.match(LABELLED_END_MARKER_PATTERN) ?? normalized.match(COMPACT_END_MARKER_PATTERN);
149
157
  if (compactEnd) {
150
158
  return { version: REPL_SUBMISSION_DISPLAY_VERSION, phase: "complete", anchorId: compactEnd[1] };
151
159
  }
@@ -174,6 +182,20 @@ function consumeExactDisplayLine(value, offset, line) {
174
182
  return value[end] === "\n" ? end + 1 : end;
175
183
  }
176
184
 
185
+ function consumeWrappedDisplayLine(value, offset, line) {
186
+ const exact = consumeExactDisplayLine(value, offset, line);
187
+ if (exact !== null) return exact;
188
+ // Some captures retain hard wraps inside a printed preview line. Match
189
+ // its known text, allowing only inserted line breaks, not arbitrary output.
190
+ let end = offset;
191
+ for (const character of line) {
192
+ while (end > offset && value[end] === "\n") end += 1;
193
+ if (!value.startsWith(character, end)) return null;
194
+ end += character.length;
195
+ }
196
+ return consumeExactDisplayLine(value, end, "");
197
+ }
198
+
177
199
  function findExactDisplayLine(value, line, useLast = false) {
178
200
  let index = useLast ? value.lastIndexOf(line) : value.indexOf(line);
179
201
  while (index >= 0) {
@@ -190,9 +212,14 @@ function findExactDisplayLine(value, line, useLast = false) {
190
212
  return null;
191
213
  }
192
214
 
193
- function removeMarkerLine(value, marker, useLast = false) {
215
+ function removeMarkerLine(value, marker, useLast = false, trailingGap = false) {
194
216
  const found = findExactDisplayLine(value, marker, useLast);
195
- return found ? value.slice(0, found.index) + value.slice(found.end) : value;
217
+ if (!found) return value;
218
+ // Consume at most our one following blank line. Preserve user whitespace
219
+ // before the anchor and any additional blank lines after it; older captures
220
+ // without a separator (or without the new display field) still work.
221
+ const end = found.end + (trailingGap && value[found.end] === "\n" ? 1 : 0);
222
+ return value.slice(0, found.index) + value.slice(end);
196
223
  }
197
224
 
198
225
  export function stripReplSubmissionDisplay(output, display) {
@@ -200,28 +227,23 @@ export function stripReplSubmissionDisplay(output, display) {
200
227
  if (!display || display.enabled !== true) return value;
201
228
  const begin = findExactDisplayLine(value, display.beginMarker);
202
229
  if (begin) {
203
- const beginIndex = begin.index;
204
- const afterBegin = value.slice(begin.end);
205
- const outputDivider = display.outputMarker
206
- ? findExactDisplayLine(afterBegin, display.outputMarker)
207
- : null;
208
- if (outputDivider) {
209
- // The plain divider is an unambiguous boundary because it is emitted
210
- // before user code runs. Removing through it is resilient to terminal
211
- // wrapping or whitespace changes within the displayed source preview.
212
- const suffixStart = begin.end + outputDivider.end;
213
- value = value.slice(0, beginIndex) + value.slice(suffixStart);
214
- } else {
215
- // If the runtime disappears mid-prefix, remove only contiguous exact
216
- // request lines and preserve any different error text after them.
217
- let suffixStart = beginIndex;
218
- for (const line of display.prefixLines) {
219
- const next = consumeExactDisplayLine(value, suffixStart, line);
220
- if (next === null) break;
221
- suffixStart = next;
222
- }
223
- value = value.slice(0, beginIndex) + value.slice(suffixStart);
230
+ // Remove only our single leading blank line, not the loader's newline
231
+ // or any additional output whitespace. Older unpadded captures still work.
232
+ const leadingGap = display.prefixLines[0] === "" && begin.index > 0 &&
233
+ value[begin.index - 1] === "\n" && (begin.index === 1 || value[begin.index - 2] === "\n");
234
+ const beginIndex = begin.index - (leadingGap ? 1 : 0);
235
+ // Unprefixed source can itself contain a line reading "── output ──".
236
+ // Consume the known preview before its divider rather than treating the
237
+ // first marker-looking source line as the start of runtime output. If a
238
+ // prefix is incomplete, preserve everything after the matched portion.
239
+ let suffixStart = begin.index;
240
+ const prefixLines = display.prefixLines[0] === "" ? display.prefixLines.slice(1) : display.prefixLines;
241
+ for (const line of prefixLines) {
242
+ const next = consumeWrappedDisplayLine(value, suffixStart, line);
243
+ if (next === null) break;
244
+ suffixStart = next;
224
245
  }
246
+ value = value.slice(0, beginIndex) + value.slice(suffixStart);
225
247
  }
226
- return removeMarkerLine(value, display.endMarker, true);
248
+ return removeMarkerLine(value, display.endMarker, true, display.suffixLines?.at(-1) === "");
227
249
  }
@@ -12,6 +12,32 @@ function isStudioNestedZedTerminal(env) {
12
12
  return zedTerm === "1" || zedTerm === "true";
13
13
  }
14
14
 
15
+ /**
16
+ * Muxy before 2.2 marked each pane with its ID and the app's socket.
17
+ *
18
+ * @param {NodeJS.ProcessEnv | Record<string, string | undefined>} env
19
+ */
20
+ function isStudioLegacyMuxyPane(env) {
21
+ const paneId = String(env.MUXY_PANE_ID ?? "").trim();
22
+ const socketPath = String(env.MUXY_SOCKET_PATH ?? "").trim();
23
+ return Boolean(paneId && socketPath);
24
+ }
25
+
26
+ /**
27
+ * Muxy 2.2 marks each terminal with its server's and session's IDs, and sets
28
+ * TERM_PROGRAM=muxy. Another terminal app opened from a Muxy pane inherits the IDs
29
+ * but sets its own TERM_PROGRAM (tmux sets "tmux"), so the IDs alone aren't enough,
30
+ * and TERM_PROGRAM alone isn't either.
31
+ *
32
+ * @param {NodeJS.ProcessEnv | Record<string, string | undefined>} env
33
+ */
34
+ function isStudioMuxyTerminal(env) {
35
+ const serverId = String(env.MUXY_SERVER_ID ?? "").trim();
36
+ const sessionId = String(env.MUXY_SESSION_ID ?? "").trim();
37
+ const termProgram = String(env.TERM_PROGRAM ?? "").trim().toLowerCase();
38
+ return Boolean(serverId && sessionId && termProgram === "muxy");
39
+ }
40
+
15
41
  /**
16
42
  * Detect whether the current process is running inside Muxy itself rather than
17
43
  * a nested application terminal that inherited Muxy's environment.
@@ -20,9 +46,8 @@ function isStudioNestedZedTerminal(env) {
20
46
  * @returns {boolean}
21
47
  */
22
48
  export function isStudioMuxySession(env = process.env) {
23
- const paneId = String(env.MUXY_PANE_ID ?? "").trim();
24
- const socketPath = String(env.MUXY_SOCKET_PATH ?? "").trim();
25
- return Boolean(paneId && socketPath && !isStudioNestedZedTerminal(env));
49
+ if (isStudioNestedZedTerminal(env)) return false;
50
+ return isStudioLegacyMuxyPane(env) || isStudioMuxyTerminal(env);
26
51
  }
27
52
 
28
53
  /**
@@ -6,7 +6,10 @@ const STUDIO_REPL_PROMPT_COMMAND_ENVIRONMENT = "PROMPT_COMMAND=";
6
6
  * Studio's own sessions: pi-studio-repl-<runtime>, then an optional custom-command
7
7
  * hash and an optional new-session suffix. Verified Stop accepts only these.
8
8
  */
9
- export const STUDIO_REPL_SESSION_NAME = /^pi-studio-repl-(?:shell|python|ipython|julia|r|ghci|clojure)(?:-[a-f0-9]{8})?(?:-[a-z0-9]+-[a-f0-9]{6})?$/;
9
+ export const STUDIO_REPL_SESSION_NAME = /^pi-studio-repl-(?:shell|python|ipython|julia|r|ghci|clojure|ruby|java|octave|matlab|gnuplot|cpp)(?:-[a-f0-9]{8})?(?:-[a-z0-9]+-[a-f0-9]{6})?$/;
10
+
11
+ /** Studio's gnuplot sessions. Their Stop also ends gnuplot and Qt helpers that carry the session's owner marker. */
12
+ export const isStudioGnuplotSession = (name) => /^pi-studio-repl-gnuplot(?:-|$)/.test(name);
10
13
 
11
14
  /** Fields read for each pane, in the order firstStudioReplPanes expects. */
12
15
  export const STUDIO_REPL_PANE_FORMAT = "#{window_index}\t#{pane_index}\t#{pane_id}\t#{session_name}\t#{session_id}\t#{session_created}\t#{@pi_repl_runtime}\t#{@pi_repl_record_id}\t#{@pi_repl_record_version}";
@@ -24,9 +27,10 @@ export const STUDIO_REPL_PANE_FORMAT = "#{window_index}\t#{pane_index}\t#{pane_i
24
27
  * @param {string} sessionName
25
28
  * @param {string} cwd
26
29
  * @param {string} command
30
+ * @param {string[]} [environment] more NAME=value settings for the runtime
27
31
  * @returns {string[]}
28
32
  */
29
- export function buildStudioReplTmuxStartArgs(sessionName, cwd, command) {
33
+ export function buildStudioReplTmuxStartArgs(sessionName, cwd, command, environment = []) {
30
34
  return [
31
35
  "new-session",
32
36
  "-d",
@@ -39,6 +43,7 @@ export function buildStudioReplTmuxStartArgs(sessionName, cwd, command) {
39
43
  cwd,
40
44
  "-e",
41
45
  STUDIO_REPL_PROMPT_COMMAND_ENVIRONMENT,
46
+ ...environment.flatMap((setting) => ["-e", setting]),
42
47
  command,
43
48
  ];
44
49
  }
@@ -108,6 +113,12 @@ const STUDIO_REPL_READY_PROMPTS = {
108
113
  r: /^>[ \t]*$/,
109
114
  ghci: /^\*?[A-Za-z0-9_.:]+(?: \*?[A-Za-z0-9_.:]+)*>[ \t]*$/,
110
115
  clojure: /^[^\s>]+=>[ \t]*$/,
116
+ ruby: /^irb\([^\n]*\):\d+(?::0)?>[ \t]*$/,
117
+ java: /^jshell>[ \t]*$/,
118
+ octave: /^octave:\d+>[ \t]*$/,
119
+ matlab: /^>>[ \t]*$/,
120
+ gnuplot: /^gnuplot>[ \t]*$/,
121
+ cpp: /^\[cling\]\$[ \t]*$/,
111
122
  };
112
123
 
113
124
  /**
@@ -129,11 +140,29 @@ export function isStudioReplReadyLine(runtime, line) {
129
140
  return Boolean(prompt && prompt.test(value));
130
141
  }
131
142
 
132
- /** @param {string} line */
133
- function isStudioReplPrompt(line) {
143
+ /**
144
+ * As in pi-repl, Octave and MATLAB's prompts count only for their own submissions, and
145
+ * so does Cling's: >> or [cling]$ could be another runtime's output.
146
+ *
147
+ * @param {string} submissionLine
148
+ * @returns {RegExp | null}
149
+ */
150
+ function scopedPromptFor(submissionLine) {
151
+ if (submissionLine.startsWith("eval(fileread(")) return /^(?:octave:\d+>|>>)\s*$/;
152
+ if (submissionLine.startsWith("#include ")) return /^\[cling\]\$\s*$/;
153
+ return null;
154
+ }
155
+
156
+ /**
157
+ * @param {string} line
158
+ * @param {RegExp | null} [scoped] the submission's own runtime prompt, from scopedPromptFor
159
+ */
160
+ function isStudioReplPrompt(line, scoped = null) {
134
161
  return /^(?:>>>|In \[\d+\]:|\.\.\.:|>|\+)\s*$/.test(line)
135
162
  || /^(?:ghci|Prelude|\*?[A-Za-z0-9_.:]+)>\s*$/.test(line)
136
- || /^[^\s>]+=>\s*$/.test(line);
163
+ || /^[^\s>]+=>\s*$/.test(line)
164
+ || /^irb\(.*\)[:\d]+[>*]\s*$/.test(line)
165
+ || Boolean(scoped && scoped.test(line));
137
166
  }
138
167
 
139
168
  /** @param {string} text */
@@ -147,13 +176,14 @@ const compact = (text) => text.replace(/\s+/g, "");
147
176
  * @param {string[]} lines
148
177
  * @param {string} submissionLine
149
178
  * @param {boolean} anyPrefix Shell prompts are the user's own
179
+ * @param {RegExp | null} [scoped] the submission's own runtime prompt
150
180
  * @returns {boolean} whether the echo was found and removed
151
181
  */
152
- function removeLoaderEcho(lines, submissionLine, anyPrefix) {
182
+ function removeLoaderEcho(lines, submissionLine, anyPrefix, scoped = null) {
153
183
  const first = lines[0] ?? "";
154
184
  const prefixOk = (/** @type {number} */ index) => {
155
185
  const prefix = first.slice(0, index).trim();
156
- return anyPrefix || !prefix || isStudioReplPrompt(prefix);
186
+ return anyPrefix || !prefix || isStudioReplPrompt(prefix, scoped);
157
187
  };
158
188
  const index = first.indexOf(submissionLine);
159
189
  if (index >= 0 && prefixOk(index)) {
@@ -206,13 +236,14 @@ export function cleanStudioReplOutput(delta, details) {
206
236
  while (lines.length && !lines[lines.length - 1].trim()) lines.pop();
207
237
  };
208
238
  dropBlankEdges();
239
+ const scoped = scopedPromptFor(details.submissionLine || "");
209
240
  // Prompt rows before this submission's echo are scaffolding. Without an echo
210
241
  // (terminal echo off, say) they may be output, so they stay.
211
242
  let lead = 0;
212
- while (lead < lines.length && (!lines[lead].trim() || isStudioReplPrompt(lines[lead].trim()))) lead += 1;
243
+ while (lead < lines.length && (!lines[lead].trim() || isStudioReplPrompt(lines[lead].trim(), scoped))) lead += 1;
213
244
  if (lead < lines.length && details.submissionLine) {
214
245
  const rest = lines.slice(lead);
215
- if (removeLoaderEcho(rest, details.submissionLine, details.runtime === "shell")) lines.splice(0, lines.length, ...rest);
246
+ if (removeLoaderEcho(rest, details.submissionLine, details.runtime === "shell", scoped)) lines.splice(0, lines.length, ...rest);
216
247
  }
217
248
  const silent = /:pi-studio\/silent\)$/.test(details.submissionLine || "") ? ":pi-studio/silent" : "";
218
249
  const promptLine = String(details.promptLine || "").trim();
@@ -223,7 +254,7 @@ export function cleanStudioReplOutput(delta, details) {
223
254
  while (lines.length) {
224
255
  const last = lines[lines.length - 1].trim();
225
256
  if (!last) { lines.pop(); continue; }
226
- if (!removedPrompt && (isStudioReplPrompt(last) || (promptLine && last === promptLine))) {
257
+ if (!removedPrompt && (isStudioReplPrompt(last, scoped) || (promptLine && last === promptLine))) {
227
258
  lines.pop();
228
259
  removedPrompt = true;
229
260
  continue;