@moxxy/plugin-terminal 0.41.3 → 0.42.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/src/terminal.ts CHANGED
@@ -1,6 +1,9 @@
1
1
  import { randomBytes } from 'node:crypto';
2
- import { defineSurface, defineTool, z, type SurfaceInstance } from '@moxxy/sdk';
3
- import { createTerminalProcess, type TerminalProcess } from './pty.js';
2
+ import { rmSync, writeFileSync } from 'node:fs';
3
+ import { tmpdir } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import { defineSurface, defineTool, waitFor, z, type SurfaceInstance } from '@moxxy/sdk';
6
+ import { createTerminalProcess, type PromptSignal, type TerminalProcess } from './pty.js';
4
7
 
5
8
  /**
6
9
  * Shared terminal processes, keyed by cwd. The surface and the `terminal` tool
@@ -188,11 +191,11 @@ const terminalInputSchema = z.object({
188
191
  });
189
192
 
190
193
  /**
191
- * The `terminal` tool runs a command in the SHARED terminal the user sees. It
192
- * appends a unique sentinel that echoes the exit code, then reads output until
193
- * the sentinel returns — reliable completion detection in an interactive,
194
- * input-echoing shell. The command and its output stay visible to the user, who
195
- * can take over at any time.
194
+ * The `terminal` tool runs a command in the SHARED terminal the user sees and
195
+ * reads its output until the shell is back at its prompt. zsh and bash report
196
+ * that themselves (shell-hooks.ts); any other shell is typed a unique sentinel
197
+ * that echoes the exit code. The command and its output stay visible to the
198
+ * user, who can take over at any time.
196
199
  */
