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.
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,10 @@ import {
87
88
  cleanupPrivateReplControlFiles,
88
89
  createPrivateReplControlFiles,
89
90
  } from "./shared/repl-control-files.js";
91
+ import { buildMLanguageControlSource, mStringLiteral } from "./shared/repl-m-language.js";
92
+ import { buildGnuplotDriverSource, buildGnuplotGuardSource, buildGnuplotSubmissionLine } from "./shared/repl-gnuplot.js";
93
+ import { GNUPLOT_OWNER_ENV, GNUPLOT_OWNER_OPTION } from "./shared/repl-gnuplot-processes.js";
94
+ import { buildCppDriverSource, buildCppRequest, cppInclude, createCppControlCleanup, prepareCppSubmission, readCppCompletion } from "./shared/repl-cpp.js";
90
95
  import { buildStudioForwardingHint, buildStudioSshTunnelHint, isStudioSshSession as isSshSession } from "./shared/studio-ssh-hint.js";
91
96
  import {
92
97
  buildStudioPendingPage,
@@ -165,7 +170,7 @@ type StudioSourceKind = "file" | "last-response" | "blank";
165
170
  type TerminalActivityPhase = "idle" | "running" | "tool" | "responding";
166
171
  type StudioPromptMode = "response" | "run" | "effective";
167
172
  type StudioPromptTriggerKind = "run" | "steer";
168
- type StudioReplRuntime = "shell" | "python" | "ipython" | "julia" | "r" | "ghci" | "clojure";
173
+ type StudioReplRuntime = "shell" | "python" | "ipython" | "julia" | "r" | "ghci" | "clojure" | "ruby" | "java" | "octave" | "matlab" | "gnuplot" | "cpp";
169
174
  type ReplSubmissionEchoMode = "off" | "summary" | "full";
170
175
  type ReplSubmissionDisplay = ReturnType<typeof createReplSubmissionDisplay>;
171
176
  type StudioQuizAngle = "general" | "scientist" | "mathematician" | "statistician" | "developer" | "reviewer";
@@ -1092,6 +1097,8 @@ const STUDIO_REPL_SEND_MAX_CHARS = 200_000;
1092
1097
  const STUDIO_REPL_SEND_DEFAULT_TIMEOUT_MS = 20_000;
1093
1098
  const STUDIO_REPL_SEND_MAX_TIMEOUT_MS = 120_000;
1094
1099
  const STUDIO_REPL_START_WAIT_MS = 20_000;
1100
+ // MATLAB took 31 s to reach its prompt on an M-series Mac (R2024b, 20 Oct).
1101
+ const STUDIO_REPL_MATLAB_START_WAIT_MS = 120_000;
1095
1102
  const STUDIO_REPL_START_POLL_MS = 250;
1096
1103
  const STUDIO_REPL_JOURNAL_MAX_ENTRIES = 300;
1097
1104
  const STUDIO_REPL_RUNTIME_OPTION = "@pi_repl_runtime";
@@ -1108,21 +1115,27 @@ const STUDIO_REPL_RUNTIME_LABELS: Record<StudioReplRuntime, string> = {
1108
1115
  r: "R",
1109
1116
  ghci: "GHCi",
1110
1117
  clojure: "Clojure",
1118
+ ruby: "Ruby",
1119
+ java: "Java",
1120
+ octave: "Octave",
1121
+ matlab: "MATLAB",
1122
+ gnuplot: "gnuplot",
1123
+ cpp: "C++",
1111
1124
  };
1112
1125
  const STUDIO_REPL_SEND_TOOL_PARAMS = Type.Object({
1113
1126
  code: Type.String({ description: "Code to execute in the active or selected Studio REPL session." }),
1114
1127
  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." })),
1128
+ 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
1129
  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
1130
  echoMode: Type.Optional(Type.Union(
1118
1131
  [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." },
1132
+ { 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
1133
  )),
1121
1134
  });
1122
1135
  const STUDIO_REPL_TOOL_ECHO_MODE = normalizeReplSubmissionEchoMode(process.env.PI_STUDIO_REPL_ECHO_MODE) as ReplSubmissionEchoMode;
1123
1136
  const STUDIO_REPL_STATUS_TOOL_PARAMS = Type.Object({
1124
1137
  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." })),
1138
+ 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
1139
  });
1127
1140
  const STUDIO_EXPORT_INPUT_FORMAT_DESCRIPTION = "Optional input format: auto, markdown, or latex. Defaults to auto.";
1128
1141
  const STUDIO_EXPORT_PDF_OPTIONS_TOOL_PARAMS = Type.Object({
@@ -11211,7 +11224,13 @@ function isStudioReplRuntime(value: unknown): value is StudioReplRuntime {
11211
11224
  || value === "julia"
11212
11225
  || value === "r"
11213
11226
  || value === "ghci"
11214
- || value === "clojure";
11227
+ || value === "clojure"
11228
+ || value === "ruby"
11229
+ || value === "java"
11230
+ || value === "octave"
11231
+ || value === "matlab"
11232
+ || value === "gnuplot"
11233
+ || value === "cpp";
11215
11234
  }
11216
11235
 
11217
11236
  function normalizeStudioReplRuntime(value: unknown): StudioReplRuntime | null {
@@ -11227,6 +11246,14 @@ function getDefaultStudioReplRuntimeCommand(runtime: StudioReplRuntime): string
11227
11246
  if (runtime === "julia") return "julia";
11228
11247
  if (runtime === "r") return "R";
11229
11248
  if (runtime === "ghci") return "ghci";
11249
+ if (runtime === "ruby") return "irb";
11250
+ if (runtime === "java") return "jshell";
11251
+ // Stop closes the tmux session, and on SIGHUP or SIGTERM Octave would otherwise dump its
11252
+ // workspace to octave-workspace in the working directory. --persist keeps it interactive.
11253
+ if (runtime === "octave") return "octave-cli --quiet --interactive --persist --eval 'sighup_dumps_octave_core(false); sigterm_dumps_octave_core(false);'";
11254
+ if (runtime === "matlab") return "matlab -nodesktop -nosplash";
11255
+ if (runtime === "gnuplot") return "gnuplot";
11256
+ if (runtime === "cpp") return "cling";
11230
11257
  return "clojure";
11231
11258
  }
11232
11259
 
@@ -11261,7 +11288,7 @@ function inferStudioReplSessionRuntime(sessionName: string): { runtime: StudioRe
11261
11288
  const studioMatch = sessionName.match(/^pi-studio-repl-([a-z0-9-]+)$/i);
11262
11289
  if (studioMatch) {
11263
11290
  const raw = (studioMatch[1] || "").toLowerCase();
11264
- const runtime = (["clojure", "python", "ipython", "julia", "shell", "ghci", "r"] as StudioReplRuntime[])
11291
+ const runtime = (["clojure", "python", "ipython", "julia", "shell", "ghci", "ruby", "java", "octave", "matlab", "gnuplot", "cpp", "r"] as StudioReplRuntime[])
11265
11292
  .find((candidate) => raw === candidate || raw.startsWith(`${candidate}-`));
11266
11293
  return { runtime: runtime ?? "unknown", source: "studio" };
11267
11294
  }
@@ -11435,11 +11462,14 @@ function captureStudioReplSession(sessionName: string, pinned?: StudioReplSessio
11435
11462
  return { ok: true, transcript: String(result.stdout || "").replace(/[\t ]+$/gm, "").trimEnd(), session };
11436
11463
  }
11437
11464
 
11465
+ // tmux's answer when a session or its server has gone, not just a slow or failed call (Sol).
11466
+ const STUDIO_TMUX_GONE = /can't find session|no server running|error connecting to/i;
11467
+
11438
11468
  // The pane's cursor row, where a runtime shows its prompt; dead once its command has
11439
11469
  // exited, gone once the pane has closed or left the session.
11440
11470
  function readStudioReplCursorRow(sessionId: string, paneId: string): { gone?: boolean; dead?: boolean; pid?: string; line?: string } {
11441
11471
  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 };
11472
+ if (!panes.ok) return STUDIO_TMUX_GONE.test(panes.stderr) ? { gone: true } : {};
11443
11473
  const fields = panes.stdout.split("\n").map((line) => line.split("\t")).find(([id]) => id === paneId);
11444
11474
  if (!fields) return { gone: true };
11445
11475
  const [, dead = "", row = "", pid = ""] = fields;
@@ -11461,8 +11491,13 @@ async function startStudioReplSession(runtime: StudioReplRuntime, cwd: string, o
11461
11491
  return { ok: true, session, message: `${label} REPL is already running.` };
11462
11492
  };
11463
11493
  if (running()) return reuse();
11464
- const command = getStudioReplRuntimeCommand(runtime, commandOverride);
11465
- const created = runStudioTmux(buildStudioReplTmuxStartArgs(sessionName, cwd || process.cwd(), command), { timeout: 5_000 });
11494
+ // As in pi-repl, MATLAB is told to start in the working directory; it can otherwise
11495
+ // start in its own userpath.
11496
+ const command = getStudioReplRuntimeCommand(runtime, commandOverride) + (runtime === "matlab" && !commandOverride ? ` -sd ${shellQuote(cwd || process.cwd())}` : "");
11497
+ // As in pi-repl: gnuplot and the Qt helpers it starts inherit an owner marker, so Stop
11498
+ // can find helpers that have left the session's process tree.
11499
+ const gnuplotOwner = runtime === "gnuplot" ? randomUUID().replace(/-/g, "") : "";
11500
+ const created = runStudioTmux(buildStudioReplTmuxStartArgs(sessionName, cwd || process.cwd(), command, gnuplotOwner ? [`${GNUPLOT_OWNER_ENV}=${gnuplotOwner}`] : []), { timeout: 5_000 });
11466
11501
  if (!created.ok) {
11467
11502
  // Another tab may have started the same session first; share it.
11468
11503
  if (running()) return reuse();
@@ -11473,10 +11508,11 @@ async function startStudioReplSession(runtime: StudioReplRuntime, cwd: string, o
11473
11508
  const [sessionId = "", paneId = ""] = created.stdout.trim().split("\t");
11474
11509
  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
11510
  runStudioTmux(["set-option", "-q", "-t", sessionId, STUDIO_REPL_RUNTIME_OPTION, runtime], { timeout: 3_000 });
11511
+ if (gnuplotOwner) runStudioTmux(["set-option", "-q", "-t", sessionId, GNUPLOT_OWNER_OPTION, gnuplotOwner], { timeout: 3_000 });
11476
11512
  const started = `Started ${options?.newSession ? "new " : ""}${label} REPL${commandOverride ? ` with custom command: ${commandOverride}` : ""}`;
11477
11513
  const exited = `${label} exited while starting. Check the command: ${command}.`;
11478
11514
  // 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;
11515
+ const deadline = Date.now() + (runtime === "matlab" ? STUDIO_REPL_MATLAB_START_WAIT_MS : STUDIO_REPL_START_WAIT_MS);
11480
11516
  let ready = false;
11481
11517
  while (true) {
11482
11518
  const row = readStudioReplCursorRow(sessionId, paneId);
@@ -11532,7 +11568,7 @@ async function stopStudioReplSession(sessionName: string): Promise<{ ok: true; m
11532
11568
  return { ok: true, message: `Closed ${sessionName}.`, session };
11533
11569
  }
11534
11570
  try {
11535
- await stopVerifiedReplSession({ tmux: (args: string[]) => runStudioTmuxAsync(args), sessionName, sessionNamePattern: STUDIO_REPL_SESSION_NAME });
11571
+ await stopVerifiedReplSession({ tmux: (args: string[]) => runStudioTmuxAsync(args), sessionName, sessionNamePattern: STUDIO_REPL_SESSION_NAME, isGnuplotSession: isStudioGnuplotSession });
11536
11572
  return { ok: true, message: `Stopped ${sessionName}.`, session };
11537
11573
  } catch (error) {
11538
11574
  // After tmux has closed the session, the shared stop wraps its reason as the cause.
@@ -11548,6 +11584,9 @@ type StudioReplControlFiles = {
11548
11584
  doneFile: string;
11549
11585
  // GHCi's guard and driver scripts, removed along with the source.
11550
11586
  helpers?: Array<{ dir: string; sourceFile: string; doneFile: string }>;
11587
+ // C++ completes when its driver writes a valid reply to the done file, and its
11588
+ // cleanup removes only the control files it created.
11589
+ cpp?: { completion: ReturnType<typeof prepareCppSubmission>["completion"]; cleanup: () => void };
11551
11590
  };
11552
11591
 
11553
11592
  type StudioReplPreparedSubmission = {
@@ -11597,6 +11636,11 @@ function getStudioReplControlExtension(runtime: StudioReplRuntime): string {
11597
11636
  if (runtime === "r") return "R";
11598
11637
  if (runtime === "ghci") return "ghci";
11599
11638
  if (runtime === "clojure") return "clj";
11639
+ if (runtime === "ruby") return "rb";
11640
+ if (runtime === "java") return "java";
11641
+ if (runtime === "octave" || runtime === "matlab") return "m";
11642
+ if (runtime === "gnuplot") return "gp";
11643
+ if (runtime === "cpp") return "cpp";
11600
11644
  if (runtime === "shell") return "sh";
11601
11645
  return "py";
11602
11646
  }
@@ -11627,9 +11671,41 @@ function buildStudioClojureDisplayStatements(display: ReplSubmissionDisplay, ind
11627
11671
  return display.prefixLines.map((line) => `${indent}(clojure.core/println ${JSON.stringify(line)})`);
11628
11672
  }
11629
11673
 
11674
+ // As in pi-repl 0.8.6: prints the pane's cursor column, or exits non-zero; tmux gets
11675
+ // 500 ms. A wrapper runs it with Node and ends a line before its footer unless it prints
11676
+ // 0. Only the wrapper reads its output, so it never reaches the pane: a query that
11677
+ // outlives its wait can't print after the done file (Sol, Astra, candidate80).
11678
+ // process.exit ends Node even if a startup hook in NODE_OPTIONS would keep it running,
11679
+ // and each wrapper also limits the whole helper to 5 s.
11680
+ // With the display Off, the footers still end a line that output left open, and add
11681
+ // nothing else. Otherwise the runtime's prompt follows the output on the same row,
11682
+ // which the record mistook for a prompt row, and line editors such as gnuplot's then
11683
+ // redraw the next pasted line wrongly (Astra, candidate90).
11684
+ const STUDIO_CURSOR_COLUMN_QUERY = 'let code = 1; try { require("node:fs").writeSync(1, require("node:child_process").execFileSync("tmux", ["-N", "display-message", "-p", "-t", process.env.TMUX_PANE, "#{cursor_x}"], { encoding: "utf8", timeout: 500, killSignal: "SIGKILL", maxBuffer: 128, stdio: ["ignore", "pipe", "ignore"] }).trim()); code = 0; } catch {} process.exit(code);';
11685
+
11686
+ function buildStudioPythonFooter(display: ReplSubmissionDisplay): string[] {
11687
+ return [
11688
+ " import subprocess as __pi_studio_subprocess",
11689
+ " import sys as __pi_studio_sys",
11690
+ " __pi_studio_column = ''",
11691
+ " try:",
11692
+ " __pi_studio_sys.stdout.flush()",
11693
+ " __pi_studio_sys.stderr.flush()",
11694
+ ` __pi_studio_query = __pi_studio_subprocess.run([${JSON.stringify(process.execPath)}, '-e', ${JSON.stringify(STUDIO_CURSOR_COLUMN_QUERY)}], stdin=__pi_studio_subprocess.DEVNULL, stdout=__pi_studio_subprocess.PIPE, stderr=__pi_studio_subprocess.DEVNULL, timeout=5)`,
11695
+ " if __pi_studio_query.returncode == 0:",
11696
+ " __pi_studio_column = __pi_studio_query.stdout.decode('utf-8', 'replace').strip()",
11697
+ // run() kills the query on any exception. Ctrl-C here must not skip the done file.
11698
+ " except BaseException:",
11699
+ " pass",
11700
+ " if __pi_studio_column != '0':",
11701
+ " __pi_studio_builtins.print()",
11702
+ ...display.suffixLines.map((line) => ` __pi_studio_builtins.print(${JSON.stringify(line)})`),
11703
+ ];
11704
+ }
11705
+
11630
11706
  function buildStudioPythonControlSource(runtime: "python" | "ipython", code: string, doneFile: string, display: ReplSubmissionDisplay): string {
11631
11707
  const prefix = buildStudioPythonDisplayStatements(display);
11632
- const completion = display.enabled ? [` __pi_studio_builtins.print(${JSON.stringify(display.endMarker)})`] : [];
11708
+ const completion = buildStudioPythonFooter(display);
11633
11709
  if (runtime === "ipython") {
11634
11710
  return [
11635
11711
  "from pathlib import Path as __pi_studio_path",
@@ -11673,8 +11749,44 @@ function buildStudioPythonControlSource(runtime: "python" | "ipython", code: str
11673
11749
  ].join("\n");
11674
11750
  }
11675
11751
 
11752
+ function buildStudioJuliaFooter(display: ReplSubmissionDisplay): string[] {
11753
+ const query = `Cmd([${juliaStringLiteral(process.execPath)}, "-e", ${juliaStringLiteral(STUDIO_CURSOR_COLUMN_QUERY)}])`;
11754
+ return [
11755
+ ' local __pi_studio_column = ""',
11756
+ " local __pi_studio_query = nothing",
11757
+ // The wait, not the read, is bounded: a child the helper started could
11758
+ // keep the pipe open after the helper exits. An interrupt does not end
11759
+ // the wait, since killing Node early would leave its tmux child
11760
+ // running. After 5 s a helper still running is killed, and the pipe
11761
+ // is closed so that the reader ends too.
11762
+ " try",
11763
+ " flush(stdout)",
11764
+ " flush(stderr)",
11765
+ ` __pi_studio_query = open(pipeline(${query}, stdin=devnull, stderr=devnull), "r")`,
11766
+ " local __pi_studio_reader = @async read(__pi_studio_query, String)",
11767
+ " local __pi_studio_deadline = time_ns() + 5_000_000_000",
11768
+ " local __pi_studio_finished = false",
11769
+ " while !__pi_studio_finished && time_ns() < __pi_studio_deadline",
11770
+ " try",
11771
+ " __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",
11772
+ " catch",
11773
+ " end",
11774
+ " end",
11775
+ " __pi_studio_finished && success(__pi_studio_query) && (__pi_studio_column = strip(fetch(__pi_studio_reader)))",
11776
+ " catch",
11777
+ " finally",
11778
+ " if !isnothing(__pi_studio_query)",
11779
+ " process_exited(__pi_studio_query) || kill(__pi_studio_query, Base.SIGKILL)",
11780
+ " try close(__pi_studio_query.out) catch end",
11781
+ " end",
11782
+ " end",
11783
+ ' __pi_studio_column == "0" || Base.println()',
11784
+ ...display.suffixLines.map((line) => ` Base.println(${juliaStringLiteral(line)})`),
11785
+ ];
11786
+ }
11787
+
11676
11788
  function buildStudioJuliaControlSource(code: string, doneFile: string, display: ReplSubmissionDisplay): string {
11677
- const completion = display.enabled ? [` Base.println(${juliaStringLiteral(display.endMarker)})`] : [];
11789
+ const completion = buildStudioJuliaFooter(display);
11678
11790
  return [
11679
11791
  ...buildStudioJuliaDisplayStatements(display),
11680
11792
  "try",
@@ -11691,8 +11803,20 @@ function buildStudioJuliaControlSource(code: string, doneFile: string, display:
11691
11803
  ].join("\n");
11692
11804
  }
11693
11805
 
11806
+ function buildStudioRFooter(display: ReplSubmissionDisplay): string[] {
11807
+ return [
11808
+ " try({ flush(stdout()); flush(stderr()) }, silent = TRUE)",
11809
+ // system2 quotes the command but not its arguments, and kills it after
11810
+ // 5 s. A failed query sets a status; an error or Ctrl-C here gives
11811
+ // NULL, not a lost done file.
11812
+ ` .__pi_studio_column <- tryCatch(suppressWarnings(system2(${JSON.stringify(process.execPath)}, c("-e", ${JSON.stringify(shellQuote(STUDIO_CURSOR_COLUMN_QUERY))}), stdout = TRUE, stderr = FALSE, timeout = 5)), error = function(e) NULL, interrupt = function(e) NULL)`,
11813
+ ' if (!is.null(attr(.__pi_studio_column, "status")) || !identical(trimws(paste(.__pi_studio_column, collapse = "")), "0")) base::cat("\\n")',
11814
+ ...display.suffixLines.map((line) => ` base::cat(${JSON.stringify(`${line}\n`)})`),
11815
+ ];
11816
+ }
11817
+
11694
11818
  function buildStudioRControlSource(code: string, doneFile: string, display: ReplSubmissionDisplay): string {
11695
- const completion = display.enabled ? [` base::cat(${JSON.stringify(`${display.endMarker}\n`)})`] : [];
11819
+ const completion = buildStudioRFooter(display);
11696
11820
  return [
11697
11821
  "local({",
11698
11822
  ...buildStudioRDisplayStatements(display, " "),
@@ -11735,13 +11859,58 @@ function buildStudioGhciControlSource(code: string, doneFile: string, display: R
11735
11859
  ].filter(Boolean).join("\n") + "\n";
11736
11860
  }
11737
11861
 
11862
+ // The cursor column for a footer run by a shell: Studio's supervisor below runs the query,
11863
+ // bounded, and Ctrl+C stops only the query. Empty if the query fails. ${NODE_OPTIONS-}
11864
+ // because the Shell runtime's footer runs in the user's shell, which may have set -u (Astra).
11865
+ function buildStudioShellCursorColumn(): string {
11866
+ return `__pi_studio_column=$(NODE_OPTIONS= ${shellQuote(process.execPath)} -e ${shellQuote(STUDIO_CURSOR_COLUMN_SUPERVISOR)} -- "\${NODE_OPTIONS-}" </dev/null 2>/dev/null) || __pi_studio_column=`;
11867
+ }
11868
+
11738
11869
  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)}`;
11870
+ // As in pi-repl: end the line only when output left the cursor mid-line, then print the
11871
+ // footer. trap : INT keeps Ctrl+C from ending this shell before the done file (Astra,
11872
+ // candidate90); a trap isn't inherited, so the query still stops at once.
11873
+ const suffix = display.suffixLines.map((line) => `command printf '%s\\n' ${shellQuote(line)}; `).join("");
11874
+ return `:! trap : INT; ${buildStudioShellCursorColumn()}; [ "$__pi_studio_column" = 0 ] || command printf '\\n'; ${suffix}touch ${shellQuote(doneFile)}`;
11875
+ }
11876
+
11877
+ function buildStudioClojureFooter(display: ReplSubmissionDisplay): string[] {
11878
+ const builder = `(java.lang.ProcessBuilder. ^java.util.List [${JSON.stringify(process.execPath)} "-e" ${JSON.stringify(STUDIO_CURSOR_COLUMN_QUERY)}])`;
11879
+ return [
11880
+ " (try (.flush *out*) (.flush *err*) (catch Throwable _))",
11881
+ // An interrupt left pending by the code would end the wait at once, so
11882
+ // it is cleared for the query and restored afterwards. One that arrives
11883
+ // during the wait is noted and the wait goes on: killing Node early
11884
+ // would leave its tmux child running. The query is killed after 5 s.
11885
+ " (let [pi-studio-interrupted (volatile! (Thread/interrupted))",
11886
+ ` pi-studio-query (try (.start (.redirectError ${builder} java.lang.ProcessBuilder$Redirect/DISCARD)) (catch Throwable _ nil))`,
11887
+ " pi-studio-deadline (+ (System/nanoTime) 5000000000)",
11888
+ " pi-studio-column (when pi-studio-query",
11889
+ " (try",
11890
+ " (.close (.getOutputStream pi-studio-query))",
11891
+ " (when (and (loop []",
11892
+ " (let [left (- pi-studio-deadline (System/nanoTime))",
11893
+ " exited (when (pos? left)",
11894
+ " (try (.waitFor pi-studio-query left java.util.concurrent.TimeUnit/NANOSECONDS)",
11895
+ " (catch InterruptedException _ (vreset! pi-studio-interrupted true) :interrupted)))]",
11896
+ " (if (= exited :interrupted) (recur) exited)))",
11897
+ " (zero? (.exitValue pi-studio-query)))",
11898
+ // Only what is waiting: a child of Node could hold the pipe open.
11899
+ " (let [in (.getInputStream pi-studio-query)",
11900
+ " bytes (byte-array (min 32 (.available in)))",
11901
+ " n (.read in bytes)]",
11902
+ ' (.trim (String. bytes 0 (int (max 0 n)) "UTF-8"))))',
11903
+ " (catch Throwable _ nil)",
11904
+ " (finally (.destroyForcibly pi-studio-query))))]",
11905
+ " (when @pi-studio-interrupted (.interrupt (Thread/currentThread)))",
11906
+ ' (when-not (= pi-studio-column "0") (clojure.core/println))',
11907
+ ...display.suffixLines.map((line) => ` (clojure.core/println ${JSON.stringify(line)})`),
11908
+ " nil)",
11909
+ ];
11741
11910
  }
11742
11911
 
11743
11912
  function buildStudioClojureControlSource(code: string, doneFile: string, display: ReplSubmissionDisplay): string {
11744
- const completion = display.enabled ? [` (clojure.core/println ${JSON.stringify(display.endMarker)})`] : [];
11913
+ const completion = buildStudioClojureFooter(display);
11745
11914
  return [
11746
11915
  "(let [code " + JSON.stringify(code) + "]",
11747
11916
  ...buildStudioClojureDisplayStatements(display, " "),
@@ -11760,13 +11929,203 @@ function buildStudioClojureControlSource(code: string, doneFile: string, display
11760
11929
  ].join("\n");
11761
11930
  }
11762
11931
 
11932
+ // Ruby (irb) and Java (JShell), as in pi-repl 0.8.5: each wrapper queries tmux for the
11933
+ // cursor column itself; Java's completion runs from an outer /open driver, as GHCi's does.
11934
+ function rubyStringLiteral(value: string): string {
11935
+ // JSON escaping leaves Ruby's #{...}, #@... and #$... interpolation active.
11936
+ // ASCII escapes also keep Unicode paths intact through older IRB input editors.
11937
+ return JSON.stringify(value).replace(/#/g, "\\#")
11938
+ .replace(/[^\x00-\x7f]/gu, (character) => `\\u{${character.codePointAt(0)!.toString(16)}}`);
11939
+ }
11940
+
11941
+ function buildStudioRubyControlSource(code: string, doneFile: string, display: ReplSubmissionDisplay): string {
11942
+ const prefix = display.enabled ? display.prefixLines.map((line) => ` puts ${rubyStringLiteral(line)}`) : [];
11943
+ // Query the actual terminal column rather than intercepting user stdout.
11944
+ // Keep the old newline guard if the bounded, read-only query is unavailable.
11945
+ const completion = [
11946
+ ' __pi_studio_column = ""',
11947
+ " begin",
11948
+ " $stdout.flush",
11949
+ " $stderr.flush",
11950
+ // Ruby's $? is thread-local: do not replace the user's last child status.
11951
+ " __pi_studio_column = Thread.new do",
11952
+ " begin",
11953
+ ` IO.popen(["tmux", "-N", "display-message", "-p", "-t", ENV.fetch("TMUX_PANE"), ${rubyStringLiteral("#{cursor_x}")}], err: File::NULL) do |__pi_studio_query|`,
11954
+ " begin",
11955
+ " if IO.select([__pi_studio_query], nil, nil, 0.5)",
11956
+ " __pi_studio_bytes = __pi_studio_query.read_nonblock(32, exception: false)",
11957
+ ' __pi_studio_bytes.is_a?(String) ? __pi_studio_bytes.strip : ""',
11958
+ " else",
11959
+ ' ""',
11960
+ " end",
11961
+ " ensure",
11962
+ // Reap only our own query process, including on timeout; never leave an
11963
+ // IO.popen close waiting indefinitely for a stuck tmux client to exit.
11964
+ " Process.kill('KILL', __pi_studio_query.pid) rescue nil",
11965
+ " end",
11966
+ " end",
11967
+ " rescue StandardError",
11968
+ ' ""',
11969
+ " end",
11970
+ " end.value",
11971
+ " rescue StandardError",
11972
+ ' __pi_studio_column = ""',
11973
+ " end",
11974
+ ' puts unless __pi_studio_column == "0"',
11975
+ ...display.suffixLines.map((line) => ` puts ${rubyStringLiteral(line)}`),
11976
+ ];
11977
+ return [
11978
+ "begin",
11979
+ ...prefix,
11980
+ ` __pi_studio_code = ${rubyStringLiteral(code)}`,
11981
+ " __pi_studio_context = defined?(IRB) && IRB.respond_to?(:CurrentContext) && IRB.CurrentContext",
11982
+ " __pi_studio_binding = __pi_studio_context ? __pi_studio_context.workspace.binding : TOPLEVEL_BINDING",
11983
+ " __pi_studio_result = eval(__pi_studio_code, __pi_studio_binding, '<pi-studio-repl>', 1)",
11984
+ " p __pi_studio_result unless __pi_studio_result.nil?",
11985
+ "rescue Exception => __pi_studio_e",
11986
+ " $stderr.puts __pi_studio_e.full_message(highlight: false)",
11987
+ "ensure",
11988
+ // The done file is written even if Ctrl+C lands during the footer: IRB's
11989
+ // IRB::Abort and Ruby's Interrupt aren't StandardErrors, so the query's
11990
+ // rescue lets them through, and Studio would wait for this send forever (Sol).
11991
+ " begin",
11992
+ ...completion.map((line) => ` ${line}`),
11993
+ " ensure",
11994
+ ` File.write(${rubyStringLiteral(doneFile)}, "done\\n")`,
11995
+ " end",
11996
+ // IRB checks echo? immediately after evaluating the loader. Suppress
11997
+ // just that result, restoring the original method before returning.
11998
+ " begin",
11999
+ " if __pi_studio_context && __pi_studio_context.respond_to?(:echo?)",
12000
+ " __pi_studio_echo_owner = __pi_studio_context.singleton_class",
12001
+ " __pi_studio_echo_owned = __pi_studio_echo_owner.instance_methods(false).include?(:echo?)",
12002
+ " __pi_studio_echo_original = __pi_studio_context.method(:echo?)",
12003
+ " __pi_studio_context.define_singleton_method(:echo?) do",
12004
+ " if __pi_studio_echo_owned",
12005
+ " __pi_studio_echo_owner.send(:define_method, :echo?, __pi_studio_echo_original)",
12006
+ " else",
12007
+ " __pi_studio_echo_owner.send(:remove_method, :echo?)",
12008
+ " end",
12009
+ " false",
12010
+ " end",
12011
+ " end",
12012
+ " rescue StandardError",
12013
+ // If a customised/frozen context refuses the hook, keep normal IRB
12014
+ // behaviour rather than fail the already completed submission.
12015
+ " end",
12016
+ "end",
12017
+ ].join("\n");
12018
+ }
12019
+
12020
+ function buildStudioJavaControlSource(code: string, doneFile: string, display: ReplSubmissionDisplay): string {
12021
+ if (/[\r\n]/.test(doneFile)) throw new Error("JShell control paths cannot contain line breaks.");
12022
+ const prefix = display.enabled ? display.prefixLines.map((line) => `java.lang.System.out.println(${JSON.stringify(line)});`) : [];
12023
+ // /open evaluates top-level snippets in the existing JShell. Completion
12024
+ // stays in the outer driver, outside this source file's parser state.
12025
+ return [...prefix, code.replace(/\r/g, "").trimEnd(), ""].join("\n");
12026
+ }
12027
+
12028
+ function buildStudioJavaDriverSource(sourceFile: string, doneFile: string, display: ReplSubmissionDisplay): string {
12029
+ // Only add a newline when the terminal is mid-line. The scoped query does
12030
+ // not replace System.out/err, change user declarations, or emit another /open.
12031
+ const completion = [
12032
+ ' String __pi_studio_column = "";',
12033
+ " java.lang.Process __pi_studio_query = null;",
12034
+ " try {",
12035
+ " java.lang.System.out.flush();",
12036
+ " java.lang.System.err.flush();",
12037
+ ` __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();`,
12038
+ " if (__pi_studio_query.waitFor(500, java.util.concurrent.TimeUnit.MILLISECONDS) && __pi_studio_query.exitValue() == 0) {",
12039
+ // Do not wait for EOF if an unexpected descendant inherits the pipe.
12040
+ " byte[] __pi_studio_bytes = new byte[32];",
12041
+ " int __pi_studio_count = __pi_studio_query.getInputStream().read(__pi_studio_bytes, 0, Math.min(32, __pi_studio_query.getInputStream().available()));",
12042
+ " __pi_studio_column = new String(__pi_studio_bytes, 0, Math.max(0, __pi_studio_count), java.nio.charset.StandardCharsets.UTF_8).trim();",
12043
+ " }",
12044
+ " } catch (Exception __pi_studio_ignored) {",
12045
+ ' __pi_studio_column = "";',
12046
+ " } finally {",
12047
+ " if (__pi_studio_query != null) {",
12048
+ " try { __pi_studio_query.destroyForcibly(); } catch (Exception __pi_studio_ignored) {}",
12049
+ " }",
12050
+ " }",
12051
+ ' if (!"0".equals(__pi_studio_column)) java.lang.System.out.println();',
12052
+ ...display.suffixLines.map((line) => ` java.lang.System.out.println(${JSON.stringify(line)});`),
12053
+ ];
12054
+ return [
12055
+ buildStudioReplSubmissionLine("java", sourceFile, doneFile),
12056
+ "{",
12057
+ // As for Ruby. JShell stops a snippet with an asynchronous StopExecutionException,
12058
+ // which isn't an Exception. During waitFor it surfaces as one the footer catches, but
12059
+ // elsewhere in the footer only finally is sure to run.
12060
+ "try {",
12061
+ ...completion,
12062
+ "} finally {",
12063
+ ` java.nio.file.Files.write(java.nio.file.Paths.get(${JSON.stringify(doneFile)}), new byte[]{100, 111, 110, 101, 10});`,
12064
+ "}",
12065
+ "}",
12066
+ ].join("\n");
12067
+ }
12068
+
12069
+ // Octave and MATLAB: pi-repl's shared buildMLanguageDriverSource, with two changes Sol and
12070
+ // Astra held candidate88 on, until pi-repl takes them:
12071
+ // - The column query is STUDIO_CURSOR_COLUMN_QUERY, which exits once it has written, run by
12072
+ // STUDIO_CURSOR_COLUMN_SUPERVISOR, which kills it after 5 s: system() itself has no time
12073
+ // limit. It writes to a private file, not to system()'s pipe, so nothing it leaves running
12074
+ // can hold that pipe open, and the file goes even if the script is interrupted (as in
12075
+ // pi-repl 0.10.1). The script exits 0 or 1: given a status such as 137, MATLAB printed the
12076
+ // command and "Killed" (Astra).
12077
+ // - In Octave, Ctrl+C during a cleanup action ended it before the done file was written.
12078
+ // unwind_protect_cleanup writes it even then. MATLAB finishes a cleanup action despite
12079
+ // Ctrl+C, and has no unwind_protect.
12080
+ // Runs STUDIO_CURSOR_COLUMN_QUERY in a child Node, with the caller's NODE_OPTIONS (its
12081
+ // argument), and kills it after 5 s. The supervisor runs without NODE_OPTIONS, so no startup
12082
+ // hook can stall it, keep it running or catch its timer; SIGKILL can't be caught either. It
12083
+ // signals only its own child, which Node tracks, so never a process ID since reused (Sol). A
12084
+ // preload that catches SIGALRM made perl's alarm wait for its stall (Astra). It ignores Ctrl+C
12085
+ // and hangups, so the deadline holds then too; the query gets the default handling.
12086
+ const STUDIO_CURSOR_COLUMN_SUPERVISOR = `for (const signal of ["SIGINT", "SIGHUP", "SIGTERM"]) process.on(signal, () => {}); const child = require("node:child_process").spawn(process.execPath, ["-e", ${JSON.stringify(STUDIO_CURSOR_COLUMN_QUERY)}], { stdio: ["ignore", "inherit", "ignore"], env: { ...process.env, NODE_OPTIONS: process.argv[1] ?? "" } }); const timer = setTimeout(() => child.kill("SIGKILL"), 5000); child.on("error", () => process.exit(1)); child.on("exit", (code) => { clearTimeout(timer); process.exit(code === 0 ? 0 : 1); });`;
12087
+
12088
+ function buildStudioMLanguageDriverSource(runtime: "octave" | "matlab", sourceFile: string, doneFile: string, display: ReplSubmissionDisplay): string {
12089
+ const query = [
12090
+ // The shell's own messages would reach the pane through system().
12091
+ "exec 2>/dev/null",
12092
+ "f=$(mktemp) || exit 1",
12093
+ `trap 'rm -f "$f"' EXIT`,
12094
+ "trap 'exit 1' HUP INT TERM",
12095
+ // After --, Node takes "$NODE_OPTIONS" as the script's argument, not as its own option.
12096
+ `NODE_OPTIONS= ${shellQuote(process.execPath)} -e ${shellQuote(STUDIO_CURSOR_COLUMN_SUPERVISOR)} -- "$NODE_OPTIONS" >"$f" </dev/null; s=$?`,
12097
+ 'cat "$f"',
12098
+ '[ "$s" = 0 ]',
12099
+ ].join("; ");
12100
+ const footer = [
12101
+ ...(runtime === "octave" ? ["fflush(1);"] : []),
12102
+ "try",
12103
+ // /bin/sh whatever the user's shell is: MATLAB runs system() with $SHELL.
12104
+ ` [pi_repl_status,pi_repl_column]=system(${mStringLiteral(`/bin/sh -c ${shellQuote(query)}`)});`,
12105
+ "catch",
12106
+ " pi_repl_status=-1; pi_repl_column='';",
12107
+ "end",
12108
+ "if pi_repl_status~=0 || ~strcmp(strtrim(pi_repl_column),'0'); fprintf(1,'\\n'); end",
12109
+ ...display.suffixLines.map((line) => `fprintf(1,'%s\\n',${mStringLiteral(line)});`),
12110
+ ];
12111
+ const done = `fclose(fopen(${mStringLiteral(doneFile)},'w'));`;
12112
+ const finish = (runtime === "octave"
12113
+ ? ["unwind_protect", ...footer, "unwind_protect_cleanup", done, "end_unwind_protect"]
12114
+ : [...footer, done]).join("\n");
12115
+ // As in pi-repl: parameters give eval its own slots, so no helper variables, ans, cwd or
12116
+ // path changes reach the base workspace, and even clear all can't remove the guard.
12117
+ const cleanup = `onCleanup(@() feval(@(pi_repl_status,pi_repl_column) eval(${mStringLiteral(finish)}),-1,''))`;
12118
+ return `feval(@(pi_repl_error,pi_repl_guard) eval(fileread(${mStringLiteral(sourceFile)})),[],${cleanup});\n`;
12119
+ }
12120
+
11763
12121
  function buildStudioShellControlSource(code: string, display: ReplSubmissionDisplay): string {
11764
- if (!display.enabled) return `${code.replace(/\r/g, "").trimEnd()}\n`;
11765
12122
  return [
11766
12123
  ...display.prefixLines.map((line) => `command printf '%s\\n' ${shellQuote(line)}`),
11767
12124
  code.replace(/\r/g, "").trimEnd(),
11768
12125
  "__pi_studio_repl_status=$?",
11769
- `command printf '%s\\n' ${shellQuote(display.endMarker)}`,
12126
+ // The footer runs in a subshell that traps Ctrl+C, so an interrupt there doesn't end the
12127
+ // loader's command line before its done file, in bash or zsh (Astra, candidate90).
12128
+ `( trap : INT; ${buildStudioShellCursorColumn()}; [ "$__pi_studio_column" = 0 ] || command printf '\\n'${display.suffixLines.map((line) => `; command printf '%s\\n' ${shellQuote(line)}`).join("")} )`,
11770
12129
  "return \"$__pi_studio_repl_status\"",
11771
12130
  ].filter(Boolean).join("\n") + "\n";
11772
12131
  }
@@ -11777,6 +12136,13 @@ function buildStudioReplControlSource(runtime: StudioReplRuntime, code: string,
11777
12136
  if (runtime === "r") return buildStudioRControlSource(code, doneFile, display);
11778
12137
  if (runtime === "ghci") return buildStudioGhciControlSource(code, doneFile, display);
11779
12138
  if (runtime === "clojure") return buildStudioClojureControlSource(code, doneFile, display);
12139
+ if (runtime === "ruby") return buildStudioRubyControlSource(code, doneFile, display);
12140
+ if (runtime === "java") return buildStudioJavaControlSource(code, doneFile, display);
12141
+ if (runtime === "octave" || runtime === "matlab") return buildMLanguageControlSource(code, display);
12142
+ // As in pi-repl: gnuplot loads the code as written; its driver prints the display.
12143
+ if (runtime === "gnuplot") return code + "\n";
12144
+ // As in pi-repl: the driver reads the C++ as written and prints the display itself.
12145
+ if (runtime === "cpp") return code;
11780
12146
  if (runtime === "shell") return buildStudioShellControlSource(code, display);
11781
12147
  return null;
11782
12148
  }
@@ -11787,6 +12153,11 @@ function buildStudioReplSubmissionLine(runtime: StudioReplRuntime, sourceFile: s
11787
12153
  if (runtime === "r") return `source(${quotedPath}, local=.GlobalEnv)`;
11788
12154
  if (runtime === "ghci") return `:script ${quotedPath}`;
11789
12155
  if (runtime === "clojure") return `(do (load-file ${quotedPath}) :pi-studio/silent)`;
12156
+ if (runtime === "ruby") return `load ${rubyStringLiteral(sourceFile)}; nil`;
12157
+ if (runtime === "java") return `/open ${sourceFile}`;
12158
+ if (runtime === "octave" || runtime === "matlab") return `eval(fileread(${mStringLiteral(sourceFile)}));`;
12159
+ if (runtime === "gnuplot") return buildGnuplotSubmissionLine(sourceFile);
12160
+ if (runtime === "cpp") return cppInclude(sourceFile);
11790
12161
  if (runtime === "shell") return `. ${shellQuote(sourceFile)}; touch ${shellQuote(doneFile)}`;
11791
12162
  return `exec(open(${quotedPath}, encoding="utf-8").read(), globals())`;
11792
12163
  }
@@ -11797,6 +12168,7 @@ function unsupportedStudioReplRuntimeMessage(sessionName: string): string {
11797
12168
 
11798
12169
  function cleanupStudioReplControlFiles(controlFiles: StudioReplControlFiles | undefined): void {
11799
12170
  if (!controlFiles) return;
12171
+ if (controlFiles.cpp) return controlFiles.cpp.cleanup();
11800
12172
  cleanupPrivateReplControlFiles(controlFiles);
11801
12173
  for (const helper of controlFiles.helpers ?? []) cleanupPrivateReplControlFiles(helper);
11802
12174
  }
@@ -11807,13 +12179,17 @@ function prepareStudioReplSubmission(
11807
12179
  runtime: StudioReplRuntime,
11808
12180
  ): StudioReplPreparedSubmission {
11809
12181
  const normalizedSource = String(source || "").replace(/\r\n/g, "\n").replace(/\r/g, "\n");
12182
+ if (runtime === "cpp" && normalizedSource.includes("\0")) throw new Error("C++ source cannot contain NUL bytes; no code was sent.");
11810
12183
  const display = createReplSubmissionDisplay({
11811
12184
  entryId: details.submissionId,
11812
12185
  origin: "pi-studio",
11813
12186
  code: normalizedSource,
11814
12187
  mode: details.echoMode,
11815
12188
  });
12189
+ // As in pi-repl, control filenames start with the display's id.
12190
+ const controlOptions = { anchorId: display.anchorId };
11816
12191
  const controlFiles: StudioReplControlFiles = createPrivateReplControlFiles({
12192
+ ...controlOptions,
11817
12193
  extension: getStudioReplControlExtension(runtime),
11818
12194
  buildSource: ({ doneFile }: StudioReplControlFiles) => {
11819
12195
  const source = buildStudioReplControlSource(runtime, normalizedSource, doneFile, display);
@@ -11828,11 +12204,13 @@ function prepareStudioReplSubmission(
11828
12204
  // guard's script, and the driver still completes.
11829
12205
  try {
11830
12206
  const guard = createPrivateReplControlFiles({
12207
+ ...controlOptions,
11831
12208
  extension: "ghci",
11832
12209
  buildSource: () => buildStudioReplSubmissionLine("ghci", controlFiles.sourceFile, controlFiles.doneFile) + "\n",
11833
12210
  });
11834
12211
  controlFiles.helpers = [guard];
11835
12212
  const driver = createPrivateReplControlFiles({
12213
+ ...controlOptions,
11836
12214
  extension: "ghci",
11837
12215
  buildSource: () => [
11838
12216
  buildStudioReplSubmissionLine("ghci", guard.sourceFile, controlFiles.doneFile),
@@ -11847,6 +12225,88 @@ function prepareStudioReplSubmission(
11847
12225
  throw error;
11848
12226
  }
11849
12227
  }
12228
+ if (runtime === "java") {
12229
+ // As in pi-repl: JShell echoes only the outer /open. Its nested load of the
12230
+ // source returns before completion, even if the source is rejected or unfinished.
12231
+ try {
12232
+ const driver = createPrivateReplControlFiles({
12233
+ ...controlOptions,
12234
+ extension: "java",
12235
+ buildSource: () => buildStudioJavaDriverSource(controlFiles.sourceFile, controlFiles.doneFile, display),
12236
+ });
12237
+ controlFiles.helpers = [driver];
12238
+ loader = driver.sourceFile;
12239
+ } catch (error) {
12240
+ cleanupStudioReplControlFiles(controlFiles);
12241
+ throw error;
12242
+ }
12243
+ }
12244
+ if (runtime === "octave" || runtime === "matlab") {
12245
+ // pi-repl's M driver, as Studio's port below: the code runs in the base workspace,
12246
+ // and a function-local onCleanup writes the footer and done file, even after an
12247
+ // error, return, interrupt or clear all.
12248
+ try {
12249
+ const driver = createPrivateReplControlFiles({
12250
+ ...controlOptions,
12251
+ extension: "m",
12252
+ buildSource: () => buildStudioMLanguageDriverSource(runtime, controlFiles.sourceFile, controlFiles.doneFile, display),
12253
+ });
12254
+ controlFiles.helpers = [driver];
12255
+ loader = driver.sourceFile;
12256
+ } catch (error) {
12257
+ cleanupStudioReplControlFiles(controlFiles);
12258
+ throw error;
12259
+ }
12260
+ }
12261
+ if (runtime === "gnuplot") {
12262
+ // pi-repl's shared gnuplot driver: a Node script gnuplot loads through a pipe. It
12263
+ // feeds gnuplot the code and then a guard that acknowledges it returned; on an error
12264
+ // or Ctrl+C gnuplot closes the pipe instead. Either way the driver prints the footer
12265
+ // and writes the done file, without typing into the terminal or changing settings.
12266
+ try {
12267
+ const guard = createPrivateReplControlFiles({
12268
+ ...controlOptions,
12269
+ extension: "gp",
12270
+ buildSource: ({ doneFile }: StudioReplControlFiles) => buildGnuplotGuardSource(doneFile),
12271
+ });
12272
+ controlFiles.helpers = [guard];
12273
+ const driver = createPrivateReplControlFiles({
12274
+ ...controlOptions,
12275
+ extension: "cjs",
12276
+ buildSource: () => buildGnuplotDriverSource(controlFiles.sourceFile, guard.sourceFile, guard.doneFile, controlFiles.doneFile, display),
12277
+ });
12278
+ controlFiles.helpers.push(driver);
12279
+ loader = driver.sourceFile;
12280
+ } catch (error) {
12281
+ cleanupStudioReplControlFiles(controlFiles);
12282
+ throw error;
12283
+ }
12284
+ }
12285
+ if (runtime === "cpp") {
12286
+ // pi-repl's Cling driver: a header Cling includes, whose initializer reads a request
12287
+ // naming the source and the display, both checked by identity. It evaluates the code
12288
+ // one prompt group at a time, prints the footer, then writes a reply with the result.
12289
+ try {
12290
+ const request = createPrivateReplControlFiles({
12291
+ ...controlOptions,
12292
+ extension: "req",
12293
+ buildSource: () => buildCppRequest(controlFiles.sourceFile, controlFiles.doneFile, display),
12294
+ });
12295
+ controlFiles.helpers = [request];
12296
+ const cpp = prepareCppSubmission(request.sourceFile, controlFiles.doneFile);
12297
+ const driver = createPrivateReplControlFiles({
12298
+ ...controlOptions,
12299
+ extension: "hxx",
12300
+ buildSource: () => buildCppDriverSource(request.sourceFile, controlFiles.doneFile),
12301
+ });
12302
+ controlFiles.helpers.push(driver);
12303
+ controlFiles.cpp = { completion: cpp.completion, cleanup: createCppControlCleanup(cpp.completion, [controlFiles.sourceFile, request.sourceFile, driver.sourceFile]) };
12304
+ loader = driver.sourceFile;
12305
+ } catch (error) {
12306
+ cleanupStudioReplControlFiles(controlFiles);
12307
+ throw error;
12308
+ }
12309
+ }
11850
12310
  return {
11851
12311
  runtime,
11852
12312
  usedControlFile: true,
@@ -11856,13 +12316,16 @@ function prepareStudioReplSubmission(
11856
12316
  };
11857
12317
  }
11858
12318
 
11859
- function pasteTextToStudioReplPane(text: string, paneTarget: string): { ok: true } | { ok: false; message: string; submissionStarted: boolean } {
12319
+ function pasteTextToStudioReplPane(text: string, paneTarget: string, bracketed = false): { ok: true } | { ok: false; message: string; submissionStarted: boolean } {
11860
12320
  const bufferName = `pi-studio-repl-${randomUUID().replace(/-/g, "")}`;
11861
12321
  const target = paneTarget;
11862
12322
  const loadResult = runStudioTmux(["load-buffer", "-b", bufferName, "-"], { input: text, timeout: 5_000 });
11863
12323
  if (!loadResult.ok) return { ok: false, message: loadResult.message || "Failed to load text into tmux buffer.", submissionStarted: false };
11864
12324
  try {
11865
- const pasteResult = runStudioTmux(["paste-buffer", "-d", "-b", bufferName, "-t", target], { timeout: 5_000 });
12325
+ // As in pi-repl 0.8.5: -p brackets the paste only if the REPL asked for bracketed
12326
+ // pastes. Julia then draws a line that wraps in the pane once, not once per
12327
+ // character, which left copies of its first row in the output.
12328
+ const pasteResult = runStudioTmux(["paste-buffer", ...(bracketed ? ["-p"] : []), "-d", "-b", bufferName, "-t", target], { timeout: 5_000 });
11866
12329
  if (!pasteResult.ok) return { ok: false, message: pasteResult.message || "Failed to paste text into REPL session.", submissionStarted: false };
11867
12330
  const enterResult = runStudioTmux(["send-keys", "-t", target, "C-m"], { timeout: 5_000 });
11868
12331
  if (!enterResult.ok) return { ok: false, message: enterResult.message || "Failed to send Enter to REPL session.", submissionStarted: true };
@@ -11891,7 +12354,7 @@ function sendTextToStudioReplSession(
11891
12354
  submissionId: options.submissionId || `pi-studio:local:${randomUUID()}`,
11892
12355
  echoMode: normalizeReplSubmissionEchoMode(options.echoMode, STUDIO_REPL_TOOL_ECHO_MODE) as ReplSubmissionEchoMode,
11893
12356
  }, runtime);
11894
- const pasted = pasteTextToStudioReplPane(prepared.submissionText, paneTarget);
12357
+ const pasted = pasteTextToStudioReplPane(prepared.submissionText, paneTarget, runtime === "julia");
11895
12358
  if (!pasted.ok) return {
11896
12359
  ok: false,
11897
12360
  message: pasted.message,
@@ -12120,15 +12583,50 @@ function clearStudioReplJournal(sessionName: string): void {
12120
12583
  clearReplSessionRecord(session.recordId, getStudioReplSessionRecordIdentity(session));
12121
12584
  }
12122
12585
 
12123
- async function waitForStudioReplDoneFile(doneFile: string | undefined, timeoutMs: number, signal?: AbortSignal): Promise<boolean> {
12124
- if (!doneFile) return false;
12586
+ // As in pi-repl, a C++ submission is complete only once its reply is valid: an empty,
12587
+ // partial or replaced done file stays pending.
12588
+ function isStudioReplSubmissionDone(controlFiles: StudioReplControlFiles): boolean {
12589
+ return controlFiles.cpp ? readCppCompletion(controlFiles.cpp.completion) !== undefined : existsSync(controlFiles.doneFile);
12590
+ }
12591
+
12592
+ // Whether the pane a send went to has ended: closed, its session or tmux server gone, or kept
12593
+ // dead by remain-on-exit. Undefined when tmux didn't answer, which counts as neither (Sol).
12594
+ function hasStudioReplPaneEnded(session: StudioReplSessionInfo): boolean | undefined {
12595
+ const panes = runStudioTmux(["list-panes", "-s", "-t", session.tmuxSessionId, "-F", "#{pane_id}\t#{pane_dead}"], { timeout: 3_000 });
12596
+ if (!panes.ok) return STUDIO_TMUX_GONE.test(panes.stderr) ? true : undefined;
12597
+ const pane = panes.stdout.split("\n").map((line) => line.split("\t")).find(([id]) => id === session.target);
12598
+ return !pane || pane[1] === "1";
12599
+ }
12600
+
12601
+ // A send whose session ended before it completed. Its record keeps what the pane still showed.
12602
+ class StudioReplSessionEndedError extends Error {
12603
+ constructor(sessionName: string, readonly paneOutput = "") {
12604
+ super(`${sessionName} ended while running the code.`);
12605
+ }
12606
+
12607
+ get recordText(): string {
12608
+ return [this.message, this.paneOutput].filter(Boolean).join("\n\n");
12609
+ }
12610
+ }
12611
+
12612
+ async function waitForStudioReplDoneFile(controlFiles: StudioReplControlFiles | undefined, timeoutMs: number, signal?: AbortSignal, session?: StudioReplSessionInfo): Promise<{ completed: boolean; ended: boolean }> {
12613
+ if (!controlFiles?.doneFile) return { completed: false, ended: false };
12125
12614
  const deadline = Date.now() + clampStudioReplSendTimeout(timeoutMs);
12615
+ let nextPaneCheck = Date.now() + 1_000;
12616
+ let endedChecks = 0;
12126
12617
  while (Date.now() < deadline) {
12127
- if (existsSync(doneFile)) return true;
12128
- if (signal?.aborted) return false;
12618
+ if (isStudioReplSubmissionDone(controlFiles)) return { completed: true, ended: false };
12619
+ if (signal?.aborted) return { completed: false, ended: false };
12620
+ // A runtime that exits or crashes, as Cling does on a null dereference, ends the
12621
+ // wait instead of the timeout, as in pi-repl. Two checks a second apart.
12622
+ if (session && Date.now() >= nextPaneCheck) {
12623
+ endedChecks = hasStudioReplPaneEnded(session) === true ? endedChecks + 1 : 0;
12624
+ if (endedChecks >= 2 && !isStudioReplSubmissionDone(controlFiles)) return { completed: false, ended: true };
12625
+ nextPaneCheck = Date.now() + 1_000;
12626
+ }
12129
12627
  await sleep(100);
12130
12628
  }
12131
- return existsSync(doneFile);
12629
+ return { completed: isStudioReplSubmissionDone(controlFiles), ended: false };
12132
12630
  }
12133
12631
 
12134
12632
  function sleepWithoutKeepingStudioProcessAlive(ms: number): Promise<void> {
@@ -12150,8 +12648,9 @@ function retainStudioReplSubmissionUntilSettled(
12150
12648
  let nextIdentityCheck = 0;
12151
12649
  let missingChecks = 0;
12152
12650
  try {
12153
- while (!existsSync(controlFiles.doneFile)) {
12154
- if (!existsSync(controlFiles.sourceFile)) return;
12651
+ while (!isStudioReplSubmissionDone(controlFiles)) {
12652
+ // As in pi-repl, only a C++ reply settles it, not its missing source.
12653
+ if (!controlFiles.cpp && !existsSync(controlFiles.sourceFile)) return;
12155
12654
  if (Date.now() >= nextIdentityCheck) {
12156
12655
  try {
12157
12656
  const current = inspectStudioReplSession(session.sessionName);
@@ -12181,7 +12680,7 @@ async function releaseOrRetainStudioReplSubmission(
12181
12680
  session: StudioReplSessionInfo | null,
12182
12681
  controlFiles: StudioReplControlFiles | undefined,
12183
12682
  ): Promise<void> {
12184
- if (session && controlFiles && !existsSync(controlFiles.doneFile)) {
12683
+ if (session && controlFiles && !isStudioReplSubmissionDone(controlFiles)) {
12185
12684
  retainStudioReplSubmissionUntilSettled(session, controlFiles, lease);
12186
12685
  return;
12187
12686
  }
@@ -12808,8 +13307,8 @@ ${cssVarsBlock}
12808
13307
  <option value="literate">Send mode: Literate</option>
12809
13308
  </select>
12810
13309
  <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>
13310
+ <option value="off">Pane echo: Off</option>
13311
+ <option value="summary" selected>Pane echo: Summary</option>
12813
13312
  <option value="full">Pane echo: Full (raw code)</option>
12814
13313
  </select>
12815
13314
  </div>
@@ -13436,12 +13935,16 @@ export default function (pi: ExtensionAPI) {
13436
13935
  name: "studio_repl_send",
13437
13936
  label: "Send to Studio REPL",
13438
13937
  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.",
13938
+ 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
13939
  promptGuidelines: [
13441
13940
  "Use studio_repl_send when the user asks to run code in the active Studio REPL.",
13442
13941
  "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.",
13942
+ "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
13943
  "If several REPL sessions of the same runtime are running, use studio_repl_status first or pass the exact sessionName when known.",
13944
+ "In Java (JShell), use System.out.println(...) for values you want to see: code is loaded with /open, which doesn't echo expression results.",
13945
+ "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.",
13946
+ "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.",
13947
+ "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
13948
  ],
13446
13949
  parameters: STUDIO_REPL_SEND_TOOL_PARAMS,
13447
13950
  executionMode: "sequential",
@@ -13535,8 +14038,9 @@ export default function (pi: ExtensionAPI) {
13535
14038
  submittedSession = currentSession;
13536
14039
 
13537
14040
  let completed = false;
14041
+ let ended = false;
13538
14042
  if (sent.controlFiles?.doneFile) {
13539
- completed = await waitForStudioReplDoneFile(sent.controlFiles.doneFile, timeoutMs, signal);
14043
+ ({ completed, ended } = await waitForStudioReplDoneFile(sent.controlFiles, timeoutMs, signal, currentSession));
13540
14044
  if (signal?.aborted && !completed) {
13541
14045
  throw new Error("studio_repl_send was aborted after submission; the shared session remains busy until the running code settles.");
13542
14046
  }
@@ -13544,7 +14048,7 @@ export default function (pi: ExtensionAPI) {
13544
14048
  await sleep(Math.min(750, timeoutMs));
13545
14049
  }
13546
14050
  const after = captureStudioReplSession(currentSession.sessionName, currentSession);
13547
- if (!after.ok) throw new Error(`Could not capture ${currentSession.sessionName} after sending: ${after.message}`);
14051
+ if (!after.ok) throw ended ? new StudioReplSessionEndedError(currentSession.sessionName) : new Error(`Could not capture ${currentSession.sessionName} after sending: ${after.message}`);
13548
14052
  if (!isSameStudioReplSessionLifetime(currentSession, after.session)) {
13549
14053
  throw new Error(`REPL session ${currentSession.sessionName} changed before Studio captured the result.`);
13550
14054
  }
@@ -13557,6 +14061,8 @@ export default function (pi: ExtensionAPI) {
13557
14061
  promptLine: beforeTranscript.split("\n").at(-1),
13558
14062
  completed,
13559
14063
  });
14064
+ // A pane kept dead by remain-on-exit still shows what the code printed.
14065
+ if (ended) throw new StudioReplSessionEndedError(currentSession.sessionName, output);
13560
14066
  const status: StudioReplJournalEntry["status"] = sent.controlFiles?.doneFile
13561
14067
  ? (completed ? "captured" : "timeout")
13562
14068
  : (output.trim() ? "captured" : "sent");
@@ -13621,19 +14127,22 @@ export default function (pi: ExtensionAPI) {
13621
14127
  } as Record<string, unknown>,
13622
14128
  };
13623
14129
  } catch (error) {
14130
+ // An ended session is an error whatever its output says; only Studio's own messages
14131
+ // are read for "timed out" (Sol).
14132
+ const ended = error instanceof StudioReplSessionEndedError ? error.recordText : undefined;
13624
14133
  if (journalEntry) {
13625
14134
  try {
13626
14135
  recordStudioReplJournalEntry({
13627
14136
  ...journalEntry,
13628
- output: error instanceof Error ? error.message : String(error),
13629
- status: error instanceof Error && /timed out/i.test(error.message) ? "timeout" : "error",
14137
+ output: ended ?? (error instanceof Error ? error.message : String(error)),
14138
+ status: ended === undefined && error instanceof Error && /timed out/i.test(error.message) ? "timeout" : "error",
13630
14139
  completedAt: Date.now(),
13631
14140
  }, submittedSession || selected.session);
13632
14141
  } catch {
13633
14142
  // Preserve the execution error when record maintenance also fails.
13634
14143
  }
13635
14144
  }
13636
- throw error;
14145
+ throw ended === undefined ? error : new Error(ended);
13637
14146
  } finally {
13638
14147
  if (!published) broadcastStudioReplSelection();
13639
14148
  await releaseOrRetainStudioReplSubmission(lease, submittedSession, submittedControlFiles);
@@ -16729,13 +17238,14 @@ export default function (pi: ExtensionAPI) {
16729
17238
  });
16730
17239
  const timeoutMs = STUDIO_REPL_SEND_DEFAULT_TIMEOUT_MS;
16731
17240
  let completed = false;
17241
+ let ended = false;
16732
17242
  if (sent.controlFiles?.doneFile) {
16733
- completed = await waitForStudioReplDoneFile(sent.controlFiles.doneFile, timeoutMs);
17243
+ ({ completed, ended } = await waitForStudioReplDoneFile(sent.controlFiles, timeoutMs, undefined, currentSession));
16734
17244
  } else {
16735
17245
  await sleep(Math.min(750, timeoutMs));
16736
17246
  }
16737
17247
  const after = captureStudioReplSession(msg.sessionName, currentSession);
16738
- if (!after.ok) throw new Error(`Could not capture ${msg.sessionName} after sending: ${after.message}`);
17248
+ if (!after.ok) throw ended ? new StudioReplSessionEndedError(msg.sessionName) : new Error(`Could not capture ${msg.sessionName} after sending: ${after.message}`);
16739
17249
  if (!isSameStudioReplSessionLifetime(currentSession, after.session)) {
16740
17250
  throw new Error(`REPL session ${msg.sessionName} changed before Studio captured the result.`);
16741
17251
  }
@@ -16748,6 +17258,8 @@ export default function (pi: ExtensionAPI) {
16748
17258
  promptLine: beforeTranscript.split("\n").at(-1),
16749
17259
  completed,
16750
17260
  });
17261
+ // A pane kept dead by remain-on-exit still shows what the code printed.
17262
+ if (ended) throw new StudioReplSessionEndedError(msg.sessionName, output);
16751
17263
  updateStudioReplJournalEntryOutput(
16752
17264
  msg.requestId,
16753
17265
  msg.sessionName,
@@ -16761,7 +17273,7 @@ export default function (pi: ExtensionAPI) {
16761
17273
  if (journalEntry) updateStudioReplJournalEntryOutput(
16762
17274
  msg.requestId,
16763
17275
  msg.sessionName,
16764
- message,
17276
+ error instanceof StudioReplSessionEndedError ? error.recordText : message,
16765
17277
  "error",
16766
17278
  submittedSession || session,
16767
17279
  );