First upload version 0.0.1

This commit is contained in:
Neyra
2026-02-05 15:27:49 +08:00
commit 8e9b7201ed
4182 changed files with 593136 additions and 0 deletions

View File

@@ -0,0 +1,22 @@
export declare const enum ConsoleInteractionKey {
ctrlC = "\u0003",
upArrow = "\u001B[A",
downArrow = "\u001B[B",
enter = "\r"
}
export declare class ConsoleInteraction {
constructor({ stdin }?: {
stdin?: NodeJS.ReadStream;
});
get isActive(): boolean;
start(): void;
stop(): void;
onKey(key: string | ConsoleInteractionKey | (string | ConsoleInteractionKey)[], callback: () => void): ConsoleInteractionOnKeyHandle;
static yesNoQuestion(question: string): Promise<boolean>;
}
export declare class ConsoleInteractionOnKeyHandle {
private constructor();
dispose(): void;
[Symbol.dispose](): void;
get disposed(): boolean;
}

View File

@@ -0,0 +1,122 @@
import process from "process";
import chalk from "chalk";
export var ConsoleInteractionKey;
(function (ConsoleInteractionKey) {
ConsoleInteractionKey["ctrlC"] = "\u0003";
ConsoleInteractionKey["upArrow"] = "\u001B[A";
ConsoleInteractionKey["downArrow"] = "\u001B[B";
ConsoleInteractionKey["enter"] = "\r";
})(ConsoleInteractionKey || (ConsoleInteractionKey = {}));
export class ConsoleInteraction {
/** @internal */ _keyCallbacks = new Map();
/** @internal */ _stdin;
/** @internal */ _isActive = false;
constructor({ stdin = process.stdin } = {}) {
this._stdin = stdin;
this._onData = this._onData.bind(this);
}
get isActive() {
return this._isActive;
}
start() {
if (this._isActive)
return;
this._isActive = true;
if (this._stdin.isTTY)
this._stdin.setRawMode(true);
this._stdin.on("data", this._onData);
this._stdin.resume();
}
stop() {
if (!this._isActive)
return;
this._isActive = false;
if (this._stdin.isTTY)
this._stdin.setRawMode(false);
this._stdin.off("data", this._onData);
this._stdin.pause();
}
onKey(key, callback) {
if (typeof key === "string")
key = [key];
for (const k of key) {
if (!this._keyCallbacks.has(k))
this._keyCallbacks.set(k, []);
this._keyCallbacks.get(k).push(callback);
}
return ConsoleInteractionOnKeyHandle._create(() => {
for (const k of key) {
const callbacks = this._keyCallbacks.get(k);
if (callbacks == null)
continue;
const index = callbacks.indexOf(callback);
if (index >= 0)
callbacks.splice(index, 1);
}
});
}
/** @internal */
_onData(data) {
if (!this._isActive)
return;
const key = data.toString();
const callbacks = this._keyCallbacks.get(key) ?? [];
if (callbacks.length === 0 && key === ConsoleInteractionKey.ctrlC) {
process.stdout.write("\n");
this.stop();
process.exit(0);
}
for (const callback of callbacks) {
try {
callback();
}
catch (err) {
console.error(err);
}
}
}
static yesNoQuestion(question) {
return new Promise((resolve) => {
const interaction = new ConsoleInteraction();
interaction.onKey(["Y", "y"], () => {
resolve(true);
interaction.stop();
process.stdout.write("\n");
});
interaction.onKey(["N", "n"], () => {
resolve(false);
interaction.stop();
process.stdout.write("\n");
});
console.log();
process.stdout.write(question + " " + chalk.gray("(Y/n) "));
interaction.start();
});
}
}
export class ConsoleInteractionOnKeyHandle {
/** @internal */
_dispose;
constructor(dispose) {
this._dispose = dispose;
this.dispose = this.dispose.bind(this);
this[Symbol.dispose] = this[Symbol.dispose].bind(this);
}
dispose() {
if (this._dispose != null) {
this._dispose();
this._dispose = null;
}
}
[Symbol.dispose]() {
this.dispose();
}
get disposed() {
return this._dispose == null;
}
/** @internal */
static _create(dispose) {
return new ConsoleInteractionOnKeyHandle(dispose);
}
}
//# sourceMappingURL=ConsoleInteraction.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"ConsoleInteraction.js","sourceRoot":"","sources":["../../../src/cli/utils/ConsoleInteraction.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,SAAS,CAAC;AAC9B,OAAO,KAAK,MAAM,OAAO,CAAC;AAE1B,MAAM,CAAN,IAAkB,qBAKjB;AALD,WAAkB,qBAAqB;IACnC,yCAAgB,CAAA;IAChB,6CAAoB,CAAA;IACpB,+CAAsB,CAAA;IACtB,qCAAY,CAAA;AAChB,CAAC,EALiB,qBAAqB,KAArB,qBAAqB,QAKtC;AAED,MAAM,OAAO,kBAAkB;IAC3B,gBAAgB,CAA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C,MAAM,CAAC,OAAO,CAAC,GAAG,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAC3D,CAAC;IAEM,OAAO;QACV,IAAI,IAAI,CAAC,QAAQ,IAAI,IAAI,EAAE,CAAC;YACxB,IAAI,CAAC,QAAQ,EAAE,CAAC;YAChB,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC;QACzB,CAAC;IACL,CAAC;IAEM,CAAC,MAAM,CAAC,OAAO,CAAC;QACnB,IAAI,CAAC,OAAO,EAAE,CAAC;IACnB,CAAC;IAED,IAAW,QAAQ;QACf,OAAO,IAAI,CAAC,QAAQ,IAAI,IAAI,CAAC;IACjC,CAAC;IAED,gBAAgB;IACT,MAAM,CAAC,OAAO,CAAC,OAAmB;QACrC,OAAO,IAAI,6BAA6B,CAAC,OAAO,CAAC,CAAC;IACtD,CAAC;CACJ"}

View File

@@ -0,0 +1,24 @@
export declare class ConsoleTable<const T extends readonly ConsoleTableColumn[]> {
private readonly _columns;
private readonly _columnSeparator;
private readonly _drawHeaderRowSeparator;
constructor(columns: T, { columnSeparator, drawHeaderRowSeparator }?: {
columnSeparator?: string;
drawHeaderRowSeparator?: boolean;
});
logHeader({ drawRowSeparator }?: {
drawRowSeparator?: boolean;
}): void;
logLine(data: {
[key in T[number]["key"]]?: string;
}): void;
}
export type ConsoleTableColumn<K extends string = string> = {
readonly key: K;
readonly title?: string;
readonly titleFormatter?: (value: string) => string;
readonly width?: number;
readonly valueFormatter?: (value: string) => string;
readonly canSpanOverEmptyColumns?: boolean;
readonly visible?: boolean;
};

View File

@@ -0,0 +1,90 @@
import chalk from "chalk";
import sliceAnsi from "slice-ansi";
import stripAnsi from "strip-ansi";
export class ConsoleTable {
_columns;
_columnSeparator;
_drawHeaderRowSeparator;
constructor(columns, { columnSeparator = chalk.gray(" | "), drawHeaderRowSeparator = true } = {}) {
this._columns = filterHiddenColumns(columns);
this._columnSeparator = columnSeparator;
this._drawHeaderRowSeparator = drawHeaderRowSeparator;
}
logHeader({ drawRowSeparator = this._drawHeaderRowSeparator } = {}) {
let logLine = "";
for (let i = 0; i < this._columns.length; i++) {
const column = this._columns[i];
const canSpanOverEmptyColumns = column.canSpanOverEmptyColumns ?? false;
let title = column.title ?? " ";
let columnSize = getColumnWidth(column);
title = toOneLine(title);
title = (column.titleFormatter ?? defaultTitleFormatter)(title);
while (title.length > columnSize && canSpanOverEmptyColumns && i < this._columns.length - 1) {
i++;
const nextColumn = this._columns[i];
if (nextColumn.title != null) {
i--;
break;
}
columnSize += stripAnsi(this._columnSeparator).length + getColumnWidth(nextColumn);
}
const moreText = "...";
if (stripAnsi(title).length > columnSize)
title = sliceAnsi(title, 0, columnSize - moreText.length) + chalk.gray(moreText);
title = title + " ".repeat(Math.max(0, columnSize - stripAnsi(title).length));
title = sliceAnsi(title, 0, columnSize);
if (i < this._columns.length - 1)
title += this._columnSeparator;
logLine += title;
}
console.info(logLine);
if (drawRowSeparator)
console.info(chalk.gray("-".repeat(stripAnsi(logLine).length)));
}
logLine(data) {
let logLine = "";
for (let i = 0; i < this._columns.length; i++) {
const column = this._columns[i];
let value = data[column.key];
const canSpanOverEmptyColumns = column.canSpanOverEmptyColumns ?? false;
if (value != null && column.valueFormatter != null)
value = column.valueFormatter(value);
if (value == null)
value = "";
value = toOneLine(value);
const valueWithoutAnsi = stripAnsi(value);
let columnSize = getColumnWidth(column);
while (valueWithoutAnsi.length > columnSize && canSpanOverEmptyColumns && i < this._columns.length - 1) {
i++;
const nextColumn = this._columns[i];
const nextValue = data[nextColumn.key];
if (nextValue != null) {
i--;
break;
}
columnSize += stripAnsi(this._columnSeparator).length + getColumnWidth(nextColumn);
}
const moreText = "...";
if (valueWithoutAnsi.length > columnSize)
value = sliceAnsi(value, 0, columnSize - moreText.length) + chalk.gray(moreText);
value = value + " ".repeat(Math.max(0, columnSize - valueWithoutAnsi.length));
value = sliceAnsi(value, 0, columnSize);
if (i < this._columns.length - 1)
value += this._columnSeparator;
logLine += value;
}
console.info(logLine);
}
}
const defaultTitleFormatter = (value) => chalk.bold(value);
function getColumnWidth(column) {
return column.width ?? stripAnsi(toOneLine(column.title ?? " ")).length;
}
function toOneLine(text) {
return text.replaceAll("\n", chalk.gray("\\n"));
}
function filterHiddenColumns(columns) {
return columns
.filter((column) => column.visible !== false);
}
//# sourceMappingURL=ConsoleTable.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"ConsoleTable.js","sourceRoot":"","sources":["../../../src/cli/utils/ConsoleTable.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,SAAS,MAAM,YAAY,CAAC;AACnC,OAAO,SAAS,MAAM,YAAY,CAAC;AAEnC,MAAM,OAAO,YAAY;IACJ,QAAQ,CAAI;IACZ,gBAAgB,CAAS;IACzB,uBAAuB,CAAU;IAElD,YAAmB,OAAU,EAAE,EAC3B,eAAe,GAAG,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,EACnC,sBAAsB,GAAG,IAAI,KAI7B,EAAE;QACF,IAAI,CAAC,QAAQ,GAAG,mBAAmB,CAAC,OAAO,CAAC,CAAC;QAC7C,IAAI,CAAC,gBAAgB,GAAG,eAAe,CAAC;QACxC,IAAI,CAAC,uBAAuB,GAAG,sBAAsB,CAAC;IAC1D,CAAC;IAEM,SAAS,CAAC,EAAC,gBAAgB,GAAG,IAAI,CAAC,uBAAuB,KAAkC,EAAE;QACjG,IAAI,OAAO,GAAG,EAAE,CAAC;QAEjB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,QAAQ,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;YAC5C,MAAM,MAAM,GAAG,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAE,CAAC;YACjC,MAAM,uBAAuB,GAAG,MAAM,CAAC,uBAAuB,IAAI,KAAK,CAAC;YACxE,IAAI,KAAK,GAAG,MAAM,CAAC,KAAK,IAA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,OAAO,IAAI,CAAC,UAAU,CAAC,IAAI,EAAE,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC;AACpD,CAAC;AAED,SAAS,mBAAmB,CAAgD,OAAU;IAClF,OAAO,OAAO;SACT,MAAM,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,OAAO,KAAK,KAAK,CAAuC,CAAC;AAC5F,CAAC"}

