char-fork/llama.cpp

git clone https://git.t4t.associates/char-fork/llama.cpp

Aleksander Grygierui: Constants refactor (#26908)e21152dc9

char/aliceai-t5-moe
2.6 KiB93 linesraw
1import {
2	CWD_CHANGED_PREFIX,
3	CWD_CLEARED_TEXT,
4	CWD_LINK_REGEX,
5	FILE_URI_PREFIX,
6	HOME_TILDE,
7	HOME_TILDE_PREFIX,
8	PATH_SEPARATOR,
9	TRAILING_SLASHES_REGEX
10} from '$lib/constants';
11
12export function lastPathSegment(p: string): string {
13	const trimmed = p.replace(TRAILING_SLASHES_REGEX, '');
14	const idx = trimmed.lastIndexOf(PATH_SEPARATOR);
15
16	return idx === -1 ? trimmed : trimmed.slice(idx + 1);
17}
18
19// `~/...` under `home`; falls back to the basename when home is unknown
20// or the path is outside it.
21export function abbreviateWorkingDir(
22	path: string | null | undefined,
23	home: string | null | undefined
24): string {
25	if (!path) return '';
26
27	if (!home) return lastPathSegment(path);
28
29	if (path === home) return HOME_TILDE;
30
31	if (path.startsWith(home + PATH_SEPARATOR))
32		return HOME_TILDE_PREFIX + path.slice(home.length + 1);
33
34	return lastPathSegment(path);
35}
36
37// Unlike abbreviateWorkingDir, paths outside `home` are returned
38// unchanged - used where the full path matters.
39export function abbreviateHome(path: string, home: string | null | undefined): string {
40	if (!home) return path;
41
42	if (path === home) return HOME_TILDE;
43
44	if (path.startsWith(home + PATH_SEPARATOR))
45		return HOME_TILDE_PREFIX + path.slice(home.length + 1);
46
47	return path;
48}
49
50export { CWD_CHANGED_PREFIX, CWD_CLEARED_TEXT } from '$lib/constants';
51
52export interface CwdMessageInfo {
53	// absolute server-side path, null when the cwd was cleared
54	path: string | null;
55	// display form shown in the UI (e.g. ~/Documents)
56	display: string;
57}
58
59/**
60 * Format a synthetic cwd-change message. The path travels as
61 * `[file:///abs/path](display)` so both the absolute and short form are
62 * visible to the model and parseable back by the UI.
63 */
64export function formatCwdMessage(cwd: string, home: string | null): string {
65	const display = abbreviateWorkingDir(cwd, home);
66
67	return `${CWD_CHANGED_PREFIX}[${FILE_URI_PREFIX}${cwd}](${display}).`;
68}
69
70/**
71 * Parse a synthetic cwd message back into its parts. The caller must
72 * already know the message is synthetic (via the persisted `isSynthetic`
73 * flag); this only extracts the path.
74 */
75export function parseCwdMessage(content: string): CwdMessageInfo | null {
76	const trimmed = content.trim();
77
78	if (trimmed === CWD_CLEARED_TEXT) {
79		return { display: '', path: null };
80	}
81
82	if (trimmed.startsWith(CWD_CHANGED_PREFIX)) {
83		const rest = trimmed.slice(CWD_CHANGED_PREFIX.length);
84		// not anchored to the end: guidance may follow the link
85		const link = rest.match(CWD_LINK_REGEX);
86
87		if (link) return { display: link[2], path: link[1] };
88
89		return { display: rest, path: rest };
90	}
91
92	return null;
93}