pi-studio 0.10.5 → 0.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.ts CHANGED
@@ -59,6 +59,7 @@ import {
59
59
  cleanStudioReplOutput,
60
60
  firstStudioReplPanes,
61
61
  buildStudioReplDeadPaneCloseArgs,
62
+ isStudioGnuplotSession,
62
63
  isStudioReplReadyLine,
63
64
  STUDIO_REPL_PANE_FORMAT,
64
65
  STUDIO_REPL_SESSION_NAME,
@@ -87,6 +88,11 @@ import {
87
88
  cleanupPrivateReplControlFiles,
88
89
  createPrivateReplControlFiles,
89
90
  } from "./shared/repl-control-files.js";
91
+ import { CURSOR_COLUMN_QUERY, CURSOR_COLUMN_SUPERVISOR } from "./shared/repl-cursor-column.js";
92
+ import { buildMLanguageControlSource, buildMLanguageDriverSource, mStringLiteral } from "./shared/repl-m-language.js";
93
+ import { buildGnuplotDriverSource, buildGnuplotGuardSource, buildGnuplotSubmissionLine } from "./shared/repl-gnuplot.js";
94
+ import { GNUPLOT_OWNER_ENV, GNUPLOT_OWNER_OPTION } from "./shared/repl-gnuplot-processes.js";
95
+ import { buildCppDriverSource, buildCppRequest, cppInclude, createCppControlCleanup, prepareCppSubmission, readCppCompletion } from "./shared/repl-cpp.js";
90
96
  import { buildStudioForwardingHint, buildStudioSshTunnelHint, isStudioSshSession as isSshSession } from "./shared/studio-ssh-hint.js";
91
97
  import {
92
98
  buildStudioPendingPage,
@@ -165,7 +171,7 @@ type StudioSourceKind = "file" | "last-response" | "blank";
165
171
  type TerminalActivityPhase = "idle" | "running" | "tool" | "responding";
166
172
  type StudioPromptMode = "response" | "run" | "effective";
167
173
  type StudioPromptTriggerKind = "run" | "steer";
168
- type StudioReplRuntime = "shell" | "python" | "ipython" | "julia" | "r" | "ghci" | "clojure";
174
+ type StudioReplRuntime = "shell" | "python" | "ipython" | "julia" | "r" | "ghci" | "clojure" | "ruby" | "java" | "octave" | "matlab" | "gnuplot" | "cpp";
169
175
  type ReplSubmissionEchoMode = "off" | "summary" | "full";
170
176
  type ReplSubmissionDisplay = ReturnType<typeof createReplSubmissionDisplay>;
171
177
  type StudioQuizAngle = "general" | "scientist" | "mathematician" | "statistician" | "developer" | "reviewer";
@@ -1092,6 +1098,8 @@ const STUDIO_REPL_SEND_MAX_CHARS = 200_000;
1092
1098
  const STUDIO_REPL_SEND_DEFAULT_TIMEOUT_MS = 20_000;
1093
1099
  const STUDIO_REPL_SEND_MAX_TIMEOUT_MS = 120_000;
1094
1100
  const STUDIO_REPL_START_WAIT_MS = 20_000;
1101
+ // MATLAB took 31 s to reach its prompt on an M-series Mac (R2024b, 20 Oct).
1102
+ const STUDIO_REPL_MATLAB_START_WAIT_MS = 120_000;
1095
1103
  const STUDIO_REPL_START_POLL_MS = 250;
1096
1104
  const STUDIO_REPL_JOURNAL_MAX_ENTRIES = 300;
1097
1105
  const STUDIO_REPL_RUNTIME_OPTION = "@pi_repl_runtime";
@@ -1108,21 +1116,27 @@ const STUDIO_REPL_RUNTIME_LABELS: Record<StudioReplRuntime, string> = {
1108
1116
  r: "R",
1109
1117
  ghci: "GHCi",
1110
1118
  clojure: "Clojure",
1119
+ ruby: "Ruby",
1120
+ java: "Java",
1121
+ octave: "Octave",
1122
+ matlab: "MATLAB",
1123
+ gnuplot: "gnuplot",
1124
+ cpp: "C++",
1111
1125
  };
1112
1126
  const STUDIO_REPL_SEND_TOOL_PARAMS = Type.Object({
1113
1127
  code: Type.String({ description: "Code to execute in the active or selected Studio REPL session." }),
1114
1128
  sessionName: Type.Optional(Type.String({ description: "Exact Studio/pi-repl tmux session name. If omitted, Studio uses the active REPL session, or the first session matching target." })),
1115
- target: Type.Optional(Type.String({ description: "Optional runtime target: shell, python, ipython, julia, r, ghci, or clojure. Used when sessionName is omitted." })),
1129
+ target: Type.Optional(Type.String({ description: "Optional runtime target: shell, python, ipython, julia, r, ghci, clojure, ruby, java, octave, matlab, gnuplot, or cpp. Used when sessionName is omitted." })),
1116
1130
  timeoutMs: Type.Optional(Type.Number({ description: "Maximum time to wait for completion when Studio can detect it (default 20000, max 120000).", minimum: 1000, maximum: STUDIO_REPL_SEND_MAX_TIMEOUT_MS })),
1117
1131
  echoMode: Type.Optional(Type.Union(
1118
1132
  [Type.Literal("off"), Type.Literal("summary"), Type.Literal("full")],
1119
- { description: "How much submitted code to echo visibly in the raw REPL pane. Defaults to PI_STUDIO_REPL_ECHO_MODE or off. Summary shows short submissions in full and truncates longer ones; Full has larger bounds and writes source code into persistent raw terminal history." },
1133
+ { description: "How much submitted code to echo visibly in the raw REPL pane. Defaults to PI_STUDIO_REPL_ECHO_MODE or summary. Summary shows short submissions in full and truncates longer ones; Full has larger bounds and writes source code into persistent raw terminal history." },
1120
1134
  )),
1121
1135
  });
1122
1136
  const STUDIO_REPL_TOOL_ECHO_MODE = normalizeReplSubmissionEchoMode(process.env.PI_STUDIO_REPL_ECHO_MODE) as ReplSubmissionEchoMode;
1123
1137
  const STUDIO_REPL_STATUS_TOOL_PARAMS = Type.Object({
1124
1138
  sessionName: Type.Optional(Type.String({ description: "Exact Studio/pi-repl tmux session name to inspect." })),
1125
- target: Type.Optional(Type.String({ description: "Optional runtime target: shell, python, ipython, julia, r, ghci, or clojure. If omitted, report all Studio-visible REPL sessions." })),
1139
+ target: Type.Optional(Type.String({ description: "Optional runtime target: shell, python, ipython, julia, r, ghci, clojure, ruby, java, octave, matlab, gnuplot, or cpp. If omitted, report all Studio-visible REPL sessions." })),
1126
1140
  });
1127
1141
  const STUDIO_EXPORT_INPUT_FORMAT_DESCRIPTION = "Optional input format: auto, markdown, or latex. Defaults to auto.";
1128
1142
  const STUDIO_EXPORT_PDF_OPTIONS_TOOL_PARAMS = Type.Object({
@@ -11211,7 +11225,13 @@ function isStudioReplRuntime(value: unknown): value is StudioReplRuntime {
11211
11225
  || value === "julia"
11212
11226
  || value === "r"
11213
11227
  || value === "ghci"
11214
- || value === "clojure";
11228
+ || value === "clojure"
11229
+ || value === "ruby"
11230
+ || value === "java"
11231
+ || value === "octave"
11232
+ || value === "matlab"
11233
+ || value === "gnuplot"
11234
+ || value === "cpp";
11215
11235
  }
11216
11236
 
11217
11237
  function normalizeStudioReplRuntime(value: unknown): StudioReplRuntime | null {
@@ -11227,6 +11247,14 @@ function getDefaultStudioReplRuntimeCommand(runtime: StudioReplRuntime): string
11227
11247
  if (runtime === "julia") return "julia";
11228
11248
  if (runtime === "r") return "R";
11229
11249
  if (runtime === "ghci") return "ghci";
11250
+ if (runtime === "ruby") return "irb";
11251
+ if (runtime === "java") return "jshell";
11252
+ // Stop closes the tmux session, and on SIGHUP or SIGTERM Octave would otherwise dump its
11253
+ // workspace to octave-workspace in the working directory. --persist keeps it interactive.
11254
+ if (runtime === "octave") return "octave-cli --quiet --interactive --persist --eval 'sighup_dumps_octave_core(false); sigterm_dumps_octave_core(false);'";
11255
+ if (runtime === "matlab") return "matlab -nodesktop -nosplash";
11256
+ if (runtime === "gnuplot") return "gnuplot";
11257
+ if (runtime === "cpp") return "cling";
11230
11258
  return "clojure";
11231
11259
  }
11232
11260
 
@@ -11261,7 +11289,7 @@ function inferStudioReplSessionRuntime(sessionName: string): { runtime: StudioRe
11261
11289
  const studioMatch = sessionName.match(/^pi-studio-repl-([a-z0-9-]+)$/i);
11262
11290
  if (studioMatch) {
11263
11291
  const raw = (studioMatch[1] || "").toLowerCase();
11264
- const runtime = (["clojure", "python", "ipython", "julia", "shell", "ghci", "r"] as StudioReplRuntime[])
11292
+ const runtime = (["clojure", "python", "ipython", "julia", "shell", "ghci", "ruby", "java", "octave", "matlab", "gnuplot", "cpp", "r"] as StudioReplRuntime[])
11265
11293
  .find((candidate) => raw === candidate || raw.startsWith(`${candidate}-`));
11266
11294
  return { runtime: runtime ?? "unknown", source: "studio" };
11267
11295
  }
@@ -11435,11 +11463,14 @@ function captureStudioReplSession(sessionName: string, pinned?: StudioReplSessio
11435
11463
  return { ok: true, transcript: String(result.stdout || "").replace(/[\t ]+$/gm, "").trimEnd(), session };
11436
11464
  }
11437
11465
 
11466
+ // tmux's answer when a session or its server has gone, not just a slow or failed call (Sol).
11467
+ const STUDIO_TMUX_GONE = /can't find session|no server running|error connecting to/i;
11468
+
11438
11469
  // The pane's cursor row, where a runtime shows its prompt; dead once its command has
11439
11470
  // exited, gone once the pane has closed or left the session.
11440
11471
  function readStudioReplCursorRow(sessionId: string, paneId: string): { gone?: boolean; dead?: boolean; pid?: string; line?: string } {
11441
11472
  const panes = runStudioTmux(["list-panes", "-s", "-t", sessionId, "-F", "#{pane_id}\t#{pane_dead}\t#{cursor_y}\t#{pane_pid}"], { timeout: 3_000 });
11442
- if (!panes.ok) return { gone: true };
11473
+ if (!panes.ok) return STUDIO_TMUX_GONE.test(panes.stderr) ? { gone: true } : {};
11443
11474
  const fields = panes.stdout.split("\n").map((line) => line.split("\t")).find(([id]) => id === paneId);
11444
11475
  if (!fields) return { gone: true };
11445
11476
  const [, dead = "", row = "", pid = ""] = fields;
@@ -11461,8 +11492,13 @@ async function startStudioReplSession(runtime: StudioReplRuntime, cwd: string, o
11461
11492
  return { ok: true, session, message: `${label} REPL is already running.` };
11462
11493
  };
11463
11494
  if (running()) return reuse();
11464
- const command = getStudioReplRuntimeCommand(runtime, commandOverride);
11465
- const created = runStudioTmux(buildStudioReplTmuxStartArgs(sessionName, cwd || process.cwd(), command), { timeout: 5_000 });
11495
+ // As in pi-repl, MATLAB is told to start in the working directory; it can otherwise
11496
+ // start in its own userpath.
11497
+ const command = getStudioReplRuntimeCommand(runtime, commandOverride) + (runtime === "matlab" && !commandOverride ? ` -sd ${shellQuote(cwd || process.cwd())}` : "");
11498
+ // As in pi-repl: gnuplot and the Qt helpers it starts inherit an owner marker, so Stop
11499
+ // can find helpers that have left the session's process tree.
11500
+ const gnuplotOwner = runtime === "gnuplot" ? randomUUID().replace(/-/g, "") : "";
11501
+ const created = runStudioTmux(buildStudioReplTmuxStartArgs(sessionName, cwd || process.cwd(), command, gnuplotOwner ? [`${GNUPLOT_OWNER_ENV}=${gnuplotOwner}`] : []), { timeout: 5_000 });
11466
11502
  if (!created.ok) {
11467
11503
  // Another tab may have started the same session first; share it.
11468
11504
  if (running()) return reuse();
@@ -11473,10 +11509,11 @@ async function startStudioReplSession(runtime: StudioReplRuntime, cwd: string, o
11473
11509
  const [sessionId = "", paneId = ""] = created.stdout.trim().split("\t");
11474
11510
  if (!/^\$\d+$/.test(sessionId) || !/^%\d+$/.test(paneId)) return { ok: false, message: `Started ${sessionName}, but tmux didn't report its ID. Check it before running code.` };
11475
11511
  runStudioTmux(["set-option", "-q", "-t", sessionId, STUDIO_REPL_RUNTIME_OPTION, runtime], { timeout: 3_000 });
11512
+ if (gnuplotOwner) runStudioTmux(["set-option", "-q", "-t", sessionId, GNUPLOT_OWNER_OPTION, gnuplotOwner], { timeout: 3_000 });
11476
11513
  const started = `Started ${options?.newSession ? "new " : ""}${label} REPL${commandOverride ? ` with custom command: ${commandOverride}` : ""}`;
11477
11514
  const exited = `${label} exited while starting. Check the command: ${command}.`;
11478
11515
  // Wait for the runtime's normal prompt, only reading the pane: no probe, Enter or Ctrl-C (Sol).
11479
- const deadline = Date.now() + STUDIO_REPL_START_WAIT_MS;
11516
+ const deadline = Date.now() + (runtime === "matlab" ? STUDIO_REPL_MATLAB_START_WAIT_MS : STUDIO_REPL_START_WAIT_MS);
11480
11517
  let ready = false;
11481
11518
  while (true) {
11482
11519
  const row = readStudioReplCursorRow(sessionId, paneId);
@@ -11532,7 +11569,7 @@ async function stopStudioReplSession(sessionName: string): Promise<{ ok: true; m
11532
11569
  return { ok: true, message: `Closed ${sessionName}.`, session };
11533
11570
  }
11534
11571
  try {
11535
- await stopVerifiedReplSession({ tmux: (args: string[]) => runStudioTmuxAsync(args), sessionName, sessionNamePattern: STUDIO_REPL_SESSION_NAME });
11572
+ await stopVerifiedReplSession({ tmux: (args: string[]) => runStudioTmuxAsync(args), sessionName, sessionNamePattern: STUDIO_REPL_SESSION_NAME, isGnuplotSession: isStudioGnuplotSession });
11536
11573
  return { ok: true, message: `Stopped ${sessionName}.`, session };
11537
11574
  } catch (error) {
11538
11575
  // After tmux has closed the session, the shared stop wraps its reason as the cause.
@@ -11548,6 +11585,9 @@ type StudioReplControlFiles = {
11548
11585
  doneFile: string;
11549
11586
  // GHCi's guard and driver scripts, removed along with the source.
11550
11587
  helpers?: Array<{ dir: string; sourceFile: string; doneFile: string }>;
11588
+ // C++ completes when its driver writes a valid reply to the done file, and its
11589
+ // cleanup removes only the control files it created.
11590
+ cpp?: { completion: ReturnType<typeof prepareCppSubmission>["completion"]; cleanup: () => void };
11551
11591
  };
11552
11592
 
11553
11593
  type StudioReplPreparedSubmission = {
@@ -11597,6 +11637,11 @@ function getStudioReplControlExtension(runtime: StudioReplRuntime): string {
11597
11637
  if (runtime === "r") return "R";
11598
11638
  if (runtime === "ghci") return "ghci";
11599
11639
  if (runtime === "clojure") return "clj";
11640
+ if (runtime === "ruby") return "rb";
11641
+ if (runtime === "java") return "java";
11642
+ if (runtime === "octave" || runtime === "matlab") return "m";
11643
+ if (runtime === "gnuplot") return "gp";
11644
+ if (runtime === "cpp") return "cpp";
11600
11645
  if (runtime === "shell") return "sh";
11601
11646
  return "py";
11602
11647
  }
@@ -11627,9 +11672,41 @@ function buildStudioClojureDisplayStatements(display: ReplSubmissionDisplay, ind
11627
11672
  return display.prefixLines.map((line) => `${indent}(clojure.core/println ${JSON.stringify(line)})`);
11628
11673
  }
11629
11674
 
11675
+ // CURSOR_COLUMN_QUERY (shared with pi-repl) prints the pane's cursor column, or exits
11676
+ // non-zero; tmux gets 500 ms. A wrapper runs it with Node and ends a line before its
11677
+ // footer unless it prints 0. Only the wrapper reads its output, so it never reaches the
11678
+ // pane: a query that outlives its wait can't print after the done file (Sol, Astra,
11679
+ // candidate80).
11680
+ // process.exit ends Node even if a startup hook in NODE_OPTIONS would keep it running,
11681
+ // and each wrapper also limits the whole helper to 5 s.
11682
+ // With the display Off, the footers still end a line that output left open, and add
11683
+ // nothing else. Otherwise the runtime's prompt follows the output on the same row,
11684
+ // which the record mistook for a prompt row, and line editors such as gnuplot's then
11685
+ // redraw the next pasted line wrongly (Astra, candidate90).
11686
+
11687
+ function buildStudioPythonFooter(display: ReplSubmissionDisplay): string[] {
11688
+ return [
11689
+ " import subprocess as __pi_studio_subprocess",
11690
+ " import sys as __pi_studio_sys",
11691
+ " __pi_studio_column = ''",
11692
+ " try:",
11693
+ " __pi_studio_sys.stdout.flush()",
11694
+ " __pi_studio_sys.stderr.flush()",
11695
+ ` __pi_studio_query = __pi_studio_subprocess.run([${JSON.stringify(process.execPath)}, '-e', ${JSON.stringify(CURSOR_COLUMN_QUERY)}], stdin=__pi_studio_subprocess.DEVNULL, stdout=__pi_studio_subprocess.PIPE, stderr=__pi_studio_subprocess.DEVNULL, timeout=5)`,
11696
+ " if __pi_studio_query.returncode == 0:",
11697
+ " __pi_studio_column = __pi_studio_query.stdout.decode('utf-8', 'replace').strip()",
11698
+ // run() kills the query on any exception. Ctrl-C here must not skip the done file.
11699
+ " except BaseException:",
11700
+ " pass",
11701
+ " if __pi_studio_column != '0':",
11702
+ " __pi_studio_builtins.print()",
11703
+ ...display.suffixLines.map((line) => ` __pi_studio_builtins.print(${JSON.stringify(line)})`),
11704
+ ];
11705
+ }
11706
+
11630
11707
  function buildStudioPythonControlSource(runtime: "python" | "ipython", code: string, doneFile: string, display: ReplSubmissionDisplay): string {
11631
11708
  const prefix = buildStudioPythonDisplayStatements(display);
11632
- const completion = display.enabled ? [` __pi_studio_builtins.print(${JSON.stringify(display.endMarker)})`] : [];
11709
+ const completion = buildStudioPythonFooter(display);
11633
11710
  if (runtime === "ipython") {
11634
11711
  return [
11635
11712
  "from pathlib import Path as __pi_studio_path",
@@ -11673,8 +11750,44 @@ function buildStudioPythonControlSource(runtime: "python" | "ipython", code: str
11673
11750
  ].join("\n");
11674
11751
  }
11675
11752
 
11753
+ function buildStudioJuliaFooter(display: ReplSubmissionDisplay): string[] {
11754
+ const query = `Cmd([${juliaStringLiteral(process.execPath)}, "-e", ${juliaStringLiteral(CURSOR_COLUMN_QUERY)}])`;
11755
+ return [
11756
+ ' local __pi_studio_column = ""',
11757
+ " local __pi_studio_query = nothing",
11758
+ // The wait, not the read, is bounded: a child the helper started could
11759
+ // keep the pipe open after the helper exits. An interrupt does not end
11760
+ // the wait, since killing Node early would leave its tmux child
11761
+ // running. After 5 s a helper still running is killed, and the pipe
11762
+ // is closed so that the reader ends too.
11763
+ " try",
11764
+ " flush(stdout)",
11765
+ " flush(stderr)",
11766
+ ` __pi_studio_query = open(pipeline(${query}, stdin=devnull, stderr=devnull), "r")`,
11767
+ " local __pi_studio_reader = @async read(__pi_studio_query, String)",
11768
+ " local __pi_studio_deadline = time_ns() + 5_000_000_000",
11769
+ " local __pi_studio_finished = false",
11770
+ " while !__pi_studio_finished && time_ns() < __pi_studio_deadline",
11771
+ " try",
11772
+ " __pi_studio_finished = timedwait(() -> istaskdone(__pi_studio_reader) && process_exited(__pi_studio_query), max(0.01, (signed(__pi_studio_deadline) - signed(time_ns())) / 1e9); pollint=0.01) === :ok",
11773
+ " catch",
11774
+ " end",
11775
+ " end",
11776
+ " __pi_studio_finished && success(__pi_studio_query) && (__pi_studio_column = strip(fetch(__pi_studio_reader)))",
11777
+ " catch",
11778
+ " finally",
11779
+ " if !isnothing(__pi_studio_query)",
11780
+ " process_exited(__pi_studio_query) || kill(__pi_studio_query, Base.SIGKILL)",
11781
+ " try close(__pi_studio_query.out) catch end",
11782
+ " end",
11783
+ " end",
11784
+ ' __pi_studio_column == "0" || Base.println()',
11785
+ ...display.suffixLines.map((line) => ` Base.println(${juliaStringLiteral(line)})`),
11786
+ ];
11787
+ }
11788
+
11676
11789
  function buildStudioJuliaControlSource(code: string, doneFile: string, display: ReplSubmissionDisplay): string {
11677
- const completion = display.enabled ? [` Base.println(${juliaStringLiteral(display.endMarker)})`] : [];
11790
+ const completion = buildStudioJuliaFooter(display);
11678
11791
  return [
11679
11792
  ...buildStudioJuliaDisplayStatements(display),
11680
11793
  "try",
@@ -11691,8 +11804,20 @@ function buildStudioJuliaControlSource(code: string, doneFile: string, display:
11691
11804
  ].join("\n");
11692
11805
  }
11693
11806
 
11807
+ function buildStudioRFooter(display: ReplSubmissionDisplay): string[] {
11808
+ return [
11809
+ " try({ flush(stdout()); flush(stderr()) }, silent = TRUE)",
11810
+ // system2 quotes the command but not its arguments, and kills it after
11811
+ // 5 s. A failed query sets a status; an error or Ctrl-C here gives
11812
+ // NULL, not a lost done file.
11813
+ ` .__pi_studio_column <- tryCatch(suppressWarnings(system2(${JSON.stringify(process.execPath)}, c("-e", ${JSON.stringify(shellQuote(CURSOR_COLUMN_QUERY))}), stdout = TRUE, stderr = FALSE, timeout = 5)), error = function(e) NULL, interrupt = function(e) NULL)`,
11814
+ ' if (!is.null(attr(.__pi_studio_column, "status")) || !identical(trimws(paste(.__pi_studio_column, collapse = "")), "0")) base::cat("\\n")',
11815
+ ...display.suffixLines.map((line) => ` base::cat(${JSON.stringify(`${line}\n`)})`),
11816
+ ];
11817
+ }
11818
+
11694
11819
  function buildStudioRControlSource(code: string, doneFile: string, display: ReplSubmissionDisplay): string {
11695
- const completion = display.enabled ? [` base::cat(${JSON.stringify(`${display.endMarker}\n`)})`] : [];
11820
+ const completion = buildStudioRFooter(display);
11696
11821
  return [
11697
11822
  "local({",
11698
11823
  ...buildStudioRDisplayStatements(display, " "),
@@ -11735,13 +11860,58 @@ function buildStudioGhciControlSource(code: string, doneFile: string, display: R
11735
11860
  ].filter(Boolean).join("\n") + "\n";
11736
11861
  }
11737
11862
 
11863
+ // The cursor column for a footer run by a shell: Studio's supervisor below runs the query,
11864
+ // bounded, and Ctrl+C stops only the query. Empty if the query fails. ${NODE_OPTIONS-}
11865
+ // because the Shell runtime's footer runs in the user's shell, which may have set -u (Astra).
11866
+ function buildStudioShellCursorColumn(): string {
11867
+ return `__pi_studio_column=$(NODE_OPTIONS= ${shellQuote(process.execPath)} -e ${shellQuote(CURSOR_COLUMN_SUPERVISOR)} -- "\${NODE_OPTIONS-}" </dev/null 2>/dev/null) || __pi_studio_column=`;
11868
+ }
11869
+
11738
11870
  function buildStudioGhciCompletionLine(doneFile: string, display: ReplSubmissionDisplay): string {
11739
- const completion = display.enabled ? `command printf '%s\\n' ${shellQuote(display.endMarker)}; ` : "";
11740
- return `:! ${completion}touch ${shellQuote(doneFile)}`;
11871
+ // As in pi-repl: end the line only when output left the cursor mid-line, then print the
11872
+ // footer. trap : INT keeps Ctrl+C from ending this shell before the done file (Astra,
11873
+ // candidate90); a trap isn't inherited, so the query still stops at once.
11874
+ const suffix = display.suffixLines.map((line) => `command printf '%s\\n' ${shellQuote(line)}; `).join("");
11875
+ return `:! trap : INT; ${buildStudioShellCursorColumn()}; [ "$__pi_studio_column" = 0 ] || command printf '\\n'; ${suffix}touch ${shellQuote(doneFile)}`;
11876
+ }
11877
+
11878
+ function buildStudioClojureFooter(display: ReplSubmissionDisplay): string[] {
11879
+ const builder = `(java.lang.ProcessBuilder. ^java.util.List [${JSON.stringify(process.execPath)} "-e" ${JSON.stringify(CURSOR_COLUMN_QUERY)}])`;
11880
+ return [
11881
+ " (try (.flush *out*) (.flush *err*) (catch Throwable _))",
11882
+ // An interrupt left pending by the code would end the wait at once, so
11883
+ // it is cleared for the query and restored afterwards. One that arrives
11884
+ // during the wait is noted and the wait goes on: killing Node early
11885
+ // would leave its tmux child running. The query is killed after 5 s.
11886
+ " (let [pi-studio-interrupted (volatile! (Thread/interrupted))",
11887
+ ` pi-studio-query (try (.start (.redirectError ${builder} java.lang.ProcessBuilder$Redirect/DISCARD)) (catch Throwable _ nil))`,
11888
+ " pi-studio-deadline (+ (System/nanoTime) 5000000000)",
11889
+ " pi-studio-column (when pi-studio-query",
11890
+ " (try",
11891
+ " (.close (.getOutputStream pi-studio-query))",
11892
+ " (when (and (loop []",
11893
+ " (let [left (- pi-studio-deadline (System/nanoTime))",
11894
+ " exited (when (pos? left)",
11895
+ " (try (.waitFor pi-studio-query left java.util.concurrent.TimeUnit/NANOSECONDS)",
11896
+ " (catch InterruptedException _ (vreset! pi-studio-interrupted true) :interrupted)))]",
11897
+ " (if (= exited :interrupted) (recur) exited)))",
11898
+ " (zero? (.exitValue pi-studio-query)))",
11899
+ // Only what is waiting: a child of Node could hold the pipe open.
11900
+ " (let [in (.getInputStream pi-studio-query)",
11901
+ " bytes (byte-array (min 32 (.available in)))",
11902
+ " n (.read in bytes)]",
11903
+ ' (.trim (String. bytes 0 (int (max 0 n)) "UTF-8"))))',
11904
+ " (catch Throwable _ nil)",
11905
+ " (finally (.destroyForcibly pi-studio-query))))]",
11906
+ " (when @pi-studio-interrupted (.interrupt (Thread/currentThread)))",
11907
+ ' (when-not (= pi-studio-column "0") (clojure.core/println))',
11908
+ ...display.suffixLines.map((line) => ` (clojure.core/println ${JSON.stringify(line)})`),
11909
+ " nil)",
11910
+ ];
11741
11911
  }
11742
11912
 
11743
11913
  function buildStudioClojureControlSource(code: string, doneFile: string, display: ReplSubmissionDisplay): string {
11744
- const completion = display.enabled ? [` (clojure.core/println ${JSON.stringify(display.endMarker)})`] : [];
11914
+ const completion = buildStudioClojureFooter(display);
11745
11915
  return [
11746
11916
  "(let [code " + JSON.stringify(code) + "]",
11747
11917
  ...buildStudioClojureDisplayStatements(display, " "),
@@ -11760,13 +11930,151 @@ function buildStudioClojureControlSource(code: string, doneFile: string, display
11760
11930
  ].join("\n");
11761
11931
  }
11762
11932
 
11933
+ // Ruby (irb) and Java (JShell), as in pi-repl 0.8.5: each wrapper queries tmux for the
11934
+ // cursor column itself; Java's completion runs from an outer /open driver, as GHCi's does.
11935
+ function rubyStringLiteral(value: string): string {
11936
+ // JSON escaping leaves Ruby's #{...}, #@... and #$... interpolation active.
11937
+ // ASCII escapes also keep Unicode paths intact through older IRB input editors.
11938
+ return JSON.stringify(value).replace(/#/g, "\\#")
11939
+ .replace(/[^\x00-\x7f]/gu, (character) => `\\u{${character.codePointAt(0)!.toString(16)}}`);
11940
+ }
11941
+
11942
+ function buildStudioRubyControlSource(code: string, doneFile: string, display: ReplSubmissionDisplay): string {
11943
+ const prefix = display.enabled ? display.prefixLines.map((line) => ` puts ${rubyStringLiteral(line)}`) : [];
11944
+ // Query the actual terminal column rather than intercepting user stdout.
11945
+ // Keep the old newline guard if the bounded, read-only query is unavailable.
11946
+ const completion = [
11947
+ ' __pi_studio_column = ""',
11948
+ " begin",
11949
+ " $stdout.flush",
11950
+ " $stderr.flush",
11951
+ // Ruby's $? is thread-local: do not replace the user's last child status.
11952
+ " __pi_studio_column = Thread.new do",
11953
+ " begin",
11954
+ ` IO.popen(["tmux", "-N", "display-message", "-p", "-t", ENV.fetch("TMUX_PANE"), ${rubyStringLiteral("#{cursor_x}")}], err: File::NULL) do |__pi_studio_query|`,
11955
+ " begin",
11956
+ " if IO.select([__pi_studio_query], nil, nil, 0.5)",
11957
+ " __pi_studio_bytes = __pi_studio_query.read_nonblock(32, exception: false)",
11958
+ ' __pi_studio_bytes.is_a?(String) ? __pi_studio_bytes.strip : ""',
11959
+ " else",
11960
+ ' ""',
11961
+ " end",
11962
+ " ensure",
11963
+ // Reap only our own query process, including on timeout; never leave an
11964
+ // IO.popen close waiting indefinitely for a stuck tmux client to exit.
11965
+ " Process.kill('KILL', __pi_studio_query.pid) rescue nil",
11966
+ " end",
11967
+ " end",
11968
+ " rescue StandardError",
11969
+ ' ""',
11970
+ " end",
11971
+ " end.value",
11972
+ " rescue StandardError",
11973
+ ' __pi_studio_column = ""',
11974
+ " end",
11975
+ ' puts unless __pi_studio_column == "0"',
11976
+ ...display.suffixLines.map((line) => ` puts ${rubyStringLiteral(line)}`),
11977
+ ];
11978
+ return [
11979
+ "begin",
11980
+ ...prefix,
11981
+ ` __pi_studio_code = ${rubyStringLiteral(code)}`,
11982
+ " __pi_studio_context = defined?(IRB) && IRB.respond_to?(:CurrentContext) && IRB.CurrentContext",
11983
+ " __pi_studio_binding = __pi_studio_context ? __pi_studio_context.workspace.binding : TOPLEVEL_BINDING",
11984
+ " __pi_studio_result = eval(__pi_studio_code, __pi_studio_binding, '<pi-studio-repl>', 1)",
11985
+ " p __pi_studio_result unless __pi_studio_result.nil?",
11986
+ "rescue Exception => __pi_studio_e",
11987
+ " $stderr.puts __pi_studio_e.full_message(highlight: false)",
11988
+ "ensure",
11989
+ // The done file is written even if Ctrl+C lands during the footer: IRB's
11990
+ // IRB::Abort and Ruby's Interrupt aren't StandardErrors, so the query's
11991
+ // rescue lets them through, and Studio would wait for this send forever (Sol).
11992
+ " begin",
11993
+ ...completion.map((line) => ` ${line}`),
11994
+ " ensure",
11995
+ ` File.write(${rubyStringLiteral(doneFile)}, "done\\n")`,
11996
+ " end",
11997
+ // IRB checks echo? immediately after evaluating the loader. Suppress
11998
+ // just that result, restoring the original method before returning.
11999
+ " begin",
12000
+ " if __pi_studio_context && __pi_studio_context.respond_to?(:echo?)",
12001
+ " __pi_studio_echo_owner = __pi_studio_context.singleton_class",
12002
+ " __pi_studio_echo_owned = __pi_studio_echo_owner.instance_methods(false).include?(:echo?)",
12003
+ " __pi_studio_echo_original = __pi_studio_context.method(:echo?)",
12004
+ " __pi_studio_context.define_singleton_method(:echo?) do",
12005
+ " if __pi_studio_echo_owned",
12006
+ " __pi_studio_echo_owner.send(:define_method, :echo?, __pi_studio_echo_original)",
12007
+ " else",
12008
+ " __pi_studio_echo_owner.send(:remove_method, :echo?)",
12009
+ " end",
12010
+ " false",
12011
+ " end",
12012
+ " end",
12013
+ " rescue StandardError",
12014
+ // If a customised/frozen context refuses the hook, keep normal IRB
12015
+ // behaviour rather than fail the already completed submission.
12016
+ " end",
12017
+ "end",
12018
+ ].join("\n");
12019
+ }
12020
+
12021
+ function buildStudioJavaControlSource(code: string, doneFile: string, display: ReplSubmissionDisplay): string {
12022
+ if (/[\r\n]/.test(doneFile)) throw new Error("JShell control paths cannot contain line breaks.");
12023
+ const prefix = display.enabled ? display.prefixLines.map((line) => `java.lang.System.out.println(${JSON.stringify(line)});`) : [];
12024
+ // /open evaluates top-level snippets in the existing JShell. Completion
12025
+ // stays in the outer driver, outside this source file's parser state.
12026
+ return [...prefix, code.replace(/\r/g, "").trimEnd(), ""].join("\n");
12027
+ }
12028
+
12029
+ function buildStudioJavaDriverSource(sourceFile: string, doneFile: string, display: ReplSubmissionDisplay): string {
12030
+ // Only add a newline when the terminal is mid-line. The scoped query does
12031
+ // not replace System.out/err, change user declarations, or emit another /open.
12032
+ const completion = [
12033
+ ' String __pi_studio_column = "";',
12034
+ " java.lang.Process __pi_studio_query = null;",
12035
+ " try {",
12036
+ " java.lang.System.out.flush();",
12037
+ " java.lang.System.err.flush();",
12038
+ ` __pi_studio_query = new java.lang.ProcessBuilder("tmux", "-N", "display-message", "-p", "-t", java.lang.System.getenv("TMUX_PANE"), ${JSON.stringify("#{cursor_x}")}).redirectError(java.lang.ProcessBuilder.Redirect.DISCARD).start();`,
12039
+ " if (__pi_studio_query.waitFor(500, java.util.concurrent.TimeUnit.MILLISECONDS) && __pi_studio_query.exitValue() == 0) {",
12040
+ // Do not wait for EOF if an unexpected descendant inherits the pipe.
12041
+ " byte[] __pi_studio_bytes = new byte[32];",
12042
+ " int __pi_studio_count = __pi_studio_query.getInputStream().read(__pi_studio_bytes, 0, Math.min(32, __pi_studio_query.getInputStream().available()));",
12043
+ " __pi_studio_column = new String(__pi_studio_bytes, 0, Math.max(0, __pi_studio_count), java.nio.charset.StandardCharsets.UTF_8).trim();",
12044
+ " }",
12045
+ " } catch (Exception __pi_studio_ignored) {",
12046
+ ' __pi_studio_column = "";',
12047
+ " } finally {",
12048
+ " if (__pi_studio_query != null) {",
12049
+ " try { __pi_studio_query.destroyForcibly(); } catch (Exception __pi_studio_ignored) {}",
12050
+ " }",
12051
+ " }",
12052
+ ' if (!"0".equals(__pi_studio_column)) java.lang.System.out.println();',
12053
+ ...display.suffixLines.map((line) => ` java.lang.System.out.println(${JSON.stringify(line)});`),
12054
+ ];
12055
+ return [
12056
+ buildStudioReplSubmissionLine("java", sourceFile, doneFile),
12057
+ "{",
12058
+ // As for Ruby. JShell stops a snippet with an asynchronous StopExecutionException,
12059
+ // which isn't an Exception. During waitFor it surfaces as one the footer catches, but
12060
+ // elsewhere in the footer only finally is sure to run.
12061
+ "try {",
12062
+ ...completion,
12063
+ "} finally {",
12064
+ ` java.nio.file.Files.write(java.nio.file.Paths.get(${JSON.stringify(doneFile)}), new byte[]{100, 111, 110, 101, 10});`,
12065
+ "}",
12066
+ "}",
12067
+ ].join("\n");
12068
+ }
12069
+
11763
12070
  function buildStudioShellControlSource(code: string, display: ReplSubmissionDisplay): string {
11764
- if (!display.enabled) return `${code.replace(/\r/g, "").trimEnd()}\n`;
11765
12071
  return [
11766
12072
  ...display.prefixLines.map((line) => `command printf '%s\\n' ${shellQuote(line)}`),
11767
12073
  code.replace(/\r/g, "").trimEnd(),
11768
12074
  "__pi_studio_repl_status=$?",
11769
- `command printf '%s\\n' ${shellQuote(display.endMarker)}`,
12075
+ // The footer runs in a subshell that traps Ctrl+C, so an interrupt there doesn't end the
12076
+ // loader's command line before its done file, in bash or zsh (Astra, candidate90).
12077
+ `( trap : INT; ${buildStudioShellCursorColumn()}; [ "$__pi_studio_column" = 0 ] || command printf '\\n'${display.suffixLines.map((line) => `; command printf '%s\\n' ${shellQuote(line)}`).join("")} )`,
11770
12078
  "return \"$__pi_studio_repl_status\"",
11771
12079
  ].filter(Boolean).join("\n") + "\n";
11772
12080
  }
@@ -11777,6 +12085,13 @@ function buildStudioReplControlSource(runtime: StudioReplRuntime, code: string,
11777
12085
  if (runtime === "r") return buildStudioRControlSource(code, doneFile, display);
11778
12086
  if (runtime === "ghci") return buildStudioGhciControlSource(code, doneFile, display);
11779
12087
  if (runtime === "clojure") return buildStudioClojureControlSource(code, doneFile, display);
12088
+ if (runtime === "ruby") return buildStudioRubyControlSource(code, doneFile, display);
12089
+ if (runtime === "java") return buildStudioJavaControlSource(code, doneFile, display);
12090
+ if (runtime === "octave" || runtime === "matlab") return buildMLanguageControlSource(code, display);
12091
+ // As in pi-repl: gnuplot loads the code as written; its driver prints the display.
12092
+ if (runtime === "gnuplot") return code + "\n";
12093
+ // As in pi-repl: the driver reads the C++ as written and prints the display itself.
12094
+ if (runtime === "cpp") return code;
11780
12095
  if (runtime === "shell") return buildStudioShellControlSource(code, display);
11781
12096
  return null;
11782
12097
  }
@@ -11787,6 +12102,11 @@ function buildStudioReplSubmissionLine(runtime: StudioReplRuntime, sourceFile: s
11787
12102
  if (runtime === "r") return `source(${quotedPath}, local=.GlobalEnv)`;
11788
12103
  if (runtime === "ghci") return `:script ${quotedPath}`;
11789
12104
  if (runtime === "clojure") return `(do (load-file ${quotedPath}) :pi-studio/silent)`;
12105
+ if (runtime === "ruby") return `load ${rubyStringLiteral(sourceFile)}; nil`;
12106
+ if (runtime === "java") return `/open ${sourceFile}`;
12107
+ if (runtime === "octave" || runtime === "matlab") return `eval(fileread(${mStringLiteral(sourceFile)}));`;
12108
+ if (runtime === "gnuplot") return buildGnuplotSubmissionLine(sourceFile);
12109
+ if (runtime === "cpp") return cppInclude(sourceFile);
11790
12110
  if (runtime === "shell") return `. ${shellQuote(sourceFile)}; touch ${shellQuote(doneFile)}`;
11791
12111
  return `exec(open(${quotedPath}, encoding="utf-8").read(), globals())`;
11792
12112
  }
@@ -11797,6 +12117,7 @@ function unsupportedStudioReplRuntimeMessage(sessionName: string): string {
11797
12117
 
11798
12118
  function cleanupStudioReplControlFiles(controlFiles: StudioReplControlFiles | undefined): void {
11799
12119
  if (!controlFiles) return;
12120
+ if (controlFiles.cpp) return controlFiles.cpp.cleanup();
11800
12121
  cleanupPrivateReplControlFiles(controlFiles);
11801
12122
  for (const helper of controlFiles.helpers ?? []) cleanupPrivateReplControlFiles(helper);
11802
12123
  }
@@ -11807,13 +12128,17 @@ function prepareStudioReplSubmission(
11807
12128
  runtime: StudioReplRuntime,
11808
12129
  ): StudioReplPreparedSubmission {
11809
12130
  const normalizedSource = String(source || "").replace(/\r\n/g, "\n").replace(/\r/g, "\n");
12131
+ if (runtime === "cpp" && normalizedSource.includes("\0")) throw new Error("C++ source cannot contain NUL bytes; no code was sent.");
11810
12132
  const display = createReplSubmissionDisplay({
11811
12133
  entryId: details.submissionId,
11812
12134
  origin: "pi-studio",
11813
12135
  code: normalizedSource,
11814
12136
  mode: details.echoMode,
11815
12137
  });
12138
+ // As in pi-repl, control filenames start with the display's id.
12139
+ const controlOptions = { anchorId: display.anchorId };
11816
12140
  const controlFiles: StudioReplControlFiles = createPrivateReplControlFiles({
12141
+ ...controlOptions,
11817
12142
  extension: getStudioReplControlExtension(runtime),
11818
12143
  buildSource: ({ doneFile }: StudioReplControlFiles) => {
11819
12144
  const source = buildStudioReplControlSource(runtime, normalizedSource, doneFile, display);
@@ -11828,11 +12153,13 @@ function prepareStudioReplSubmission(
11828
12153
  // guard's script, and the driver still completes.
11829
12154
  try {
11830
12155
  const guard = createPrivateReplControlFiles({
12156
+ ...controlOptions,
11831
12157
  extension: "ghci",
11832
12158
  buildSource: () => buildStudioReplSubmissionLine("ghci", controlFiles.sourceFile, controlFiles.doneFile) + "\n",
11833
12159
  });
11834
12160
  controlFiles.helpers = [guard];
11835
12161
  const driver = createPrivateReplControlFiles({
12162
+ ...controlOptions,
11836
12163
  extension: "ghci",
11837
12164
  buildSource: () => [
11838
12165
  buildStudioReplSubmissionLine("ghci", guard.sourceFile, controlFiles.doneFile),
@@ -11847,6 +12174,88 @@ function prepareStudioReplSubmission(
11847
12174
  throw error;
11848
12175
  }
11849
12176
  }
12177
+ if (runtime === "java") {
12178
+ // As in pi-repl: JShell echoes only the outer /open. Its nested load of the
12179
+ // source returns before completion, even if the source is rejected or unfinished.
12180
+ try {
12181
+ const driver = createPrivateReplControlFiles({
12182
+ ...controlOptions,
12183
+ extension: "java",
12184
+ buildSource: () => buildStudioJavaDriverSource(controlFiles.sourceFile, controlFiles.doneFile, display),
12185
+ });
12186
+ controlFiles.helpers = [driver];
12187
+ loader = driver.sourceFile;
12188
+ } catch (error) {
12189
+ cleanupStudioReplControlFiles(controlFiles);
12190
+ throw error;
12191
+ }
12192
+ }
12193
+ if (runtime === "octave" || runtime === "matlab") {
12194
+ // pi-repl's M driver: the code runs in the base workspace,
12195
+ // and a function-local onCleanup writes the footer and done file, even after an
12196
+ // error, return, interrupt or clear all.
12197
+ try {
12198
+ const driver = createPrivateReplControlFiles({
12199
+ ...controlOptions,
12200
+ extension: "m",
12201
+ buildSource: () => buildMLanguageDriverSource(runtime, controlFiles.sourceFile, controlFiles.doneFile, display),
12202
+ });
12203
+ controlFiles.helpers = [driver];
12204
+ loader = driver.sourceFile;
12205
+ } catch (error) {
12206
+ cleanupStudioReplControlFiles(controlFiles);
12207
+ throw error;
12208
+ }
12209
+ }
12210
+ if (runtime === "gnuplot") {
12211
+ // pi-repl's shared gnuplot driver: a Node script gnuplot loads through a pipe. It
12212
+ // feeds gnuplot the code and then a guard that acknowledges it returned; on an error
12213
+ // or Ctrl+C gnuplot closes the pipe instead. Either way the driver prints the footer
12214
+ // and writes the done file, without typing into the terminal or changing settings.
12215
+ try {
12216
+ const guard = createPrivateReplControlFiles({
12217
+ ...controlOptions,
12218
+ extension: "gp",
12219
+ buildSource: ({ doneFile }: StudioReplControlFiles) => buildGnuplotGuardSource(doneFile),
12220
+ });
12221
+ controlFiles.helpers = [guard];
12222
+ const driver = createPrivateReplControlFiles({
12223
+ ...controlOptions,
12224
+ extension: "cjs",
12225
+ buildSource: () => buildGnuplotDriverSource(controlFiles.sourceFile, guard.sourceFile, guard.doneFile, controlFiles.doneFile, display),
12226
+ });
12227
+ controlFiles.helpers.push(driver);
12228
+ loader = driver.sourceFile;
12229
+ } catch (error) {
12230
+ cleanupStudioReplControlFiles(controlFiles);
12231
+ throw error;
12232
+ }
12233
+ }
12234
+ if (runtime === "cpp") {
12235
+ // pi-repl's Cling driver: a header Cling includes, whose initializer reads a request
12236
+ // naming the source and the display, both checked by identity. It evaluates the code
12237
+ // one prompt group at a time, prints the footer, then writes a reply with the result.
12238
+ try {
12239
+ const request = createPrivateReplControlFiles({
12240
+ ...controlOptions,
12241
+ extension: "req",
12242
+ buildSource: () => buildCppRequest(controlFiles.sourceFile, controlFiles.doneFile, display),
12243
+ });
12244
+ controlFiles.helpers = [request];
12245
+ const cpp = prepareCppSubmission(request.sourceFile, controlFiles.doneFile);
12246
+ const driver = createPrivateReplControlFiles({
12247
+ ...controlOptions,
12248
+ extension: "hxx",
12249
+ buildSource: () => buildCppDriverSource(request.sourceFile, controlFiles.doneFile),
12250
+ });
12251
+ controlFiles.helpers.push(driver);
12252
+ controlFiles.cpp = { completion: cpp.completion, cleanup: createCppControlCleanup(cpp.completion, [controlFiles.sourceFile, request.sourceFile, driver.sourceFile]) };
12253
+ loader = driver.sourceFile;
12254
+ } catch (error) {
12255
+ cleanupStudioReplControlFiles(controlFiles);
12256
+ throw error;
12257
+ }
12258
+ }
11850
12259
  return {
11851
12260
  runtime,
11852
12261
  usedControlFile: true,
@@ -11856,13 +12265,16 @@ function prepareStudioReplSubmission(
11856
12265
  };
11857
12266
  }
11858
12267
 
11859
- function pasteTextToStudioReplPane(text: string, paneTarget: string): { ok: true } | { ok: false; message: string; submissionStarted: boolean } {
12268
+ function pasteTextToStudioReplPane(text: string, paneTarget: string, bracketed = false): { ok: true } | { ok: false; message: string; submissionStarted: boolean } {
11860
12269
  const bufferName = `pi-studio-repl-${randomUUID().replace(/-/g, "")}`;
11861
12270
  const target = paneTarget;
11862
12271
  const loadResult = runStudioTmux(["load-buffer", "-b", bufferName, "-"], { input: text, timeout: 5_000 });
11863
12272
  if (!loadResult.ok) return { ok: false, message: loadResult.message || "Failed to load text into tmux buffer.", submissionStarted: false };
11864
12273
  try {
11865
- const pasteResult = runStudioTmux(["paste-buffer", "-d", "-b", bufferName, "-t", target], { timeout: 5_000 });
12274
+ // As in pi-repl 0.8.5: -p brackets the paste only if the REPL asked for bracketed
12275
+ // pastes. Julia then draws a line that wraps in the pane once, not once per
12276
+ // character, which left copies of its first row in the output.
12277
+ const pasteResult = runStudioTmux(["paste-buffer", ...(bracketed ? ["-p"] : []), "-d", "-b", bufferName, "-t", target], { timeout: 5_000 });
11866
12278
  if (!pasteResult.ok) return { ok: false, message: pasteResult.message || "Failed to paste text into REPL session.", submissionStarted: false };
11867
12279
  const enterResult = runStudioTmux(["send-keys", "-t", target, "C-m"], { timeout: 5_000 });
11868
12280
  if (!enterResult.ok) return { ok: false, message: enterResult.message || "Failed to send Enter to REPL session.", submissionStarted: true };
@@ -11891,7 +12303,7 @@ function sendTextToStudioReplSession(
11891
12303
  submissionId: options.submissionId || `pi-studio:local:${randomUUID()}`,
11892
12304
  echoMode: normalizeReplSubmissionEchoMode(options.echoMode, STUDIO_REPL_TOOL_ECHO_MODE) as ReplSubmissionEchoMode,
11893
12305
  }, runtime);
11894
- const pasted = pasteTextToStudioReplPane(prepared.submissionText, paneTarget);
12306
+ const pasted = pasteTextToStudioReplPane(prepared.submissionText, paneTarget, runtime === "julia");
11895
12307
  if (!pasted.ok) return {
11896
12308
  ok: false,
11897
12309
  message: pasted.message,
@@ -12120,15 +12532,50 @@ function clearStudioReplJournal(sessionName: string): void {
12120
12532
  clearReplSessionRecord(session.recordId, getStudioReplSessionRecordIdentity(session));
12121
12533
  }
12122
12534
 
12123
- async function waitForStudioReplDoneFile(doneFile: string | undefined, timeoutMs: number, signal?: AbortSignal): Promise<boolean> {
12124
- if (!doneFile) return false;
12535
+ // As in pi-repl, a C++ submission is complete only once its reply is valid: an empty,
12536
+ // partial or replaced done file stays pending.
12537
+ function isStudioReplSubmissionDone(controlFiles: StudioReplControlFiles): boolean {
12538
+ return controlFiles.cpp ? readCppCompletion(controlFiles.cpp.completion) !== undefined : existsSync(controlFiles.doneFile);
12539
+ }
12540
+
12541
+ // Whether the pane a send went to has ended: closed, its session or tmux server gone, or kept
12542
+ // dead by remain-on-exit. Undefined when tmux didn't answer, which counts as neither (Sol).
12543
+ function hasStudioReplPaneEnded(session: StudioReplSessionInfo): boolean | undefined {
12544
+ const panes = runStudioTmux(["list-panes", "-s", "-t", session.tmuxSessionId, "-F", "#{pane_id}\t#{pane_dead}"], { timeout: 3_000 });
12545
+ if (!panes.ok) return STUDIO_TMUX_GONE.test(panes.stderr) ? true : undefined;
12546
+ const pane = panes.stdout.split("\n").map((line) => line.split("\t")).find(([id]) => id === session.target);
12547
+ return !pane || pane[1] === "1";
12548
+ }
12549
+
12550
+ // A send whose session ended before it completed. Its record keeps what the pane still showed.
12551
+ class StudioReplSessionEndedError extends Error {
12552
+ constructor(sessionName: string, readonly paneOutput = "") {
12553
+ super(`${sessionName} ended while running the code.`);
12554
+ }
12555
+
12556
+ get recordText(): string {
12557
+ return [this.message, this.paneOutput].filter(Boolean).join("\n\n");
12558
+ }
12559
+ }
12560
+
12561
+ async function waitForStudioReplDoneFile(controlFiles: StudioReplControlFiles | undefined, timeoutMs: number, signal?: AbortSignal, session?: StudioReplSessionInfo): Promise<{ completed: boolean; ended: boolean }> {
12562
+ if (!controlFiles?.doneFile) return { completed: false, ended: false };
12125
12563
  const deadline = Date.now() + clampStudioReplSendTimeout(timeoutMs);
12564
+ let nextPaneCheck = Date.now() + 1_000;
12565
+ let endedChecks = 0;
12126
12566
  while (Date.now() < deadline) {
12127
- if (existsSync(doneFile)) return true;
12128
- if (signal?.aborted) return false;
12567
+ if (isStudioReplSubmissionDone(controlFiles)) return { completed: true, ended: false };
12568
+ if (signal?.aborted) return { completed: false, ended: false };
12569
+ // A runtime that exits or crashes, as Cling does on a null dereference, ends the
12570
+ // wait instead of the timeout, as in pi-repl. Two checks a second apart.
12571
+ if (session && Date.now() >= nextPaneCheck) {
12572
+ endedChecks = hasStudioReplPaneEnded(session) === true ? endedChecks + 1 : 0;
12573
+ if (endedChecks >= 2 && !isStudioReplSubmissionDone(controlFiles)) return { completed: false, ended: true };
12574
+ nextPaneCheck = Date.now() + 1_000;
12575
+ }
12129
12576
  await sleep(100);
12130
12577
  }
12131
- return existsSync(doneFile);
12578
+ return { completed: isStudioReplSubmissionDone(controlFiles), ended: false };
12132
12579
  }
12133
12580
 
12134
12581
  function sleepWithoutKeepingStudioProcessAlive(ms: number): Promise<void> {
@@ -12150,8 +12597,9 @@ function retainStudioReplSubmissionUntilSettled(
12150
12597
  let nextIdentityCheck = 0;
12151
12598
  let missingChecks = 0;
12152
12599
  try {
12153
- while (!existsSync(controlFiles.doneFile)) {
12154
- if (!existsSync(controlFiles.sourceFile)) return;
12600
+ while (!isStudioReplSubmissionDone(controlFiles)) {
12601
+ // As in pi-repl, only a C++ reply settles it, not its missing source.
12602
+ if (!controlFiles.cpp && !existsSync(controlFiles.sourceFile)) return;
12155
12603
  if (Date.now() >= nextIdentityCheck) {
12156
12604
  try {
12157
12605
  const current = inspectStudioReplSession(session.sessionName);
@@ -12181,7 +12629,7 @@ async function releaseOrRetainStudioReplSubmission(
12181
12629
  session: StudioReplSessionInfo | null,
12182
12630
  controlFiles: StudioReplControlFiles | undefined,
12183
12631
  ): Promise<void> {
12184
- if (session && controlFiles && !existsSync(controlFiles.doneFile)) {
12632
+ if (session && controlFiles && !isStudioReplSubmissionDone(controlFiles)) {
12185
12633
  retainStudioReplSubmissionUntilSettled(session, controlFiles, lease);
12186
12634
  return;
12187
12635
  }
@@ -12808,8 +13256,8 @@ ${cssVarsBlock}
12808
13256
  <option value="literate">Send mode: Literate</option>
12809
13257
  </select>
12810
13258
  <select id="replEchoModeSelect" class="studio-flat-select" hidden aria-label="REPL submission echo" title="Choose how much submitted code Studio displays in the raw REPL pane.">
12811
- <option value="off" selected>Pane echo: Off</option>
12812
- <option value="summary">Pane echo: Summary</option>
13259
+ <option value="off">Pane echo: Off</option>
13260
+ <option value="summary" selected>Pane echo: Summary</option>
12813
13261
  <option value="full">Pane echo: Full (raw code)</option>
12814
13262
  </select>
12815
13263
  </div>
@@ -13027,6 +13475,7 @@ ${cssVarsBlock}
13027
13475
  </div>
13028
13476
  <div class="reference-meta">
13029
13477
  <span id="referenceBadge" class="source-badge">Latest response: none</span>
13478
+ <span id="referenceHistoryCount" class="source-badge" hidden></span>
13030
13479
  </div>
13031
13480
  <div id="critiqueView" class="panel-scroll rendered-markdown"><pre class="plain-markdown">No response yet.</pre></div>
13032
13481
  <div class="response-wrap">
@@ -13436,12 +13885,16 @@ export default function (pi: ExtensionAPI) {
13436
13885
  name: "studio_repl_send",
13437
13886
  label: "Send to Studio REPL",
13438
13887
  description: "Execute code in the active or selected Studio tmux-backed REPL session using Studio's safe runtime-specific submission protocol.",
13439
- promptSnippet: "Execute code in the active Studio REPL session safely, including multiline Python/R/Julia/GHCi/Clojure snippets.",
13888
+ promptSnippet: "Execute code in the active Studio REPL session safely, including multiline Python/R/Julia/GHCi/Clojure/Ruby/Java/Octave/MATLAB/gnuplot/C++ snippets.",
13440
13889
  promptGuidelines: [
13441
13890
  "Use studio_repl_send when the user asks to run code in the active Studio REPL.",
13442
13891
  "Do not improvise tmux paste-buffer commands for Studio REPL code; studio_repl_send handles multiline quoting and runtime-specific submission.",
13443
- "Submitted-code display is off by default; use echoMode='summary' or echoMode='full' only when the user asks to show code and alignment anchors in the raw pane.",
13892
+ "studio_repl_send shows bounded submitted code and alignment anchors in the raw pane by default (Summary). Use echoMode='off' when the user asks for quiet output, and echoMode='full' only when explicitly requested.",
13444
13893
  "If several REPL sessions of the same runtime are running, use studio_repl_status first or pass the exact sessionName when known.",
13894
+ "In Java (JShell), use System.out.println(...) for values you want to see: code is loaded with /open, which doesn't echo expression results.",
13895
+ "Octave and MATLAB are separate runtimes: don't substitute one for the other. Code runs in the base workspace with native semicolon and ans behaviour; use disp or fprintf for explicit output. MATLAB function definitions belong in .m files. clear, clear all, exit and quit change or end the session.",
13896
+ "gnuplot is its own runtime, not another REPL's plotting backend. Send complete gnuplot commands and use print for console results. Keep the user's terminal, output and settings; export a figure only when asked. reset changes state. In sent code, exit returns from that code; exit gnuplot ends the session. Avoid pause and input waits unless asked.",
13897
+ "C++ runs in Cling. Send complete prompt groups, with a function's opening brace on its declaration line, and #include ordinary definition or header files. Dot commands are for the terminal only. Earlier groups may run before a later error, and nothing is replayed. Exiting, a crash or Ctrl+C while code is busy can end the session. Completion means the code returned, not that it succeeded.",
13445
13898
  ],
13446
13899
  parameters: STUDIO_REPL_SEND_TOOL_PARAMS,
13447
13900
  executionMode: "sequential",
@@ -13535,8 +13988,9 @@ export default function (pi: ExtensionAPI) {
13535
13988
  submittedSession = currentSession;
13536
13989
 
13537
13990
  let completed = false;
13991
+ let ended = false;
13538
13992
  if (sent.controlFiles?.doneFile) {
13539
- completed = await waitForStudioReplDoneFile(sent.controlFiles.doneFile, timeoutMs, signal);
13993
+ ({ completed, ended } = await waitForStudioReplDoneFile(sent.controlFiles, timeoutMs, signal, currentSession));
13540
13994
  if (signal?.aborted && !completed) {
13541
13995
  throw new Error("studio_repl_send was aborted after submission; the shared session remains busy until the running code settles.");
13542
13996
  }
@@ -13544,7 +13998,7 @@ export default function (pi: ExtensionAPI) {
13544
13998
  await sleep(Math.min(750, timeoutMs));
13545
13999
  }
13546
14000
  const after = captureStudioReplSession(currentSession.sessionName, currentSession);
13547
- if (!after.ok) throw new Error(`Could not capture ${currentSession.sessionName} after sending: ${after.message}`);
14001
+ if (!after.ok) throw ended ? new StudioReplSessionEndedError(currentSession.sessionName) : new Error(`Could not capture ${currentSession.sessionName} after sending: ${after.message}`);
13548
14002
  if (!isSameStudioReplSessionLifetime(currentSession, after.session)) {
13549
14003
  throw new Error(`REPL session ${currentSession.sessionName} changed before Studio captured the result.`);
13550
14004
  }
@@ -13557,6 +14011,8 @@ export default function (pi: ExtensionAPI) {
13557
14011
  promptLine: beforeTranscript.split("\n").at(-1),
13558
14012
  completed,
13559
14013
  });
14014
+ // A pane kept dead by remain-on-exit still shows what the code printed.
14015
+ if (ended) throw new StudioReplSessionEndedError(currentSession.sessionName, output);
13560
14016
  const status: StudioReplJournalEntry["status"] = sent.controlFiles?.doneFile
13561
14017
  ? (completed ? "captured" : "timeout")
13562
14018
  : (output.trim() ? "captured" : "sent");
@@ -13621,19 +14077,22 @@ export default function (pi: ExtensionAPI) {
13621
14077
  } as Record<string, unknown>,
13622
14078
  };
13623
14079
  } catch (error) {
14080
+ // An ended session is an error whatever its output says; only Studio's own messages
14081
+ // are read for "timed out" (Sol).
14082
+ const ended = error instanceof StudioReplSessionEndedError ? error.recordText : undefined;
13624
14083
  if (journalEntry) {
13625
14084
  try {
13626
14085
  recordStudioReplJournalEntry({
13627
14086
  ...journalEntry,
13628
- output: error instanceof Error ? error.message : String(error),
13629
- status: error instanceof Error && /timed out/i.test(error.message) ? "timeout" : "error",
14087
+ output: ended ?? (error instanceof Error ? error.message : String(error)),
14088
+ status: ended === undefined && error instanceof Error && /timed out/i.test(error.message) ? "timeout" : "error",
13630
14089
  completedAt: Date.now(),
13631
14090
  }, submittedSession || selected.session);
13632
14091
  } catch {
13633
14092
  // Preserve the execution error when record maintenance also fails.
13634
14093
  }
13635
14094
  }
13636
- throw error;
14095
+ throw ended === undefined ? error : new Error(ended);
13637
14096
  } finally {
13638
14097
  if (!published) broadcastStudioReplSelection();
13639
14098
  await releaseOrRetainStudioReplSubmission(lease, submittedSession, submittedControlFiles);
@@ -16729,13 +17188,14 @@ export default function (pi: ExtensionAPI) {
16729
17188
  });
16730
17189
  const timeoutMs = STUDIO_REPL_SEND_DEFAULT_TIMEOUT_MS;
16731
17190
  let completed = false;
17191
+ let ended = false;
16732
17192
  if (sent.controlFiles?.doneFile) {
16733
- completed = await waitForStudioReplDoneFile(sent.controlFiles.doneFile, timeoutMs);
17193
+ ({ completed, ended } = await waitForStudioReplDoneFile(sent.controlFiles, timeoutMs, undefined, currentSession));
16734
17194
  } else {
16735
17195
  await sleep(Math.min(750, timeoutMs));
16736
17196
  }
16737
17197
  const after = captureStudioReplSession(msg.sessionName, currentSession);
16738
- if (!after.ok) throw new Error(`Could not capture ${msg.sessionName} after sending: ${after.message}`);
17198
+ if (!after.ok) throw ended ? new StudioReplSessionEndedError(msg.sessionName) : new Error(`Could not capture ${msg.sessionName} after sending: ${after.message}`);
16739
17199
  if (!isSameStudioReplSessionLifetime(currentSession, after.session)) {
16740
17200
  throw new Error(`REPL session ${msg.sessionName} changed before Studio captured the result.`);
16741
17201
  }
@@ -16748,6 +17208,8 @@ export default function (pi: ExtensionAPI) {
16748
17208
  promptLine: beforeTranscript.split("\n").at(-1),
16749
17209
  completed,
16750
17210
  });
17211
+ // A pane kept dead by remain-on-exit still shows what the code printed.
17212
+ if (ended) throw new StudioReplSessionEndedError(msg.sessionName, output);
16751
17213
  updateStudioReplJournalEntryOutput(
16752
17214
  msg.requestId,
16753
17215
  msg.sessionName,
@@ -16761,7 +17223,7 @@ export default function (pi: ExtensionAPI) {
16761
17223
  if (journalEntry) updateStudioReplJournalEntryOutput(
16762
17224
  msg.requestId,
16763
17225
  msg.sessionName,
16764
- message,
17226
+ error instanceof StudioReplSessionEndedError ? error.recordText : message,
16765
17227
  "error",
16766
17228
  submittedSession || session,
16767
17229
  );