View File

@@ -0,0 +1,13 @@
export declare function basicChooseFromListConsoleInteraction<T>({ title, footer, items, renderItem, canFocusItem, canSelectItem, initialFocusIndex, aboveItemsPadding, belowItemsPadding, renderSummaryOnExit, exitOnCtrlC }: {
title: string | ((focusedItem: T, rerender: () => void) => string);
footer?: string | ((focusedItem: T, rerender: () => void) => string | undefined);
items: T[];
renderItem(item: T, focused: boolean, rerender: () => void): string;
canFocusItem?(item: T): boolean;
canSelectItem?(item: T): boolean;
initialFocusIndex?: number;
aboveItemsPadding?: number;
belowItemsPadding?: number;
renderSummaryOnExit?(item: T | null): string;
exitOnCtrlC?: boolean;
}): Promise<T | null>;

View File

@@ -0,0 +1,111 @@
import process from "process";
import UpdateManager from "stdout-update";
import stripAnsi from "strip-ansi";
import sliceAnsi from "slice-ansi";
import chalk from "chalk";
import { ConsoleInteraction, ConsoleInteractionKey } from "./ConsoleInteraction.js";
import { splitAnsiToLines } from "./splitAnsiToLines.js";
export async function basicChooseFromListConsoleInteraction({ title, footer, items, renderItem, canFocusItem, canSelectItem, initialFocusIndex = 0, aboveItemsPadding = 1, belowItemsPadding = 1, renderSummaryOnExit = (item) => (item == null ? "" : renderItem(item, false, () => void 0)), exitOnCtrlC = true }) {
const updateManager = UpdateManager.getInstance();
let focusIndex = initialFocusIndex;
let scrollOffset = 0;
let rerenderTimeout = undefined;
let isDone = false;
function adjustScrollOffset(screenLines) {
if (focusIndex < scrollOffset + aboveItemsPadding)
scrollOffset = Math.max(0, focusIndex - aboveItemsPadding);
else if (focusIndex > scrollOffset + screenLines - belowItemsPadding)
scrollOffset = Math.min(Math.max(0, focusIndex - screenLines + belowItemsPadding), items.length - 1 - screenLines);
}
function scheduleRerender() {
if (isDone)
return;
if (rerenderTimeout == null)
rerenderTimeout = setTimeout(renderScreen, 0);
}
function renderScreen() {
clearTimeout(rerenderTimeout);
rerenderTimeout = undefined;
if (isDone)
return;
while (canFocusItem != null && focusIndex > 0 && !canFocusItem(items[focusIndex]))
focusIndex--;
while (canFocusItem != null && focusIndex < items.length - 1 && !canFocusItem(items[focusIndex]))
focusIndex++;
const maxWidth = (process.stdout.columns ?? 80) - 2;
const maxHeight = (process.stdout.rows ?? 24) - 2;
const focusedItem = items[focusIndex];
const titleLines = splitAnsiToLines(title instanceof Function ? title(focusedItem, scheduleRerender) : title, maxWidth);
const footerLines = splitAnsiToLines(footer instanceof Function ? footer(focusedItem, scheduleRerender) : footer, maxWidth);
const reservedLinesCount = titleLines.length + footerLines.length;
const maxItemLinesCount = Math.max(1, maxHeight - reservedLinesCount);
adjustScrollOffset(maxItemLinesCount);
updateManager.update([
...titleLines,
...items
.slice(scrollOffset, scrollOffset + maxItemLinesCount + 1)
.map((item, index) => (renderSingleLine(renderItem(item, scrollOffset + index === focusIndex, scheduleRerender), maxWidth))),
...footerLines
]);
}
updateManager.hook();
const consoleInteraction = new ConsoleInteraction();
try {
consoleInteraction.onKey(ConsoleInteractionKey.upArrow, () => {
let newFocusIndex = Math.max(0, focusIndex - 1);
while (newFocusIndex > 0 && canFocusItem != null && !canFocusItem(items[newFocusIndex]))
newFocusIndex--;
if (canFocusItem == null || canFocusItem(items[newFocusIndex])) {
focusIndex = newFocusIndex;
renderScreen();
}
});
consoleInteraction.onKey(ConsoleInteractionKey.downArrow, () => {
let newFocusIndex = Math.min(items.length - 1, focusIndex + 1);
while (newFocusIndex < items.length - 1 && canFocusItem != null && !canFocusItem(items[newFocusIndex]))
newFocusIndex++;
if (canFocusItem == null || canFocusItem(items[newFocusIndex])) {
focusIndex = newFocusIndex;
renderScreen();
}
});
process.on("SIGWINCH", renderScreen);
renderScreen();
const res = await new Promise((resolve) => {
consoleInteraction.onKey(ConsoleInteractionKey.enter, () => {
if (canSelectItem == null || canSelectItem(items[focusIndex]))
resolve(items[focusIndex]);
});
consoleInteraction.onKey(ConsoleInteractionKey.ctrlC, () => {
if (exitOnCtrlC) {
updateManager.update([""]);
consoleInteraction.stop();
updateManager.unhook(true);
process.exit(0);
}
resolve(null);
});
consoleInteraction.start();
});
isDone = true;
clearTimeout(rerenderTimeout);
rerenderTimeout = undefined;
process.off("SIGWINCH", renderScreen);
updateManager.update([
renderSummaryOnExit(res)
]);
return res;
}
finally {
consoleInteraction.stop();
updateManager.unhook(true);
}
}
function renderSingleLine(text, maxWidth) {
const textWithoutAnsi = stripAnsi(text);
const moreText = "...";
if (textWithoutAnsi.length > maxWidth)
return sliceAnsi(text, 0, maxWidth - moreText.length) + chalk.gray(moreText);
return text;
}
//# sourceMappingURL=basicChooseFromListConsoleInteraction.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,6 @@
export declare function consolePromptQuestion(question: string, { validate, renderSummaryOnExit, exitOnCtrlC, defaultValue }?: {
validate?: (input: string) => string | null | Promise<string | null>;
renderSummaryOnExit?: (item: string | null) => string;
exitOnCtrlC?: boolean;
defaultValue?: string;
}): Promise<string | null>;

View File

@@ -0,0 +1,81 @@
import readline from "readline";
import process from "process";
import chalk from "chalk";
import { splitAnsiToLines } from "./splitAnsiToLines.js";
export async function consolePromptQuestion(question, { validate, renderSummaryOnExit, exitOnCtrlC = true, defaultValue } = {}) {
let lastErrorText = "";
let lastResponse = "";
process.stdout.moveCursor(0, -1);
while (true) {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
let res = await new Promise((accept) => {
const initialCursorPosition = rl.getCursorPos();
function onSigInt() {
rl.off("SIGINT", onSigInt);
rl.close();
const linesUsed = splitAnsiToLines(lastErrorText, process.stdout.columns).length +
rl.getCursorPos().rows - initialCursorPosition.rows + 1;
clearLastLines(linesUsed);
if (exitOnCtrlC) {
rl.close();
process.exit(0);
}
else
accept(null);
}
rl.on("SIGINT", onSigInt);
rl.question(question, (res) => {
rl.off("SIGINT", onSigInt);
rl.close();
accept(res);
});
rl.write(lastResponse);
});
const linesUsed = splitAnsiToLines(lastErrorText + question + res, process.stdout.columns).length + (res != null ? 1 : 0);
if (res == null) {
clearLastLines(linesUsed);
if (renderSummaryOnExit != null) {
const summary = renderSummaryOnExit(null);
if (summary !== "")
process.stdout.write(summary + "\n");
}
return null;
}
if (res === "" && defaultValue != null)
res = defaultValue;
lastResponse = res;
const validationError = await validate?.(res);
if (validationError != null) {
clearLastLines(linesUsed);
lastErrorText = chalk.red(validationError) + "\n";
process.stdout.write(lastErrorText);
continue;
}
else if (renderSummaryOnExit != null) {
clearLastLines(linesUsed);
const summary = renderSummaryOnExit(res);
if (summary !== "")
process.stdout.write(summary + "\n");
}
else if (lastErrorText !== "") {
clearLastLines(linesUsed);
process.stdout.write(question + res + "\n");
}
return res;
}
}
function clearLastLines(linesCount) {
if (linesCount === 0)
return;
process.stdout.write("\n");
for (let i = 0; i < linesCount; i++) {
process.stdout.moveCursor(0, -1);
process.stdout.clearLine(0);
}
process.stdout.write("\n");
process.stdout.moveCursor(0, -1);
}
//# sourceMappingURL=consolePromptQuestion.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"consolePromptQuestion.js","sourceRoot":"","sources":["../../../src/cli/utils/consolePromptQuestion.ts"],"names":[],"mappings":"AAAA,OAAO,QAAQ,MAAM,UAAU,CAAC;AAChC,OAAO,OAAO,MAAM,SAAS,CAAC;AAC9B,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAC,gBAAgB,EAAC,MAAM,uBAAuB,CAAC;AAGvD,MAAM,CAAC,KAAK,UAAU,qBAAqB,CAAC,QAAgB,EAAE,EAC1D,QAAQ,EACR,mBAAmB,EACnB,WAAW,GAAG,IAAI,EAClB,YAAY,KAMZ,EAAE;IACF,IAAI,aAAa,GAAG,EAAE,CAAC;I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AC,MAAM,CAAC,KAAK,CAAC,OAAO,GAAG,IAAI,CAAC,CAAC;QAC7C,CAAC;aAAM,IAAI,aAAa,KAAK,EAAE,EAAE,CAAC;YAC9B,cAAc,CAAC,SAAS,CAAC,CAAC;YAC1B,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,QAAQ,GAAG,GAAG,GAAG,IAAI,CAAC,CAAC;QAChD,CAAC;QAED,OAAO,GAAG,CAAC;IACf,CAAC;AACL,CAAC;AAED,SAAS,cAAc,CAAC,UAAkB;IACtC,IAAI,UAAU,KAAK,CAAC;QAChB,OAAO;IAEX,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IAE3B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,UAAU,EAAE,CAAC,EAAE,EAAE,CAAC;QAClC,OAAO,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;QACjC,OAAO,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;IAChC,CAAC;IAED,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IAC3B,OAAO,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;AACrC,CAAC"}