197
200
  export function buildTerminalTool() {
198
201
  return defineTool({
@@ -271,9 +274,35 @@ const MAX_ACC = 1_000_000;
271
274
  const commandTails = new WeakMap<TerminalProcess, Promise<void>>();
272
275
 
273
276
  /**
274
- * Write `command` then a sentinel `printf` to a shared shell and collect output
275
- * until the sentinel line appears. Returns the captured output (best-effort
276
- * stripped of the echoed sentinel command) + the exit code parsed from it.
277
+ * How long a starting shell gets to show its first prompt before its commands
278
+ * are typed with a sentinel instead (its own start files replaced the hook).
279
+ */
280
+ const PROMPT_REPORT_DEADLINE_MS = 5_000;
281
+
282
+ /** Shells that showed no prompt before the deadline: their later commands do not wait for one again. */
283
+ const silent = new WeakSet<TerminalProcess>();
284
+
285
+ /** Resolves once the shell has shown a prompt; false when it reports none in time. */
286
+ async function reportsPrompt(
287
+ proc: TerminalProcess,
288
+ prompt: PromptSignal,
289
+ signal: AbortSignal | undefined,
290
+ ): Promise<boolean> {
291
+ if (silent.has(proc)) return false;
292
+ const outcome = await waitFor(() => (prompt.seen ? true : undefined), {
293
+ wakeOn: [(wake) => prompt.onPrompt(wake)],
294
+ timeoutMs: PROMPT_REPORT_DEADLINE_MS,
295
+ signal,
296
+ });
297
+ if (outcome.status === 'timeout') silent.add(proc);
298
+ return outcome.status === 'ready';
299
+ }
300
+
301
+ /**
302
+ * Write `command` to a shared shell and collect output until the shell reports
303
+ * its prompt, or, in a shell that reports none, until the sentinel `printf`
304
+ * typed after the command prints. Returns the captured output (best-effort
305
+ * stripped of the echoed command) + the exit code.
277
306
  *
278
307
  * Serialized per shared process: a command writes only once the previous one on
279
308
  * the same shell finishes, so concurrent callers never interleave their writes
@@ -320,14 +349,30 @@ function runCommandSerialized(
320
349
  return new Promise((resolve) => {
321
350
  let acc = '';
322
351
  let settled = false;
352
+ let typed: TypedCommand | undefined;
323
353
  const finish = (exitCode: number | null, timedOut: boolean): void => {
324
354
  if (settled) return;
325
355
  settled = true;
326
356
  unsubData();
327
357
  unsubExit();
358
+ unsubPrompt();
328
359
  clearTimeout(timer);
329
360
  if (onAbort) signal?.removeEventListener('abort', onAbort);
330
- resolve({ output: cleanOutput(acc, command, marker), exitCode, timedOut });
361
+ typed?.remove();
362
+ const output = cleanOutput(acc, `${command}\n${typed?.line ?? ''}`, marker);
363
+ const waiting = timedOut ? unfinishedPrompt(acc) : undefined;
364
+ if (waiting === undefined) {
365
+ resolve({ output, exitCode, timedOut });
366
+ return;
367
+ }
368
+ // The shell sits at a continuation prompt (`heredoc>`): every later command
369
+ // would be swallowed as more of this one. Ctrl-C drops only that input.
370
+ proc.write('\u0003');
371
+ resolve({
372
+ output: `${output}\n[the shell was waiting for the rest of an unfinished command (${waiting}); cancelled it with Ctrl-C]`,
373
+ exitCode,
374
+ timedOut,
375
+ });
331
376
  };
332
377
  // Already aborted before we even start? Finish immediately — don't write to
333
378
  // the shell, don't arm a timeout. The command never runs; null exit.
@@ -406,14 +451,18 @@ function runCommandSerialized(
406
451
  // immediately with the shell's exit code rather than hanging to the full
407
452
  // timeout (up to 600s) on a known-dead process.
408
453
  const unsubExit = proc.onExit((code) => finish(code, false));
454
+ let unsubPrompt = (): void => {};
409
455
  let timer: ReturnType<typeof setTimeout> | undefined;
410
456
  // Two writes to the interactive shell: the command, then the sentinel whose
411
457
  // $? reflects the command's exit. A leading newline before the printf
412
458
  // terminates any dangling/unterminated command line (trailing backslash,
413
459
  // unbalanced quote) so the sentinel is always emitted rather than consumed
414
- // as a continuation — otherwise such a command would always time out. On a
415
- // non-PTY pipe the shell still runs both sequentially.
416
- const writeAndArm = (): void => {
460
+ // as a continuation — otherwise such a command would always time out. The
461
+ // printf starts its own output with a newline too: shell hooks (zsh
462
+ // `preexec` setting the window title) print right before it, and the
463
+ // sentinel is only recognized at the start of a line. On a non-PTY pipe the
464
+ // shell still runs both sequentially.
465
+ const writeAndArm = (hooked: boolean): void => {
417
466
  if (settled) return; // shell died (or we were torn down) before our turn
418
467
  // The shell is ALREADY dead at write time (it exited before our turn, or
419
468
  // in the TOCTOU window between getSharedTerminal returning it and now).
@@ -426,17 +475,106 @@ function runCommandSerialized(
426
475
  return;
427
476
  }
428
477
  timer = setTimeout(() => finish(null, true), timeoutMs);
429
- proc.write(`${command}\n`);
430
- proc.write(`\nprintf '%s %s\\n' "${marker}" "$?"\n`);
478
+ typed = typeable(command, marker);
479
+ if (hooked && proc.prompt) {
480
+ // Nothing follows the command on the terminal's input, where the
481
+ // program it starts could read it: the shell says when it is done. A
482
+ // prompt drawn again for anything else (an empty Enter, a Ctrl-C, the
483
+ // end of a command the user typed) started no command since, so it is
484
+ // not this one's; a blank line starts none, and any prompt ends it.
485
+ const before = proc.prompt.commands;
486
+ const blank = command.trim() === '';
487
+ unsubPrompt = proc.prompt.onPrompt((exitCode, commands) => {
488
+ if (blank || commands > before) finish(exitCode, false);
489
+ });
490
+ proc.write(`${typed.line}\n`);
491
+ return;
492
+ }
493
+ proc.write(`${typed.line}\n`);
494
+ proc.write(`\n${sentinelPrintf(marker)}\n`);
495
+ };
496
+ // A shell with no prompt report, or one that has shown its prompt already,
497
+ // is decided on the spot, which keeps the single-command path synchronous.
498
+ const start = (): void => {
499
+ if (!proc.prompt || proc.prompt.seen) writeAndArm(proc.prompt !== undefined);
500
+ else void reportsPrompt(proc, proc.prompt, signal).then(writeAndArm);
431
501
  };
432
- // Idle shell → write now (keeps the single-command path fully synchronous).
433
- // Busy shell → wait our turn; the timeout clock only starts when we write, so
434
- // a command queued behind a slow predecessor doesn't burn its budget waiting.
435
- if (startWrites) void startWrites.then(writeAndArm);
436
- else writeAndArm();
502
+ // Idle shell → write now. Busy shell → wait our turn; the timeout clock only
503
+ // starts when we write, so a command queued behind a slow predecessor
504
+ // doesn't burn its budget waiting.
505
+ if (startWrites) void startWrites.then(start);
506
+ else start();
437
507
  });
438
508
  }
439
509
 
510
+ /**
511
+ * A terminal takes typed input through a buffer of about a kilobyte, and the
512
+ * shell redraws the line as each character arrives. A long or multi-line
513
+ * command typed in can lose characters, and a lost heredoc end line leaves the
514
+ * shell waiting forever. Such a command goes to a file the shell sources, so
515
+ * only one short line is typed and what it changes (cd, exports) stays, as if
516
+ * typed. Windows shells keep the typed form: `.` sourcing is POSIX.
517
+ */
518
+ const TYPED_LIMIT = 512;
519
+
520
+ interface TypedCommand {
521
+ readonly line: string;
522
+ remove(): void;
523
+ }
524
+
525
+ function typeable(command: string, marker: string): TypedCommand {
526
+ // A trailing backslash joins the next typed line to the command; in a file it ends with it.
527
+ const oneShortLine = !command.includes('\n') && command.length <= TYPED_LIMIT && !command.endsWith('\\');
528
+ if (process.platform === 'win32' || oneShortLine) {
529
+ return { line: command, remove: () => {} };
530
+ }
531
+ const file = join(tmpdir(), `moxxy-command-${marker}.sh`);
532
+ writeFileSync(file, `${command}\n`, { mode: 0o600 });
533
+ return {
534
+ line: `. '${file.replace(/'/g, `'\\''`)}'`,
535
+ remove: () => rmSync(file, { force: true }),
536
+ };
537
+ }
538
+
539
+ /** zsh's continuation prompt (`heredoc> `, `dquote> `, `for if> `) as the last line shown. */
540
+ const CONTINUATION_PROMPT = /^((?:[a-z]+ )*[a-z]+)>$/u;
541
+
542
+ function unfinishedPrompt(raw: string): string | undefined {
543
+ const last = plainText(raw).split('\n').filter((line) => line.trim() !== '').at(-1) ?? '';
544
+ return CONTINUATION_PROMPT.exec(last.trimEnd())?.[1];
545
+ }
546
+
547
+ /** The shell command that prints `<marker> <exit code>` on a line of its own. */
548
+ function sentinelPrintf(marker: string): string {
549
+ return `printf '\\n%s %s\\n' "${marker}" "$?"`;
550
+ }
551
+
552
+ // Terminal control sequences an interactive shell mixes into its output: OSC
553
+ // (window title, cwd), CSI (colors, cursor, bracketed paste) and the remaining
554
+ // two-byte escapes (keypad mode).
555
+ const CONTROL_SEQUENCE = /\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)|\u001b\[[0-?]*[ -/]*[@-~]|\u001b[ -/]*[0-~]/gu;
556
+ const OVERSTRUCK = /[^\n\u0008]\u0008/gu;
557
+
558
+ /**
559
+ * What the terminal shows as text: control sequences dropped, backspaced
560
+ * characters erased, and a line rewritten after a carriage return (a prompt
561
+ * redraw, a progress bar) reduced to what it ends up as.
562
+ */
563
+ function plainText(raw: string): string {
564
+ let text = raw.replace(CONTROL_SEQUENCE, '');
565
+ for (let before = ''; before !== text; ) {
566
+ before = text;
567
+ text = text.replace(OVERSTRUCK, '');
568
+ }
569
+ return text
570
+ .split('\n')
571
+ .map((line) => {
572
+ const shown = line.replace(/\r+$/u, '');
573
+ return shown.slice(shown.lastIndexOf('\r') + 1);
574
+ })
575
+ .join('\n');
576
+ }
577
+
440
578
  /** Strip the echoed command + sentinel lines so the model sees just the output. */
441
579
  function cleanOutput(acc: string, command: string, marker: string): string {
442
580
  // A multi-line command is echoed by an echo-on PTY one line at a time; none of
@@ -448,14 +586,9 @@ function cleanOutput(acc: string, command: string, marker: string): string {
448
586
  .map((l) => l.trim())
449
587
  .filter((l) => l.length > 0), // never strip blank output lines
450
588
  );
451
- return acc
589
+ return plainText(acc)
452
590
  .split('\n')
453
- .filter(
454
- (line) =>
455
- !line.includes(marker) &&
456
- !commandLines.has(line.trim()) &&
457
- !line.includes(`printf '%s %s\\n' "${marker}"`),
458
- )
591
+ .filter((line) => !line.includes(marker) && !commandLines.has(line.trim()))
459
592
  .join('\n')
460
593
  .trim();
461
594
  }