Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

fix(agent): selectable TUI text, system-tag stripping, and user@host @-path parsing (#8598)

Thinh Lef20a7be85bc1
diff --git a/src-tauri/src/core/cli/path_refs.rs b/src-tauri/src/core/cli/path_refs.rs
index 05513c36c..b2bd6fb36 100644
--- a/src-tauri/src/core/cli/path_refs.rs
+++ b/src-tauri/src/core/cli/path_refs.rs
@@ -11,6 +11,8 @@
//! * Images are noted inline as `(image: image/mime)` markers.
//! * Missing/unreadable items surface as inline error notices.
//! * `@http://` / `@https://` / `@file://` prefixed tokens are skipped.
+//! * `user@host`, emails and bare IPv4 tokens are not references and pass
+//! through untouched.
//! * Once resolved, the `@path` tokens are removed from the text so the model
//! sees the content directly via the injected block, not raw `@` tokens.
@@ -18,14 +20,52 @@ use std::io::Read;
use std::path::{Path, PathBuf};
use once_cell::sync::Lazy;
-/// Regex matching `@path` references.
-/// The path stops at whitespace or common punctuation.
+/// Regex scanning `@token` candidates in text; `ref_matches` applies the
+/// reference rules (boundary, URL, IPv4) on top of this token scan.
static REFERENCE_RE: Lazy<regex::Regex> = Lazy::new(|| {
// Using a raw string with hash delimiters avoids escaping quotes and backticks.
// The negated character class excludes tokens that would make bad paths.
regex::Regex::new(r###"@([^\s,;:!?'"`\[\](){}<>)\)]+)"###).unwrap()
});
+/// True when `at_idx` in `text` is the start of a reference token: the `@` is
+/// at the start of the text, or the char immediately before it is not a word
+/// character (ASCII letter/digit/underscore). This keeps `user@host` and
+/// `[email protected]` from being read as `@path` references while `@path`,
+/// `(@path)` and text in scripts without spaces still resolve.
+/// Non-ASCII letters (e.g. `看@path`) deliberately count as boundaries so CJK
+/// text can reference files without a preceding space.
+fn is_ref_start(text: &str, at_idx: usize) -> bool {
+ match text[..at_idx].chars().next_back() {
+ None => true,
+ Some(c) => !(c.is_ascii_alphanumeric() || c == '_'),
+ }
+}
+
+/// True for tokens shaped like an IPv4 address (`1.2.3.4`), which are never
+/// file paths. A trailing period (sentence punctuation) is ignored.
+fn is_ipv4_like(raw: &str) -> bool {
+ let raw = raw.trim_end_matches('.');
+ let octets: Vec<&str> = raw.split('.').collect();
+ octets.len() == 4
+ && octets
+ .iter()
+ .all(|o| !o.is_empty() && o.len() <= 3 && o.bytes().all(|b| b.is_ascii_digit()))
+}
+
+/// Iterate over `@token` spans in `text` that qualify as file references: the
+/// `@` must start a token (not be glued to a preceding word char) and the
+/// token must look like a path (not an `http`/`file://` URL or bare IPv4).
+fn ref_matches(text: &str) -> impl Iterator<Item = regex::Match<'_>> {
+ REFERENCE_RE.find_iter(text).filter(|m| {
+ let raw = &text[m.start() + 1..m.end()];
+ is_ref_start(text, m.start())
+ && !raw.starts_with("http")
+ && !raw.starts_with("file://")
+ && !is_ipv4_like(raw)
+ })
+}
+
/// Maximum bytes we will read from a single file.
const MAX_FILE_BYTES: u64 = 1024 * 1024;
@@ -37,20 +77,26 @@ const IMAGE_EXTS: &[&str] = &["jpg", "jpeg", "png", "gif", "webp", "bmp", "svg"]
// ── Public API ───────────────────────────────────────────────────────────────
+/// Index of the last `@` in `text` that starts a reference token, if any.
+/// Uses the same rules as `ref_matches`; a trailing bare `@` (empty query)
+/// still counts so the TUI hint popup can open with an empty search.
+pub fn last_ref_start(text: &str) -> Option<usize> {
+ if let Some(idx) = text.len().checked_sub(1) {
+ if text.ends_with('@') && is_ref_start(text, idx) {
+ return Some(idx);
+ }
+ }
+ ref_matches(text).map(|m| m.start()).last()
+}
+
/// Parse `@path` references from `text`.
///
/// Returns the raw path strings in order of appearance (deduplicated).
pub fn parse_references(text: &str) -> Vec<String> {
let mut seen = std::collections::HashSet::new();
let mut refs = Vec::new();
- for cap in REFERENCE_RE.captures_iter(text) {
- let raw = cap[1].trim();
- if raw.is_empty()
- || raw.starts_with("http")
- || raw.starts_with("file://")
- {
- continue;
- }
+ for m in ref_matches(text) {
+ let raw = &text[m.start() + 1..m.end()];
if seen.insert(raw.to_string()) {
refs.push(raw.to_string());
}
@@ -60,10 +106,17 @@ pub fn parse_references(text: &str) -> Vec<String> {
/// Remove all `@path` references from `text` and normalise whitespace.
pub fn strip_references(text: &str) -> String {
- let cleaned = REFERENCE_RE.replace_all(text, "");
- let mut result = String::with_capacity(cleaned.len());
+ let mut kept = String::with_capacity(text.len());
+ let mut last = 0;
+ for m in ref_matches(text) {
+ kept.push_str(&text[last..m.start()]);
+ last = m.end();
+ }
+ kept.push_str(&text[last..]);
+
+ let mut result = String::with_capacity(kept.len());
let mut prev_space = false;
- for ch in cleaned.chars() {
+ for ch in kept.chars() {
if ch.is_whitespace() {
if !prev_space {
result.push(' ');
@@ -322,4 +375,86 @@ mod tests {
assert_eq!(clean, "plain text");
assert!(block.is_empty());
}
+
+ #[test]
+ fn test_ssh_address_not_a_reference() {
+ // Regression: `ssh [email protected]` must survive verbatim.
+ let text = "please use bash to ssh [email protected]";
+ assert!(parse_references(text).is_empty());
+
+ let text = "please use bash to ssh [email protected]";
+ assert!(parse_references(text).is_empty());
+
+ let dir = std::env::temp_dir().join("path_ref_test_ssh");
+ let (clean, block) = resolve_references(text, &dir);
+ assert_eq!(clean, text);
+ assert!(block.is_empty());
+ }
+
+ #[test]
+ fn test_email_not_a_reference() {
+ let refs = parse_references("mail me at [email protected] please");
+ assert!(refs.is_empty());
+ }
+
+ #[test]
+ fn test_bare_ip_after_space_not_a_reference() {
+ let refs = parse_references("use bash to ssh @44.50.0.89 now");
+ assert!(refs.is_empty());
+
+ // Sentence-final trailing period must not turn it into a path either.
+ let refs = parse_references("please ping @44.50.0.89.");
+ assert!(refs.is_empty());
+ }
+
+ #[test]
+ fn test_reference_with_rest_of_query_survives() {
+ // The reference resolves, and the rest of the query stays intact.
+ let refs = parse_references("use @README.md to check the build steps");
+ assert_eq!(refs, vec!["README.md"]);
+
+ let dir = std::env::temp_dir().join("path_ref_test_rest");
+ let _ = std::fs::create_dir_all(&dir);
+ std::fs::write(dir.join("README.md"), b"build steps here").unwrap();
+ let (clean, block) = resolve_references("use @README.md to check the build steps", &dir);
+ assert_eq!(clean, "use to check the build steps");
+ assert!(block.contains("build steps here"));
+ }
+
+ #[test]
+ fn test_reference_with_hyphen() {
+ let refs = parse_references("diff @my-file.txt against main");
+ assert_eq!(refs, vec!["my-file.txt"]);
+ }
+
+ #[test]
+ fn test_reference_still_parsed_with_boundaries() {
+ let refs = parse_references("open @src/main.ts and (@README.md) and 看@docs/guide.md");
+ assert_eq!(refs, vec!["src/main.ts", "README.md", "docs/guide.md"]);
+ }
+
+ #[test]
+ fn test_strip_keeps_ssh_address() {
+ let cleaned = strip_references("see @src/main.ts and ssh [email protected]");
+ assert_eq!(cleaned, "see and ssh [email protected]");
+ }
+
+ #[test]
+ fn test_last_ref_start() {
+ assert_eq!(last_ref_start("ssh [email protected]"), None);
+ assert_eq!(last_ref_start("mail [email protected]"), None);
+ assert_eq!(last_ref_start("ping @44.50.0.89 now"), None);
+ assert_eq!(
+ last_ref_start("check @src/main.ts and ssh user@host"),
+ Some("check ".len())
+ );
+ assert_eq!(last_ref_start("see (@README.md)"), Some("see (".len()));
+ // Last of several qualifying references wins.
+ assert_eq!(last_ref_start("check @a and @b"), Some("check @a and ".len()));
+ // A bare trailing `@` is still a hint trigger (empty query).
+ assert_eq!(last_ref_start("@"), Some(0));
+ assert_eq!(last_ref_start("check @"), Some(6));
+ // But a mid-word `@` never is, even at the end.
+ assert_eq!(last_ref_start("ssh user@"), None);
+ }
}
diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rs
index 9a1aa5ef5..8e11d3600 100644
--- a/src-tauri/src/core/cli/tui.rs
+++ b/src-tauri/src/core/cli/tui.rs
@@ -820,7 +820,7 @@ impl App {
last_scroll: 0,
row_index: Vec::new(),
run_started: None,
- mouse_capture: true,
+ mouse_capture: false,
message_queue: std::collections::VecDeque::new(),
todos: crate::core::agent::todo::TodoList::default(),
todo_call_this_turn: false,
@@ -933,8 +933,9 @@ impl App {
/// through markdown, each `<think>` block folded to a one-line summary row
/// whose full dimmed detail is retained for expansion.
fn push_assistant_blocks(&mut self, text: &str) {
+ let text = strip_system_xml_tags(text);
let width = self.render_width();
- for (reasoning, seg) in split_reasoning(text) {
+ for (reasoning, seg) in split_reasoning(&text) {
if seg.trim().is_empty() {
continue;
}
@@ -1153,10 +1154,11 @@ impl App {
/// Extract the current `@query` from the input buffer, if any.
/// Returns `None` when the cursor is not inside or immediately after
- /// a `@`-prefixed token (no space since the `@`).
+ /// a `@`-prefixed token (no space since the `@`), or when the `@` does
+ /// not start a token (e.g. `user@host` is not a file reference).
fn path_hint_query(&self) -> Option<String> {
let before = &self.input[..self.cursor];
- let at_idx = before.rfind('@')?;
+ let at_idx = path_refs::last_ref_start(before)?;
let after_at = &before[at_idx + 1..];
if after_at.contains(' ') {
return None; // space after @ means the token ended
@@ -1199,7 +1201,7 @@ impl App {
let sel = self.path_hint_selected.min(self.path_hints.len() - 1);
let selected = &self.path_hints[sel];
let before = &self.input[..self.cursor];
- let at_idx = match before.rfind('@') {
+ let at_idx = match path_refs::last_ref_start(before) {
Some(i) => i,
None => return,
};
@@ -3009,6 +3011,29 @@ fn assistant_has_content(text: &str) -> bool {
.any(|(_, seg)| !seg.trim().is_empty())
}
+/// Regex matching `<system>`, `<system-notice>`, `<system-directive>`,
+/// `<system-conventions>`, etc. - any XML tag named `system` or `system-*`.
+/// Complete tags (`<system-notice>...</system-notice>`) are matched first; when
+/// no closing tag exists, everything from the opening tag to end-of-string is
+/// consumed. A bare word like `<systemic>` is not a tag and passes through.
+fn system_tag_re() -> &'static regex::Regex {
+ use std::sync::LazyLock;
+ static RE: LazyLock<regex::Regex> = LazyLock::new(|| {
+ regex::Regex::new(
+ r"(?s)<system(?:-[a-zA-Z]+)?>.*?</system(?:-[a-zA-Z]+)?>|<system(?:-[a-zA-Z]+)?>.*$",
+ )
+ .unwrap()
+ });
+ &RE
+}
+
+/// Strip harness-injected `<system...>` XML tags from assistant text so the
+/// user never sees raw markup. These tags carry internal instructions that
+/// should not be rendered in the TUI transcript.
+fn strip_system_xml_tags(text: &str) -> String {
+ system_tag_re().replace_all(text, "").to_string()
+}
+
fn spawn_run(args: &Arc<OrchestrationArgs>, body: serde_json::Value) -> CurrentRun {
let (tx, rx) = mpsc::unbounded_channel::<StreamEvent>();
let args = Arc::clone(args);
@@ -3205,8 +3230,10 @@ pub async fn run(
enable_raw_mode().map_err(|e| e.to_string())?;
let mut stdout = io::stdout();
- execute!(stdout, EnterAlternateScreen, EnableBracketedPaste, EnableMouseCapture)
- .map_err(|e| e.to_string())?;
+ // Mouse capture stays off by default so terminal text is selectable/copyable
+ // (Ctrl-T enables click-to-expand). `chat_loop` diffs against
+ // `app.mouse_capture` and enables it on the first tick if the user toggles.
+ execute!(stdout, EnterAlternateScreen, EnableBracketedPaste).map_err(|e| e.to_string())?;
let backend = CrosstermBackend::new(stdout);
let mut terminal = Terminal::new(backend).map_err(|e| e.to_string())?;
@@ -3285,9 +3312,9 @@ async fn chat_loop<B: Backend>(
) -> Result<(), String> {
let mut current: Option<CurrentRun> = None;
let mut ticker = tokio::time::interval(Duration::from_millis(50));
- // Mirrors app.mouse_capture; `run` enables capture on the real terminal
- // before this loop starts, so both start in sync.
- let mut mouse_capture_active = true;
+ // Mirrors app.mouse_capture; `run` sets the real terminal to the same
+ // state before this loop starts, so both start in sync.
+ let mut mouse_capture_active = false;
// Active MCP servers connect in the background; gate the first run on them
// so the model's tools (collected once per run) are ready.
@@ -4269,7 +4296,7 @@ const KEY_BINDINGS: &[(&str, &str)] = &[
("↑/↓", "Scroll the transcript"),
("Ctrl-O", "Expand or collapse all tool calls"),
("Ctrl-V", "Paste an image from the clipboard"),
- ("Ctrl-T", "Toggle mouse capture off to select/copy text"),
+ ("Ctrl-T", "Toggle mouse capture (click-to-expand vs text select)"),
("Ctrl-D", "Quit"),
];
@@ -6283,11 +6310,16 @@ fn header(app: &App) -> Paragraph<'static> {
Span::raw(format!(" {} ", app.model)),
];
// Wall-clock (local) segment, mirroring the reference status line's leading
- // HH:MM:SS. Recomputed each frame so it ticks in place.
- spans.push(Span::styled(
- format!(" {}", chrono::Local::now().format("%H:%M:%S")),
- Style::new().dim(),
- ));
+ // HH:MM:SS. Shown only while a run is active: a clock that ticks once per
+ // second repaints the screen every second, which clears the terminal's text
+ // selection mid-drag. An idle frame must be fully static so the transcript
+ // stays selectable/copyable (the 50ms ticker then emits no output at all).
+ if app.run_started.is_some() {
+ spans.push(Span::styled(
+ format!(" {}", chrono::Local::now().format("%H:%M:%S")),
+ Style::new().dim(),
+ ));
+ }
spans.push(Span::raw(format!(" {turn}")));
if app.tokens > 0 {
spans.push(Span::raw(format!(
@@ -6723,8 +6755,9 @@ mod tests {
note_update, open_config_screen,
parse_command, partial_json_field, restore_goal, restore_run_mode, restore_todos,
run_command, starting_call_lines, unescape_partial_json_string,
- running_group_row, split_reasoning, subagent_activity, subagent_name_from_run_id,
- summarize_result, tilde_path, tokens_per_second, tool_activity, tool_finished,
+ running_group_row, split_reasoning, strip_system_xml_tags, subagent_activity,
+ subagent_name_from_run_id, summarize_result, tilde_path, tokens_per_second,
+ tool_activity, tool_finished,
transcript_top_padding,
user_content_parts, App, CurrentRun, Pending, PendingImage, PickerKind, ResumeTarget,
SnapshotJob, Status, DIFF_MAX_ROWS, KEY_BINDINGS, SLASH_COMMANDS, SPINNER,
@@ -7178,6 +7211,38 @@ mod tests {
assert_eq!(segs, vec![(true, "reasoning tail".to_string())]);
}
+ #[test]
+ fn strip_system_xml_tags_removes_system_blocks() {
+ assert_eq!(
+ strip_system_xml_tags(
+ "answer<system-notice>internal nudge</system-notice>tail"
+ ),
+ "answertail"
+ );
+ }
+
+ #[test]
+ fn strip_system_xml_tags_removes_multiline_and_unterminated() {
+ assert_eq!(
+ strip_system_xml_tags(
+ "a<system-directive>\nline one\nline two</system-directive>b"
+ ),
+ "ab"
+ );
+ assert_eq!(
+ strip_system_xml_tags("a<system-notice>never closed"),
+ "a"
+ );
+ }
+
+ #[test]
+ fn strip_system_xml_tags_keeps_plain_text() {
+ assert_eq!(
+ strip_system_xml_tags("no tags here <systemic> not a tag"),
+ "no tags here <systemic> not a tag"
+ );
+ }
+
#[test]
fn live_tail_dims_open_think_block_instead_of_stripping() {
use ratatui::{backend::TestBackend, Terminal};
@@ -9478,17 +9543,17 @@ mod tests {
#[tokio::test]
async fn ctrl_t_toggles_mouse_capture() {
let mut app = test_app();
- assert!(app.mouse_capture, "capture starts on");
+ assert!(!app.mouse_capture, "capture starts off so text is selectable");
let registry: PermissionRegistry = Arc::new(tokio::sync::Mutex::new(HashMap::new()));
let mcp_servers: crate::core::state::SharedMcpServers =
Arc::new(tokio::sync::Mutex::new(HashMap::new()));
let mut current: Option<CurrentRun> = None;
let key = KeyEvent::new(KeyCode::Char('t'), KeyModifiers::CONTROL);
- handle_key(&mut app, key, &registry, &mut current, &mcp_servers).await;
- assert!(!app.mouse_capture);
handle_key(&mut app, key, &registry, &mut current, &mcp_servers).await;
assert!(app.mouse_capture);
+ handle_key(&mut app, key, &registry, &mut current, &mcp_servers).await;
+ assert!(!app.mouse_capture);
}
#[tokio::test]
diff --git a/web-app/src/containers/ChatInput.tsx b/web-app/src/containers/ChatInput.tsx
index 99f95e125..f032531f8 100644
--- a/web-app/src/containers/ChatInput.tsx
+++ b/web-app/src/containers/ChatInput.tsx
@@ -105,7 +105,7 @@ import {
parsePromptForReferences,
resolvePathReference,
searchFiles,
- REFERENCE_PATTERN,
+ stripPromptReferences,
type FilePickerEntry as FileEntry,
} from '@/lib/path-references'
import { FilePickerPopover } from '@/components/FilePickerPopover'
@@ -236,9 +236,11 @@ const ChatInput = memo(function ChatInput({
const cursorIdx = filePickerCursorPos.current ?? value.length
- // Look backwards from current cursor to find the last word starting with @
+ // Look backwards from current cursor to find the last word starting with
+ // @ (the @ must not be glued to a preceding word char, so `user@host`
+ // never opens the picker)
const beforeCursor = value.slice(0, cursorIdx)
- const atMatch = beforeCursor.match(/@([\w.\/-]*)$/)
+ const atMatch = beforeCursor.match(/(?<![A-Za-z0-9_])@([\w.\/-]*)$/)
if (atMatch) {
const query = atMatch[1] ?? ''
@@ -280,7 +282,7 @@ const ChatInput = memo(function ChatInput({
const afterCursor = prompt.slice(filePickerCursorPos.current)
// Replace the `@query` with `path/to/file` (the resolved reference)
- const textBefore = beforeCursor.replace(/@[\w.\/-]*$/, '')
+ const textBefore = beforeCursor.replace(/(?<![A-Za-z0-9_])@[\w.\/-]*$/, '')
const refText = entry.path
const newPrompt = textBefore + refText + afterCursor
@@ -332,7 +334,7 @@ const ChatInput = memo(function ChatInput({
// Remove @ references from the prompt text (they'll be replaced by the
// resolved contents above so the model sees the content directly)
- const cleanText = text.replace(REFERENCE_PATTERN, '').replace(/\s+/g, ' ').trim()
+ const cleanText = stripPromptReferences(text)
return { text: cleanText, resolvedContents }
},
diff --git a/web-app/src/lib/__tests__/path-references.test.ts b/web-app/src/lib/__tests__/path-references.test.ts
new file mode 100644
index 000000000..a0717b967
--- /dev/null
+++ b/web-app/src/lib/__tests__/path-references.test.ts
@@ -0,0 +1,57 @@
+import { describe, expect, it, vi } from 'vitest'
+import {
+ parsePromptForReferences,
+ stripPromptReferences,
+} from '../path-references'
+
+vi.mock('@janhq/core', () => ({
+ fs: {},
+}))
+
+describe('parsePromptForReferences', () => {
+ it('does not treat ssh/email addresses as references', () => {
+ expect(
+ parsePromptForReferences('please use bash to ssh [email protected]')
+ ).toEqual([])
+ expect(
+ parsePromptForReferences('please use bash to ssh [email protected]')
+ ).toEqual([])
+ expect(parsePromptForReferences('mail me at [email protected] please')).toEqual(
+ []
+ )
+ })
+
+ it('does not treat bare IPv4 as a reference, even with a trailing period', () => {
+ expect(parsePromptForReferences('use bash to ssh @44.50.0.89 now')).toEqual(
+ []
+ )
+ expect(parsePromptForReferences('please ping @44.50.0.89.')).toEqual([])
+ })
+
+ it('parses references and keeps the rest of the query', () => {
+ expect(
+ parsePromptForReferences('use @README.md to check the build steps')
+ ).toEqual(['README.md'])
+ expect(parsePromptForReferences('diff @my-file.txt against main')).toEqual(
+ ['my-file.txt']
+ )
+ expect(
+ parsePromptForReferences('open @src/main.ts and (@README.md)')
+ ).toEqual(['src/main.ts', 'README.md'])
+ })
+})
+
+describe('stripPromptReferences', () => {
+ it('strips references but keeps ssh/email addresses', () => {
+ expect(
+ stripPromptReferences('see @src/main.ts and ssh [email protected]')
+ ).toBe('see and ssh [email protected]')
+ })
+
+ it('keeps non-reference text intact', () => {
+ expect(stripPromptReferences('no refs here')).toBe('no refs here')
+ expect(stripPromptReferences('ssh [email protected]')).toBe(
+ )
+ })
+})
diff --git a/web-app/src/lib/path-references.ts b/web-app/src/lib/path-references.ts
index 2e6f62f35..c55d2bb72 100644
--- a/web-app/src/lib/path-references.ts
+++ b/web-app/src/lib/path-references.ts
@@ -15,8 +15,12 @@ export type { FilePickerEntry }
// ── Exports ──────────────────────────────────────────────────────────────────
-/** Regex matching @path references in text. */
-export const REFERENCE_PATTERN = /@([^\s,;:!?'"`)\]}>]+)/g
+/**
+ * Regex scanning `@token` candidates in text. The `@` must not be glued to a
+ * preceding word char, so `user@host` and `[email protected]` are not references;
+ * `isReferenceToken` applies the remaining rules (URL, IPv4) on top.
+ */
+export const REFERENCE_PATTERN = /(?<![A-Za-z0-9_])@([^\s,;:!?'"`)\]}>]+)/g
/** Maximum bytes we'll read from a single file. */
const MAX_FILE_BYTES = 1 * 1024 * 1024
@@ -35,6 +39,29 @@ const CODE_EXTS = new Set([
'html', 'sh', 'bash', 'zsh', 'sql', 'graphql',
])
+/** True for tokens shaped like an IPv4 address (`1.2.3.4`), which are never
+ * file paths. A trailing period (sentence punctuation) is ignored. */
+function isIpv4Like(raw: string): boolean {
+ const trimmed = raw.replace(/\.+$/, '')
+ const octets = trimmed.split('.')
+ return (
+ octets.length === 4 &&
+ octets.every((o) => o.length > 0 && o.length <= 3 && /^\d+$/.test(o))
+ )
+}
+
+/** True when a captured token qualifies as a file reference. */
+function isReferenceToken(raw: string): boolean {
+ return (
+ raw.length > 0 &&
+ !raw.startsWith('http://') &&
+ !raw.startsWith('https://') &&
+ !raw.startsWith('file://') &&
+ !raw.includes('@') &&
+ !isIpv4Like(raw)
+ )
+}
+
// ── Parsing references from text ─────────────────────────────────────────────
/**
@@ -46,17 +73,8 @@ export function parsePromptForReferences(text: string): string[] {
const refs: string[] = []
let match: RegExpExecArray | null
while ((match = REFERENCE_PATTERN.exec(text)) !== null) {
- const raw = match[1].trim()
- // Skip obvious non-paths
- if (
- !raw ||
- raw.startsWith('http://') ||
- raw.startsWith('https://') ||
- raw.startsWith('file://') ||
- raw.includes('@') ||
- raw === ''
- )
- continue
+ const raw = match[1]
+ if (!isReferenceToken(raw)) continue
if (!seen.has(raw)) {
seen.add(raw)
refs.push(raw)
@@ -65,6 +83,17 @@ export function parsePromptForReferences(text: string): string[] {
return refs
}
+/**
+ * Remove qualified @path references from `text`, leaving non-reference `@`
+ * tokens (ssh/email addresses, bare IPs) intact, and normalise whitespace.
+ */
+export function stripPromptReferences(text: string): string {
+ const cleaned = text.replace(REFERENCE_PATTERN, (match, raw: string) =>
+ isReferenceToken(raw) ? '' : match
+ )
+ return cleaned.replace(/\s+/g, ' ').trim()
+}
+
/**
* Format a path as a @reference text for insertion into the prompt.
*/