View File

@@ -0,0 +1 @@
export declare function getReadablePath(fsPath: string): string;

View File

@@ -0,0 +1,14 @@
import os from "os";
import path from "path";
export function getReadablePath(fsPath) {
const resolvedPath = path.resolve(process.cwd(), fsPath);
if (process.platform === "win32" || process.platform === "cygwin")
return resolvedPath;
let homedir = os.homedir();
if (!homedir.endsWith("/"))
homedir += "/";
if (resolvedPath.startsWith(homedir))
return "~" + resolvedPath.slice(homedir.length - "/".length);
return resolvedPath;
}
//# sourceMappingURL=getReadablePath.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"getReadablePath.js","sourceRoot":"","sources":["../../../src/cli/utils/getReadablePath.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,IAAI,MAAM,MAAM,CAAC;AAExB,MAAM,UAAU,eAAe,CAAC,MAAc;IAC1C,MAAM,YAAY,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,MAAM,CAAC,CAAC;IAEzD,IAAI,OAAO,CAAC,QAAQ,KAAK,OAAO,IAAI,OAAO,CAAC,QAAQ,KAAK,QAAQ;QAC7D,OAAO,YAAY,CAAC;IAExB,IAAI,OAAO,GAAG,EAAE,CAAC,OAAO,EAAE,CAAC;IAC3B,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAC;QACtB,OAAO,IAAI,GAAG,CAAC;IAEnB,IAAI,YAAY,CAAC,UAAU,CAAC,OAAO,CAAC;QAChC,OAAO,GAAG,GAAG,YAAY,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,GAAG,GAAG,CAAC,MAAM,CAAC,CAAC;IAEjE,OAAO,YAAY,CAAC;AACxB,CAAC"}

View File

@@ -0,0 +1,10 @@
import { Llama } from "../../bindings/Llama.js";
export declare function interactivelyAskForModel({ llama, modelsDirectory, allowLocalModels, downloadIntent, flashAttention, swaFullCache, useMmap }: {
llama: Llama;
modelsDirectory?: string;
allowLocalModels?: boolean;
downloadIntent?: boolean;
flashAttention?: boolean;
swaFullCache?: boolean;
useMmap?: boolean;
}): Promise<string>;

View File

