mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-23 16:42:19 +00:00
Accept space-separated Bash $ prompts while preserving delimiter and pending-input guards. Add recognition and extraction regression coverage. Fixes #4175 Co-authored-by: Codex <codex@openai.com>
1408 lines
53 KiB
JavaScript
1408 lines
53 KiB
JavaScript
/**
|
||
* Shell utility functions shared across AI bridge modules.
|
||
*
|
||
* Provides ANSI stripping, URL extraction, CLI resolution, path helpers,
|
||
* stream chunk serialization, and cached shell environment resolution.
|
||
*/
|
||
"use strict";
|
||
|
||
const { execFile, execFileSync } = require("node:child_process");
|
||
const { existsSync, readFileSync, statSync } = require("node:fs");
|
||
const path = require("node:path");
|
||
|
||
// ── ANSI / URL regexes ──
|
||
|
||
const ANSI_ESCAPE_REGEX = /\u001B\[[0-?]*[ -/]*[@-~]/g;
|
||
const ANSI_OSC_REGEX = /\u001B\][^\u0007]*?(?:\u0007|\u001B\\)/g;
|
||
const URL_CANDIDATE_REGEX = /https?:\/\/[^\s]+/g;
|
||
const WINDOWS_RUNNABLE_EXTENSIONS = [".exe", ".cmd", ".bat", ".com"];
|
||
const MAX_PROMPT_TRACK_TAIL = 4096;
|
||
|
||
function execFileAsync(command, args, options) {
|
||
return new Promise((resolve, reject) => {
|
||
execFile(command, args, options, (error, stdout, stderr) => {
|
||
if (error) {
|
||
error.stdout = stdout;
|
||
error.stderr = stderr;
|
||
reject(error);
|
||
return;
|
||
}
|
||
resolve({ stdout, stderr });
|
||
});
|
||
});
|
||
}
|
||
|
||
// ── ANSI stripping ──
|
||
|
||
function stripAnsi(input) {
|
||
return String(input || "").replace(ANSI_OSC_REGEX, "").replace(ANSI_ESCAPE_REGEX, "");
|
||
}
|
||
|
||
// ── Synthetic command echo ──
|
||
//
|
||
// The agent's typed command is not echoed by the PTY as-is (the wrapper
|
||
// line is filtered out in preload), so exec bridges emit a synthetic echo
|
||
// for the user to see. xterm.js treats a bare \n as "move down, keep
|
||
// column", which renders multi-line commands as a staircase. Normalize
|
||
// every line break to \r\n so each line starts at column 0.
|
||
function formatSyntheticEcho(command) {
|
||
return `${String(command ?? "").replace(/\r?\n/g, "\r\n")}\r\n`;
|
||
}
|
||
|
||
// Default PowerShell prompt (e.g. `PS C:\Users\alice>`, `PS>`,
|
||
// `PS /home/alice>`). Anchored so command output that merely starts with
|
||
// `PS` (e.g. `PSO>`) doesn't match. The `\S` after `\s+` rejects literal
|
||
// `"PS >"` (which the default prompt never emits) so a script that prints
|
||
// such a line can't trick prompt-driven shell-kind selection.
|
||
const POWERSHELL_PROMPT_PATTERN = /^PS(?:\s+\S.*)?>$/;
|
||
|
||
// Default cmd.exe prompt (e.g. `C:\>`, `C:\Users\alice>`, `D:\data>`).
|
||
// Drive letter + optional path + `>`. Rejects `C: >` (space before `>`) and
|
||
// PowerShell's `PS C:\...>` (handled by POWERSHELL_PROMPT_PATTERN first).
|
||
const CMD_PROMPT_PATTERN = /^[A-Za-z]:(?:\\[^<>"|]*)?>$/;
|
||
|
||
// Default login prompts, kept narrow so custom / fish / starship prompts do
|
||
// not flip a Windows DefaultShell soft hint:
|
||
// - bash/zsh `user@host[:path][#$]` (colon before the path; `root@host ~#` stays rejected)
|
||
// - RHEL-family `[\u@\h \W]\$` -> `[user@host path][#$]`, or `[user@host][#$]`
|
||
// with no path. `\W` may contain whitespace or `]` (`[user@host My [Project]]$`);
|
||
// the final `]` before `$`/`#` is the delimiter.
|
||
const POSIX_PROMPT_PATTERN = /^(?:[^\s@]+@[^\s:]+(?::[^\n\r]*)?|\[[^\s@\]]+@[^\s\]:]+(?:\s+[^\n\r]+)?\])[#$]$/;
|
||
|
||
// Space-separated bash PS1 `\u@\h \w $ ` renders as `user@host ~ $`.
|
||
// macOS ships zsh with `%n@%m %1~ %#`, which renders as
|
||
// `user@host ~ %` / `user@host My Project %`; privileged shells end in `#`.
|
||
// Allow spaces in the path, but keep prompt delimiters excluded so a prompt
|
||
// followed by input (`user@host ~ % echo %`) cannot count as idle. Requiring
|
||
// whitespace before the marker also rejects output such as `user@host 100%`.
|
||
const ZSH_PROMPT_PATTERN = /^[^\s@]+@[^\s:]+ [^\s%#$][^%#$\r\n]* [#$%]$/;
|
||
|
||
// SteamOS/Deck-style prompt: `(user@host path)$`. Allow markers and balanced
|
||
// single-level parentheses in the path, but not an early closing delimiter:
|
||
// otherwise a prompt followed by pending input could look like an idle prompt.
|
||
const PAREN_POSIX_PROMPT_PATTERN = /^\([^\s@()]+@[^\s:()]+\s+(?:[^()\r\n]|\([^()\r\n]*\))+\)[#$]$/;
|
||
|
||
// Host line of a two-line bash PS1 (`\u@\h: \w` then a following `$` or `#`).
|
||
// Same user@host[:path] class as POSIX_PROMPT_PATTERN's first alternative,
|
||
// without a prompt marker on this line. Oh My Zsh `ys` uses a different host
|
||
// line (`# user @ host ...`), matched separately below. A bare `$`/`#` alone
|
||
// is not a prompt.
|
||
const POSIX_PROMPT_HOST_LINE_PATTERN = /^[^\s@]+@[^\s:]+(?::[^\n\r]*)?$/;
|
||
|
||
// Oh My Zsh `ys` status line: a decorative `#`, then `user @ host` with
|
||
// spaces around `@`, then an optional remainder (directory, git, venv, time,
|
||
// exit code). Example: `# user @ host in ~ [12:34:56]`. Arbitrary text before
|
||
// a bare `$`/`#` still does not match.
|
||
const OH_MY_ZSH_YS_HOST_LINE_PATTERN = /^#\s+[^\s@]+\s+@\s+[^\s]+(?:\s+[^\n\r]+)?$/;
|
||
|
||
// Alpine's default ash PS1 omits the username: `\h:\w\$ ` -> `localhost:~# `.
|
||
// Require a hostname and a home/absolute path, excluding prompt delimiters
|
||
// within the path so partially entered commands do not count as idle prompts.
|
||
const ALPINE_PROMPT_PATTERN = /^[A-Za-z0-9_][A-Za-z0-9_.-]*:(?:~(?:\/[^#$\n\r]*)?|\/[^#$\n\r]*)[#$]$/;
|
||
|
||
// Powerlevel10k / similar Unicode prompt-ending ❯ (U+276F). Common idle forms:
|
||
// `~ ❯`, `~/path ❯`, `/tmp ❯`, short-dir `proj ❯`, optional `user@host `
|
||
// prefix (`alice@host ~ ❯`). Require a non-empty prefix and whitespace before
|
||
// ❯ so pending input (`~ ❯ echo READY`, `❯ vim`) cannot match. Bare `❯` alone
|
||
// is intentionally rejected — too ambiguous without a path/host prefix
|
||
// (same rationale as bare `$`/`#`). Do not attempt two-line bare-❯ here.
|
||
const POWERLEVEL10K_PROMPT_PATTERN =
|
||
/^(?:[^\s@]+@[^\s:]+\s+)?[^\s❯][^❯\r\n]*\s+❯$/;
|
||
|
||
// Oh My Zsh default theme (robbyrussell): leading ➜ (U+279C) then cwd (%c),
|
||
// optionally ` git:(branch)` and a dirty/clean marker. Idle forms look like
|
||
// `➜ ~`, `➜ netcatty`, `➜ ~ git:(main)`, `➜ ~ git:(main) ✗`.
|
||
// The theme emits two spaces between ➜ and %c (`➜ ` + ` %c`); require that
|
||
// so one-space pending input like `➜ ls` cannot match. Also accept the common
|
||
// single-space home form `➜ ~` (+ optional git). Only the optional git
|
||
// decoration may follow the cwd — `➜ ~ ls` / `➜ ~ echo hi` fail.
|
||
// Do not broaden to arbitrary starship themes.
|
||
const OH_MY_ZSH_ROBBYRUSSELL_PROMPT_PATTERN =
|
||
/^➜(?:\s{2,}[^\s➜][^\s➜]*|\s~)(?:\s+git:\([^)\r\n]+\))?(?:\s+[✗✓])?$/;
|
||
|
||
function isDefaultPowerShellPromptLine(line) {
|
||
return POWERSHELL_PROMPT_PATTERN.test(String(line || ""));
|
||
}
|
||
|
||
function isDefaultCmdPromptLine(line) {
|
||
return CMD_PROMPT_PATTERN.test(String(line || "").replace(/\s+$/, ""));
|
||
}
|
||
|
||
function isDefaultPosixPromptLine(line) {
|
||
const normalized = String(line || "").replace(/\s+$/, "");
|
||
// Optional virtualenv / conda / BT-panel style env name prefix: "(name) "
|
||
// before the shell prompt. Recognition only; callers still return the full
|
||
// prompt line so suffix matching sees the visible prefix (#3947).
|
||
const withoutEnvPrefix = normalized.replace(/^\([^()\n\r]+\)\s+/, "");
|
||
return (
|
||
POSIX_PROMPT_PATTERN.test(withoutEnvPrefix) ||
|
||
PAREN_POSIX_PROMPT_PATTERN.test(withoutEnvPrefix) ||
|
||
ALPINE_PROMPT_PATTERN.test(withoutEnvPrefix) ||
|
||
ZSH_PROMPT_PATTERN.test(withoutEnvPrefix) ||
|
||
POWERLEVEL10K_PROMPT_PATTERN.test(withoutEnvPrefix) ||
|
||
OH_MY_ZSH_ROBBYRUSSELL_PROMPT_PATTERN.test(withoutEnvPrefix)
|
||
);
|
||
}
|
||
|
||
function extractTrailingIdlePrompt(output) {
|
||
// Treat `\r` as a line break, not as a stripped character: PSReadLine /
|
||
// ConPTY repaints emit bare `\r` to redraw the current line, and we
|
||
// want only the redrawn line to be considered, not the concatenation
|
||
// of every overwritten frame.
|
||
const normalized = stripAnsi(output).replace(/\r/g, "\n");
|
||
if (!normalized || normalized.endsWith("\n")) return "";
|
||
|
||
const lines = normalized.split("\n");
|
||
const lastLine = lines.pop() || "";
|
||
const rightTrimmed = lastLine.replace(/\s+$/, "");
|
||
if (!rightTrimmed) return "";
|
||
|
||
if (isDefaultPowerShellPromptLine(rightTrimmed)) {
|
||
return lastLine;
|
||
}
|
||
|
||
if (isDefaultPosixPromptLine(rightTrimmed)) {
|
||
return lastLine;
|
||
}
|
||
|
||
if (isDefaultCmdPromptLine(rightTrimmed)) {
|
||
return lastLine;
|
||
}
|
||
|
||
// Two-line PS1. Classic bash is `export PS1="\u@\h: \w\n$ "`. Oh My Zsh
|
||
// `ys` paints `# user @ host ...` and then a bare `$` or `#`. Bash emits
|
||
// the newline as CR and the PTY's ONLCR adds another, so the bytes are
|
||
// `\r\r\n`. The CR-to-LF normalize above turns that into blank lines
|
||
// between the host line and `$`/`#`. Keep those blanks in the cache:
|
||
// getFreshIdlePrompt uses the same normalize, and hasExpectedPromptSuffix
|
||
// compares this CR-as-LF form against live PTY bytes. A lone `$`/`#` must
|
||
// not satisfy endsWith; the previous non-empty line has to be a recognized
|
||
// host line (classic `user@host[:path]` or Oh My Zsh `ys`).
|
||
if (rightTrimmed === "$" || rightTrimmed === "#") {
|
||
let hostIndex = lines.length - 1;
|
||
while (hostIndex >= 0 && lines[hostIndex].replace(/\s+$/, "") === "") {
|
||
hostIndex -= 1;
|
||
}
|
||
const previousLine = hostIndex >= 0 ? lines[hostIndex] : "";
|
||
const previousRightTrimmed = previousLine.replace(/\s+$/, "");
|
||
// Same optional "(name) " env prefix as isDefaultPosixPromptLine (#3947).
|
||
// Recognition only; the returned prompt keeps the visible prefix.
|
||
const previousHostLine = previousRightTrimmed.replace(/^\([^()\n\r]+\)\s+/, "");
|
||
if (
|
||
POSIX_PROMPT_HOST_LINE_PATTERN.test(previousHostLine)
|
||
|| OH_MY_ZSH_YS_HOST_LINE_PATTERN.test(previousHostLine)
|
||
) {
|
||
return `${lines.slice(hostIndex).join("\n")}\n${lastLine}`;
|
||
}
|
||
}
|
||
|
||
return "";
|
||
}
|
||
|
||
// bash and csh/tcsh print a banner to the terminal right before exiting due to
|
||
// the shell's TMOUT idle-timeout setting ("timed out waiting for input:
|
||
// auto-logout" / "auto-logout"). That exit is a clean shell exit — numeric
|
||
// code, no signal — so it is indistinguishable from a user-typed `exit` by
|
||
// exit code alone (verified: bash auto-logout exits 0). The banner is the only
|
||
// reliable discriminator, letting the SSH bridge keep the tab open for
|
||
// reconnect instead of auto-closing it (#1062, regression of #977).
|
||
const IDLE_AUTO_LOGOUT_PATTERN = /(?:timed out waiting for input:\s*)?auto-?logout$/i;
|
||
|
||
function looksLikeIdleAutoLogout(outputTail) {
|
||
if (typeof outputTail !== "string" || !outputTail) return false;
|
||
// The shell prints this banner on its own line as the very last thing before
|
||
// it exits, so anchor on the final non-empty line rather than a loose
|
||
// substring. Otherwise unrelated output that merely mentions "auto-logout"
|
||
// (e.g. `grep auto-logout /etc/profile`) followed by an intentional `exit`
|
||
// would be misclassified as a timeout and wrongly keep the tab open.
|
||
const lines = stripAnsi(outputTail.slice(-512)).replace(/\r/g, "\n").split("\n");
|
||
for (let i = lines.length - 1; i >= 0; i--) {
|
||
// Drop control bytes (e.g. the BEL bash rings before the banner) and trim.
|
||
const line = lines[i].replace(/[\x00-\x1f\x7f]/g, "").trim();
|
||
if (!line) continue;
|
||
return IDLE_AUTO_LOGOUT_PATTERN.test(line);
|
||
}
|
||
return false;
|
||
}
|
||
|
||
// ── OSC 133 (shell-integration) readiness ──
|
||
//
|
||
// A starts a prompt; B ends its rendering and starts command input; C starts
|
||
// execution/output; D finishes execution. A alone does not prove empty input.
|
||
// Keep lifecycle state beyond rolling-tail eviction, and accept custom prompts
|
||
// only while the B-marked cursor line is unchanged and no continuation arrived.
|
||
// A-only integrations retain the existing whitelist checks.
|
||
const OSC133_MARKER_PATTERN = /\u001B\]133;([ABCD])(?:;([^\u0007\u001B]*))?(?:\u0007|\u001B\\)/g;
|
||
|
||
function isOsc133PrimaryPrompt(marker) {
|
||
// Kitty's k=s marks PS2, which is unfinished command input, not a fresh PS1.
|
||
return marker[1] === "A" && !marker[2]?.split(";").includes("k=s");
|
||
}
|
||
|
||
function computeOsc133ReadyState(tail) {
|
||
if (typeof tail !== "string" || !tail) return null;
|
||
let ready = null;
|
||
for (const marker of tail.matchAll(OSC133_MARKER_PATTERN)) {
|
||
if (marker[1] !== "B") ready = isOsc133PrimaryPrompt(marker);
|
||
}
|
||
return ready;
|
||
}
|
||
|
||
function promptTrackingView(session) {
|
||
const tail = session?._promptTrackTail;
|
||
if (typeof tail !== "string" || !tail) return { tail: "", alternateScreenActive: false };
|
||
if (session.osc133Ready === true) {
|
||
const start = session._osc133PromptStart;
|
||
return {
|
||
// Never revive text from before A, or a prompt whose start was evicted.
|
||
tail: typeof start === "number" && start >= 0 ? tail.slice(start) : "",
|
||
alternateScreenActive: session._osc133PromptAltScreenAtStart === true,
|
||
};
|
||
}
|
||
return { tail, alternateScreenActive: session._promptTrackAltScreenAtTailStart === true };
|
||
}
|
||
|
||
function matchesOsc133EmptyPrompt(session, view) {
|
||
if (session._osc133PromptRedrawPending) return false;
|
||
if (session._osc133PromptLine == null) return true;
|
||
if (session._osc133PromptContinued) return false;
|
||
const { terminalCursorState } = require("../terminalLogSanitizer.cjs");
|
||
const cursor = terminalCursorState(view.tail, view);
|
||
// Readline deletion and vi replacement can emit identical BS-space-BS
|
||
// bytes. Preserve every displayed blank; output cannot certify its removal.
|
||
return cursor.column === session._osc133PromptColumn
|
||
&& cursor.line === session._osc133PromptLine;
|
||
}
|
||
|
||
function trackSessionIdlePrompt(session, chunk) {
|
||
if (!session || typeof chunk !== "string" || !chunk) return "";
|
||
|
||
const previousTail = session._promptTrackTail || "";
|
||
const combined = `${previousTail}${chunk}`;
|
||
session.osc133Ready ??= null;
|
||
for (const marker of combined.matchAll(OSC133_MARKER_PATTERN)) {
|
||
const end = marker.index + marker[0].length;
|
||
// Replaying old markers would erase pending-input state on every chunk.
|
||
// A marker split across chunks is consumed when its terminator arrives.
|
||
if (end <= previousTail.length) continue;
|
||
if (isOsc133PrimaryPrompt(marker)) {
|
||
const { alternateScreenActiveAfter } = require("../terminalLogSanitizer.cjs");
|
||
const beforeMarker = combined.slice(0, marker.index);
|
||
const priorSession = { ...session, _promptTrackTail: beforeMarker };
|
||
// A/B also occur during redraw, including multiline PS1 and packets
|
||
// ending before pending input is re-echoed. Neither A nor a newline
|
||
// proves cancellation. Keep uncertain input gated until C/D establishes
|
||
// a new command lifecycle; a redraw cannot clear this latch.
|
||
session._osc133PromptRedrawPending ||= session.osc133Ready === true
|
||
&& session._osc133PromptLine != null
|
||
&& !matchesOsc133EmptyPrompt(priorSession, promptTrackingView(priorSession));
|
||
session.osc133Ready = true;
|
||
session._osc133PromptStart = end;
|
||
session._osc133PromptAltScreenAtStart = alternateScreenActiveAfter(
|
||
combined.slice(0, end), session._promptTrackAltScreenAtTailStart === true,
|
||
);
|
||
session._osc133PromptLine = null;
|
||
session._osc133PromptEnd = -1;
|
||
session._osc133PromptContinued = false;
|
||
} else if (marker[1] === "B") {
|
||
if (session.osc133Ready === true && session._osc133PromptStart >= 0) {
|
||
const { terminalCursorState } = require("../terminalLogSanitizer.cjs");
|
||
const cursor = terminalCursorState(
|
||
combined.slice(session._osc133PromptStart, end),
|
||
{ alternateScreenActive: session._osc133PromptAltScreenAtStart === true },
|
||
);
|
||
session._osc133PromptLine = cursor.line;
|
||
session._osc133PromptColumn = cursor.column;
|
||
session._osc133PromptEnd = end;
|
||
}
|
||
} else {
|
||
// Secondary prompts continue input; only C/D establish a new lifecycle.
|
||
session._osc133PromptRedrawPending = marker[1] === "A";
|
||
session.osc133Ready = false;
|
||
session._osc133PromptLine = null;
|
||
session._osc133PromptStart = -1;
|
||
session._osc133PromptEnd = -1;
|
||
}
|
||
}
|
||
if (session._osc133PromptLine != null) {
|
||
const inputStart = Math.max(previousTail.length, session._osc133PromptEnd);
|
||
if (combined.slice(inputStart).includes("\n")) session._osc133PromptContinued = true;
|
||
}
|
||
const overflow = combined.length - MAX_PROMPT_TRACK_TAIL;
|
||
if (overflow > 0) {
|
||
// The kept tail no longer starts where the previous tail started. Replay
|
||
// the dropped prefix so an alternate-screen enter or leave that scrolls
|
||
// off is still the mode at the first kept byte.
|
||
const { alternateScreenActiveAfter } = require("../terminalLogSanitizer.cjs");
|
||
session._promptTrackAltScreenAtTailStart = alternateScreenActiveAfter(
|
||
combined.slice(0, overflow),
|
||
session._promptTrackAltScreenAtTailStart === true,
|
||
);
|
||
for (const key of ["_osc133PromptStart", "_osc133PromptEnd"]) {
|
||
if (typeof session[key] === "number") session[key] = Math.max(-1, session[key] - overflow);
|
||
}
|
||
}
|
||
const nextTail = overflow > 0 ? combined.slice(overflow) : combined;
|
||
session._promptTrackTail = nextTail;
|
||
|
||
const prompt = extractTrailingIdlePrompt(promptTrackingView(session).tail);
|
||
if (prompt) {
|
||
session.lastIdlePrompt = prompt;
|
||
session.lastIdlePromptAt = Date.now();
|
||
}
|
||
|
||
return prompt;
|
||
}
|
||
|
||
// Return `session.lastIdlePrompt` only if the PTY's recent rolling tail
|
||
// still ends with it. The cached prompt is updated only when
|
||
// extractTrailingIdlePrompt recognizes a known shape (PowerShell, cmd.exe,
|
||
// `user@host[:path][#$]`, two-line classic `user@host[:path]` or Oh My Zsh
|
||
// `ys` (`# user @ host ...`) + `$`/`#`, RHEL `[user@host path][#$]`,
|
||
// Alpine `host:path[#$]`, Powerlevel10k-style `... ❯`, or Oh My Zsh
|
||
// robbyrussell `➜ …`);
|
||
// a remote shell switch into another shell, an oh-my-posh / starship / custom
|
||
// PS1, or any unrecognized prompt would
|
||
// otherwise leave a stale value behind, which `resolveEffectiveShellKind`
|
||
// would then keep using to coerce future commands into a PowerShell
|
||
// wrapper. By re-checking the live tail we self-correct: if the visible
|
||
// last line no longer matches the cached prompt, the prompt is treated
|
||
// as expired and downstream wrapper selection / suffix matching falls
|
||
// back to `shellKind` alone.
|
||
function getFreshIdlePrompt(session) {
|
||
if (!session) return "";
|
||
|
||
// C/D gate text-shaped output. A never bypasses cache freshness or input
|
||
// checks: an earlier prompt remains marked A while a user edits a command.
|
||
if (session.osc133Ready === false) return "";
|
||
|
||
const cached = session.lastIdlePrompt;
|
||
if (!cached) return "";
|
||
|
||
const view = promptTrackingView(session);
|
||
const tail = view.tail;
|
||
if (typeof tail !== "string" || !tail) return "";
|
||
if (!matchesOsc133EmptyPrompt(session, view)) return "";
|
||
|
||
const normalizedTail = stripAnsi(tail).replace(/\r/g, "\n");
|
||
const normalizedCached = stripAnsi(cached).replace(/\r/g, "\n");
|
||
if (!normalizedCached) return "";
|
||
|
||
return normalizedTail.endsWith(normalizedCached) ? cached : "";
|
||
}
|
||
|
||
// Readiness companion to getFreshIdlePrompt. PSReadLine echoes keys (including
|
||
// the pending-input clear prefix) and then erases them with cursor-column +
|
||
// ED/EL without appending a fresh copy of the prompt. stripAnsi removes the
|
||
// erase, so the raw tail no longer ends with the cached prompt while the
|
||
// screen is still an idle default prompt (#3927). Collapse those cursor and
|
||
// erase operations, then accept only the line the cursor is actually on.
|
||
function getVisibleIdlePrompt(session) {
|
||
const view = promptTrackingView(session);
|
||
const tail = view.tail;
|
||
if (typeof tail !== "string" || !tail) return "";
|
||
|
||
// Mirror getFreshIdlePrompt: C/D gate output, B confirms an empty input line.
|
||
if (session.osc133Ready === false) return "";
|
||
if (!matchesOsc133EmptyPrompt(session, view)) return "";
|
||
|
||
const { terminalCursorLine } = require("../terminalLogSanitizer.cjs");
|
||
const cursorLine = terminalCursorLine(tail, view);
|
||
const rightTrimmed = cursorLine.replace(/\s+$/, "");
|
||
if (!rightTrimmed) return "";
|
||
if (session.osc133Ready === true && session._osc133PromptLine != null) {
|
||
// A complete B gives the custom prompt boundary; its unchanged cursor line
|
||
// and lack of continuation are checked above before bypassing shape checks.
|
||
return /\s$/.test(cursorLine) ? `${rightTrimmed} ` : rightTrimmed;
|
||
}
|
||
if (
|
||
!isDefaultPowerShellPromptLine(rightTrimmed)
|
||
&& !isDefaultPosixPromptLine(rightTrimmed)
|
||
&& !isDefaultCmdPromptLine(rightTrimmed)
|
||
) {
|
||
return "";
|
||
}
|
||
// Keep one trailing space when the visible prompt has one. Erase-to-end
|
||
// padding must not become part of the expected prompt.
|
||
return /\s$/.test(cursorLine) ? `${rightTrimmed} ` : rightTrimmed;
|
||
}
|
||
|
||
// ── URL helpers ──
|
||
|
||
function isLocalhostHostname(hostname) {
|
||
const normalized = String(hostname || "").trim().toLowerCase();
|
||
return (
|
||
normalized === "localhost" ||
|
||
normalized === "127.0.0.1" ||
|
||
normalized === "::1" ||
|
||
normalized === "[::1]" ||
|
||
normalized.endsWith(".localhost")
|
||
);
|
||
}
|
||
|
||
function extractFirstNonLocalhostUrl(output) {
|
||
const { URL } = require("node:url");
|
||
const matches = stripAnsi(output).match(URL_CANDIDATE_REGEX);
|
||
if (!matches) return null;
|
||
|
||
for (const match of matches) {
|
||
try {
|
||
const parsedUrl = new URL(match.trim().replace(/[),.;!?]+$/, ""));
|
||
if (!isLocalhostHostname(parsedUrl.hostname)) {
|
||
return parsedUrl.toString();
|
||
}
|
||
} catch {
|
||
// Ignore invalid URL candidates.
|
||
}
|
||
}
|
||
|
||
return null;
|
||
}
|
||
|
||
// ── CLI / path helpers ──
|
||
|
||
function normalizeCliPathForPlatform(filePath) {
|
||
const normalized = String(filePath || "").trim();
|
||
if (!normalized) return null;
|
||
|
||
if (process.platform !== "win32") {
|
||
// Reject directories (e.g. /Applications/Codex.app) — must be a file
|
||
try {
|
||
if (existsSync(normalized) && statSync(normalized).isFile()) return normalized;
|
||
} catch { /* stat failed */ }
|
||
return null;
|
||
}
|
||
|
||
const ext = path.extname(normalized).toLowerCase();
|
||
if (ext) {
|
||
return existsSync(normalized) ? normalized : null;
|
||
}
|
||
|
||
// Windows npm globals often contain both a POSIX shim (`codex`) and the
|
||
// actual runnable wrapper (`codex.cmd`). Prefer the wrapper when present.
|
||
for (const suffix of WINDOWS_RUNNABLE_EXTENSIONS) {
|
||
const candidate = `${normalized}${suffix}`;
|
||
if (existsSync(candidate)) {
|
||
return candidate;
|
||
}
|
||
}
|
||
|
||
return existsSync(normalized) ? normalized : null;
|
||
}
|
||
|
||
function shouldUseShellForCommand(command) {
|
||
if (process.platform !== "win32") return false;
|
||
const normalized = String(command || "").trim().toLowerCase();
|
||
return normalized.endsWith(".cmd") || normalized.endsWith(".bat");
|
||
}
|
||
|
||
function quoteWindowsShellArg(value) {
|
||
const arg = String(value ?? "");
|
||
if (!arg) return "\"\"";
|
||
return `"${arg.replace(/"/g, '\\"')}"`;
|
||
}
|
||
|
||
function buildWindowsShellCommandLine(command, args) {
|
||
return [command, ...(args || [])].map(quoteWindowsShellArg).join(" ");
|
||
}
|
||
|
||
function resolveWindowsShimToNativeExe(command, platform = process.platform) {
|
||
if (platform !== "win32") return null;
|
||
const normalized = String(command || "").trim();
|
||
if (!normalized) return null;
|
||
const ext = path.extname(normalized).toLowerCase();
|
||
if (ext !== ".cmd" && ext !== ".bat") return null;
|
||
if (!existsSync(normalized)) return null;
|
||
try {
|
||
const contents = readFileSync(normalized, "utf8");
|
||
const shimDir = path.dirname(normalized);
|
||
// Match patterns like: "%~dp0\..\node_modules\@anthropic-ai\claude-code\bin\claude.exe" %*
|
||
// or: "%~dp0\..\@openai\codex\bin\codex.exe"
|
||
const exeRefs = [...contents.matchAll(/"%~dp0\\([^"]+\.exe)"/gi)];
|
||
for (const [, relativePath] of exeRefs) {
|
||
const candidate = path.resolve(shimDir, relativePath.replace(/\\/g, "/"));
|
||
if (existsSync(candidate)) return candidate;
|
||
}
|
||
} catch {}
|
||
return null;
|
||
}
|
||
|
||
function prepareCommandForSpawn(command, args, options = {}) {
|
||
const spawnArgs = Array.isArray(args) ? args : [];
|
||
if (!shouldUseShellForCommand(command)) {
|
||
return { command, args: spawnArgs, shell: false };
|
||
}
|
||
|
||
// Cursor's Windows installer .cmd launches node.exe + index.js. Unwrapping
|
||
// to the first quoted .exe would drop the script and run node with CLI args.
|
||
if (options.unwrapNativeExe !== false) {
|
||
const nativeExePath = resolveWindowsShimToNativeExe(command);
|
||
if (nativeExePath) {
|
||
return { command: nativeExePath, args: spawnArgs, shell: false };
|
||
}
|
||
}
|
||
|
||
return {
|
||
command: buildWindowsShellCommandLine(command, spawnArgs),
|
||
args: [],
|
||
shell: true,
|
||
};
|
||
}
|
||
|
||
function resolveClaudeCodeExecutableForSdk(claudeExecutablePath, platform = process.platform) {
|
||
const normalized = String(claudeExecutablePath || "").trim();
|
||
if (!normalized) return null;
|
||
if (platform !== "win32") return normalized;
|
||
|
||
const ext = path.extname(normalized).toLowerCase();
|
||
if (ext && ext !== ".cmd" && ext !== ".bat") return normalized;
|
||
|
||
const baseDir = path.dirname(normalized);
|
||
const packageCliPath = path.join(baseDir, "node_modules", "@anthropic-ai", "claude-code", "cli.js");
|
||
if (existsSync(packageCliPath)) {
|
||
return packageCliPath;
|
||
}
|
||
|
||
// Native binary check: Claude Code >= 2.1.169 ships as native exe with no cli.js
|
||
const nativeExeCandidates = [
|
||
path.join(baseDir, "node_modules", "@anthropic-ai", "claude-code", "bin", "claude.exe"),
|
||
path.join(baseDir, "..", "node_modules", "@anthropic-ai", "claude-code", "bin", "claude.exe"),
|
||
];
|
||
for (const exePath of nativeExeCandidates) {
|
||
if (existsSync(exePath)) return exePath;
|
||
}
|
||
|
||
const shimCandidates = [normalized];
|
||
if (!ext) {
|
||
shimCandidates.push(`${normalized}.cmd`, `${normalized}.bat`);
|
||
}
|
||
|
||
for (const shimPath of shimCandidates) {
|
||
try {
|
||
if (!existsSync(shimPath)) continue;
|
||
const contents = readFileSync(shimPath, "utf8");
|
||
if (!/node_modules[\\/]+@anthropic-ai[\\/]+claude-code[\\/]+cli\.js/i.test(contents)) {
|
||
continue;
|
||
}
|
||
if (existsSync(packageCliPath)) {
|
||
return packageCliPath;
|
||
}
|
||
} catch {
|
||
// Fall back to the original executable path below.
|
||
}
|
||
}
|
||
|
||
return normalized;
|
||
}
|
||
|
||
function normalizeClaudeCodeExecutableEnvForSdk(env, platform = process.platform) {
|
||
if (!env?.CLAUDE_CODE_EXECUTABLE) return env;
|
||
const resolved = resolveClaudeCodeExecutableForSdk(env.CLAUDE_CODE_EXECUTABLE, platform);
|
||
if (!resolved || resolved === env.CLAUDE_CODE_EXECUTABLE) return env;
|
||
return {
|
||
...env,
|
||
CLAUDE_CODE_EXECUTABLE: resolved,
|
||
};
|
||
}
|
||
|
||
const CODEX_WIN32_PLATFORM_PACKAGES = {
|
||
x64: { triple: "x86_64-pc-windows-msvc", package: "@openai/codex-win32-x64" },
|
||
arm64: { triple: "aarch64-pc-windows-msvc", package: "@openai/codex-win32-arm64" },
|
||
};
|
||
|
||
function resolveCodexNativeExecutableWin32(moduleSearchDirs, arch = process.arch) {
|
||
const archKey = arch === "arm64" ? "arm64" : "x64";
|
||
const { triple, package: platformPackage } = CODEX_WIN32_PLATFORM_PACKAGES[archKey];
|
||
|
||
for (const dir of moduleSearchDirs) {
|
||
if (!dir) continue;
|
||
const candidates = [
|
||
path.join(dir, "node_modules", platformPackage, "vendor", triple, "bin", "codex.exe"),
|
||
path.join(dir, "node_modules", platformPackage, "vendor", triple, "codex", "codex.exe"),
|
||
];
|
||
for (const candidate of candidates) {
|
||
if (existsSync(candidate)) {
|
||
return candidate;
|
||
}
|
||
}
|
||
}
|
||
|
||
return null;
|
||
}
|
||
|
||
function getNvmdHomeFromShimDir(shimDir) {
|
||
const normalized = String(shimDir || "").trim();
|
||
if (!normalized) return null;
|
||
if (path.basename(normalized).toLowerCase() !== "bin") return null;
|
||
const home = path.dirname(normalized);
|
||
// nvm-desktop / nvmd-command layout: $NVMD_HOME/{bin,versions,default,packages.json}
|
||
if (
|
||
existsSync(path.join(home, "versions")) ||
|
||
existsSync(path.join(home, "packages.json")) ||
|
||
existsSync(path.join(home, "default"))
|
||
) {
|
||
return home;
|
||
}
|
||
return null;
|
||
}
|
||
|
||
function readNvmdDefaultVersion(nvmdHome) {
|
||
try {
|
||
const raw = readFileSync(path.join(nvmdHome, "default"), "utf8").trim();
|
||
return raw || null;
|
||
} catch {
|
||
return null;
|
||
}
|
||
}
|
||
|
||
function readNvmdPackageVersions(nvmdHome, packageBinName) {
|
||
try {
|
||
const raw = readFileSync(path.join(nvmdHome, "packages.json"), "utf8");
|
||
const data = JSON.parse(raw);
|
||
const versions = data && data[packageBinName];
|
||
if (!Array.isArray(versions)) return [];
|
||
return versions.map((v) => String(v || "").trim()).filter(Boolean);
|
||
} catch {
|
||
return [];
|
||
}
|
||
}
|
||
|
||
function getNvmdVersionsDirectory(nvmdHome) {
|
||
try {
|
||
const raw = readFileSync(path.join(nvmdHome, "setting.json"), "utf8");
|
||
const data = JSON.parse(raw);
|
||
const custom = data && typeof data.directory === "string" ? data.directory.trim() : "";
|
||
if (custom) return custom;
|
||
} catch {
|
||
// Fall back to the default versions/ directory.
|
||
}
|
||
return path.join(nvmdHome, "versions");
|
||
}
|
||
|
||
function getNvmdCodexVersionRoots(nvmdHome) {
|
||
if (!nvmdHome) return [];
|
||
const versionsDir = getNvmdVersionsDirectory(nvmdHome);
|
||
const candidates = [
|
||
...readNvmdPackageVersions(nvmdHome, "codex").reverse(),
|
||
readNvmdDefaultVersion(nvmdHome),
|
||
].filter(Boolean);
|
||
|
||
const roots = [];
|
||
const seen = new Set();
|
||
for (const version of candidates) {
|
||
const root = path.join(versionsDir, version);
|
||
if (seen.has(root) || !existsSync(root)) continue;
|
||
seen.add(root);
|
||
roots.push(root);
|
||
}
|
||
return roots;
|
||
}
|
||
|
||
function getCodexNativeSearchDirsForShim(shimDir) {
|
||
const dirs = [shimDir];
|
||
const parentDir = path.dirname(shimDir);
|
||
if (
|
||
path.basename(shimDir).toLowerCase() === ".bin" &&
|
||
path.basename(parentDir).toLowerCase() === "node_modules"
|
||
) {
|
||
dirs.push(path.dirname(parentDir));
|
||
}
|
||
dirs.push(path.join(shimDir, "node_modules", "@openai", "codex"));
|
||
|
||
// nvm-desktop installs global CLIs under $NVMD_HOME/versions/<ver>/, while
|
||
// $NVMD_HOME/bin/codex{.cmd,.exe} are only nvmd router shims. Expand search
|
||
// into the active/recorded Node version roots so the SDK can spawn the real
|
||
// native codex.exe (codexPathOverride) instead of falling back to bundled
|
||
// optional deps that Netcatty deliberately does not ship.
|
||
const nvmdHome = getNvmdHomeFromShimDir(shimDir);
|
||
for (const versionRoot of getNvmdCodexVersionRoots(nvmdHome)) {
|
||
dirs.push(versionRoot);
|
||
dirs.push(path.join(versionRoot, "node_modules", "@openai", "codex"));
|
||
}
|
||
return dirs;
|
||
}
|
||
|
||
function getCodexNativePathDirsWin32(nativeExecutablePath) {
|
||
const normalized = String(nativeExecutablePath || "").trim();
|
||
if (!normalized || path.basename(normalized).toLowerCase() !== "codex.exe") {
|
||
return [];
|
||
}
|
||
|
||
const executableDir = path.dirname(normalized);
|
||
const packageRoot = path.dirname(executableDir);
|
||
const dirs = [];
|
||
if (path.basename(executableDir).toLowerCase() === "bin") {
|
||
dirs.push(path.join(packageRoot, "codex-path"));
|
||
} else if (path.basename(executableDir).toLowerCase() === "codex") {
|
||
dirs.push(path.join(packageRoot, "path"));
|
||
}
|
||
return dirs.filter((dir) => existsSync(dir));
|
||
}
|
||
|
||
function getPathEnvKey(env, platform = process.platform) {
|
||
if (platform !== "win32") return "PATH";
|
||
const keys = Object.keys(env || {}).filter((key) => key.toLowerCase() === "path");
|
||
return keys.includes("Path") ? "Path" : keys.at(-1) || "PATH";
|
||
}
|
||
|
||
function addCodexExecutableEnvForSdk(env, codexExecutablePath, platform = process.platform) {
|
||
if (platform !== "win32" || !codexExecutablePath) return env;
|
||
const pathDirs = getCodexNativePathDirsWin32(codexExecutablePath);
|
||
if (pathDirs.length === 0) return env;
|
||
|
||
const nextEnv = { ...(env || {}) };
|
||
const pathKey = getPathEnvKey(nextEnv, platform);
|
||
for (const key of Object.keys(nextEnv)) {
|
||
if (key.toLowerCase() === "path" && key !== pathKey) {
|
||
delete nextEnv[key];
|
||
}
|
||
}
|
||
const delimiter = platform === "win32" ? ";" : path.delimiter;
|
||
const existingEntries = String(nextEnv[pathKey] || "")
|
||
.split(delimiter)
|
||
.filter((entry) => entry && !pathDirs.includes(entry));
|
||
nextEnv[pathKey] = [...pathDirs, ...existingEntries].join(delimiter);
|
||
return nextEnv;
|
||
}
|
||
|
||
function resolveCodexExecutableForSdk(codexExecutablePath, platform = process.platform) {
|
||
const normalized = String(codexExecutablePath || "").trim();
|
||
if (!normalized) return null;
|
||
if (platform !== "win32") return normalized;
|
||
|
||
const ext = path.extname(normalized).toLowerCase();
|
||
const baseDir = path.dirname(normalized);
|
||
const moduleSearchDirs = getCodexNativeSearchDirsForShim(baseDir);
|
||
const nvmdHome = getNvmdHomeFromShimDir(baseDir);
|
||
|
||
// nvmd's Windows package shim is a copy of nvmd.exe named codex.exe. Prefer
|
||
// the real native binary under versions/<ver>/ when that layout is present.
|
||
if (ext === ".exe") {
|
||
if (nvmdHome) {
|
||
const nativeExe = resolveCodexNativeExecutableWin32(moduleSearchDirs);
|
||
if (nativeExe) return nativeExe;
|
||
}
|
||
return normalized;
|
||
}
|
||
|
||
if (ext === ".js" && /[\\/]codex\.js$/i.test(normalized)) {
|
||
const codexPackageRoot = path.dirname(path.dirname(normalized));
|
||
const globalPrefix = path.resolve(codexPackageRoot, "..", "..", "..");
|
||
const nativeExe = resolveCodexNativeExecutableWin32([
|
||
globalPrefix,
|
||
codexPackageRoot,
|
||
...moduleSearchDirs,
|
||
]);
|
||
if (nativeExe) return nativeExe;
|
||
}
|
||
|
||
if (ext && ext !== ".cmd" && ext !== ".bat" && ext !== ".ps1") {
|
||
return normalized;
|
||
}
|
||
|
||
const nativeExe = resolveCodexNativeExecutableWin32(moduleSearchDirs);
|
||
if (nativeExe) return nativeExe;
|
||
|
||
const shimCandidates = [normalized];
|
||
if (!ext) {
|
||
shimCandidates.push(`${normalized}.cmd`, `${normalized}.bat`);
|
||
}
|
||
|
||
for (const shimPath of shimCandidates) {
|
||
try {
|
||
if (!existsSync(shimPath)) continue;
|
||
const contents = readFileSync(shimPath, "utf8");
|
||
if (!/@openai[\\/]codex[\\/]bin[\\/]codex\.js/i.test(contents)) {
|
||
continue;
|
||
}
|
||
const resolved = resolveCodexNativeExecutableWin32(moduleSearchDirs);
|
||
if (resolved) return resolved;
|
||
} catch {
|
||
// Fall back to the original executable path below.
|
||
}
|
||
}
|
||
|
||
return ext === ".cmd" || ext === ".bat" || ext === ".ps1" ? null : normalized;
|
||
}
|
||
|
||
function resolveCodebuddyExecutableForSdk(codebuddyExecutablePath, platform = process.platform) {
|
||
const normalized = String(codebuddyExecutablePath || "").trim();
|
||
if (!normalized) return null;
|
||
if (platform !== "win32") return normalized;
|
||
|
||
const ext = path.extname(normalized).toLowerCase();
|
||
// A native exe or an explicit .js entry can be launched by the Agent SDK as-is.
|
||
if (ext === ".exe" || ext === ".js") return normalized;
|
||
// Any other concrete, non-shim extension: leave it untouched.
|
||
if (ext && ext !== ".cmd" && ext !== ".bat" && ext !== ".ps1") return normalized;
|
||
|
||
// Windows npm globals expose `codebuddy.cmd` / `codebuddy.ps1` shims (and an
|
||
// extensionless POSIX shim). The Agent SDK launches the CLI through `node`
|
||
// (electron-as-node in a packaged app), which cannot parse a batch/POSIX shim
|
||
// as JavaScript — the spawned process exits immediately and the SDK surfaces
|
||
// "CLI process stdout closed unexpectedly". Resolve the shim to the package's
|
||
// real `bin/codebuddy` JS entry so the SDK runs it exactly as on macOS/Linux.
|
||
const baseDir = path.dirname(normalized);
|
||
const packageRoots = [
|
||
path.join(baseDir, "node_modules", "@tencent-ai", "codebuddy-code"),
|
||
path.join(baseDir, "..", "node_modules", "@tencent-ai", "codebuddy-code"),
|
||
];
|
||
for (const root of packageRoots) {
|
||
const binJs = path.join(root, "bin", "codebuddy");
|
||
if (existsSync(binJs)) return binJs;
|
||
}
|
||
|
||
// Fall back to parsing the shim for the bin/codebuddy path it references.
|
||
const shimCandidates = [normalized];
|
||
if (!ext) shimCandidates.push(`${normalized}.cmd`, `${normalized}.bat`);
|
||
for (const shimPath of shimCandidates) {
|
||
try {
|
||
if (!existsSync(shimPath)) continue;
|
||
const contents = readFileSync(shimPath, "utf8");
|
||
const match = contents.match(/([^"\s]*codebuddy-code[\\/]bin[\\/]codebuddy)/i);
|
||
if (match) {
|
||
const ref = match[1].replace(/^%~dp0[\\/]?/i, "").replace(/[\\/]+/g, path.sep);
|
||
const binJs = path.isAbsolute(ref) ? ref : path.resolve(path.dirname(shimPath), ref);
|
||
if (existsSync(binJs)) return binJs;
|
||
}
|
||
} catch {
|
||
// Try the next shim candidate.
|
||
}
|
||
}
|
||
|
||
// Could not locate the JS entry — return null so the caller falls back to the
|
||
// SDK's bundled CLI rather than handing `node` an unrunnable shim.
|
||
return ext === ".cmd" || ext === ".bat" || ext === ".ps1" ? null : normalized;
|
||
}
|
||
|
||
function resolveCopilotExecutableForSdk(copilotExecutablePath, platform = process.platform) {
|
||
const normalized = String(copilotExecutablePath || "").trim();
|
||
if (!normalized) return null;
|
||
if (platform !== "win32") return normalized;
|
||
|
||
const ext = path.extname(normalized).toLowerCase();
|
||
// A native exe or an explicit .js entry can be launched by the SDK as-is.
|
||
if (ext === ".exe" || ext === ".js") return normalized;
|
||
// Any other concrete, non-shim extension: leave it untouched. npm also
|
||
// writes a copilot.ps1 wrapper next to the .cmd one; it cannot be spawned
|
||
// without a shell either, so it resolves to the JS entry the same way.
|
||
if (ext && ext !== ".cmd" && ext !== ".bat" && ext !== ".ps1") return normalized;
|
||
|
||
// Windows npm globals expose `copilot.cmd` shims that launch node with the
|
||
// package's npm-loader.js. The Copilot SDK spawns `path` through node
|
||
// WITHOUT shell:true, and Node >= 18.20 refuses to spawn .cmd/.bat shims
|
||
// (EINVAL), so resolve the shim to the real JS entry before handing it to
|
||
// RuntimeConnection.forStdio — same treatment as the other per-CLI resolvers.
|
||
const shimCandidates = [normalized];
|
||
if (!ext) shimCandidates.push(`${normalized}.cmd`, `${normalized}.bat`);
|
||
|
||
const shimDir = path.dirname(normalized);
|
||
// npm global layout: <prefix>\copilot.cmd + <prefix>\node_modules\@github\copilot\
|
||
// Local project layout: node_modules\.bin\copilot.cmd + ..\@github\copilot\
|
||
const packageRoots = [
|
||
path.join(shimDir, "node_modules", "@github", "copilot"),
|
||
path.join(shimDir, "..", "@github", "copilot"),
|
||
];
|
||
// Loader-first is the default for npm shim resolution. The official 1.0.59
|
||
// loader forwards unchanged arguments to the same platform executable via
|
||
// spawnSync without windowsHide; it does not add runtime initialization.
|
||
// The Copilot SDK driver resolves that installed executable after this step
|
||
// so the SDK can hide and own it directly, retaining the loader as fallback.
|
||
// This opt-in still selects the native entry at the resolver boundary.
|
||
const preferNative = process.env.NETCATTY_COPILOT_PREFER_NATIVE === "1";
|
||
for (const root of packageRoots) {
|
||
if (preferNative) {
|
||
const nativeExe = path.join(
|
||
root, "..", `copilot-${platform}-${process.arch}`, "copilot.exe",
|
||
);
|
||
if (existsSync(nativeExe)) return nativeExe;
|
||
}
|
||
const loaderJs = path.join(root, "npm-loader.js");
|
||
if (existsSync(loaderJs)) return loaderJs;
|
||
}
|
||
|
||
// Fall back to parsing the shim for the npm-loader.js path it references.
|
||
for (const shimPath of shimCandidates) {
|
||
try {
|
||
if (!existsSync(shimPath)) continue;
|
||
const contents = readFileSync(shimPath, "utf8");
|
||
const match = contents.match(/node_modules[\\/]+@github[\\/]copilot[\\/][\w\\/.-]+\.js/i);
|
||
if (match) {
|
||
const loaderJs = path.resolve(path.dirname(shimPath), match[0]);
|
||
if (existsSync(loaderJs)) {
|
||
// Same opt-in native preference as the package-root path above.
|
||
if (preferNative) {
|
||
const nativeExe = path.join(
|
||
path.dirname(loaderJs), "..", `copilot-${platform}-${process.arch}`, "copilot.exe",
|
||
);
|
||
if (existsSync(nativeExe)) return nativeExe;
|
||
}
|
||
return loaderJs;
|
||
}
|
||
}
|
||
} catch {
|
||
// Try the next shim candidate.
|
||
}
|
||
}
|
||
|
||
// Could not locate the JS entry — return the original path unchanged so the
|
||
// caller keeps its previous behavior instead of losing the custom path.
|
||
return normalized;
|
||
}
|
||
|
||
function resolveSdkBinPath(command, shellEnv, platform = process.platform) {
|
||
const raw = resolveCliFromPath(command, shellEnv);
|
||
if (!raw) return null;
|
||
if (platform !== "win32") return raw;
|
||
if (command === "codex") {
|
||
return resolveCodexExecutableForSdk(raw, platform);
|
||
}
|
||
if (command === "claude") {
|
||
return resolveClaudeCodeExecutableForSdk(raw, platform);
|
||
}
|
||
return raw;
|
||
}
|
||
|
||
async function resolveSdkBinPathAsync(command, shellEnv, platform = process.platform) {
|
||
const raw = await resolveCliFromPathAsync(command, shellEnv);
|
||
if (!raw) return null;
|
||
if (platform !== "win32") return raw;
|
||
if (command === "codex") {
|
||
return resolveCodexExecutableForSdk(raw, platform);
|
||
}
|
||
if (command === "claude") {
|
||
return resolveClaudeCodeExecutableForSdk(raw, platform);
|
||
}
|
||
return raw;
|
||
}
|
||
|
||
function resolveCliFromPath(command, shellEnv) {
|
||
// Validate command: only allow valid binary names (alphanumeric, hyphens, underscores, dots)
|
||
if (!command || !/^[a-zA-Z0-9._-]+$/.test(command)) {
|
||
return null;
|
||
}
|
||
|
||
if (shellEnv) {
|
||
try {
|
||
const whichCmd = process.platform === "win32" ? "where" : "which";
|
||
const resolved = execFileSync(whichCmd, [command], {
|
||
encoding: "utf8",
|
||
timeout: 3000,
|
||
stdio: ["pipe", "pipe", "pipe"],
|
||
env: shellEnv,
|
||
}).trim();
|
||
for (const candidate of resolved.split(/\r?\n/)) {
|
||
const normalized = normalizeCliPathForPlatform(candidate);
|
||
if (normalized) return normalized;
|
||
}
|
||
} catch {
|
||
// Not found on PATH
|
||
}
|
||
}
|
||
return null;
|
||
}
|
||
|
||
async function resolveCliFromPathAsync(command, shellEnv) {
|
||
// Validate command: only allow valid binary names (alphanumeric, hyphens, underscores, dots)
|
||
if (!command || !/^[a-zA-Z0-9._-]+$/.test(command)) {
|
||
return null;
|
||
}
|
||
|
||
if (shellEnv) {
|
||
try {
|
||
const whichCmd = process.platform === "win32" ? "where" : "which";
|
||
const { stdout } = await execFileAsync(whichCmd, [command], {
|
||
encoding: "utf8",
|
||
timeout: 3000,
|
||
env: shellEnv,
|
||
});
|
||
const resolved = String(stdout || "").trim();
|
||
for (const candidate of resolved.split(/\r?\n/)) {
|
||
const normalized = normalizeCliPathForPlatform(candidate);
|
||
if (normalized) return normalized;
|
||
}
|
||
} catch {
|
||
// Not found on PATH
|
||
}
|
||
}
|
||
return null;
|
||
}
|
||
|
||
function toUnpackedAsarPath(filePath) {
|
||
const unpackedPath = filePath.replace(/app\.asar([\\/])/, "app.asar.unpacked$1");
|
||
if (unpackedPath !== filePath && existsSync(unpackedPath)) {
|
||
return unpackedPath;
|
||
}
|
||
return filePath;
|
||
}
|
||
|
||
function isPlausibleCliVersionOutput(value) {
|
||
const line = stripAnsi(String(value || "")).trim().split(/\r?\n/)[0]?.trim() || "";
|
||
if (!line) return false;
|
||
if (/^(?:file|node):\/\//i.test(line)) return false;
|
||
if (/^\s*at\s+/i.test(line)) return false;
|
||
if (/\b(?:Error|TypeError|ReferenceError|SyntaxError|ERR_[A-Z_]+)\b/.test(line)) return false;
|
||
return /(?:^|[^\d])v?\d+(?:\.\d+){1,3}(?:[-+][0-9A-Za-z.-]+)?(?:$|[^\d])/.test(line);
|
||
}
|
||
|
||
// ── Shell environment (cached) ──
|
||
|
||
let _cachedShellEnv = null;
|
||
let _shellEnvPromise = null;
|
||
let _shellEnvGeneration = 0;
|
||
|
||
/**
|
||
* Run the user's login shell once to print its PATH. Used as a fallback when
|
||
* the main `-ilc env` capture in getShellEnv fails (layer-0 fix-path).
|
||
*/
|
||
function defaultRunLoginShellPath() {
|
||
let shell = process.env.SHELL || "/bin/zsh";
|
||
if (!path.isAbsolute(shell) || !existsSync(shell)) {
|
||
shell = "/bin/zsh";
|
||
}
|
||
return execFileSync(shell, ["-ilc", 'echo -n "$PATH"'], {
|
||
encoding: "utf8",
|
||
timeout: 4000,
|
||
stdio: ["ignore", "pipe", "ignore"],
|
||
env: { ...process.env, HOME: process.env.HOME || "" },
|
||
});
|
||
}
|
||
|
||
async function defaultRunLoginShellPathAsync() {
|
||
let shell = process.env.SHELL || "/bin/zsh";
|
||
if (!path.isAbsolute(shell) || !existsSync(shell)) {
|
||
shell = "/bin/zsh";
|
||
}
|
||
const { stdout } = await execFileAsync(shell, ["-ilc", 'echo -n "$PATH"'], {
|
||
encoding: "utf8",
|
||
timeout: 4000,
|
||
env: { ...process.env, HOME: process.env.HOME || "" },
|
||
});
|
||
return stdout;
|
||
}
|
||
|
||
/**
|
||
* Union a login-shell PATH ahead of basePath and de-duplicate, so a GUI launch
|
||
* (Finder/Dock) with a stripped PATH still discovers user-installed CLIs.
|
||
* Returns basePath unchanged on win32 or if the login-shell probe fails.
|
||
*/
|
||
function mergeLoginShellPath({
|
||
basePath,
|
||
runLoginShellPath = defaultRunLoginShellPath,
|
||
platform = process.platform,
|
||
delimiter = path.delimiter,
|
||
}) {
|
||
if (platform === "win32") return basePath;
|
||
let shellPath = "";
|
||
try {
|
||
shellPath = String(runLoginShellPath() || "").trim();
|
||
} catch {
|
||
return basePath;
|
||
}
|
||
if (!shellPath) return basePath;
|
||
const seen = new Set();
|
||
const out = [];
|
||
for (const part of [...shellPath.split(delimiter), ...String(basePath || "").split(delimiter)]) {
|
||
const p = part.trim();
|
||
if (p && !seen.has(p)) { seen.add(p); out.push(p); }
|
||
}
|
||
return out.join(delimiter);
|
||
}
|
||
|
||
// ── Windows live PATH refresh ──
|
||
//
|
||
// A GUI-launched Electron process freezes process.env at launch. When a CLI is
|
||
// installed *after* Netcatty starts (its installer appends to the user/system
|
||
// PATH in the registry), a freshly opened cmd/PowerShell sees it but Netcatty
|
||
// does not — and clicking "Refresh" can't help, because process.env never
|
||
// changes for the life of the process. So on Windows we re-read the authoritative
|
||
// PATH from the registry (the value a brand-new shell would inherit) and merge it
|
||
// with the in-process PATH. This mirrors the login-shell PATH probe used on
|
||
// macOS/Linux and fixes CLIs (e.g. CodeBuddy) that "work in cmd" but don't scan.
|
||
|
||
function parseRegQueryPath(stdout) {
|
||
// `reg query` prints e.g.: " Path REG_EXPAND_SZ C:\\a;C:\\b"
|
||
for (const line of String(stdout || "").split(/\r?\n/)) {
|
||
const match = line.match(/^\s*Path\s+REG_(?:EXPAND_)?SZ\s+(.*\S)\s*$/i);
|
||
if (match) return match[1];
|
||
}
|
||
return "";
|
||
}
|
||
|
||
function expandWindowsEnvRefs(value, env = process.env) {
|
||
return String(value || "").replace(/%([^%]+)%/g, (whole, name) => {
|
||
const key = Object.keys(env).find((k) => k.toLowerCase() === String(name).toLowerCase());
|
||
return key && typeof env[key] === "string" ? env[key] : whole;
|
||
});
|
||
}
|
||
|
||
function mergeWindowsPath(...pathStrings) {
|
||
const seen = new Set();
|
||
const out = [];
|
||
for (const str of pathStrings) {
|
||
for (const part of String(str || "").split(";")) {
|
||
const trimmed = part.trim().replace(/^"|"$/g, "");
|
||
if (!trimmed) continue;
|
||
const dedupeKey = trimmed.toLowerCase().replace(/[\\/]+$/, "");
|
||
if (seen.has(dedupeKey)) continue;
|
||
seen.add(dedupeKey);
|
||
out.push(trimmed);
|
||
}
|
||
}
|
||
return out.join(";");
|
||
}
|
||
|
||
function getWindowsKnownCliPathDirs(env = process.env) {
|
||
const dirs = [];
|
||
if (env.APPDATA) dirs.push(path.join(env.APPDATA, "npm"));
|
||
if (env.LOCALAPPDATA) {
|
||
dirs.push(path.join(env.LOCALAPPDATA, "pnpm"));
|
||
dirs.push(path.join(env.LOCALAPPDATA, "Yarn", "bin"));
|
||
}
|
||
return dirs.filter((dir) => existsSync(dir));
|
||
}
|
||
|
||
// Windows appends the user PATH to the machine PATH. Keep that ordering even
|
||
// though both registry queries run concurrently.
|
||
const WINDOWS_PATH_HIVES = [
|
||
"HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment",
|
||
"HKCU\\Environment",
|
||
];
|
||
|
||
async function readWindowsRegistryPaths({
|
||
exec = execFileAsync,
|
||
env = process.env,
|
||
timeoutMs = 1000,
|
||
} = {}) {
|
||
return Promise.all(WINDOWS_PATH_HIVES.map(async (hive) => {
|
||
let timer;
|
||
try {
|
||
// The JS deadline also bounds an unresponsive process callback. The
|
||
// child-process timeout remains responsible for terminating reg.exe.
|
||
const result = await Promise.race([
|
||
exec("reg", ["query", hive, "/v", "Path"], {
|
||
encoding: "utf8",
|
||
timeout: timeoutMs,
|
||
windowsHide: true,
|
||
}),
|
||
new Promise((resolve) => {
|
||
timer = setTimeout(() => resolve(null), timeoutMs);
|
||
}),
|
||
]);
|
||
return result ? expandWindowsEnvRefs(parseRegQueryPath(result.stdout), env) : null;
|
||
} catch {
|
||
return null;
|
||
} finally {
|
||
clearTimeout(timer);
|
||
}
|
||
}));
|
||
}
|
||
|
||
async function readWindowsRegistryPath(options) {
|
||
return mergeWindowsPath(...await readWindowsRegistryPaths(options));
|
||
}
|
||
|
||
// Share a short-lived registry snapshot across simultaneous local terminals.
|
||
// Cache raw values so each terminal expands references using its own env.
|
||
function createWindowsLivePathResolver({
|
||
exec = execFileAsync,
|
||
now = Date.now,
|
||
ttlMs = 5000,
|
||
timeoutMs = 1000,
|
||
} = {}) {
|
||
const cachedPaths = [null, null];
|
||
let refreshedAt = -Infinity;
|
||
let pending = null;
|
||
|
||
return async function resolveWindowsLivePath({
|
||
basePath,
|
||
env = process.env,
|
||
platform = process.platform,
|
||
knownCliDirs = getWindowsKnownCliPathDirs,
|
||
} = {}) {
|
||
if (platform !== "win32") return basePath;
|
||
if (!pending && now() - refreshedAt >= ttlMs) {
|
||
pending = readWindowsRegistryPaths({ exec, env: {}, timeoutMs })
|
||
.then((paths) => {
|
||
// A failed hive retains its last successful value; one unavailable
|
||
// hive must not discard the other half of a cached PATH.
|
||
paths.forEach((value, index) => {
|
||
if (value !== null) cachedPaths[index] = value;
|
||
});
|
||
refreshedAt = now();
|
||
})
|
||
.finally(() => { pending = null; });
|
||
}
|
||
if (pending) await pending;
|
||
|
||
let knownDirs = "";
|
||
try {
|
||
knownDirs = (knownCliDirs(env) || []).join(";");
|
||
} catch { /* Best-effort fallback only. */ }
|
||
|
||
const registryPath = expandWindowsEnvRefs(mergeWindowsPath(...cachedPaths), env);
|
||
if (!registryPath && !knownDirs) return basePath;
|
||
// Registry order reflects a fresh shell; inherited entries remain a
|
||
// fallback, and guessed package-manager bins must never take precedence.
|
||
// With no machine snapshot, retain inherited system precedence rather
|
||
// than accidentally promoting user directories above system binaries.
|
||
return cachedPaths[0] === null
|
||
? mergeWindowsPath(basePath || "", registryPath, knownDirs)
|
||
: mergeWindowsPath(registryPath, basePath || "", knownDirs);
|
||
};
|
||
}
|
||
|
||
const resolveWindowsLivePath = createWindowsLivePathResolver();
|
||
|
||
async function getShellEnv() {
|
||
if (_cachedShellEnv) return _cachedShellEnv;
|
||
if (_shellEnvPromise) return _shellEnvPromise;
|
||
|
||
const generation = _shellEnvGeneration;
|
||
_shellEnvPromise = (async () => {
|
||
const home = process.env.HOME || "";
|
||
const extraPaths = [
|
||
`${home}/.local/bin`,
|
||
`${home}/.npm-global/bin`,
|
||
"/usr/local/bin",
|
||
"/opt/homebrew/bin",
|
||
];
|
||
|
||
if (process.platform === "win32") {
|
||
// Re-read the live PATH from the registry so CLIs installed after launch
|
||
// (e.g. CodeBuddy) are discoverable without restarting Netcatty, then fold
|
||
// in well-known npm/pnpm/yarn global bin dirs as a belt-and-suspenders.
|
||
let registryPath = "";
|
||
try {
|
||
registryPath = await readWindowsRegistryPath();
|
||
} catch {
|
||
registryPath = "";
|
||
}
|
||
const knownDirs = getWindowsKnownCliPathDirs().join(path.delimiter);
|
||
const nextEnv = {
|
||
...process.env,
|
||
PATH: mergeWindowsPath(registryPath, process.env[getPathEnvKey(process.env, "win32")] || "", knownDirs),
|
||
};
|
||
if (generation === _shellEnvGeneration) {
|
||
_cachedShellEnv = nextEnv;
|
||
}
|
||
return nextEnv;
|
||
}
|
||
|
||
// On macOS/Linux, spawn a login shell to capture the real environment.
|
||
try {
|
||
let shell = process.env.SHELL || "/bin/zsh";
|
||
if (!path.isAbsolute(shell) || !existsSync(shell)) {
|
||
shell = "/bin/zsh";
|
||
}
|
||
const { stdout: envOutput } = await execFileAsync(shell, ['-ilc', 'env'], {
|
||
encoding: "utf8",
|
||
timeout: 10000,
|
||
env: { ...process.env, HOME: home },
|
||
});
|
||
const envMap = {};
|
||
for (const line of envOutput.split("\n")) {
|
||
const idx = line.indexOf("=");
|
||
if (idx > 0) {
|
||
envMap[line.slice(0, idx)] = line.slice(idx + 1);
|
||
}
|
||
}
|
||
const shellPath = envMap.PATH || "";
|
||
const mergedPath = [...extraPaths, shellPath, process.env.PATH || ""].join(path.delimiter);
|
||
// Layer-0 fix-path: front-load + de-duplicate the login-shell PATH we just
|
||
// captured (reuse the `-ilc env` result above — no second shell spawn).
|
||
const nextEnv = {
|
||
...envMap,
|
||
...process.env,
|
||
PATH: mergeLoginShellPath({ basePath: mergedPath, runLoginShellPath: () => shellPath }),
|
||
};
|
||
if (generation === _shellEnvGeneration) {
|
||
_cachedShellEnv = nextEnv;
|
||
}
|
||
return nextEnv;
|
||
} catch {
|
||
// `-ilc env` failed — try a lighter login-shell PATH probe as a fallback so
|
||
// GUI-launch PATH stripping still doesn't break CLI discovery (layer-0).
|
||
const basePath = [...extraPaths, process.env.PATH || ""].join(path.delimiter);
|
||
let loginShellPath = "";
|
||
try {
|
||
loginShellPath = await defaultRunLoginShellPathAsync();
|
||
} catch {
|
||
loginShellPath = "";
|
||
}
|
||
const nextEnv = {
|
||
...process.env,
|
||
PATH: mergeLoginShellPath({
|
||
basePath,
|
||
runLoginShellPath: () => loginShellPath,
|
||
}),
|
||
};
|
||
if (generation === _shellEnvGeneration) {
|
||
_cachedShellEnv = nextEnv;
|
||
}
|
||
return nextEnv;
|
||
}
|
||
})().finally(() => {
|
||
if (generation === _shellEnvGeneration) {
|
||
_shellEnvPromise = null;
|
||
}
|
||
});
|
||
|
||
return _shellEnvPromise;
|
||
}
|
||
|
||
/**
|
||
* Drop the shell-env cache so the next getShellEnv() call re-spawns the
|
||
* login shell. Useful when the user has just exported a new variable in
|
||
* their rc file and clicks "Refresh Status" without restarting the app.
|
||
*/
|
||
function invalidateShellEnvCache() {
|
||
_shellEnvGeneration += 1;
|
||
_cachedShellEnv = null;
|
||
_shellEnvPromise = null;
|
||
}
|
||
|
||
module.exports = {
|
||
stripAnsi,
|
||
formatSyntheticEcho,
|
||
extractTrailingIdlePrompt,
|
||
getFreshIdlePrompt,
|
||
getVisibleIdlePrompt,
|
||
computeOsc133ReadyState,
|
||
isDefaultPowerShellPromptLine,
|
||
isDefaultCmdPromptLine,
|
||
isDefaultPosixPromptLine,
|
||
trackSessionIdlePrompt,
|
||
looksLikeIdleAutoLogout,
|
||
isLocalhostHostname,
|
||
extractFirstNonLocalhostUrl,
|
||
normalizeCliPathForPlatform,
|
||
shouldUseShellForCommand,
|
||
quoteWindowsShellArg,
|
||
buildWindowsShellCommandLine,
|
||
prepareCommandForSpawn,
|
||
resolveWindowsShimToNativeExe,
|
||
resolveClaudeCodeExecutableForSdk,
|
||
normalizeClaudeCodeExecutableEnvForSdk,
|
||
resolveCodexExecutableForSdk,
|
||
addCodexExecutableEnvForSdk,
|
||
resolveCodebuddyExecutableForSdk,
|
||
resolveCopilotExecutableForSdk,
|
||
resolveSdkBinPath,
|
||
resolveSdkBinPathAsync,
|
||
resolveCliFromPath,
|
||
resolveCliFromPathAsync,
|
||
toUnpackedAsarPath,
|
||
isPlausibleCliVersionOutput,
|
||
mergeLoginShellPath,
|
||
getPathEnvKey,
|
||
parseRegQueryPath,
|
||
expandWindowsEnvRefs,
|
||
mergeWindowsPath,
|
||
readWindowsRegistryPath,
|
||
createWindowsLivePathResolver,
|
||
resolveWindowsLivePath,
|
||
getShellEnv,
|
||
invalidateShellEnvCache,
|
||
};
|