@causyne/agent 1.20.35 → 1.20.38
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/LICENSE +1 -1
- package/package.json +1 -1
- package/src/agentLoop.js +77 -9
- package/src/agentLoop.ts +68 -8
- package/src/contextManager.js +15 -1
- package/src/historyPruner.js +43 -5
- package/src/historyPruner.ts +38 -5
- package/src/smartToolsUse.js +9 -5
- package/src/smartToolsUse.ts +10 -5
- package/src/tools/sysRun.js +22 -6
- package/src/tools/sysRun.ts +23 -6
- package/src/tui/chatRenderer.js +39 -46
- package/src/tui/homeView.js +0 -1
- package/src/tui/homeView.ts +0 -1
- package/src/tui/markdownMath.js +250 -0
- package/src/tui/markdownMath.ts +263 -0
- package/src/tui/messageActionPlacement.js +79 -8
- package/src/tui/messageActionPlacement.ts +102 -9
- package/src/tui/messageInteraction.js +43 -9
- package/src/tui/messageInteraction.ts +51 -17
- package/src/tui/overlay.js +191 -192
- package/src/tui/overlay.ts +320 -0
- package/src/tui/prompt.js +4 -1
- package/src/tui/stageSurface.js +4 -1
- package/src/tui/text.js +204 -208
- package/src/tui/text.ts +360 -0
- package/src/tui/toolOutputNormalizer.js +210 -0
- package/src/tui/toolOutputNormalizer.ts +229 -0
- package/src/tui/turnRail.js +11 -1
- package/src/tui/turnRail.ts +11 -1
- package/src/tui/text.d.ts +0 -7
package/src/tui/chatRenderer.js
CHANGED
|
@@ -25,6 +25,8 @@ import { composerWidth, openingRows, sessionRows } from './layout.js';
|
|
|
25
25
|
import { sessionComposerWidth } from './sessionSidebar.js';
|
|
26
26
|
import { chatProseWidth, wrappedChatRows } from './textLayout.js';
|
|
27
27
|
import { activityRows } from './activityLayout.js';
|
|
28
|
+
import { cleanToolOutputPreview, normalizeHistoricalToolResult } from './toolOutputNormalizer.js';
|
|
29
|
+
import { formatMarkdownMath } from './markdownMath.js';
|
|
28
30
|
|
|
29
31
|
// Bound the preview AFTER wrapping, not by source newlines: one 400 KB line of
|
|
30
32
|
// minified output would otherwise become thousands of rows and lock the
|
|
@@ -199,11 +201,11 @@ function inline(text) {
|
|
|
199
201
|
});
|
|
200
202
|
}
|
|
201
203
|
|
|
204
|
+
out = out.replace(/`([^`]+)`/g, (_m, code) => stash(HAS_COLOR ? paint('accent', code) : code));
|
|
205
|
+
out = formatMarkdownMath(out);
|
|
202
206
|
out = HAS_COLOR
|
|
203
|
-
? out
|
|
204
|
-
|
|
205
|
-
.replace(/\*\*([^*]+)\*\*/g, (m, strong) => bold(strong))
|
|
206
|
-
: out.replace(/`([^`]+)`/g, '$1').replace(/\*\*([^*]+)\*\*/g, '$1');
|
|
207
|
+
? out.replace(/\*\*([^*]+)\*\*/g, (m, strong) => bold(strong))
|
|
208
|
+
: out.replace(/\*\*([^*]+)\*\*/g, '$1');
|
|
207
209
|
|
|
208
210
|
if (stashed.length > 0) {
|
|
209
211
|
out = out.replace(/\u0000(\d+)\u0000/g, (m, index) => stashed[Number(index)] || '');
|
|
@@ -612,33 +614,35 @@ export class ChatRenderer {
|
|
|
612
614
|
|
|
613
615
|
// Restore active implementation plan if update_plan was called
|
|
614
616
|
if (toolName === 'update_plan' && args && Array.isArray(args.plan)) {
|
|
615
|
-
this.onAgentPlan({
|
|
617
|
+
this.onAgentPlan({
|
|
618
|
+
plan: args.plan.map(item => ({
|
|
619
|
+
...item,
|
|
620
|
+
text: item.text || item.step || item.content || ''
|
|
621
|
+
}))
|
|
622
|
+
});
|
|
616
623
|
}
|
|
617
624
|
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
// Look up corresponding tool result
|
|
625
|
+
// Look up corresponding tool result before emitting step start so
|
|
626
|
+
// internal synthesis checkpoints (which never emit steps live) can be skipped.
|
|
621
627
|
const toolMsg = call.id ? toolResultsById.get(call.id) : null;
|
|
622
628
|
if (toolMsg) {
|
|
623
629
|
renderedToolMessages.add(toolMsg);
|
|
624
|
-
|
|
625
|
-
if (
|
|
626
|
-
|
|
627
|
-
}
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
}
|
|
636
|
-
} else {
|
|
637
|
-
result = { success: true, output: '' };
|
|
630
|
+
const normalized = normalizeHistoricalToolResult(toolName, toolMsg);
|
|
631
|
+
if (normalized.skipStep) {
|
|
632
|
+
continue;
|
|
633
|
+
}
|
|
634
|
+
if (toolName === 'update_plan' && Array.isArray(normalized.plan)) {
|
|
635
|
+
this.onAgentPlan({
|
|
636
|
+
plan: normalized.plan.map(item => ({
|
|
637
|
+
...item,
|
|
638
|
+
text: item.text || item.step || item.content || ''
|
|
639
|
+
}))
|
|
640
|
+
});
|
|
638
641
|
}
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
+
this.onStepStart({ tool: toolName, args });
|
|
643
|
+
this.onStepComplete({ tool: toolName, result: normalized.result, elapsed: '' });
|
|
644
|
+
} else {
|
|
645
|
+
this.onStepStart({ tool: toolName, args });
|
|
642
646
|
}
|
|
643
647
|
}
|
|
644
648
|
}
|
|
@@ -647,26 +651,13 @@ export class ChatRenderer {
|
|
|
647
651
|
if (!renderedToolMessages.has(msg)) {
|
|
648
652
|
renderedToolMessages.add(msg);
|
|
649
653
|
const toolName = msg.name || 'tool';
|
|
650
|
-
|
|
651
|
-
if (
|
|
652
|
-
|
|
653
|
-
} else if (typeof msg.content === 'string') {
|
|
654
|
-
try {
|
|
655
|
-
result = JSON.parse(msg.content);
|
|
656
|
-
} catch {
|
|
657
|
-
result = {
|
|
658
|
-
success: !msg.content.toLowerCase().startsWith('error') && !msg.content.toLowerCase().includes('failed'),
|
|
659
|
-
output: msg.content
|
|
660
|
-
};
|
|
661
|
-
}
|
|
662
|
-
} else {
|
|
663
|
-
result = { success: true, output: '' };
|
|
654
|
+
const normalized = normalizeHistoricalToolResult(toolName, msg, { unpaired: true });
|
|
655
|
+
if (normalized.skipStep) {
|
|
656
|
+
continue;
|
|
664
657
|
}
|
|
665
|
-
if (result.success === undefined) result.success = true;
|
|
666
|
-
if (msg.spillPath && !result.spillPath) result.spillPath = msg.spillPath;
|
|
667
658
|
|
|
668
659
|
this.onStepStart({ tool: toolName, args: {} });
|
|
669
|
-
this.onStepComplete({ result, elapsed: '' });
|
|
660
|
+
this.onStepComplete({ tool: toolName, result: normalized.result, elapsed: '' });
|
|
670
661
|
}
|
|
671
662
|
} else if (role === 'system') {
|
|
672
663
|
const text = typeof msg.content === 'string' ? msg.content : '';
|
|
@@ -864,7 +855,8 @@ export class ChatRenderer {
|
|
|
864
855
|
const mark = done ? paint('success', GLYPHS.check)
|
|
865
856
|
: active ? paint('accent', GLYPHS.arrow)
|
|
866
857
|
: paint('muted', GLYPHS.dot);
|
|
867
|
-
const
|
|
858
|
+
const text = item.text || item.step || item.content || '';
|
|
859
|
+
const label = done ? dim(safeDisplay(text)) : paint('ink', safeDisplay(text));
|
|
868
860
|
this.write(` ${mark} ${truncate(label, width - 5, GLYPHS.ellipsis)}`);
|
|
869
861
|
}
|
|
870
862
|
this.write();
|
|
@@ -904,7 +896,7 @@ export class ChatRenderer {
|
|
|
904
896
|
if (result.success) {
|
|
905
897
|
const elapsedText = elapsed ? ` ${dim(elapsed)}` : '';
|
|
906
898
|
this.write(` ${paint('success', GLYPHS.check)}${elapsedText}`);
|
|
907
|
-
this.renderOutputPreview(result);
|
|
899
|
+
this.renderOutputPreview(result, msg?.tool || '');
|
|
908
900
|
return;
|
|
909
901
|
}
|
|
910
902
|
const detail = `${safeDisplay(result.error || 'failed')}${elapsed ? ` · ${elapsed}` : ''}`;
|
|
@@ -961,10 +953,11 @@ export class ChatRenderer {
|
|
|
961
953
|
this.lastOutput = { text: payload, spillPath: result.spillPath || null };
|
|
962
954
|
}
|
|
963
955
|
|
|
964
|
-
renderOutputPreview(result) {
|
|
965
|
-
const
|
|
956
|
+
renderOutputPreview(result, toolName = '') {
|
|
957
|
+
const rawPayload = typeof result.output === 'string' ? result.output
|
|
966
958
|
: typeof result.log === 'string' ? result.log
|
|
967
959
|
: '';
|
|
960
|
+
const payload = cleanToolOutputPreview(rawPayload, toolName);
|
|
968
961
|
if (!payload) return;
|
|
969
962
|
|
|
970
963
|
const source = payload.length > PREVIEW_SOURCE_BUDGET
|
package/src/tui/homeView.js
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { sessionBanner } from './banner.js';
|
|
2
2
|
import { centerRows } from './layout.js';
|
|
3
|
-
// @ts-expect-error overlay.js is awaiting TypeScript migration.
|
|
4
3
|
import { panelRows } from './overlay.js';
|
|
5
4
|
/** A modal before the first conversation belongs to the centered home view. */
|
|
6
5
|
export function isStartupDialog(surface) {
|
package/src/tui/homeView.ts
CHANGED
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Terminal LaTeX Math Normalizer.
|
|
3
|
+
*
|
|
4
|
+
* Converts inline (`$...$`, `\(...\)`) and display (`$$...$$`, `\[...\]`) LaTeX
|
|
5
|
+
* math notation into clean, human-readable Unicode mathematical notation for
|
|
6
|
+
* terminal rendering, while preserving currency (`$100`), shell variables
|
|
7
|
+
* (`$HOME`), and code spans untouched.
|
|
8
|
+
*/
|
|
9
|
+
const GREEK_AND_SYMBOLS = {
|
|
10
|
+
alpha: 'α',
|
|
11
|
+
beta: 'β',
|
|
12
|
+
gamma: 'γ',
|
|
13
|
+
delta: 'δ',
|
|
14
|
+
epsilon: 'ε',
|
|
15
|
+
varepsilon: 'ε',
|
|
16
|
+
zeta: 'ζ',
|
|
17
|
+
eta: 'η',
|
|
18
|
+
theta: 'θ',
|
|
19
|
+
vartheta: 'θ',
|
|
20
|
+
iota: 'ι',
|
|
21
|
+
kappa: 'κ',
|
|
22
|
+
lambda: 'λ',
|
|
23
|
+
mu: 'μ',
|
|
24
|
+
nu: 'ν',
|
|
25
|
+
xi: 'ξ',
|
|
26
|
+
pi: 'π',
|
|
27
|
+
varpi: 'π',
|
|
28
|
+
rho: 'ρ',
|
|
29
|
+
varrho: 'ρ',
|
|
30
|
+
sigma: 'σ',
|
|
31
|
+
varsigma: 'ς',
|
|
32
|
+
tau: 'τ',
|
|
33
|
+
upsilon: 'υ',
|
|
34
|
+
phi: 'φ',
|
|
35
|
+
varphi: 'φ',
|
|
36
|
+
chi: 'χ',
|
|
37
|
+
psi: 'ψ',
|
|
38
|
+
omega: 'ω',
|
|
39
|
+
Gamma: 'Γ',
|
|
40
|
+
Delta: 'Δ',
|
|
41
|
+
Theta: 'Θ',
|
|
42
|
+
Lambda: 'Λ',
|
|
43
|
+
Xi: 'Ξ',
|
|
44
|
+
Pi: 'Π',
|
|
45
|
+
Sigma: 'Σ',
|
|
46
|
+
Upsilon: 'Υ',
|
|
47
|
+
Phi: 'Φ',
|
|
48
|
+
Psi: 'Ψ',
|
|
49
|
+
Omega: 'Ω',
|
|
50
|
+
in: '∈',
|
|
51
|
+
notin: '∉',
|
|
52
|
+
subset: '⊂',
|
|
53
|
+
subseteq: '⊆',
|
|
54
|
+
supset: '⊃',
|
|
55
|
+
supseteq: '⊇',
|
|
56
|
+
cup: '∪',
|
|
57
|
+
cap: '∩',
|
|
58
|
+
emptyset: '∅',
|
|
59
|
+
varnothing: '∅',
|
|
60
|
+
le: '≤',
|
|
61
|
+
leq: '≤',
|
|
62
|
+
ge: '≥',
|
|
63
|
+
geq: '≥',
|
|
64
|
+
ne: '≠',
|
|
65
|
+
neq: '≠',
|
|
66
|
+
approx: '≈',
|
|
67
|
+
equiv: '≡',
|
|
68
|
+
sim: '∼',
|
|
69
|
+
simeq: '≃',
|
|
70
|
+
cong: '≅',
|
|
71
|
+
propto: '∝',
|
|
72
|
+
times: '×',
|
|
73
|
+
cdot: '·',
|
|
74
|
+
cdots: '⋯',
|
|
75
|
+
ldots: '…',
|
|
76
|
+
dots: '…',
|
|
77
|
+
pm: '±',
|
|
78
|
+
mp: '∓',
|
|
79
|
+
div: '÷',
|
|
80
|
+
to: '→',
|
|
81
|
+
rightarrow: '→',
|
|
82
|
+
leftarrow: '←',
|
|
83
|
+
leftrightarrow: '↔',
|
|
84
|
+
Rightarrow: '⇒',
|
|
85
|
+
Leftarrow: '⇐',
|
|
86
|
+
Leftrightarrow: '⇔',
|
|
87
|
+
iff: '⇔',
|
|
88
|
+
implies: '⇒',
|
|
89
|
+
mapsto: '↦',
|
|
90
|
+
infty: '∞',
|
|
91
|
+
partial: '∂',
|
|
92
|
+
nabla: '∇',
|
|
93
|
+
forall: '∀',
|
|
94
|
+
exists: '∃',
|
|
95
|
+
nexists: '∄',
|
|
96
|
+
sum: '∑',
|
|
97
|
+
prod: '∏',
|
|
98
|
+
int: '∫',
|
|
99
|
+
oint: '∮',
|
|
100
|
+
oplus: '⊕',
|
|
101
|
+
otimes: '⊗',
|
|
102
|
+
perp: '⊥',
|
|
103
|
+
parallel: '∥',
|
|
104
|
+
angle: '∠',
|
|
105
|
+
circ: '∘',
|
|
106
|
+
degree: '°',
|
|
107
|
+
ell: 'ℓ',
|
|
108
|
+
hbar: 'ℏ',
|
|
109
|
+
Re: 'ℜ',
|
|
110
|
+
Im: 'ℑ'
|
|
111
|
+
};
|
|
112
|
+
const FUNCTION_MACROS = new Set([
|
|
113
|
+
'min', 'max', 'sup', 'inf', 'lim', 'limsup', 'liminf',
|
|
114
|
+
'log', 'ln', 'lg', 'exp',
|
|
115
|
+
'sin', 'cos', 'tan', 'cot', 'sec', 'csc',
|
|
116
|
+
'arcsin', 'arccos', 'arctan',
|
|
117
|
+
'sinh', 'cosh', 'tanh', 'coth',
|
|
118
|
+
'det', 'dim', 'ker', 'deg', 'gcd', 'Pr', 'arg', 'bmod', 'mod',
|
|
119
|
+
'argmin', 'argmax', 'tr', 'rank', 'diag', 'cov', 'var'
|
|
120
|
+
]);
|
|
121
|
+
const SUPERSCRIPT_DIGITS = {
|
|
122
|
+
'0': '⁰',
|
|
123
|
+
'1': '¹',
|
|
124
|
+
'2': '²',
|
|
125
|
+
'3': '³',
|
|
126
|
+
'4': '⁴',
|
|
127
|
+
'5': '⁵',
|
|
128
|
+
'6': '⁶',
|
|
129
|
+
'7': '⁷',
|
|
130
|
+
'8': '⁸',
|
|
131
|
+
'9': '⁹'
|
|
132
|
+
};
|
|
133
|
+
/**
|
|
134
|
+
* Convert the interior of a LaTeX math expression into readable terminal text.
|
|
135
|
+
*/
|
|
136
|
+
export function renderLatexExpression(rawExpr) {
|
|
137
|
+
let out = rawExpr.trim();
|
|
138
|
+
if (!out)
|
|
139
|
+
return '';
|
|
140
|
+
// 1. Unwrap text/font macros (\text{...}, \mathrm{...}, \operatorname{...}, etc.)
|
|
141
|
+
const textMacroRe = /\\(?:text|textbf|textit|textrm|texttt|mathrm|mathbf|mathit|mathsf|mathtt|mathcal|mathbb|operatorname)\*?\s*\{([^{}]*)\}/g;
|
|
142
|
+
for (let pass = 0; pass < 4 && textMacroRe.test(out); pass++) {
|
|
143
|
+
out = out.replace(textMacroRe, '$1');
|
|
144
|
+
}
|
|
145
|
+
// 2. Convert \frac{a}{b} and \sqrt{x}
|
|
146
|
+
const fracRe = /\\(?:d|t)?frac\s*\{([^{}]+)\}\s*\{([^{}]+)\}/g;
|
|
147
|
+
for (let pass = 0; pass < 3 && fracRe.test(out); pass++) {
|
|
148
|
+
out = out.replace(fracRe, (_m, num, den) => {
|
|
149
|
+
const n = num.trim();
|
|
150
|
+
const d = den.trim();
|
|
151
|
+
const nSimple = /^[a-zA-Z0-9_α-ωΑ-Ω]+$/.test(n);
|
|
152
|
+
const dSimple = /^[a-zA-Z0-9_α-ωΑ-Ω]+$/.test(d);
|
|
153
|
+
return `${nSimple ? n : `(${n})`}/${dSimple ? d : `(${d})`}`;
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
const sqrtRe = /\\sqrt\s*\{([^{}]+)\}/g;
|
|
157
|
+
for (let pass = 0; pass < 3 && sqrtRe.test(out); pass++) {
|
|
158
|
+
out = out.replace(sqrtRe, (_m, inner) => {
|
|
159
|
+
const trimmed = inner.trim();
|
|
160
|
+
return /^[a-zA-Z0-9_α-ωΑ-Ω]+$/.test(trimmed) ? `√${trimmed}` : `√(${trimmed})`;
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
// 3. Strip sizing and spacing directives
|
|
164
|
+
out = out
|
|
165
|
+
.replace(/\\(?:left|right|big|Big|bigg|Bigg|[bB]igl|[bB]igr|limits|nolimits|displaystyle|textstyle)\b\s*/g, '')
|
|
166
|
+
.replace(/\\(?:quad|qquad)\b/g, ' ')
|
|
167
|
+
.replace(/\\[,;:!]/g, ' ')
|
|
168
|
+
.replace(/\\\{/g, '{')
|
|
169
|
+
.replace(/\\\}/g, '}')
|
|
170
|
+
.replace(/\\%/g, '%')
|
|
171
|
+
.replace(/\\_/g, '_');
|
|
172
|
+
// 4. Replace named functions and Greek/math symbols
|
|
173
|
+
out = out.replace(/\\([a-zA-Z]+)(\s*)/g, (full, name, trailingSpace) => {
|
|
174
|
+
if (FUNCTION_MACROS.has(name)) {
|
|
175
|
+
return name + (trailingSpace || '');
|
|
176
|
+
}
|
|
177
|
+
const sym = GREEK_AND_SYMBOLS[name];
|
|
178
|
+
if (sym !== undefined) {
|
|
179
|
+
// Preserve a space if the symbol is a binary relation/operator and had trailing space,
|
|
180
|
+
// or if the next character would otherwise run into an operator.
|
|
181
|
+
return sym + (trailingSpace.length > 0 && /^[∈∉⊂⊆⊃⊇∪∩≤≥≠≈≡∼≃≅∝×·±∓÷→←↔⇒⇐⇔↦]$/.test(sym) ? ' ' : '');
|
|
182
|
+
}
|
|
183
|
+
return full;
|
|
184
|
+
});
|
|
185
|
+
// 5. Simplify braced subscripts and superscripts
|
|
186
|
+
out = out
|
|
187
|
+
.replace(/_\{([a-zA-Z0-9α-ωΑ-Ω+-]+)\}/g, '_$1')
|
|
188
|
+
.replace(/_\{([^{}]+)\}/g, '_($1)')
|
|
189
|
+
.replace(/\^\{([0-9])\}/g, (_m, d) => SUPERSCRIPT_DIGITS[d] ?? `^${d}`)
|
|
190
|
+
.replace(/\^([23])(?![0-9])/g, (_m, d) => SUPERSCRIPT_DIGITS[d] ?? `^${d}`)
|
|
191
|
+
.replace(/\^\{([a-zA-Z0-9α-ωΑ-Ω+-]+)\}/g, '^$1')
|
|
192
|
+
.replace(/\^\{([^{}]+)\}/g, '^($1)');
|
|
193
|
+
return out.replace(/\s{2,}/g, ' ').trim();
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* Determine whether the content between single `$ ... $` delimiters is genuine
|
|
197
|
+
* mathematical notation rather than currency or prose between two prices.
|
|
198
|
+
*/
|
|
199
|
+
function isLikelyInlineMath(inner) {
|
|
200
|
+
const trimmed = inner.trim();
|
|
201
|
+
if (!trimmed || trimmed.length > 160)
|
|
202
|
+
return false;
|
|
203
|
+
// Plain currency/number ($100, $19.99, $50k) or shell variable ($HOME)
|
|
204
|
+
if (/^\d+(?:[.,]\d+)*[kKmMbB]?$/.test(trimmed))
|
|
205
|
+
return false;
|
|
206
|
+
if (/^[A-Z_][A-Z0-9_]{1,30}$/.test(trimmed))
|
|
207
|
+
return false;
|
|
208
|
+
// Starts with digits followed by ordinary prose words (e.g. "$100 today and $200")
|
|
209
|
+
if (/^\d+(?:[.,]\d+)?\s+[a-z]{2,}\b/i.test(trimmed) && !/\\[a-zA-Z]+|[=<>≤≥∈]/.test(trimmed)) {
|
|
210
|
+
return false;
|
|
211
|
+
}
|
|
212
|
+
// Contains any LaTeX command, subscript/superscript, or mathematical relation/operator
|
|
213
|
+
if (/\\[a-zA-Z]+/.test(trimmed))
|
|
214
|
+
return true;
|
|
215
|
+
if (/[_^]/.test(trimmed))
|
|
216
|
+
return true;
|
|
217
|
+
if (/[=<>≤≥≠≈∈±×÷]/.test(trimmed))
|
|
218
|
+
return true;
|
|
219
|
+
// Single math variable ($x$, $s$, $N$) or bracketed interval/tuple ($[0, 1]$, $(x, y)$)
|
|
220
|
+
if (/^[a-zA-Z]$/.test(trimmed))
|
|
221
|
+
return true;
|
|
222
|
+
if (/^[\[(][0-9a-zA-Z.,\s+-]+[\])]$/.test(trimmed))
|
|
223
|
+
return true;
|
|
224
|
+
if (/^[a-zA-Z0-9_]+\s*[+\-*/]\s*[a-zA-Z0-9_]+/.test(trimmed))
|
|
225
|
+
return true;
|
|
226
|
+
return false;
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* Format LaTeX math spans inside a markdown prose line (after code spans and
|
|
230
|
+
* links have already been stashed).
|
|
231
|
+
*/
|
|
232
|
+
export function formatMarkdownMath(text) {
|
|
233
|
+
if (!text || (!text.includes('$') && !text.includes('\\')))
|
|
234
|
+
return text;
|
|
235
|
+
let out = text;
|
|
236
|
+
// 1. Display math $$...$$
|
|
237
|
+
out = out.replace(/\$\$((?:[^$]|\\\$)+?)\$\$/g, (_m, expr) => renderLatexExpression(expr));
|
|
238
|
+
// 2. Explicit LaTeX delimiters \[...\] and \(...\)
|
|
239
|
+
out = out.replace(/\\\[([\s\S]+?)\\\]/g, (_m, expr) => renderLatexExpression(expr));
|
|
240
|
+
out = out.replace(/\\\(([\s\S]+?)\\\)/g, (_m, expr) => renderLatexExpression(expr));
|
|
241
|
+
// 3. Inline math $...$
|
|
242
|
+
out = out.replace(/(?<![\\$\w])\$(?!\s)((?:[^$\n\\]|\\.)+?)(?<!\s)\$(?![$\d])/g, (full, expr) => {
|
|
243
|
+
if (!isLikelyInlineMath(expr))
|
|
244
|
+
return full;
|
|
245
|
+
return renderLatexExpression(expr);
|
|
246
|
+
});
|
|
247
|
+
// 4. Unescape literal \$ that the author escaped for markdown
|
|
248
|
+
out = out.replace(/\\\$/g, '$');
|
|
249
|
+
return out;
|
|
250
|
+
}
|
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Terminal LaTeX Math Normalizer.
|
|
3
|
+
*
|
|
4
|
+
* Converts inline (`$...$`, `\(...\)`) and display (`$$...$$`, `\[...\]`) LaTeX
|
|
5
|
+
* math notation into clean, human-readable Unicode mathematical notation for
|
|
6
|
+
* terminal rendering, while preserving currency (`$100`), shell variables
|
|
7
|
+
* (`$HOME`), and code spans untouched.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
const GREEK_AND_SYMBOLS: Readonly<Record<string, string>> = {
|
|
11
|
+
alpha: 'α',
|
|
12
|
+
beta: 'β',
|
|
13
|
+
gamma: 'γ',
|
|
14
|
+
delta: 'δ',
|
|
15
|
+
epsilon: 'ε',
|
|
16
|
+
varepsilon: 'ε',
|
|
17
|
+
zeta: 'ζ',
|
|
18
|
+
eta: 'η',
|
|
19
|
+
theta: 'θ',
|
|
20
|
+
vartheta: 'θ',
|
|
21
|
+
iota: 'ι',
|
|
22
|
+
kappa: 'κ',
|
|
23
|
+
lambda: 'λ',
|
|
24
|
+
mu: 'μ',
|
|
25
|
+
nu: 'ν',
|
|
26
|
+
xi: 'ξ',
|
|
27
|
+
pi: 'π',
|
|
28
|
+
varpi: 'π',
|
|
29
|
+
rho: 'ρ',
|
|
30
|
+
varrho: 'ρ',
|
|
31
|
+
sigma: 'σ',
|
|
32
|
+
varsigma: 'ς',
|
|
33
|
+
tau: 'τ',
|
|
34
|
+
upsilon: 'υ',
|
|
35
|
+
phi: 'φ',
|
|
36
|
+
varphi: 'φ',
|
|
37
|
+
chi: 'χ',
|
|
38
|
+
psi: 'ψ',
|
|
39
|
+
omega: 'ω',
|
|
40
|
+
Gamma: 'Γ',
|
|
41
|
+
Delta: 'Δ',
|
|
42
|
+
Theta: 'Θ',
|
|
43
|
+
Lambda: 'Λ',
|
|
44
|
+
Xi: 'Ξ',
|
|
45
|
+
Pi: 'Π',
|
|
46
|
+
Sigma: 'Σ',
|
|
47
|
+
Upsilon: 'Υ',
|
|
48
|
+
Phi: 'Φ',
|
|
49
|
+
Psi: 'Ψ',
|
|
50
|
+
Omega: 'Ω',
|
|
51
|
+
in: '∈',
|
|
52
|
+
notin: '∉',
|
|
53
|
+
subset: '⊂',
|
|
54
|
+
subseteq: '⊆',
|
|
55
|
+
supset: '⊃',
|
|
56
|
+
supseteq: '⊇',
|
|
57
|
+
cup: '∪',
|
|
58
|
+
cap: '∩',
|
|
59
|
+
emptyset: '∅',
|
|
60
|
+
varnothing: '∅',
|
|
61
|
+
le: '≤',
|
|
62
|
+
leq: '≤',
|
|
63
|
+
ge: '≥',
|
|
64
|
+
geq: '≥',
|
|
65
|
+
ne: '≠',
|
|
66
|
+
neq: '≠',
|
|
67
|
+
approx: '≈',
|
|
68
|
+
equiv: '≡',
|
|
69
|
+
sim: '∼',
|
|
70
|
+
simeq: '≃',
|
|
71
|
+
cong: '≅',
|
|
72
|
+
propto: '∝',
|
|
73
|
+
times: '×',
|
|
74
|
+
cdot: '·',
|
|
75
|
+
cdots: '⋯',
|
|
76
|
+
ldots: '…',
|
|
77
|
+
dots: '…',
|
|
78
|
+
pm: '±',
|
|
79
|
+
mp: '∓',
|
|
80
|
+
div: '÷',
|
|
81
|
+
to: '→',
|
|
82
|
+
rightarrow: '→',
|
|
83
|
+
leftarrow: '←',
|
|
84
|
+
leftrightarrow: '↔',
|
|
85
|
+
Rightarrow: '⇒',
|
|
86
|
+
Leftarrow: '⇐',
|
|
87
|
+
Leftrightarrow: '⇔',
|
|
88
|
+
iff: '⇔',
|
|
89
|
+
implies: '⇒',
|
|
90
|
+
mapsto: '↦',
|
|
91
|
+
infty: '∞',
|
|
92
|
+
partial: '∂',
|
|
93
|
+
nabla: '∇',
|
|
94
|
+
forall: '∀',
|
|
95
|
+
exists: '∃',
|
|
96
|
+
nexists: '∄',
|
|
97
|
+
sum: '∑',
|
|
98
|
+
prod: '∏',
|
|
99
|
+
int: '∫',
|
|
100
|
+
oint: '∮',
|
|
101
|
+
oplus: '⊕',
|
|
102
|
+
otimes: '⊗',
|
|
103
|
+
perp: '⊥',
|
|
104
|
+
parallel: '∥',
|
|
105
|
+
angle: '∠',
|
|
106
|
+
circ: '∘',
|
|
107
|
+
degree: '°',
|
|
108
|
+
ell: 'ℓ',
|
|
109
|
+
hbar: 'ℏ',
|
|
110
|
+
Re: 'ℜ',
|
|
111
|
+
Im: 'ℑ'
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
const FUNCTION_MACROS = new Set([
|
|
115
|
+
'min', 'max', 'sup', 'inf', 'lim', 'limsup', 'liminf',
|
|
116
|
+
'log', 'ln', 'lg', 'exp',
|
|
117
|
+
'sin', 'cos', 'tan', 'cot', 'sec', 'csc',
|
|
118
|
+
'arcsin', 'arccos', 'arctan',
|
|
119
|
+
'sinh', 'cosh', 'tanh', 'coth',
|
|
120
|
+
'det', 'dim', 'ker', 'deg', 'gcd', 'Pr', 'arg', 'bmod', 'mod',
|
|
121
|
+
'argmin', 'argmax', 'tr', 'rank', 'diag', 'cov', 'var'
|
|
122
|
+
]);
|
|
123
|
+
|
|
124
|
+
const SUPERSCRIPT_DIGITS: Readonly<Record<string, string>> = {
|
|
125
|
+
'0': '⁰',
|
|
126
|
+
'1': '¹',
|
|
127
|
+
'2': '²',
|
|
128
|
+
'3': '³',
|
|
129
|
+
'4': '⁴',
|
|
130
|
+
'5': '⁵',
|
|
131
|
+
'6': '⁶',
|
|
132
|
+
'7': '⁷',
|
|
133
|
+
'8': '⁸',
|
|
134
|
+
'9': '⁹'
|
|
135
|
+
};
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Convert the interior of a LaTeX math expression into readable terminal text.
|
|
139
|
+
*/
|
|
140
|
+
export function renderLatexExpression(rawExpr: string): string {
|
|
141
|
+
let out = rawExpr.trim();
|
|
142
|
+
if (!out) return '';
|
|
143
|
+
|
|
144
|
+
// 1. Unwrap text/font macros (\text{...}, \mathrm{...}, \operatorname{...}, etc.)
|
|
145
|
+
const textMacroRe = /\\(?:text|textbf|textit|textrm|texttt|mathrm|mathbf|mathit|mathsf|mathtt|mathcal|mathbb|operatorname)\*?\s*\{([^{}]*)\}/g;
|
|
146
|
+
for (let pass = 0; pass < 4 && textMacroRe.test(out); pass++) {
|
|
147
|
+
out = out.replace(textMacroRe, '$1');
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// 2. Convert \frac{a}{b} and \sqrt{x}
|
|
151
|
+
const fracRe = /\\(?:d|t)?frac\s*\{([^{}]+)\}\s*\{([^{}]+)\}/g;
|
|
152
|
+
for (let pass = 0; pass < 3 && fracRe.test(out); pass++) {
|
|
153
|
+
out = out.replace(fracRe, (_m, num: string, den: string) => {
|
|
154
|
+
const n = num.trim();
|
|
155
|
+
const d = den.trim();
|
|
156
|
+
const nSimple = /^[a-zA-Z0-9_α-ωΑ-Ω]+$/.test(n);
|
|
157
|
+
const dSimple = /^[a-zA-Z0-9_α-ωΑ-Ω]+$/.test(d);
|
|
158
|
+
return `${nSimple ? n : `(${n})`}/${dSimple ? d : `(${d})`}`;
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const sqrtRe = /\\sqrt\s*\{([^{}]+)\}/g;
|
|
163
|
+
for (let pass = 0; pass < 3 && sqrtRe.test(out); pass++) {
|
|
164
|
+
out = out.replace(sqrtRe, (_m, inner: string) => {
|
|
165
|
+
const trimmed = inner.trim();
|
|
166
|
+
return /^[a-zA-Z0-9_α-ωΑ-Ω]+$/.test(trimmed) ? `√${trimmed}` : `√(${trimmed})`;
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// 3. Strip sizing and spacing directives
|
|
171
|
+
out = out
|
|
172
|
+
.replace(/\\(?:left|right|big|Big|bigg|Bigg|[bB]igl|[bB]igr|limits|nolimits|displaystyle|textstyle)\b\s*/g, '')
|
|
173
|
+
.replace(/\\(?:quad|qquad)\b/g, ' ')
|
|
174
|
+
.replace(/\\[,;:!]/g, ' ')
|
|
175
|
+
.replace(/\\\{/g, '{')
|
|
176
|
+
.replace(/\\\}/g, '}')
|
|
177
|
+
.replace(/\\%/g, '%')
|
|
178
|
+
.replace(/\\_/g, '_');
|
|
179
|
+
|
|
180
|
+
// 4. Replace named functions and Greek/math symbols
|
|
181
|
+
out = out.replace(/\\([a-zA-Z]+)(\s*)/g, (full, name: string, trailingSpace: string) => {
|
|
182
|
+
if (FUNCTION_MACROS.has(name)) {
|
|
183
|
+
return name + (trailingSpace || '');
|
|
184
|
+
}
|
|
185
|
+
const sym = GREEK_AND_SYMBOLS[name];
|
|
186
|
+
if (sym !== undefined) {
|
|
187
|
+
// Preserve a space if the symbol is a binary relation/operator and had trailing space,
|
|
188
|
+
// or if the next character would otherwise run into an operator.
|
|
189
|
+
return sym + (trailingSpace.length > 0 && /^[∈∉⊂⊆⊃⊇∪∩≤≥≠≈≡∼≃≅∝×·±∓÷→←↔⇒⇐⇔↦]$/.test(sym) ? ' ' : '');
|
|
190
|
+
}
|
|
191
|
+
return full;
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
// 5. Simplify braced subscripts and superscripts
|
|
195
|
+
out = out
|
|
196
|
+
.replace(/_\{([a-zA-Z0-9α-ωΑ-Ω+-]+)\}/g, '_$1')
|
|
197
|
+
.replace(/_\{([^{}]+)\}/g, '_($1)')
|
|
198
|
+
.replace(/\^\{([0-9])\}/g, (_m, d: string) => SUPERSCRIPT_DIGITS[d] ?? `^${d}`)
|
|
199
|
+
.replace(/\^([23])(?![0-9])/g, (_m, d: string) => SUPERSCRIPT_DIGITS[d] ?? `^${d}`)
|
|
200
|
+
.replace(/\^\{([a-zA-Z0-9α-ωΑ-Ω+-]+)\}/g, '^$1')
|
|
201
|
+
.replace(/\^\{([^{}]+)\}/g, '^($1)');
|
|
202
|
+
|
|
203
|
+
return out.replace(/\s{2,}/g, ' ').trim();
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* Determine whether the content between single `$ ... $` delimiters is genuine
|
|
208
|
+
* mathematical notation rather than currency or prose between two prices.
|
|
209
|
+
*/
|
|
210
|
+
function isLikelyInlineMath(inner: string): boolean {
|
|
211
|
+
const trimmed = inner.trim();
|
|
212
|
+
if (!trimmed || trimmed.length > 160) return false;
|
|
213
|
+
|
|
214
|
+
// Plain currency/number ($100, $19.99, $50k) or shell variable ($HOME)
|
|
215
|
+
if (/^\d+(?:[.,]\d+)*[kKmMbB]?$/.test(trimmed)) return false;
|
|
216
|
+
if (/^[A-Z_][A-Z0-9_]{1,30}$/.test(trimmed)) return false;
|
|
217
|
+
|
|
218
|
+
// Starts with digits followed by ordinary prose words (e.g. "$100 today and $200")
|
|
219
|
+
if (/^\d+(?:[.,]\d+)?\s+[a-z]{2,}\b/i.test(trimmed) && !/\\[a-zA-Z]+|[=<>≤≥∈]/.test(trimmed)) {
|
|
220
|
+
return false;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// Contains any LaTeX command, subscript/superscript, or mathematical relation/operator
|
|
224
|
+
if (/\\[a-zA-Z]+/.test(trimmed)) return true;
|
|
225
|
+
if (/[_^]/.test(trimmed)) return true;
|
|
226
|
+
if (/[=<>≤≥≠≈∈±×÷]/.test(trimmed)) return true;
|
|
227
|
+
|
|
228
|
+
// Single math variable ($x$, $s$, $N$) or bracketed interval/tuple ($[0, 1]$, $(x, y)$)
|
|
229
|
+
if (/^[a-zA-Z]$/.test(trimmed)) return true;
|
|
230
|
+
if (/^[\[(][0-9a-zA-Z.,\s+-]+[\])]$/.test(trimmed)) return true;
|
|
231
|
+
if (/^[a-zA-Z0-9_]+\s*[+\-*/]\s*[a-zA-Z0-9_]+/.test(trimmed)) return true;
|
|
232
|
+
|
|
233
|
+
return false;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Format LaTeX math spans inside a markdown prose line (after code spans and
|
|
238
|
+
* links have already been stashed).
|
|
239
|
+
*/
|
|
240
|
+
export function formatMarkdownMath(text: string): string {
|
|
241
|
+
if (!text || (!text.includes('$') && !text.includes('\\'))) return text;
|
|
242
|
+
|
|
243
|
+
let out = text;
|
|
244
|
+
|
|
245
|
+
// 1. Display math $$...$$
|
|
246
|
+
out = out.replace(/\$\$((?:[^$]|\\\$)+?)\$\$/g, (_m, expr: string) => renderLatexExpression(expr));
|
|
247
|
+
|
|
248
|
+
// 2. Explicit LaTeX delimiters \[...\] and \(...\)
|
|
249
|
+
out = out.replace(/\\\[([\s\S]+?)\\\]/g, (_m, expr: string) => renderLatexExpression(expr));
|
|
250
|
+
out = out.replace(/\\\(([\s\S]+?)\\\)/g, (_m, expr: string) => renderLatexExpression(expr));
|
|
251
|
+
|
|
252
|
+
// 3. Inline math $...$
|
|
253
|
+
out = out.replace(/(?<![\\$\w])\$(?!\s)((?:[^$\n\\]|\\.)+?)(?<!\s)\$(?![$\d])/g, (full, expr: string) => {
|
|
254
|
+
if (!isLikelyInlineMath(expr)) return full;
|
|
255
|
+
return renderLatexExpression(expr);
|
|
256
|
+
});
|
|
257
|
+
|
|
258
|
+
// 4. Unescape literal \$ that the author escaped for markdown
|
|
259
|
+
out = out.replace(/\\\$/g, '$');
|
|
260
|
+
|
|
261
|
+
return out;
|
|
262
|
+
}
|
|
263
|
+
|