@@ -0,0 +1,471 @@
import path from "path";
import process from "process";
import chalk from "chalk";
import fs from "fs-extra";
import stripAnsi from "strip-ansi";
import logSymbols from "log-symbols";
import { getReadableContextSize } from "../../utils/getReadableContextSize.js";
import { arrowChar } from "../../consts.js";
import { getGgufSplitPartsInfo } from "../../gguf/utils/resolveSplitGgufParts.js";
import { withProgressLog } from "../../utils/withProgressLog.js";
import { GgufInsights } from "../../gguf/insights/GgufInsights.js";
import { readGgufFileInfo } from "../../gguf/readGgufFileInfo.js";
import { getPrettyBuildGpuName } from "../../bindings/consts.js";
import { isUrl } from "../../utils/isUrl.js";
import { isModelUri, parseModelUri } from "../../utils/parseModelUri.js";
import { resolveModelRecommendationFileOptions } from "./resolveModelRecommendationFileOptions.js";
import { getReadablePath } from "./getReadablePath.js";
import { basicChooseFromListConsoleInteraction } from "./basicChooseFromListConsoleInteraction.js";
import { splitAnsiToLines } from "./splitAnsiToLines.js";
import { consolePromptQuestion } from "./consolePromptQuestion.js";
import { renderInfoLine } from "./printInfoLine.js";
import { renderModelCompatibilityPercentageWithColors } from "./renderModelCompatibilityPercentageWithColors.js";
import { toBytes } from "./toBytes.js";
const vramStateUpdateInterval = 1000;
export async function interactivelyAskForModel({ llama, modelsDirectory, allowLocalModels = true, downloadIntent = true, flashAttention = false, swaFullCache = false, useMmap }) {
let localModelFileOptions = [];
const recommendedModelOptions = [];
const activeInteractionController = new AbortController();
let scheduledTitleRerenderTimeout = undefined;
let vramState = await llama.getVramState();
const canUseGpu = vramState.total > 0;
if (allowLocalModels && modelsDirectory != null && await fs.existsSync(modelsDirectory)) {
const ggufFileNames = (await fs.readdir(modelsDirectory))
.filter((fileName) => {
if (!fileName.endsWith(".gguf"))
return false;
const partsInfo = getGgufSplitPartsInfo(fileName);
return partsInfo == null || partsInfo.part === 1;
});
let readItems = 0;
const renderProgress = () => ("(" + String(readItems)
.padStart(String(ggufFileNames.length).length, "0") + "/" + ggufFileNames.length + ")");
if (ggufFileNames.length > 0)
await withProgressLog({
loadingText: "Reading local models directory",
failText: "Failed to read local models directory",
successText: "Read local models directory",
noSuccessLiveStatus: true,
initialProgressBarText: renderProgress()
}, async (progressUpdater) => {
localModelFileOptions = await Promise.all(ggufFileNames.map(async (fileName) => {
const filePath = path.join(modelsDirectory, fileName);
let ggufInsights = undefined;
try {
const ggufFileInfo = await readGgufFileInfo(filePath, {
sourceType: "filesystem",
signal: activeInteractionController.signal
});
ggufInsights = await GgufInsights.from(ggufFileInfo, llama);
}
catch (err) {
// do nothing
}
readItems++;
progressUpdater.setProgress(readItems / ggufFileNames.length, renderProgress());
const compatibilityScore = await ggufInsights?.configurationResolver.scoreModelConfigurationCompatibility({
flashAttention: flashAttention && ggufInsights?.flashAttentionSupported,
swaFullCache,
useMmap
});
return {
type: "localModel",
title: fileName,
path: filePath,
addedDate: (await fs.stat(filePath)).birthtimeMs,
ggufInsights: ggufInsights,
compatibilityScore: compatibilityScore?.compatibilityScore,
compatibilityBonusScore: compatibilityScore?.bonusScore,
compatibilityContextSize: compatibilityScore?.resolvedValues.contextSize
};
}));
localModelFileOptions = localModelFileOptions.sort((a, b) => {
if (a.compatibilityScore == null && b.compatibilityScore == null)
return b.addedDate - a.addedDate;
else if (a.compatibilityScore == null)
return -1;
else if (b.compatibilityScore == null)
return 1;
else if (b.compatibilityScore === a.compatibilityScore &&
b.compatibilityBonusScore != null && a.compatibilityBonusScore != null)
return b.compatibilityBonusScore - a.compatibilityBonusScore;
return b.compatibilityScore - a.compatibilityScore;
});
});
}
try {
// if this file gets very big, we don't want to load it on every CLI usage
const { recommendedModels } = await import("../recommendedModels.js");
for (const recommendedModel of recommendedModels) {
const potentialUris = resolveModelRecommendationFileOptions(recommendedModel);
if (potentialUris.length > 0)
recommendedModelOptions.push({
type: "recommendedModel",
title: recommendedModel.name,
potentialUris,
description: recommendedModel.description
});
}
}
catch (err) {
// do nothing
}
let initialFocusIndex = 3; // first model option
const options = [
{
type: "action",
text: allowLocalModels
? "Enter a model URI or file path..."
: "Enter a model URI...",
key: "getPath"
},
...((localModelFileOptions.length === 0 || modelsDirectory == null)
? []
: [
{
type: "separator",
text: () => " " + chalk.gray("-".repeat(4))
},
{
type: "separator",
text: " " + chalk.bold("Downloaded models") + " " + chalk.dim(`(${getReadablePath(modelsDirectory)})`)
},
...localModelFileOptions
]),
...(recommendedModelOptions.length === 0
? []
: [
{
type: "separator",
text: () => " " + chalk.gray("-".repeat(4))
},
{
type: "separator",
text: " " + chalk.bold("Recommended models") + (downloadIntent
? (" " + chalk.dim("(select to download)"))
: "")
},
...recommendedModelOptions
])
];
try {
while (true) {
const minWidth = Math.min(80 + (flashAttention ? 26 : 0), process.stdout.columns - 1);
const selectedItem = await basicChooseFromListConsoleInteraction({
title(item, rerender) {
const title = chalk.bold("Select a model:") + " ";
const vramStateText = vramState.total === 0
? chalk.bgGray(" " +
"No GPU" +
" ")
: (chalk.bgGray(" " +
chalk.yellow("GPU:") + " " + getPrettyBuildGpuName(llama.gpu) +
" ") +
" " +
chalk.bgGray(" " +
chalk.yellow("VRAM usage:") + " " +
(String(Math.floor((vramState.used / vramState.total) * 100 * 100) / 100) + "%") + " " +
chalk.dim("(" + toBytes(vramState.used) + "/" + toBytes(vramState.total) + ")") +
" ") + (!flashAttention
? ""
: (" " +
chalk.bgGray(" " +
chalk.yellow("Flash attention:") + " " + "enabled" +
" "))));
const pad = Math.max(0, minWidth - (stripAnsi(title).length + stripAnsi(vramStateText).length));
clearTimeout(scheduledTitleRerenderTimeout);
scheduledTitleRerenderTimeout = setTimeout(async () => {
const newVramState = await llama.getVramState();
if (vramState.used !== newVramState.used || vramState.total !== newVramState.total) {
vramState = newVramState;
rerender();
}
}, vramStateUpdateInterval);
return [
title,
" ".repeat(pad),
vramStateText
].join("");
},
footer(item) {
if (item.type !== "recommendedModel" || item.description == null)
return undefined;
const leftPad = 3;
const maxWidth = Math.max(1, process.stdout.columns - 2 - leftPad);
const lines = splitAnsiToLines(item.description, maxWidth);
return " \n" +
" ".repeat(leftPad) + chalk.bold.gray("Model description") + "\n" +
lines.map((line) => (" ".repeat(leftPad) + line))
.join("\n") + "\n" +
splitAnsiToLines(renderRecommendedModelTechnicalInfo(item.selectedUri, maxWidth, canUseGpu), maxWidth)
.map((line) => (" ".repeat(leftPad) + line))
.join("\n");
},
items: options,
renderItem(item, focused, rerender) {
return renderSelectionItem(item, focused, rerender, activeInteractionController.signal, llama, flashAttention, swaFullCache, useMmap);
},
canFocusItem(item) {
return item.type === "recommendedModel" || item.type === "localModel" || item.type === "action";
},
canSelectItem(item) {
if (item.type === "recommendedModel")
return item.selectedUri != null;
return item.type === "localModel" || item.type === "action";
},
initialFocusIndex: Math.min(initialFocusIndex, options.length - 1),
aboveItemsPadding: 1,
belowItemsPadding: 1,
renderSummaryOnExit(item) {
if (item == null || item.type === "action" || item.type === "separator")
return "";
else if (item.type === "localModel") {
const modelTitle = item.title instanceof Function
? item.title()
: item.title;
return logSymbols.success + " Selected model " + chalk.blue(modelTitle);
}
else if (item.type === "recommendedModel") {
const modelTitle = item.title instanceof Function
? item.title()
: item.title;
return logSymbols.success + " Selected model " + chalk.blue(modelTitle);
}
void item;
return "";
},
exitOnCtrlC: true
});
if (selectedItem == null || selectedItem.type === "separator")
continue;
else if (selectedItem.type === "localModel")
return selectedItem.path;
else if (selectedItem.type === "recommendedModel" && selectedItem.selectedUri != null)
return selectedItem.selectedUri.uri;
else if (selectedItem.type === "action") {
if (selectedItem.key === "getPath") {
initialFocusIndex = 0;
const selectedModelUriOrPath = await askForModelUriOrPath(allowLocalModels);
if (selectedModelUriOrPath == null)
continue;
return selectedModelUriOrPath;
}
}
}
}
finally {
activeInteractionController.abort();
}
}
async function askForModelUriOrPath(allowLocalModels) {
return await consolePromptQuestion(allowLocalModels
? chalk.bold("Enter a model URI or file path: ")
: chalk.bold("Enter a model URI: "), {
exitOnCtrlC: false,
async validate(input) {
if (isUrl(input, false)) {
try {
new URL(input);
}
catch (err) {
return "Invalid URL";
}
return null;
}
try {
if (parseModelUri(input) != null)
return null;
}
catch (err) {
return err instanceof Error
? (err?.message || "Invalid model URI")
: "Invalid model URI";
}
if (!allowLocalModels)
return "Only URIs are allowed";
try {
if (await fs.pathExists(input))
return null;
return "File does not exist";
}
catch (err) {
return "Invalid path";
}
},
renderSummaryOnExit(item) {
if (item == null)
return "";
if (isUrl(item, false))
return logSymbols.success + " Entered model URL " + chalk.blue(item);
else if (isModelUri(item)) {
return logSymbols.success + " Entered model URI " + chalk.blue(item);
}
else
return logSymbols.success + " Entered model path " + chalk.blue(item);
}
});
}
function renderSelectionItem(item, focused, rerender, abortSignal, llama, flashAttention, swaFullCache, useMmap) {
if (item.type === "localModel") {
let modelText = item.title instanceof Function
? item.title()
: item.title;
if (item.ggufInsights != null)
modelText += " " + renderModelCompatibility(item.ggufInsights, item.compatibilityScore, item.compatibilityContextSize);
else
modelText += " " + chalk.bgGray.yellow(" Cannot read metadata ");
return renderSelectableItem(modelText, focused);
}
else if (item.type === "recommendedModel") {
let modelText = item.title instanceof Function
? item.title()
: item.title;
if (item.selectedUri == null) {
if (item.uriSelectionLoadingState == null) {
item.uriSelectionLoadingState = "loading";
void selectFileForModelRecommendation({
recommendedModelOption: item,
abortSignal,
rerenderOption: rerender,
llama,
flashAttention,
swaFullCache,
useMmap
});
}
if (item.uriSelectionLoadingState === "loading")
modelText += " " + chalk.bgGray.yellow(" Loading info ");
else if (item.uriSelectionLoadingState === "done")
modelText += " " + chalk.bgGray.yellow(" Failed to load info ");
else
void item.uriSelectionLoadingState;
}
else
modelText += " " + renderModelCompatibility(item.selectedUri.ggufInsights, item.selectedUri.compatibilityScore.compatibilityScore, item.selectedUri.compatibilityScore.resolvedValues.contextSize);
return renderSelectableItem(modelText, focused);
}
else if (item.type === "separator") {
return item.text instanceof Function
? item.text()
: item.text;
}
else if (item.type === "action") {
const actionText = item.text instanceof Function
? item.text()
: item.text;
return renderSelectableItem(actionText, focused);
}
void item;
return "";
}
function renderSelectableItem(text, focused) {
if (focused)
return " " + chalk.cyan(arrowChar) + " " + chalk.cyan(text);
return " * " + text;
}
function renderModelCompatibility(ggufInsights, compatibilityScore, compatibilityContextSize) {
const info = [];
if (compatibilityScore != null)
info.push(renderModelCompatibilityPercentageWithColors(compatibilityScore * 100) + chalk.whiteBright(" compatibility")
+ (compatibilityContextSize == null
? ""
: (chalk.gray(" | ") + chalk.yellow(getReadableContextSize(compatibilityContextSize)) + chalk.whiteBright(" context"))));
info.push(chalk.yellow("Size:") + " " + chalk.whiteBright(toBytes(ggufInsights.modelSize)));
return info
.map((item) => chalk.bgGray(" " + item + " "))
.join(" ");
}
function renderRecommendedModelTechnicalInfo(modelSelectedUri, maxWidth, canUseGpu) {
if (modelSelectedUri == null)
return " \n" + chalk.bgGray.yellow(" Loading info ") + "\n ";
const ggufInsights = modelSelectedUri.ggufInsights;
const compatibilityScore = modelSelectedUri.compatibilityScore;
const longestTitle = Math.max("Model info".length, "Resolved config".length) + 1;
return " \n" + [
renderInfoLine({
title: "Model info",
padTitle: longestTitle,
separateLines: false,
maxWidth,
info: [{
title: "Size",
value: toBytes(ggufInsights.modelSize)
}, {
show: ggufInsights.trainContextSize != null,
title: "Train context size",
value: () => getReadableContextSize(ggufInsights.trainContextSize ?? 0)
}]
}),
renderInfoLine({
title: "Resolved config",
padTitle: longestTitle,
separateLines: false,
maxWidth,
info: [{
title: "",
value: renderModelCompatibilityPercentageWithColors(compatibilityScore.compatibilityScore * 100) + " compatibility"
}, {
show: ggufInsights.trainContextSize != null,
title: "Context size",
value: getReadableContextSize(compatibilityScore.resolvedValues.contextSize)
}, {
show: canUseGpu,
title: "GPU layers",
value: () => (compatibilityScore.resolvedValues.gpuLayers + "/" + ggufInsights.totalLayers + " " +
chalk.dim(`(${Math.floor((compatibilityScore.resolvedValues.gpuLayers / ggufInsights.totalLayers) * 100)}%)`))
}, {
show: canUseGpu,
title: "VRAM usage",
value: () => toBytes(compatibilityScore.resolvedValues.totalVramUsage)
}, {
title: "RAM usage",
value: () => toBytes(compatibilityScore.resolvedValues.totalRamUsage)
}]
})
].join("\n");
}
async function selectFileForModelRecommendation({ recommendedModelOption, llama, abortSignal, rerenderOption, flashAttention, swaFullCache, useMmap }) {
try {
let bestScore = undefined;
let bestScoreSelectedUri = undefined;
for (const potentialUri of recommendedModelOption.potentialUris) {
if (abortSignal.aborted)
return;
try {
const ggufFileInfo = await readGgufFileInfo(potentialUri, {
sourceType: "network",
signal: abortSignal
});
const ggufInsights = await GgufInsights.from(ggufFileInfo, llama);
if (abortSignal.aborted)
return;
const compatibilityScore = await ggufInsights.configurationResolver.scoreModelConfigurationCompatibility({
flashAttention,
swaFullCache,
useMmap
});
if (bestScore == null || compatibilityScore.compatibilityScore > bestScore) {
bestScore = compatibilityScore.compatibilityScore;
bestScoreSelectedUri = {
uri: potentialUri,
ggufInsights,
compatibilityScore
};
if (bestScore === 1)
break;
}
}
catch (err) {
// do nothing
}
}
recommendedModelOption.selectedUri = bestScoreSelectedUri;
recommendedModelOption.uriSelectionLoadingState = "done";
rerenderOption();
}
catch (err) {
recommendedModelOption.uriSelectionLoadingState = "done";
rerenderOption();
}
}
//# sourceMappingURL=interactivelyAskForModel.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
export declare function isRunningUnderRosetta(): Promise<boolean>;

View File

@@ -0,0 +1,20 @@
import path from "path";
import { fileURLToPath } from "url";
import process from "process";
import { getPlatform } from "../../bindings/utils/getPlatform.js";
import { spawnCommand } from "../../utils/spawnCommand.js";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
export async function isRunningUnderRosetta() {
const platform = getPlatform();
// // only check for rosetta on macOS when x64 is detected
if (platform !== "mac" || process.arch !== "x64")
return false;
try {
const res = await spawnCommand("sysctl", ["-n", "sysctl.proc_translated"], __dirname, process.env, false);
return res.combinedStd.trim() === "1";
}
catch (err) {
return false;
}
}
//# sourceMappingURL=isRunningUnderRosetta.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"isRunningUnderRosetta.js","sourceRoot":"","sources":["../../../src/cli/utils/isRunningUnderRosetta.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAC,aAAa,EAAC,MAAM,KAAK,CAAC;AAClC,OAAO,OAAO,MAAM,SAAS,CAAC;AAC9B,OAAO,EAAC,WAAW,EAAC,MAAM,qCAAqC,CAAC;AAChE,OAAO,EAAC,YAAY,EAAC,MAAM,6BAA6B,CAAC;AAEzD,MAAM,SAAS,GAAG,IAAI,CAAC,OAAO,CAAC,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;AAE/D,MAAM,CAAC,KAAK,UAAU,qBAAqB;IACvC,MAAM,QAAQ,GAAG,WAAW,EAAE,CAAC;IAE/B,0DAA0D;IAC1D,IAAI,QAAQ,KAAK,KAAK,IAAI,OAAO,CAAC,IAAI,KAAK,KAAK;QAC5C,OAAO,KAAK,CAAC;IAEjB,IAAI,CAAC;QACD,MAAM,GAAG,GAAG,MAAM,YAAY,CAAC,QAAQ,EAAE,CAAC,IAAI,EAAE,wBAAwB,CAAC,EAAE,SAAS,EAAE,OAAO,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;QAE1G,OAAO,GAAG,CAAC,WAAW,CAAC,IAAI,EAAE,KAAK,GAAG,CAAC;IAC1C,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACX,OAAO,KAAK,CAAC;IACjB,CAAC;AACL,CAAC"}

View File

@@ -0,0 +1,2 @@
import { BuildGpu } from "../../bindings/types.js";
export declare function logUsedGpuTypeOption(gpu: BuildGpu): void;

