Instructions to use VladHong/llama-cpp-K2-FAST2 with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- llama.cpp
How to use VladHong/llama-cpp-K2-FAST2 with llama.cpp:
Install (macOS, Linux)
curl -LsSf https://llama.app/install.sh | sh # Start a local OpenAI-compatible server with a web UI: llama serve -hf VladHong/llama-cpp-K2-FAST2 # Run inference directly in the terminal: llama cli -hf VladHong/llama-cpp-K2-FAST2
Install from WinGet (Windows)
winget install llama.cpp # Start a local OpenAI-compatible server with a web UI: llama serve -hf VladHong/llama-cpp-K2-FAST2 # Run inference directly in the terminal: llama cli -hf VladHong/llama-cpp-K2-FAST2
Build from source code
git clone https://github.com/ggml-org/llama.cpp.git cd llama.cpp cmake -B build cmake --build build -j --target llama-app # Start a local OpenAI-compatible server with a web UI: ./build/bin/llama serve -hf VladHong/llama-cpp-K2-FAST2 # Run inference directly in the terminal: ./build/bin/llama cli -hf VladHong/llama-cpp-K2-FAST2
Use Docker
docker model run hf.co/VladHong/llama-cpp-K2-FAST2
- Llama new
- LM Studio
- Jan
- Ollama
How to use VladHong/llama-cpp-K2-FAST2 with Ollama:
ollama run hf.co/VladHong/llama-cpp-K2-FAST2
- Unsloth Desktop
- Docker Model Runner
How to use VladHong/llama-cpp-K2-FAST2 with Docker Model Runner:
docker model run hf.co/VladHong/llama-cpp-K2-FAST2
- Lemonade
How to use VladHong/llama-cpp-K2-FAST2 with Lemonade:
Pull the model
# Download Lemonade from https://lemonade-server.ai/ lemonade pull VladHong/llama-cpp-K2-FAST2
Run and chat with the model
lemonade run user.llama-cpp-K2-FAST2-{{QUANT_TAG}}List all available models
lemonade list
- Atomic Chat
File size: 27,986 Bytes
c59fd93 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 | /**
* Maps between the chat-form-input-rich's markdown source and the
* badge/code/text token stream the DOM is built from. A badge is one
* opaque source contribution (`[name](file://path)`); its own subtree
* is never walked, and the caret cannot land inside it, so offsets
* resolve to the nearest badge edge. Code spans (`<code data-code-token>`)
* are EDITABLE, unlike badges: they carry the full source segment
* (backtick fences included) as their text, so their textContent
* serializes verbatim and source offsets map 1:1 to text offsets.
*
* The tokenizer emits a flat DOM (text nodes + badges + code spans),
* but browsers restructure it on Enter (`<div>` line wrappers, `<br>`
* shapes). Serialization folds those back into `\n` so the source
* never diverges from what is on screen; both offset mappers
* understand the same shapes.
*
* The newline separating a fenced block from adjacent content is a
* SOURCE-level concept, never stored in the DOM: the block is
* display:block, so a leading `\n` in the following text node would
* render as a phantom empty line. Serialization synthesizes exactly
* one `\n` at every block boundary and `buildFragment` strips it from
* text tokens. A text node's own leading/trailing `\n` next to a
* block is an ADDITIONAL blank line.
*/
import {
decodeFileLinkPath,
fileMentionLinkRe,
getMentionBadgeIconPaths,
getMentionBadgeLabel
} from './mention-badge';
import {
CODE_TOKEN_ATTR,
MENTION_BADGE_CLASSNAME,
MENTION_BADGE_DATA_ATTRS,
MENTION_BADGE_ICON_CLASSNAME,
MENTION_BADGE_SVG_ATTRIBUTES,
SETTINGS_KEYS
} from '$lib/constants';
import { BooleanString, ChatFormInputRichTokenKind } from '$lib/enums';
import { settingsStore } from '$lib/stores/settings/index.svelte';
import { toolsStore } from '$lib/stores/tools.svelte';
import type { ChatFormInputRichToken } from '$lib/types/chat-form-input-rich';
// Block wrappers browsers insert for newlines; each folds back into a
// single `\n` during serialization.
const BLOCK_TAG_NAMES = new Set(['DIV', 'P']);
// `file://` is required so plain URLs stay as text; `)` terminates only
// when not followed by whitespace or `[` (adjacent badges keep working).
const MENTION_BADGE_RE = fileMentionLinkRe('g');
function badgeSourceLength(name: string, path: string): number {
if (!name || !path) return 0;
return `[${name}](file://${path})`.length;
}
/**
* Recognize complete code spans. Fenced blocks (triple backticks,
* optional language, possibly multiline) take priority over inline
* spans (single backticks, single line, non-empty). Only CLOSED
* spans match: an unclosed fence stays plain text until the closing
* backticks land. The match includes the fences so the token's
* source length equals its rendered text length.
*/
const CODE_SPAN_RE = /(```[\s\S]*?```)|(`[^`\n]+`)/g;
/**
* Cheap gate check for `ChatForm`: does the buffer contain a
* complete code span (inline or fenced)? Used to promote the plain
* textarea to the chat-form-input-rich renderer.
*/
export function containsCodeSpan(value: string): boolean {
CODE_SPAN_RE.lastIndex = 0;
return CODE_SPAN_RE.test(value);
}
const CODE_FENCE_RE = /```/g;
/**
* Is `offset` inside a fenced code block region? Toggle-based: an
* odd number of ``` fences before the offset means the position
* sits in block content. Unlike `containsCodeSpan` this also
* counts the still-OPEN fence while the user is typing a block
* (no closing ``` yet), so Enter can add a line instead of
* submitting the message.
*/
export function isOffsetInCodeBlock(source: string, offset: number): boolean {
let inside = false;
CODE_FENCE_RE.lastIndex = 0;
let match: RegExpExecArray | null;
while ((match = CODE_FENCE_RE.exec(source)) !== null) {
if (match.index + match[0].length > offset) break;
inside = !inside;
}
return inside;
}
/**
* Tokenize a markdown source value into the segments the
* chat-form-input-rich will render. Code spans are carved out first
* (their content is literal - a `file://` link inside backticks
* must NOT render as a badge), then plain text and badges
* interleave in the remaining gaps. Any whitespace after a badge
* stays in a plain text token so the round trip is byte-exact.
*/
export function tokenizeContent(input: string): ChatFormInputRichToken[] {
const tokens: ChatFormInputRichToken[] = [];
let cursor = 0;
CODE_SPAN_RE.lastIndex = 0;
let match: RegExpExecArray | null;
while ((match = CODE_SPAN_RE.exec(input)) !== null) {
const start = match.index;
if (start > cursor) {
pushTextAndBadgeTokens(input.slice(cursor, start), tokens);
}
tokens.push(
match[1] !== undefined
? { kind: ChatFormInputRichTokenKind.CODE_BLOCK, text: match[1] }
: { kind: ChatFormInputRichTokenKind.CODE_INLINE, text: match[2] }
);
cursor = start + match[0].length;
}
if (cursor < input.length) {
pushTextAndBadgeTokens(input.slice(cursor), tokens);
}
return tokens;
}
/**
* Tokenize a code-free segment into text and badge tokens.
*/
function pushTextAndBadgeTokens(input: string, tokens: ChatFormInputRichToken[]) {
let cursor = 0;
MENTION_BADGE_RE.lastIndex = 0;
let match: RegExpExecArray | null;
while ((match = MENTION_BADGE_RE.exec(input)) !== null) {
const [whole, name, path] = match;
const start = match.index;
if (start > cursor) {
tokens.push({ kind: ChatFormInputRichTokenKind.TEXT, text: input.slice(cursor, start) });
}
tokens.push({ kind: ChatFormInputRichTokenKind.BADGE, name, path });
cursor = start + whole.length;
}
if (cursor < input.length) {
tokens.push({ kind: ChatFormInputRichTokenKind.TEXT, text: input.slice(cursor) });
}
}
function isCodeBlockElement(node: Node | null): node is HTMLElement {
return (
node instanceof HTMLElement &&
node.getAttribute(CODE_TOKEN_ATTR) === ChatFormInputRichTokenKind.CODE_BLOCK
);
}
/**
* Serialize a chat-form-input-rich subtree back to source. `<br>` and block
* wrappers the browser inserted for newlines fold back into `\n` (a
* trailing `<br>` is the browser's caret placeholder, not a newline);
* any other element is transparent. Code spans serialize their
* textContent verbatim (fences included). One separator `\n` is
* synthesized at every fenced-block boundary (the DOM never stores
* it), and a `<br>` adjacent to a code block is an escape hatch, not
* a newline.
*/
export function serializeContent(root: HTMLElement): string {
let out = '';
let pendingBlockBoundary = false;
const walk = (parent: Node) => {
let first = true; // no source-contributing sibling seen yet
for (const child of Array.from(parent.childNodes)) {
if (child.nodeType === Node.TEXT_NODE) {
const text = child.textContent ?? '';
if (text.length > 0) {
if (pendingBlockBoundary) {
out += '\n';
pendingBlockBoundary = false;
}
out += text;
first = false;
}
continue;
}
if (child.nodeType !== Node.ELEMENT_NODE) continue;
const el = child as HTMLElement;
if (el.getAttribute(MENTION_BADGE_DATA_ATTRS.BADGE) === BooleanString.TRUE) {
const name = el.getAttribute(MENTION_BADGE_DATA_ATTRS.NAME) ?? '';
const path = el.getAttribute(MENTION_BADGE_DATA_ATTRS.PATH) ?? '';
if (name && path) {
if (pendingBlockBoundary) {
out += '\n';
pendingBlockBoundary = false;
}
out += `[${name}](file://${path})`;
first = false;
}
continue;
}
const codeToken = el.getAttribute(CODE_TOKEN_ATTR);
if (codeToken !== null) {
const isBlock = codeToken === ChatFormInputRichTokenKind.CODE_BLOCK;
if (isBlock && (pendingBlockBoundary || !first)) out += '\n';
pendingBlockBoundary = false;
walk(el);
first = false;
if (isBlock) pendingBlockBoundary = true;
continue;
}
if (el.tagName === 'BR') {
const isHatch =
isCodeBlockElement(el.previousSibling) || isCodeBlockElement(el.nextSibling);
if (!isHatch && el.nextSibling) {
if (pendingBlockBoundary) {
out += '\n';
pendingBlockBoundary = false;
}
out += '\n';
first = false;
}
continue;
}
if (BLOCK_TAG_NAMES.has(el.tagName)) {
if (pendingBlockBoundary || !first) out += '\n';
pendingBlockBoundary = false;
walk(el);
first = false;
continue;
}
walk(el);
if (pendingBlockBoundary) first = false;
}
};
walk(root);
return out;
}
/**
* Compare the live DOM's non-text structure against a token stream.
* Only element contributions are compared (badges by name/path, code
* spans by kind and source segment): text nodes are owned by the
* browser between rebuilds, so their split/merge state is irrelevant.
* A mismatch means token boundaries shifted (a code span was just
* completed or broken) and the DOM needs a rebuild to restyle.
*/
export function domMatchesTokens(root: HTMLElement, tokens: ChatFormInputRichToken[]): boolean {
const expected = tokens.filter((token) => token.kind !== ChatFormInputRichTokenKind.TEXT);
let index = 0;
const walk = (parent: Node): boolean => {
for (const child of Array.from(parent.childNodes)) {
if (child.nodeType !== Node.ELEMENT_NODE) continue;
const el = child as HTMLElement;
const isBadge = el.getAttribute(MENTION_BADGE_DATA_ATTRS.BADGE) === BooleanString.TRUE;
const isCode = el.getAttribute(CODE_TOKEN_ATTR) !== null;
if (!isBadge && !isCode) {
if (!walk(el)) return false;
continue;
}
const token = expected[index++];
if (!token) return false;
if (isBadge) {
if (token.kind !== ChatFormInputRichTokenKind.BADGE) return false;
if (token.name !== (el.getAttribute(MENTION_BADGE_DATA_ATTRS.NAME) ?? '')) return false;
if (token.path !== (el.getAttribute(MENTION_BADGE_DATA_ATTRS.PATH) ?? '')) return false;
continue;
}
const codeKind: ChatFormInputRichTokenKind =
el.getAttribute(CODE_TOKEN_ATTR) === ChatFormInputRichTokenKind.CODE_BLOCK
? ChatFormInputRichTokenKind.CODE_BLOCK
: ChatFormInputRichTokenKind.CODE_INLINE;
if (token.kind !== codeKind) return false;
if (
token.kind === ChatFormInputRichTokenKind.CODE_INLINE ||
token.kind === ChatFormInputRichTokenKind.CODE_BLOCK
) {
if (token.text !== (el.textContent ?? '')) return false;
}
}
return true;
};
return walk(root) && index === expected.length;
}
/**
* Plain-text offset of a `Range` in the root; null range (selection
* lost) falls back to buffer length. Walked against the live DOM (not
* a clone) so a `<br>` keeps its trailing/not-trailing context. Code
* spans count their full textContent (fences included) and the caret
* may land inside them; synthesized block boundaries count one `\n`
* once the caret is past them.
*/
export function rangeToTextOffset(root: HTMLElement, range: Range | null): number {
if (!range) return serializeContent(root).length;
// A point is at/before the caret iff it falls inside [root start, caret].
const pre = range.cloneRange();
pre.selectNodeContents(root);
pre.setEnd(range.endContainer, range.endOffset);
const atOrBeforeCaret = (node: Node, offset: number) => pre.comparePoint(node, offset) !== 1;
let total = 0;
let done = false;
// DOM position of a code block's synthesized after-boundary, set
// when walking past a block and consumed by the next contributing
// sibling (counts one `\n` once the caret is past it).
let pendingPoint: { node: Node; index: number } | null = null;
const walk = (parent: Node) => {
let first = true;
for (const child of Array.from(parent.childNodes)) {
if (done) return;
if (child.nodeType === Node.TEXT_NODE) {
const text = child.textContent ?? '';
if (text.length === 0) continue;
if (pendingPoint) {
const { index, node } = pendingPoint;
pendingPoint = null;
if (!atOrBeforeCaret(node, index)) {
done = true;
return;
}
total += 1;
}
if (!atOrBeforeCaret(child, 0)) {
done = true;
return;
}
if (range.endContainer === child) {
total += range.endOffset;
done = true;
return;
}
total += text.length;
first = false;
continue;
}
if (child.nodeType !== Node.ELEMENT_NODE) continue;
const el = child as HTMLElement;
const parentNode = el.parentNode as Node;
const elIndex = Array.prototype.indexOf.call(parentNode.childNodes, el);
if (pendingPoint) {
const { index, node } = pendingPoint;
pendingPoint = null;
if (!atOrBeforeCaret(node, index)) {
done = true;
return;
}
total += 1;
}
if (el.getAttribute(MENTION_BADGE_DATA_ATTRS.BADGE) === BooleanString.TRUE) {
const len = badgeSourceLength(
el.getAttribute(MENTION_BADGE_DATA_ATTRS.NAME) ?? '',
el.getAttribute(MENTION_BADGE_DATA_ATTRS.PATH) ?? ''
);
if (len === 0) continue;
if (!atOrBeforeCaret(parentNode, elIndex + 1)) {
done = true;
return;
}
total += len;
first = false;
continue;
}
const codeToken = el.getAttribute(CODE_TOKEN_ATTR);
if (codeToken !== null) {
const isBlock = codeToken === ChatFormInputRichTokenKind.CODE_BLOCK;
if (isBlock && !first) {
if (!atOrBeforeCaret(el, 0)) {
done = true;
return;
}
total += 1;
}
walk(el);
first = false;
if (isBlock) pendingPoint = { index: elIndex + 1, node: parentNode };
continue;
}
if (el.tagName === 'BR') {
const isHatch =
isCodeBlockElement(el.previousSibling) || isCodeBlockElement(el.nextSibling);
if (isHatch || !el.nextSibling) continue;
if (!atOrBeforeCaret(parentNode, elIndex + 1)) {
done = true;
return;
}
total += 1;
first = false;
continue;
}
if (BLOCK_TAG_NAMES.has(el.tagName)) {
if (!first) {
if (!atOrBeforeCaret(el, 0)) {
done = true;
return;
}
total += 1;
}
walk(el);
first = false;
continue;
}
const before = total;
walk(el);
if (total > before) first = false;
}
};
walk(root);
return total;
}
/**
* Materialize a token stream into a DOM subtree: text nodes for text
* tokens, `<span data-mention-badge="true">` elements for badges,
* `<code data-code-token>` elements for code spans. The badge's class
* string + inline SVG are shared with the rehype plugin via
* `$lib/constants`.
*/
export function buildFragment(tokens: ChatFormInputRichToken[]): DocumentFragment {
const fragment = document.createDocumentFragment();
for (let index = 0; index < tokens.length; index++) {
const token = tokens[index];
if (token.kind === ChatFormInputRichTokenKind.TEXT) {
let text = token.text;
// The separator \n at a fenced-block boundary is synthesized
// at serialization time; keeping it in the DOM would render a
// phantom empty line next to the block.
if (
tokens[index - 1]?.kind === ChatFormInputRichTokenKind.CODE_BLOCK &&
text.startsWith('\n')
) {
text = text.slice(1);
}
if (
tokens[index + 1]?.kind === ChatFormInputRichTokenKind.CODE_BLOCK &&
text.endsWith('\n')
) {
text = text.slice(0, -1);
}
if (text.length === 0) continue;
fragment.appendChild(document.createTextNode(text));
continue;
}
if (
token.kind === ChatFormInputRichTokenKind.CODE_INLINE ||
token.kind === ChatFormInputRichTokenKind.CODE_BLOCK
) {
const code = document.createElement('code');
code.setAttribute(CODE_TOKEN_ATTR, token.kind);
code.textContent = token.text;
fragment.appendChild(code);
continue;
}
// A leading badge gets an empty text node prepended: without a real
// text position at the buffer start, the spot before the badge is
// unreachable via keyboard (ArrowLeft/Home).
if (!fragment.lastChild) {
fragment.appendChild(document.createTextNode(''));
}
const badge = document.createElement('span');
badge.setAttribute(MENTION_BADGE_DATA_ATTRS.BADGE, BooleanString.TRUE);
badge.setAttribute(MENTION_BADGE_DATA_ATTRS.NAME, token.name);
badge.setAttribute(MENTION_BADGE_DATA_ATTRS.PATH, token.path);
badge.title = decodeFileLinkPath(token.path);
badge.className = MENTION_BADGE_CLASSNAME;
badge.contentEditable = 'false';
const svg = document.createElementNS(MENTION_BADGE_SVG_ATTRIBUTES['xmlns'], 'svg');
for (const [attr, value] of Object.entries(MENTION_BADGE_SVG_ATTRIBUTES)) {
svg.setAttribute(attr, value);
}
for (const cls of MENTION_BADGE_ICON_CLASSNAME.split(/\s+/).filter(Boolean)) {
svg.classList.add(cls);
}
for (const d of getMentionBadgeIconPaths(token.path)) {
const path = document.createElementNS(MENTION_BADGE_SVG_ATTRIBUTES['xmlns'], 'path');
path.setAttribute('d', d);
svg.appendChild(path);
}
const label = document.createElement('span');
label.classList.add('shrink-0', 'truncate');
label.textContent = getMentionBadgeLabel(
token.name,
decodeFileLinkPath(token.path),
settingsStore.getConfig(SETTINGS_KEYS.SHOW_FULL_PATH_IN_MENTIONS),
toolsStore.serverHome
);
badge.appendChild(svg);
badge.appendChild(label);
fragment.appendChild(badge);
}
return fragment;
}
// A sibling provides a reachable caret line when it is an element
// (badge, another block, an existing hatch) or a non-empty text node.
function hasLineBeside(node: Node | null): boolean {
if (!node) return false;
if (node.nodeType === Node.ELEMENT_NODE) return true;
return (node.textContent ?? '') !== '';
}
/**
* A code block at the END of the buffer needs an editable line after
* it: without one the caret cannot leave the block with
* ArrowDown/ArrowRight. A trailing `<br>` provides that line while
* staying transparent to serialization (skipped as a hatch), and is
* removed again once real content takes its place.
*
* No hatch is added BEFORE a leading block: the empty line above it
* is transient and managed by the component (created when the caret
* arrows onto it, removed when the caret leaves). A transient
* leading hatch found here is kept; the browser's lone placeholder
* `<br>` in an empty root is left untouched.
*/
export function syncCodeBlockHatches(root: HTMLElement) {
for (const child of Array.from(root.childNodes)) {
if (child.nodeName !== 'BR') continue;
const isPlaceholder = root.childNodes.length === 1;
const isLeadingHatch = !child.previousSibling && isCodeBlockElement(child.nextSibling);
const isTrailingHatch = !child.nextSibling && isCodeBlockElement(child.previousSibling);
// A hatch goes stale once real content takes over its line:
// content before a leading hatch, content after a trailing one,
// or a text node after the block already providing the line.
// A `<br>` with no code block around is a real newline (browser
// Shift+Enter shape) and stays.
let prevElement = child.previousSibling;
while (prevElement && prevElement.nodeType !== Node.ELEMENT_NODE) {
prevElement = prevElement.previousSibling;
}
const nearBlock =
isCodeBlockElement(child.nextSibling) ||
isCodeBlockElement(child.previousSibling) ||
isCodeBlockElement(prevElement);
if (!isPlaceholder && !isLeadingHatch && !isTrailingHatch && nearBlock) {
child.remove();
}
}
for (const child of Array.from(root.childNodes)) {
if (!isCodeBlockElement(child)) continue;
if (!hasLineBeside(child.nextSibling)) {
child.after(document.createElement('br'));
}
}
}
/**
* Strip the separator and artificial newlines from an all-newline text
* node directly after a fenced block. Chromium's line break at the
* buffer end inserts an extra artificial `\n` so the new line has
* height, and the first `\n` after a block doubles as the fence's
* separator line (synthesized at serialization time). Removing both
* makes Shift+Enter after a block land the caret on the line directly
* below the block, like a plain textarea would.
*
* Only all-newline text nodes are touched: a node with real content
* carries intentional blank lines and is left alone. Returns true when
* the DOM changed.
*/
export function stripBlockBoundaryLineBreaks(root: HTMLElement): boolean {
let changed = false;
for (const child of Array.from(root.childNodes)) {
if (child.nodeType !== Node.TEXT_NODE) continue;
if (!isCodeBlockElement(child.previousSibling)) continue;
let text = child.textContent ?? '';
if (!/^\n{2,}$/.test(text)) continue;
text = text.slice(1);
const atBufferEnd = !child.nextSibling || child.nextSibling.nodeName === 'BR';
if (atBufferEnd) {
text = text.slice(0, -1);
}
child.textContent = text;
changed = true;
}
return changed;
}
const WORD_CHAR_RE = /[\p{L}\p{N}_]/u;
/**
* Word-jump target (Option+Arrow / Ctrl+Arrow) in source offsets, or null
* when the jump crosses no badge and native word movement should handle
* it. Badge spans are masked to word characters, so a badge counts as
* exactly one word.
*/
export function badgeAwareWordJump(
source: string,
offset: number,
direction: 'forward' | 'backward'
): number | null {
let masked = '';
const badgeSpans: Array<[number, number]> = [];
for (const token of tokenizeContent(source)) {
const len =
token.kind === ChatFormInputRichTokenKind.BADGE
? badgeSourceLength(token.name, token.path)
: token.text.length;
if (token.kind === ChatFormInputRichTokenKind.BADGE)
badgeSpans.push([masked.length, masked.length + len]);
masked += token.kind === ChatFormInputRichTokenKind.BADGE ? 'a'.repeat(len) : token.text;
}
if (badgeSpans.length === 0) return null;
const isWord = (index: number) => WORD_CHAR_RE.test(masked[index]);
const spanStartingAt = (index: number) => badgeSpans.find(([start]) => start === index);
const spanEndingAt = (index: number) => badgeSpans.find(([, end]) => end === index);
const n = masked.length;
let i = offset;
if (direction === 'forward') {
// Entering a badge completes the word phase at the badge's end edge.
if (!(i < n && isWord(i))) {
while (i < n && !isWord(i)) i++;
}
while (i < n && isWord(i)) {
const span = spanStartingAt(i);
if (span) {
i = span[1];
break;
}
i++;
}
} else {
if (!(i > 0 && isWord(i - 1))) {
while (i > 0 && !isWord(i - 1)) i--;
}
while (i > 0 && isWord(i - 1)) {
const span = spanEndingAt(i);
if (span) {
i = span[0];
break;
}
i--;
}
}
if (i === offset) return null;
const lo = Math.min(offset, i);
const hi = Math.max(offset, i);
return badgeSpans.some(([start, end]) => start < hi && end > lo) ? i : null;
}
/**
* 0 when `caret` sits exactly at a leading badge's end edge, null
* otherwise. Plain ArrowLeft there has no native previous position, so
* the host snaps the caret to the buffer start manually.
*/
export function leadingBadgeEdgeOffset(source: string, caret: number): number | null {
const [first] = tokenizeContent(source);
if (!first || first.kind !== ChatFormInputRichTokenKind.BADGE) return null;
return caret === badgeSourceLength(first.name, first.path) ? 0 : null;
}
/**
* Translate a plain-text offset into a degenerate `Range` at that
* position in the DOM; out-of-range offsets clamp to buffer end (before
* a trailing escape hatch, not after it). Zero offset lands BEFORE a
* badge or code span, and an offset exactly at a code span's end lands
* AFTER it, so typing at a code span's edge extends the surrounding
* text. Interior code-span offsets land in the element's text.
* Understands the same block/`<br>` newline shapes as
* `serializeContent`.
*/
export function textOffsetToRange(root: HTMLElement, offset: number): Range {
const range = document.createRange();
let remaining = offset;
let landed = false;
let pendingBlockBoundary = false;
const land = (node: Node, nodeOffset: number) => {
range.setStart(node, nodeOffset);
range.setEnd(node, nodeOffset);
landed = true;
};
const walk = (parent: Node) => {
let first = true;
for (const child of Array.from(parent.childNodes)) {
if (landed) return;
if (child.nodeType === Node.TEXT_NODE) {
const text = child.textContent ?? '';
if (text.length === 0) continue;
if (pendingBlockBoundary) {
// The synthesized separator maps to the near edge of the
// content that follows the block.
pendingBlockBoundary = false;
if (remaining === 0) {
land(child, 0);
return;
}
remaining -= 1;
}
if (remaining <= text.length) {
land(child, remaining);
return;
}
remaining -= text.length;
first = false;
continue;
}
if (child.nodeType !== Node.ELEMENT_NODE) continue;
const el = child as HTMLElement;
if (el.getAttribute(MENTION_BADGE_DATA_ATTRS.BADGE) === BooleanString.TRUE) {
const len = badgeSourceLength(
el.getAttribute(MENTION_BADGE_DATA_ATTRS.NAME) ?? '',
el.getAttribute(MENTION_BADGE_DATA_ATTRS.PATH) ?? ''
);
if (len === 0) continue;
if (pendingBlockBoundary) {
pendingBlockBoundary = false;
if (remaining === 0) {
range.setStartBefore(el);
range.setEndBefore(el);
landed = true;
return;
}
remaining -= 1;
}
if (remaining <= len) {
if (remaining === 0) {
range.setStartBefore(el);
range.setEndBefore(el);
} else {
range.setStartAfter(el);
range.setEndAfter(el);
}
landed = true;
return;
}
remaining -= len;
first = false;
continue;
}
const codeToken = el.getAttribute(CODE_TOKEN_ATTR);
if (codeToken !== null) {
const isBlock = codeToken === ChatFormInputRichTokenKind.CODE_BLOCK;
if (isBlock && (pendingBlockBoundary || !first)) {
pendingBlockBoundary = false;
if (remaining === 0) {
range.setStartBefore(el);
range.setEndBefore(el);
landed = true;
return;
}
remaining -= 1;
}
const len = (el.textContent ?? '').length;
if (remaining === 0) {
range.setStartBefore(el);
range.setEndBefore(el);
landed = true;
return;
}
if (remaining === len) {
range.setStartAfter(el);
range.setEndAfter(el);
landed = true;
return;
}
if (remaining < len) {
walk(el);
return;
}
remaining -= len;
if (isBlock) remaining -= 1;
first = false;
continue;
}
if (el.tagName === 'BR') {
const isHatch =
isCodeBlockElement(el.previousSibling) || isCodeBlockElement(el.nextSibling);
if (isHatch) {
// Escape hatch: no source length; offset 0 lands before it
// so text typed there takes its place.
if (remaining === 0) {
range.setStartBefore(el);
range.setEndBefore(el);
landed = true;
}
continue;
}
if (!el.nextSibling) continue;
if (pendingBlockBoundary) {
pendingBlockBoundary = false;
if (remaining === 0) {
range.setStartBefore(el);
range.setEndBefore(el);
landed = true;
return;
}
remaining -= 1;
}
if (remaining === 0) {
range.setStartBefore(el);
range.setEndBefore(el);
landed = true;
return;
}
remaining -= 1;
first = false;
continue;
}
if (BLOCK_TAG_NAMES.has(el.tagName)) {
if (pendingBlockBoundary || !first) {
pendingBlockBoundary = false;
if (remaining === 0) {
// The boundary newline belongs to the previous line.
range.setStartBefore(el);
range.setEndBefore(el);
landed = true;
return;
}
remaining -= 1;
}
walk(el);
first = false;
continue;
}
const before = remaining;
walk(el);
if (remaining < before) first = false;
}
};
walk(root);
if (!landed) {
const last = root.lastChild;
if (last && last.nodeName === 'BR') {
range.setStartBefore(last);
range.setEndBefore(last);
} else {
range.selectNodeContents(root);
range.collapse(false);
}
}
return range;
}
|