View File

@@ -0,0 +1,9 @@
import chalk from "chalk";
import { getPrettyBuildGpuName } from "../../bindings/consts.js";
export function logUsedGpuTypeOption(gpu) {
if (gpu == false)
console.log(`${chalk.yellow("GPU:")} disabled`);
else
console.log(`${chalk.yellow("GPU:")} ${getPrettyBuildGpuName(gpu)}`);
}
//# sourceMappingURL=logUsedGpuTypeOption.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"logUsedGpuTypeOption.js","sourceRoot":"","sources":["../../../src/cli/utils/logUsedGpuTypeOption.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAE1B,OAAO,EAAC,qBAAqB,EAAC,MAAM,0BAA0B,CAAC;AAE/D,MAAM,UAAU,oBAAoB,CAAC,GAAa;IAC9C,IAAI,GAAG,IAAI,KAAK;QACZ,OAAO,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;;QAEhD,OAAO,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,qBAAqB,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;AAC7E,CAAC"}

View File

@@ -0,0 +1,12 @@
import { LlamaContext } from "../../evaluator/LlamaContext/LlamaContext.js";
export declare function printCommonInfoLines({ context, draftContext, minTitleLength, useMmap, useDirectIo, logBatchSize, tokenMeterEnabled, printBos, printEos }: {
context: LlamaContext;
draftContext?: LlamaContext;
minTitleLength?: number;
useMmap?: boolean;
useDirectIo?: boolean;
logBatchSize?: boolean;
tokenMeterEnabled?: boolean;
printBos?: boolean;
printEos?: boolean;
}): Promise<number>;

View File

@@ -0,0 +1,154 @@
import chalk from "chalk";
import { getPrettyBuildGpuName } from "../../bindings/consts.js";
import { getPlatform } from "../../bindings/utils/getPlatform.js";
import { printInfoLine } from "./printInfoLine.js";
import { toBytes } from "./toBytes.js";
export async function printCommonInfoLines({ context, draftContext, minTitleLength = 0, useMmap, useDirectIo, logBatchSize = false, tokenMeterEnabled = false, printBos = false, printEos = false }) {
const platform = getPlatform();
const llama = context._llama;
const model = context.model;
const padTitle = Math.max(minTitleLength, "Context".length + 1, draftContext != null
? ("Draft context".length + 1)
: 0);
if (llama.gpu !== false) {
const [vramState, deviceNames] = await Promise.all([
llama.getVramState(),
llama.getGpuDeviceNames()
]);
printInfoLine({
title: "GPU",
padTitle: padTitle,
info: [{
title: "Type",
value: getPrettyBuildGpuName(llama.gpu)
}, {
title: "VRAM",
value: toBytes(vramState.total)
}, {
title: "Name",
value: toOneLine(deviceNames.join(", "))
}]
});
}
printInfoLine({
title: "Model",
padTitle: padTitle,
info: [{
title: "Type",
value: toOneLine(model.typeDescription)
}, {
title: "Size",
value: toBytes(model.size)
}, {
show: llama.gpu !== false,
title: "GPU layers",
value: `${model.gpuLayers}/${model.fileInsights.totalLayers} offloaded ${chalk.dim(`(${Math.floor((model.gpuLayers / model.fileInsights.totalLayers) * 100)}%)`)}`
}, {
title: "mmap",
value: !model._llama.supportsMmap
? "unsupported"
: (useMmap || useMmap == null)
? "enabled"
: "disabled"
}, {
title: "Direct I/O",
show: platform !== "mac", // Direct IO is not supported on macOS
value: platform === "mac"
? "unsupported"
: (useDirectIo || useDirectIo == null)
? "enabled"
: "disabled"
}, {
show: printBos,
title: "BOS",
value: () => toOneLine(String(model.tokens.bosString))
}, {
show: printEos,
title: "EOS",
value: () => toOneLine(String(model.tokens.eosString))
}, {
title: "Train context size",
value: model.trainContextSize.toLocaleString("en-US")
}]
});
printInfoLine({
title: "Context",
padTitle: padTitle,
info: [{
title: "Size",
value: context.contextSize.toLocaleString("en-US")
}, {
title: "Threads",
value: context.currentThreads.toLocaleString("en-US")
}, {
show: logBatchSize,
title: "Batch size",
value: context.batchSize.toLocaleString("en-US")
}, {
show: context.flashAttention,
title: "Flash attention",
value: "enabled"
}, {
show: tokenMeterEnabled,
title: "Token meter",
value: "enabled"
}]
});
if (draftContext != null) {
const draftModel = draftContext.model;
printInfoLine({
title: "Draft model",
padTitle: padTitle,
info: [{
title: "Type",
value: toOneLine(draftModel.typeDescription)
}, {
title: "Size",
value: toBytes(draftModel.size)
}, {
show: llama.gpu !== false,
title: "GPU layers",
value: `${draftModel.gpuLayers}/${draftModel.fileInsights.totalLayers} offloaded ${chalk.dim(`(${Math.floor((draftModel.gpuLayers / draftModel.fileInsights.totalLayers) * 100)}%)`)}`
}, {
show: printBos,
title: "BOS",
value: () => toOneLine(String(draftModel.tokens.bosString))
}, {
show: printEos,
title: "EOS",
value: () => toOneLine(String(draftModel.tokens.eosString))
}, {
title: "Train context size",
value: draftModel.trainContextSize.toLocaleString("en-US")
}]
});
printInfoLine({
title: "Draft context",
padTitle: padTitle,
info: [{
title: "Size",
value: draftContext.contextSize.toLocaleString("en-US")
}, {
title: "Threads",
value: draftContext.currentThreads.toLocaleString("en-US")
}, {
show: logBatchSize,
title: "Batch size",
value: draftContext.batchSize.toLocaleString("en-US")
}, {
show: draftContext.flashAttention,
title: "Flash attention",
value: "enabled"
}, {
show: tokenMeterEnabled,
title: "Token meter",
value: "enabled"
}]
});
}
return padTitle;
}
function toOneLine(text) {
return text.replaceAll("\n", chalk.gray("\\n"));
}
//# sourceMappingURL=printCommonInfoLines.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"printCommonInfoLines.js","sourceRoot":"","sources":["../../../src/cli/utils/printCommonInfoLines.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAC,qBAAqB,EAAC,MAAM,0BAA0B,CAAC;AAE/D,OAAO,EAAC,WAAW,EAAC,MAAM,qCAAqC,CAAC;AAChE,OAAO,EAAC,aAAa,EAAC,MAAM,oBAAoB,CAAC;AACjD,OAAO,EAAC,OAAO,EAAC,MAAM,cAAc,CAAC;AAErC,MAAM,CAAC,KAAK,UAAU,oBAAoB,CAAC,EACvC,OAAO,EACP,YAAY,EACZ,cAAc,GAAG,CAAC,EAClB,OAAO,EACP,WAAW,EACX,YAAY,GAAG,KAAK,EACpB,iBAAiB,GAAG,KAAK,EACzB,QAAQ,GAAG,KAAK,EAChB,QAAQ,GAAG,KAAK,EAWnB;IACG,MAAM,QAAQ,GAAG,WAAW,EAAE,CAAC;IAC/B,MAAM,KAAK,GAAG,OAAO,CAAC,MAAM,CAAC;IAC7B,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC;IAC5B,MAAM,QAAQ,GAAG,IAAI,CAAC,GAAG,CACrB,cAAc,EACd,SAAS,CAAC,MAAM,GAAG,CAAC,EACpB,YAAY,IAAI,IAAI;QAChB,CAAC,CAAC,CAAC,eAAe,CAAC,MAAM,GAAG,CAAC,CAAC;QAC9B,CAAC,CAAC,CAAC,CACV,CAAC;IAEF,IAAI,KAAK,CAAC,GAAG,KAAK,KAAK,EAAE,CAAC;QACtB,MAAM,CACF,SAAS,EACT,WAAW,CACd,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC;YAClB,KAAK,CAAC,YAAY,EAA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BAAoB;oBAC3B,KAAK,EAAE,UAAU,CAAC,gBAAgB,CAAC,cAAc,CAAC,OAAO,CAAC;iBAC7D,CAAC;SACL,CAAC,CAAC;QACH,aAAa,CAAC;YACV,KAAK,EAAE,eAAe;YACtB,QAAQ,EAAE,QAAQ;YAClB,IAAI,EAAE,CAAC;oBACH,KAAK,EAAE,MAAM;oBACb,KAAK,EAAE,YAAY,CAAC,WAAW,CAAC,cAAc,CAAC,OAAO,CAAC;iBAC1D,EAAE;oBACC,KAAK,EAAE,SAAS;oBAChB,KAAK,EAAE,YAAY,CAAC,cAAc,CAAC,cAAc,CAAC,OAAO,CAAC;iBAC7D,EAAE;oBACC,IAAI,EAAE,YAAY;oBAClB,KAAK,EAAE,YAAY;oBACnB,KAAK,EAAE,YAAY,CAAC,SAAS,CAAC,cAAc,CAAC,OAAO,CAAC;iBACxD,EAAE;oBACC,IAAI,EAAE,YAAY,CAAC,cAAc;oBACjC,KAAK,EAAE,iBAAiB;oBACxB,KAAK,EAAE,SAAS;iBACnB,EAAE;oBACC,IAAI,EAAE,iBAAiB;oBACvB,KAAK,EAAE,aAAa;oBACpB,KAAK,EAAE,SAAS;iBACnB,CAAC;SACL,CAAC,CAAC;IACP,CAAC;IAED,OAAO,QAAQ,CAAC;AACpB,CAAC;AAED,SAAS,SAAS,CAAC,IAAY;IAC3B,OAAO,IAAI,CAAC,UAAU,CAAC,IAAI,EAAE,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC;AACpD,CAAC"}

View File

@@ -0,0 +1,12 @@
export declare function printInfoLine(options: Parameters<typeof renderInfoLine>[0]): void;
export declare function renderInfoLine({ title, padTitle, separateLines, info, maxWidth }: {
title?: string;
padTitle?: number;
separateLines?: boolean;
info: Array<{
title: string;
value: string | (() => string);
show?: boolean;
}>;
maxWidth?: number;
}): string;

View File

@@ -0,0 +1,54 @@
import chalk from "chalk";
import stripAnsi from "strip-ansi";
export function printInfoLine(options) {
console.info(renderInfoLine(options));
}
export function renderInfoLine({ title, padTitle = 0, separateLines = false, info, maxWidth = process.stdout.columns - 1 }) {
const res = [];
const items = [];
if (separateLines) {
if (title != null && title.length > 0)
res.push(chalk.yellowBright(`${title.trim()}`));
for (const { title, value, show } of info) {
if (show === false)
continue;
if (title == null || title === "")
items.push(value instanceof Function ? value() : value);
else
items.push(`${chalk.yellow(title + ":")} ${value instanceof Function ? value() : value}`);
}
const itemPrefix = `${chalk.dim("|")} `;
res.push(itemPrefix + items.join("\n" + itemPrefix));
return res.join("\n") + "\n";
}
else {
if (title != null && title.length > 0)
res.push(chalk.yellowBright(`${title.padEnd(padTitle, " ")}`));
for (const { title, value, show } of info) {
if (show === false)
continue;
if (title == null || title === "")
items.push(chalk.bgGray(` ${value instanceof Function ? value() : value} `));
else
items.push(chalk.bgGray(` ${chalk.yellow(title + ":")} ${value instanceof Function ? value() : value} `));
}
const startPad = stripAnsi(res.join(" ")).length + (res.length > 0 ? " ".length : 0);
res.push(splitItemsIntoLines(items, maxWidth - startPad).join("\n" + " ".repeat(startPad)));
return res.join(" ");
}
}
function splitItemsIntoLines(items, maxLineLength) {
const lines = [];
let currentLine = [];
for (const item of items) {
if (stripAnsi([...currentLine, item].join(" ")).length > maxLineLength) {
lines.push(currentLine.join(" "));
currentLine = [];
}
currentLine.push(item);
}
if (currentLine.length > 0)
lines.push(currentLine.join(" "));
return lines;
}
//# sourceMappingURL=printInfoLine.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"printInfoLine.js","sourceRoot":"","sources":["../../../src/cli/utils/printInfoLine.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,SAAS,MAAM,YAAY,CAAC;AAEnC,MAAM,UAAU,aAAa,CAAC,OAA6C;IACvE,OAAO,CAAC,IAAI,CAAC,cAAc,CAAC,OAAO,CAAC,CAAC,CAAC;AAC1C,CAAC;AAED,MAAM,UAAU,cAAc,CAAC,EAC3B,KAAK,EAAE,QAAQ,GAAG,CAAC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AAW,GAAa,EAAE,CAAC;IAE/B,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QACvB,IAAI,SAAS,CAAC,CAAC,GAAG,WAAW,EAAE,IAAI,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,GAAG,aAAa,EAAE,CAAC;YACrE,KAAK,CAAC,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;YAClC,WAAW,GAAG,EAAE,CAAC;QACrB,CAAC;QAED,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAC3B,CAAC;IAED,IAAI,WAAW,CAAC,MAAM,GAAG,CAAC;QACtB,KAAK,CAAC,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;IAEtC,OAAO,KAAK,CAAC;AACjB,CAAC"}

View File

@@ -0,0 +1,2 @@
import { ResolveModelDestination } from "../../utils/resolveModelDestination.js";
export declare function printModelDestination(modelDestination: ResolveModelDestination): void;

View File

@@ -0,0 +1,11 @@
import chalk from "chalk";
import { getReadablePath } from "./getReadablePath.js";
export function printModelDestination(modelDestination) {
if (modelDestination.type === "url")
console.info(`${chalk.yellow("URL:")} ${modelDestination.url}`);
else if (modelDestination.type === "uri")
console.info(`${chalk.yellow("URI:")} ${modelDestination.uri}`);
else
console.info(`${chalk.yellow("File:")} ${getReadablePath(modelDestination.path)}`);
}
//# sourceMappingURL=printModelDestination.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"printModelDestination.js","sourceRoot":"","sources":["../../../src/cli/utils/printModelDestination.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAE1B,OAAO,EAAC,eAAe,EAAC,MAAM,sBAAsB,CAAC;AAErD,MAAM,UAAU,qBAAqB,CAAC,gBAAyC;IAC3E,IAAI,gBAAgB,CAAC,IAAI,KAAK,KAAK;QAC/B,OAAO,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,gBAAgB,CAAC,GAAG,EAAE,CAAC,CAAC;SAC/D,IAAI,gBAAgB,CAAC,IAAI,KAAK,KAAK;QACpC,OAAO,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,gBAAgB,CAAC,GAAG,EAAE,CAAC,CAAC;;QAEhE,OAAO,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC,MAAM,CAAC,OAAO,CAAC,IAAI,eAAe,CAAC,gBAAgB,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;AAC3F,CAAC"}

View File

@@ -0,0 +1,19 @@
export declare const enum ProjectTemplateParameter {
ProjectName = "projectName",
CurrentModuleVersion = "currentNodeLlamaCppModuleVersion",
ModelUriOrUrl = "modelUriOrUrl",
ModelUriOrFilename = "modelUriOrFilename"
}
export type PackagedFileEntry = {
path: string[];
content: string;
};
export type ProjectTemplate = {
files: PackagedFileEntry[];
};
export declare function getProjectTemplateParameterText(parameter: ProjectTemplateParameter, escapeText?: boolean | 0 | 1 | 2): string;
export declare function scaffoldProjectTemplate({ template, parameters, directoryPath }: {
template: ProjectTemplate;
parameters: Record<ProjectTemplateParameter, string>;
directoryPath: string;
}): Promise<void>;

View File

@@ -0,0 +1,47 @@
import path from "path";
import fs from "fs-extra";
export var ProjectTemplateParameter;
(function (ProjectTemplateParameter) {
ProjectTemplateParameter["ProjectName"] = "projectName";
ProjectTemplateParameter["CurrentModuleVersion"] = "currentNodeLlamaCppModuleVersion";
ProjectTemplateParameter["ModelUriOrUrl"] = "modelUriOrUrl";
ProjectTemplateParameter["ModelUriOrFilename"] = "modelUriOrFilename";
})(ProjectTemplateParameter || (ProjectTemplateParameter = {}));
export function getProjectTemplateParameterText(parameter, escapeText = true) {
let escapes = "";
if (escapeText === true || escapeText === 1)
escapes = "|escape";
else if (escapeText === 2)
escapes = "|escape|escape";
return "{{" + parameter + escapes + "}}";
}
function applyProjectTemplateParameters(template, parameters) {
for (const [parameter, value] of Object.entries(parameters)) {
template = template.split(getProjectTemplateParameterText(parameter, 0)).join(String(value));
template = template.split(getProjectTemplateParameterText(parameter, 1)).join(JSON.stringify(String(value)).slice(1, -1));
template = template.split(getProjectTemplateParameterText(parameter, 2)).join(JSON.stringify(JSON.stringify(String(value)).slice(1, -1)).slice(1, -1));
}
return template;
}
export async function scaffoldProjectTemplate({ template, parameters, directoryPath }) {
for (const file of template.files) {
const filePath = path.join(directoryPath, ...file.path);
const fileContent = transformFileContent({
content: applyProjectTemplateParameters(file.content, parameters),
originalPath: file.path,
parameters
});
await fs.ensureDir(path.dirname(filePath));
await fs.writeFile(filePath, fileContent, "utf8");
}
}
function transformFileContent({ content, originalPath, parameters }) {
if (originalPath.length === 1 && originalPath[0] === "package.json") {
const packageJson = JSON.parse(content);
if (parameters[ProjectTemplateParameter.ProjectName] != null)
packageJson.name = parameters[ProjectTemplateParameter.ProjectName];
return JSON.stringify(packageJson, null, 2);
}
return content;
}
//# sourceMappingURL=projectTemplates.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"projectTemplates.js","sourceRoot":"","sources":["../../../src/cli/utils/projectTemplates.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,MAAM,UAAU,CAAC;AAE1B,MAAM,CAAN,IAAkB,wBAKjB;AALD,WAAkB,wBAAwB;IACtC,uDAA2B,CAAA;IAC3B,qFAAyD,CAAA;IACzD,2DAA+B,CAAA;IAC/B,qEAAyC,CAAA;AAC7C,CAAC,EALiB,wBAAwB,KAAxB,wBAAwB,QAKzC;AAWD,MAAM,UAAU,+BAA+B,CAAC,SAAmC,EAAE,aAAkC,IAAI;IACvH,IAAI,OAAO,GAAG,EAAE,CAAC;IACjB,IAAI,UAAU,KAAK,IAAI,IAAI,UAAU,KAAK,CAAC;QACvC,OAAO,GAAG,SAAS,CAAC;SACnB,IAAI,UAAU,KAAK,CAAC;QACrB,OAAO,GAAG,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AC;YACrC,OAAO,EAAE,8BAA8B,CAAC,IAAI,CAAC,OAAO,EAAE,UAAU,CAAC;YACjE,YAAY,EAAE,IAAI,CAAC,IAAI;YACvB,UAAU;SACb,CAAC,CAAC;QAEH,MAAM,EAAE,CAAC,SAAS,CAAC,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC;QAC3C,MAAM,EAAE,CAAC,SAAS,CAAC,QAAQ,EAAE,WAAW,EAAE,MAAM,CAAC,CAAC;IACtD,CAAC;AACL,CAAC;AAED,SAAS,oBAAoB,CAAC,EAC1B,OAAO,EAAE,YAAY,EAAE,UAAU,EAGpC;IACG,IAAI,YAAY,CAAC,MAAM,KAAK,CAAC,IAAI,YAAY,CAAC,CAAC,CAAC,KAAK,cAAc,EAAE,CAAC;QAClE,MAAM,WAAW,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;QAExC,IAAI,UAAU,CAAC,wBAAwB,CAAC,WAAW,CAAC,IAAI,IAAI;YACxD,WAAW,CAAC,IAAI,GAAG,UAAU,CAAC,wBAAwB,CAAC,WAAW,CAAC,CAAC;QAExE,OAAO,IAAI,CAAC,SAAS,CAAC,WAAW,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;IAChD,CAAC;IAED,OAAO,OAAO,CAAC;AACnB,CAAC"}

View File

@@ -0,0 +1,6 @@
export declare function renderModelCompatibilityPercentageWithColors(percentage: number, { greenBright, green, yellow, yellowBright }?: {
greenBright?: number;
green?: number;
yellow?: number;
yellowBright?: number;
}): string;

View File

@@ -0,0 +1,14 @@
import chalk from "chalk";
export function renderModelCompatibilityPercentageWithColors(percentage, { greenBright = 100, green = 95, yellow = 85, yellowBright = 75 } = {}) {
const percentageText = String(Math.floor(percentage)) + "%";
if (percentage >= greenBright)
return chalk.greenBright(percentageText);
else if (percentage >= green)
return chalk.green(percentageText);
else if (percentage >= yellow)
return chalk.yellow(percentageText);
else if (percentage >= yellowBright)
return chalk.yellowBright(percentageText);
return chalk.red(percentageText);
}
//# sourceMappingURL=renderModelCompatibilityPercentageWithColors.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"renderModelCompatibilityPercentageWithColors.js","sourceRoot":"","sources":["../../../src/cli/utils/renderModelCompatibilityPercentageWithColors.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAE1B,MAAM,UAAU,4CAA4C,CAAC,UAAkB,EAAE,EAC7E,WAAW,GAAG,GAAG,EACjB,KAAK,GAAG,EAAE,EACV,MAAM,GAAG,EAAE,EACX,YAAY,GAAG,EAAE,KAMjB,EAAE;IACF,MAAM,cAAc,GAAG,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC,GAAG,GAAG,CAAC;IAE5D,IAAI,UAAU,IAAI,WAAW;QACzB,OAAO,KAAK,CAAC,WAAW,CAAC,cAAc,CAAC,CAAC;SACxC,IAAI,UAAU,IAAI,KAAK;QACxB,OAAO,KAAK,CAAC,KAAK,CAAC,cAAc,CAAC,CAAC;SAClC,IAAI,UAAU,IAAI,MAAM;QACzB,OAAO,KAAK,CAAC,MAAM,CAAC,cAAc,CAAC,CAAC;SACnC,IAAI,UAAU,IAAI,YAAY;QAC/B,OAAO,KAAK,CAAC,YAAY,CAAC,cAAc,CAAC,CAAC;IAE9C,OAAO,KAAK,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC;AACrC,CAAC"}

View File

@@ -0,0 +1,16 @@
import { Llama } from "../../bindings/Llama.js";
export declare function resolveCommandGgufPath(ggufPath: string | undefined, llama: Llama, fetchHeaders?: Record<string, string>, { targetDirectory, flashAttention, swaFullCache, useMmap, consoleTitle }?: {
targetDirectory?: string;
flashAttention?: boolean;
swaFullCache?: boolean;
useMmap?: boolean;
consoleTitle?: string;
}): Promise<string>;
export declare function tryCoercingModelUri(ggufPath: string): {
uri: string;
modifiedRegion: {
start: number;
end: number;
};
} | undefined;
export declare function printDidYouMeanUri(ggufPath: string): void;

View File

@@ -0,0 +1,116 @@
import process from "process";
import chalk from "chalk";
import fs from "fs-extra";
import { cliModelsDirectory } from "../../config.js";
import { createModelDownloader } from "../../utils/createModelDownloader.js";
import { resolveModelDestination } from "../../utils/resolveModelDestination.js";
import { ggufQuantNames } from "../../gguf/utils/ggufQuantNames.js";
import { getConsoleLogPrefix } from "../../utils/getConsoleLogPrefix.js";
import { isModelUri } from "../../utils/parseModelUri.js";
import { ConsoleInteraction, ConsoleInteractionKey } from "./ConsoleInteraction.js";
import { getReadablePath } from "./getReadablePath.js";
import { interactivelyAskForModel } from "./interactivelyAskForModel.js";
export async function resolveCommandGgufPath(ggufPath, llama, fetchHeaders, { targetDirectory = cliModelsDirectory, flashAttention = false, swaFullCache = false, useMmap, consoleTitle = "File" } = {}) {
if (ggufPath == null)
ggufPath = await interactivelyAskForModel({
llama,
modelsDirectory: targetDirectory,
allowLocalModels: true,
downloadIntent: true,
flashAttention,
swaFullCache,
useMmap
});
const resolvedModelDestination = resolveModelDestination(ggufPath);
if (resolvedModelDestination.type === "file") {
try {
if (await fs.pathExists(resolvedModelDestination.path))
return resolvedModelDestination.path;
}
catch (err) {
throw new Error(`Invalid path: ${resolvedModelDestination.path}`);
}
console.error(`${chalk.red("File does not exist:")} ${resolvedModelDestination.path}`);
printDidYouMeanUri(ggufPath);
process.exit(1);
}
const downloader = await createModelDownloader({
modelUri: resolvedModelDestination.type === "uri"
? resolvedModelDestination.uri
: resolvedModelDestination.url,
dirPath: targetDirectory,
headers: fetchHeaders,
showCliProgress: true,
deleteTempFileOnCancel: false,
skipExisting: false
});
if (downloader.totalFiles === 1 && await fs.pathExists(downloader.entrypointFilePath)) {
const fileStats = await fs.stat(downloader.entrypointFilePath);
if (downloader.totalSize === fileStats.size) {
console.info(`${chalk.yellow(consoleTitle + ":")} ${getReadablePath(downloader.entrypointFilePath)}`);
return downloader.entrypointFilePath;
}
const res = await ConsoleInteraction.yesNoQuestion(`There's already an local ${chalk.blue(downloader.entrypointFilePath)} file that's different from the remote one.\n` +
"Download it and override the existing file?");
if (!res) {
console.info("Loading the existing file");
console.info(`${chalk.yellow(consoleTitle + ":")} ${getReadablePath(downloader.entrypointFilePath)}`);
return downloader.entrypointFilePath;
}
await fs.remove(downloader.entrypointFilePath);
}
const consoleInteraction = new ConsoleInteraction();
consoleInteraction.onKey(ConsoleInteractionKey.ctrlC, async () => {
await downloader.cancel();
consoleInteraction.stop();
process.exit(0);
});
console.info(`Downloading to ${chalk.yellow(getReadablePath(targetDirectory))}${downloader.splitBinaryParts != null
? chalk.gray(` (combining ${downloader.splitBinaryParts} parts into a single file)`)
: ""}`);
consoleInteraction.start();
await downloader.download();
consoleInteraction.stop();
console.info(`${chalk.yellow(consoleTitle + ":")} ${getReadablePath(downloader.entrypointFilePath)}`);
return downloader.entrypointFilePath;
}
export function tryCoercingModelUri(ggufPath) {
const modelNamePart = ggufPath.split("/").pop() ?? "";
const possibleQuant = modelNamePart.includes(":")
? modelNamePart.split(":").pop()
: undefined;
const foundSlashes = ggufPath.split("/").filter((part) => part !== "").length - 1;
if (ggufPath.startsWith("/") || ggufPath.startsWith("./") || ggufPath.startsWith("../") || ggufPath.slice(1, 3) === ":\\")
return undefined;
if (
// <user>/<model>/<file-path>
foundSlashes >= 2 ||
(
// <user>/<model>
// <user>/<model>:<valid quant or "latest">
foundSlashes === 1 &&
(possibleQuant == null || possibleQuant === "latest" || ggufQuantNames.has(possibleQuant.toUpperCase())))) {
const possibleUri = "hf:" + ggufPath;
if (isModelUri(possibleUri)) {
return {
uri: possibleUri,
modifiedRegion: {
start: 0,
end: "hf:".length
}
};
}
}
return undefined;
}
export function printDidYouMeanUri(ggufPath) {
const coercedUriRes = tryCoercingModelUri(ggufPath);
if (coercedUriRes != null) {
const uriText = styleTextRange(coercedUriRes.uri, coercedUriRes.modifiedRegion.start, coercedUriRes.modifiedRegion.end, (text) => chalk.underline(text));
console.info(getConsoleLogPrefix() + `Did you mean "${chalk.blue(uriText)}"?`);
}
}
function styleTextRange(text, start, end, style) {
return text.slice(0, start) + style(text.slice(start, end)) + text.slice(end);
}
//# sourceMappingURL=resolveCommandGgufPath.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"resolveCommandGgufPath.js","sourceRoot":"","sources":["../../../src/cli/utils/resolveCommandGgufPath.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,SAAS,CAAC;AAC9B,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,MAAM,UAAU,CAAC;AAC1B,OAAO,EAAC,kBAAkB,EAAC,MAAM,iBAAiB,CAAC;AAEnD,OAAO,EAAC,qBAAqB,EAAC,MAAM,sCAAsC,CAAC;AAC3E,OAAO,EAAC,uBAAuB,EAAC,MAAM,wCAAwC,CAAC;AAC/E,OAAO,EAAC,cAAc,EAAC,MAAM,oCAAoC,CAAC;AAClE,OAAO,EAAC,mBAAmB,EAAC,MAAM,oCAAoC,CAAC;AACvE,OAAO,EAAC,UAAU,EAAC,MAAM,8BAA8B,CAAC;AACxD,OAAO,EAAC,kBAAkB,EAAE,qBAAqB,EAAC,MAAM,yBAAyB,CAAC;AAClF,OAAO,EAAC,eAAe,EAAC,MAAM,sBAAsB,CAAC;AACrD,OAAO,EAAC,wBAAwB,EAAC,MAAM,+BAA+B,CAAC;AAEvE,MAAM,CAAC,KAAK,UAAU,sBAAsB,CAAC,QAA4B,EAAE,KAAY,EAAE,YAAqC,EAAE,EAC5H,eAAe,GAAG,kBAAkB,EAAE,cAAc,GAAG,KAAK,EAAE,YAAY,GAAG,KAAK,EAAE,OAAO,EAAE,YAAY,GAAG,MAAM,KAGlH,EAAE;IACF,IAAI,QAAQ,IAAI,IAAI;QAChB,QAAQ,GAAG,MAAM,wBAAwB,CAAC;YACtC,KAAK;YACL,eAAe,EAAE,eAAe;YAChC,gBAAgB,EAAE,IAAI;YACtB,cAAc,EAAE,IAAI;YACpB,cAAc;YACd,YAAY;YACZ,OAAO;SACV,CAAC,CAAC;IAEP,MAAM,wBAAwB,GAAG,uBAAuB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QAAQ,CAAC;QACrC,IAAI,UAAU,CAAC,WAAW,CAAC,EAAE,CAAC;YAC1B,OAAO;gBACH,GAAG,EAAE,WAAW;gBAChB,cAAc,EAAE;oBACZ,KAAK,EAAE,CAAC;oBACR,GAAG,EAAE,KAAK,CAAC,MAAM;iBACpB;aACJ,CAAC;QACN,CAAC;IACL,CAAC;IAED,OAAO,SAAS,CAAC;AACrB,CAAC;AAED,MAAM,UAAU,kBAAkB,CAAC,QAAgB;IAC/C,MAAM,aAAa,GAAG,mBAAmB,CAAC,QAAQ,CAAC,CAAC;IACpD,IAAI,aAAa,IAAI,IAAI,EAAE,CAAC;QACxB,MAAM,OAAO,GAAG,cAAc,CAC1B,aAAa,CAAC,GAAG,EACjB,aAAa,CAAC,cAAc,CAAC,KAAK,EAClC,aAAa,CAAC,cAAc,CAAC,GAAG,EAChC,CAAC,IAAI,EAAE,EAAE,CAAC,KAAK,CAAC,SAAS,CAAC,IAAI,CAAC,CAClC,CAAC;QAEF,OAAO,CAAC,IAAI,CAAC,mBAAmB,EAAE,GAAG,iBAAiB,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;IACnF,CAAC;AACL,CAAC;AAED,SAAS,cAAc,CAAC,IAAY,EAAE,KAAa,EAAE,GAAW,EAAE,KAA+B;IAC7F,OAAO,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,KAAK,CAAC,GAAG,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;AAClF,CAAC"}

View File

@@ -0,0 +1 @@
export declare function resolveHeaderFlag(header?: string[] | string): Record<string, string>;

View File

@@ -0,0 +1,21 @@
export function resolveHeaderFlag(header) {
if (typeof header === "string")
header = [header];
if (header == null || header.length === 0)
return {};
const res = {};
for (const headerItem of header) {
const colonIndex = headerItem.indexOf(":");
if (colonIndex < 0)
throw new Error(`Invalid header item: ${headerItem}`);
const key = headerItem.slice(0, colonIndex).trim();
if (Object.hasOwn(res, key))
throw new Error(`Duplicate header key: ${key}`);
let value = headerItem.slice(colonIndex + 1);
if (value.startsWith(" "))
value = value.slice(1);
res[key] = value;
}
return res;
}
//# sourceMappingURL=resolveHeaderFlag.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"resolveHeaderFlag.js","sourceRoot":"","sources":["../../../src/cli/utils/resolveHeaderFlag.ts"],"names":[],"mappings":"AAAA,MAAM,UAAU,iBAAiB,CAAC,MAA0B;IACxD,IAAI,OAAO,MAAM,KAAK,QAAQ;QAC1B,MAAM,GAAG,CAAC,MAAM,CAAC,CAAC;IAEtB,IAAI,MAAM,IAAI,IAAI,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC;QACrC,OAAO,EAAE,CAAC;IAEd,MAAM,GAAG,GAA2B,EAAE,CAAC;IAEvC,KAAK,MAAM,UAAU,IAAI,MAAM,EAAE,CAAC;QAC9B,MAAM,UAAU,GAAG,UAAU,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;QAE3C,IAAI,UAAU,GAAG,CAAC;YACd,MAAM,IAAI,KAAK,CAAC,wBAAwB,UAAU,EAAE,CAAC,CAAC;QAE1D,MAAM,GAAG,GAAG,UAAU,CAAC,KAAK,CAAC,CAAC,EAAE,UAAU,CAAC,CAAC,IAAI,EAAE,CAAC;QAEnD,IAAI,MAAM,CAAC,MAAM,CAAC,GAAG,EAAE,GAAG,CAAC;YACvB,MAAM,IAAI,KAAK,CAAC,yBAAyB,GAAG,EAAE,CAAC,CAAC;QAEpD,IAAI,KAAK,GAAG,UAAU,CAAC,KAAK,CAAC,UAAU,GAAG,CAAC,CAAC,CAAC;QAC7C,IAAI,KAAK,CAAC,UAAU,CAAC,GAAG,CAAC;YACrB,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;QAE3B,GAAG,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;IACrB,CAAC;IAED,OAAO,GAAG,CAAC;AACf,CAAC"}

View File

@@ -0,0 +1,14 @@
export type ModelURI = (`${`http://${string}/${string}` | `https://${string}/${string}` | `hf:${string}/${string}/${string}` | `huggingface:${string}/${string}/${string}`}${".gguf" | `.gguf.part${number}of${number}`}`) | (`hf:${string}/${string}:${string}` | `huggingface:${string}/${string}:${string}` | `hf.co/${string}/${string}:${string}` | `huggingface.co/${string}/${string}:${string}`);
export type ModelRecommendation = {
name: string;
abilities: ("code" | "chat" | "complete" | "infill" | "functionCalling" | "reasoning")[];
description?: string;
/**
* Files ordered by quality.
* The first file that has 100% compatibility with the current system
* will be used (and the rest of the files won't even be tested),
* otherwise, the file with the highest compatibility will be used.
*/
fileOptions: ModelURI[];
};
export declare function resolveModelRecommendationFileOptions(modelRecommendation: ModelRecommendation): string[];

View File

@@ -0,0 +1,12 @@
import { resolveModelDestination } from "../../utils/resolveModelDestination.js";
export function resolveModelRecommendationFileOptions(modelRecommendation) {
return modelRecommendation.fileOptions.map((fileOption) => {
const resolvedModelDestination = resolveModelDestination(fileOption, true);
if (resolvedModelDestination.type === "file")
throw new Error(`File option "${fileOption}" is not a valid model URI`);
if (resolvedModelDestination.type === "uri")
return resolvedModelDestination.uri;
return resolvedModelDestination.url;
});
}
//# sourceMappingURL=resolveModelRecommendationFileOptions.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"resolveModelRecommendationFileOptions.js","sourceRoot":"","sources":["../../../src/cli/utils/resolveModelRecommendationFileOptions.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,uBAAuB,EAAC,MAAM,wCAAwC,CAAC;AAgC/E,MAAM,UAAU,qCAAqC,CAAC,mBAAwC;IAC1F,OAAO,mBAAmB,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC,UAAU,EAAE,EAAE;QACtD,MAAM,wBAAwB,GAAG,uBAAuB,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC;QAE3E,IAAI,wBAAwB,CAAC,IAAI,KAAK,MAAM;YACxC,MAAM,IAAI,KAAK,CAAC,gBAAgB,UAAU,4BAA4B,CAAC,CAAC;QAE5E,IAAI,wBAAwB,CAAC,IAAI,KAAK,KAAK;YACvC,OAAO,wBAAwB,CAAC,GAAG,CAAC;QAExC,OAAO,wBAAwB,CAAC,GAAG,CAAC;IACxC,CAAC,CAAC,CAAC;AACP,CAAC"}

View File

@@ -0,0 +1 @@
export declare function splitAnsiToLines(text: string | undefined, width: number, maxRoundToWords?: number): string[];

View File

@@ -0,0 +1,32 @@
import stripAnsi from "strip-ansi";
import sliceAnsi from "slice-ansi";
export function splitAnsiToLines(text, width, maxRoundToWords = Math.min(16, width)) {
if (text == null || text === "")
return [];
const lines = [];
const linesWithoutAnsi = stripAnsi(text).split("\n");
let textIndex = 0;
for (const line of linesWithoutAnsi) {
for (let lineIndex = 0; lineIndex < line.length;) {
let currentWidth = width;
if (maxRoundToWords > 0) {
const currentMaxWidth = Math.min(currentWidth, line.length - lineIndex);
const currentChunkLastChar = line[lineIndex + currentMaxWidth - 1];
const nextChunkFirstChar = line[lineIndex + currentMaxWidth] ?? "";
if (currentChunkLastChar !== " " && nextChunkFirstChar !== "" && nextChunkFirstChar !== " ") {
const lastSpaceIndex = line.lastIndexOf(" ", lineIndex + currentMaxWidth - 1);
if (lastSpaceIndex >= 0) {
const diff = currentMaxWidth - (lastSpaceIndex + " ".length);
if (diff > 0 && diff < maxRoundToWords && diff < currentWidth)
currentWidth -= diff;
}
}
}
lines.push(sliceAnsi(text, textIndex + lineIndex, Math.min(textIndex + lineIndex + currentWidth, textIndex + line.length)));
lineIndex += currentWidth;
}
textIndex += line.length + "\n".length;
}
return lines;
}
//# sourceMappingURL=splitAnsiToLines.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"splitAnsiToLines.js","sourceRoot":"","sources":["../../../src/cli/utils/splitAnsiToLines.ts"],"names":[],"mappings":"AAAA,OAAO,SAAS,MAAM,YAAY,CAAC;AACnC,OAAO,SAAS,MAAM,YAAY,CAAC;AAEnC,MAAM,U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YAAY;4BACzD,YAAY,IAAI,IAAI,CAAC;oBAC7B,CAAC;gBACL,CAAC;YACL,CAAC;YAED,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,SAAS,GAAG,SAAS,EAAE,IAAI,CAAC,GAAG,CAAC,SAAS,GAAG,SAAS,GAAG,YAAY,EAAE,SAAS,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;YAC5H,SAAS,IAAI,YAAY,CAAC;QAC9B,CAAC;QAED,SAAS,IAAI,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC;IAC3C,CAAC;IAED,OAAO,KAAK,CAAC;AACjB,CAAC"}

View File

@@ -0,0 +1 @@
export declare function toBytes(value: number): string;

View File

@@ -0,0 +1,5 @@
import bytes from "bytes";
export function toBytes(value) {
return bytes(value) ?? String(value);
}
//# sourceMappingURL=toBytes.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"toBytes.js","sourceRoot":"","sources":["../../../src/cli/utils/toBytes.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAE1B,MAAM,UAAU,OAAO,CAAC,KAAa;IACjC,OAAO,KAAK,CAAC,KAAK,CAAC,IAAI,MAAM,CAAC,KAAK,CAAC,CAAC;AACzC,CAAC"}

View File

@@ -0,0 +1,2 @@
export declare function withCliCommandDescriptionDocsUrl(description: string, docsUrl: string): string;
export declare function withoutCliCommandDescriptionDocsUrl(description: string | boolean): string | boolean;

View File

@@ -0,0 +1,23 @@
import { getIsInDocumentationMode } from "../../state.js";
import { documentationPageUrls } from "../../config.js";
export function withCliCommandDescriptionDocsUrl(description, docsUrl) {
const isInDocumentationMode = getIsInDocumentationMode();
if (isInDocumentationMode)
return description;
return [
description,
docsUrl
].join("\n").trim();
}
export function withoutCliCommandDescriptionDocsUrl(description) {
if (typeof description !== "string")
return description;
const lines = description.split("\n");
if (lines.length > 0 && lines[lines.length - 1].startsWith(documentationPageUrls.CLI.index))
return lines
.slice(0, -1)
.join("\n")
.trim();
return description;
}
//# sourceMappingURL=withCliCommandDescriptionDocsUrl.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"withCliCommandDescriptionDocsUrl.js","sourceRoot":"","sources":["../../../src/cli/utils/withCliCommandDescriptionDocsUrl.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,wBAAwB,EAAC,MAAM,gBAAgB,CAAC;AACxD,OAAO,EAAC,qBAAqB,EAAC,MAAM,iBAAiB,CAAC;AAEtD,MAAM,UAAU,gCAAgC,CAAC,WAAmB,EAAE,OAAe;IACjF,MAAM,qBAAqB,GAAG,wBAAwB,EAAE,CAAC;IAEzD,IAAI,qBAAqB;QACrB,OAAO,WAAW,CAAC;IAEvB,OAAO;QACH,WAAW;QACX,OAAO;KACV,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,CAAC;AACxB,CAAC;AAED,MAAM,UAAU,mCAAmC,CAAC,WAA6B;IAC7E,IAAI,OAAO,WAAW,KAAK,QAAQ;QAC/B,OAAO,WAAW,CAAC;IAEvB,MAAM,KAAK,GAAG,WAAW,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IACtC,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,IAAI,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAE,CAAC,UAAU,CAAC,qBAAqB,CAAC,GAAG,CAAC,KAAK,CAAC;QACxF,OAAO,KAAK;aACP,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;aACZ,IAAI,CAAC,IAAI,CAAC;aACV,IAAI,EAAE,CAAC;IAEhB,OAAO,WAAW,CAAC;AACvB,CAAC"}