v1.2.2 - Fix network error on background, auto-retry streaming with reconnect

This commit is contained in:
admin
2026-05-19 15:50:45 +04:00
Unverified
parent 2e327317e4
commit 1026259a20
3831 changed files with 384316 additions and 39 deletions

21
node_modules/@nicepkg/gpt-runner-shared/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2023-PRESENT Jinming Yang <https://github.com/2214962083>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

7
node_modules/@nicepkg/gpt-runner-shared/README.md generated vendored Normal file
View File

@@ -0,0 +1,7 @@
# GPT-Runner Shared
GPT-Runner Shared is the shared code of GPT-Runner.
It contains `browser` and `server` and `common` code for reused in all GPT-Runner packages.
The `common` code can be used in both client side and server side.

1
node_modules/@nicepkg/gpt-runner-shared/browser.cjs generated vendored Normal file
View File

@@ -0,0 +1 @@
module.exports = require('./dist/browser.cjs')

1
node_modules/@nicepkg/gpt-runner-shared/browser.d.ts generated vendored Normal file
View File

@@ -0,0 +1 @@
export * from './dist/browser'

1
node_modules/@nicepkg/gpt-runner-shared/browser.mjs generated vendored Normal file
View File

@@ -0,0 +1 @@
export * from './dist/browser'

1
node_modules/@nicepkg/gpt-runner-shared/common.cjs generated vendored Normal file
View File

@@ -0,0 +1 @@
module.exports = require('./dist/common.cjs')

1
node_modules/@nicepkg/gpt-runner-shared/common.d.ts generated vendored Normal file
View File

@@ -0,0 +1 @@
export * from './dist/common'

1
node_modules/@nicepkg/gpt-runner-shared/common.mjs generated vendored Normal file
View File

@@ -0,0 +1 @@
export * from './dist/common'

View File

@@ -0,0 +1,67 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
function getSearchParams(val, url) {
const defaultUrl = typeof window !== "undefined" ? window.location.href : "";
const finalUrl = url || defaultUrl || "";
const searchParams = finalUrl.split("?")?.[1] || "";
const params = new URLSearchParams(searchParams);
return params.get(val) || "";
}
function addSearchParams(urlLike, searchParams) {
const [urlBase = "", urlSearch = ""] = urlLike.split("?");
const params = new URLSearchParams(urlSearch);
Object.keys(searchParams).forEach((key) => {
params.set(key, searchParams[key]);
});
const urlSearchParams = params.toString();
if (!urlSearchParams)
return urlBase;
return `${urlBase}?${urlSearchParams}`;
}
function removeSearchParams(urlLike, searchParamKeys) {
const [urlBase = "", urlSearch = ""] = urlLike.split("?");
const params = new URLSearchParams(urlSearch);
searchParamKeys.forEach((key) => {
params.delete(key);
});
const urlSearchParams = params.toString();
if (!urlSearchParams)
return urlBase;
return `${urlBase}?${urlSearchParams}`;
}
function unsecuredCopyToClipboard(text) {
const textArea = document.createElement("textarea");
textArea.value = text;
Object.assign(textArea.style, {
position: "fixed",
right: "0",
bottom: "0",
opacity: "0",
width: "0",
height: "0",
pointerEvents: "none"
});
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {
document.execCommand("copy");
} catch (err) {
throw new Error(`Unable to copy to clipboard${err}`);
}
document.body.removeChild(textArea);
}
async function copyToClipboard(content) {
if (window.isSecureContext && navigator.clipboard)
await navigator.clipboard.writeText(content);
else
unsecuredCopyToClipboard(content);
}
exports.addSearchParams = addSearchParams;
exports.copyToClipboard = copyToClipboard;
exports.getSearchParams = getSearchParams;
exports.removeSearchParams = removeSearchParams;
exports.unsecuredCopyToClipboard = unsecuredCopyToClipboard;

View File

@@ -0,0 +1,7 @@
declare function getSearchParams(val: string, url?: string): string;
declare function addSearchParams(urlLike: string, searchParams: Record<string, any>): string;
declare function removeSearchParams(urlLike: string, searchParamKeys: string[]): string;
declare function unsecuredCopyToClipboard(text: string): void;
declare function copyToClipboard(content: string): Promise<void>;
export { addSearchParams, copyToClipboard, getSearchParams, removeSearchParams, unsecuredCopyToClipboard };

View File

@@ -0,0 +1,59 @@
function getSearchParams(val, url) {
const defaultUrl = typeof window !== "undefined" ? window.location.href : "";
const finalUrl = url || defaultUrl || "";
const searchParams = finalUrl.split("?")?.[1] || "";
const params = new URLSearchParams(searchParams);
return params.get(val) || "";
}
function addSearchParams(urlLike, searchParams) {
const [urlBase = "", urlSearch = ""] = urlLike.split("?");
const params = new URLSearchParams(urlSearch);
Object.keys(searchParams).forEach((key) => {
params.set(key, searchParams[key]);
});
const urlSearchParams = params.toString();
if (!urlSearchParams)
return urlBase;
return `${urlBase}?${urlSearchParams}`;
}
function removeSearchParams(urlLike, searchParamKeys) {
const [urlBase = "", urlSearch = ""] = urlLike.split("?");
const params = new URLSearchParams(urlSearch);
searchParamKeys.forEach((key) => {
params.delete(key);
});
const urlSearchParams = params.toString();
if (!urlSearchParams)
return urlBase;
return `${urlBase}?${urlSearchParams}`;
}
function unsecuredCopyToClipboard(text) {
const textArea = document.createElement("textarea");
textArea.value = text;
Object.assign(textArea.style, {
position: "fixed",
right: "0",
bottom: "0",
opacity: "0",
width: "0",
height: "0",
pointerEvents: "none"
});
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {
document.execCommand("copy");
} catch (err) {
throw new Error(`Unable to copy to clipboard${err}`);
}
document.body.removeChild(textArea);
}
async function copyToClipboard(content) {
if (window.isSecureContext && navigator.clipboard)
await navigator.clipboard.writeText(content);
else
unsecuredCopyToClipboard(content);
}
export { addSearchParams, copyToClipboard, getSearchParams, removeSearchParams, unsecuredCopyToClipboard };

236
node_modules/@nicepkg/gpt-runner-shared/dist/common.cjs generated vendored Normal file
View File

@@ -0,0 +1,236 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
const index = require('./shared/gpt-runner-shared.79ccd90a.cjs');
require('minimatch');
require('debug');
require('zod-to-json-schema');
require('zod');
require('axios');
require('jsonc-parser');
function singleFileConfigWithDefault(singleFileConfig) {
return {
...singleFileConfig
};
}
function userConfigWithDefault(userConfig) {
return {
model: {
type: index.ChatModelType.Openai,
modelName: "gpt-3.5-turbo-16k",
temperature: 0.9,
maxTokens: 2e3
},
rootPath: index.EnvConfig.get("GPTR_DEFAULT_ROOT_PATH") || index.getProcessCwd(),
includes: null,
excludes: index.DEFAULT_EXCLUDE_FILES,
exts: [".gpt.md"],
respectGitIgnore: true,
urlConfig: {},
...userConfig
};
}
function resolveSingleFileConfig(params, withDefault = true) {
let userConfig = withDefault ? userConfigWithDefault(params.userConfig) : params.userConfig;
const singleFileConfig = withDefault ? singleFileConfigWithDefault(params.singleFileConfig) : params.singleFileConfig;
userConfig = removeUserConfigUnsafeKey(userConfig);
const resolvedConfig = {
...singleFileConfig,
model: {
...userConfig.model,
...singleFileConfig.model
}
};
return resolvedConfig;
}
function removeUserConfigUnsafeKey(userConfig) {
const userConfigClone = {
...userConfig,
model: {
...userConfig.model
}
};
if (userConfigClone.model?.secrets)
delete userConfigClone.model.secrets;
return userConfigClone;
}
function isNumber(value) {
return Object.prototype.toString.call(value) === "[object Number]";
}
function isString(value) {
return Object.prototype.toString.call(value) === "[object String]";
}
function isNotEmptyString(value) {
return typeof value === "string" && value.length > 0;
}
function isBoolean(value) {
return Object.prototype.toString.call(value) === "[object Boolean]";
}
function isFunction(value) {
return Object.prototype.toString.call(value) === "[object Function]";
}
function isObject(value) {
return Object.prototype.toString.call(value) === "[object Object]";
}
function isShallowEqual(objA, objB, compare, compareContext) {
let ret = compare ? compare.call(compareContext, objA, objB) : void 0;
if (ret !== void 0)
return !!ret;
if (Object.is(objA, objB))
return true;
if (typeof objA !== "object" || !objA || typeof objB !== "object" || !objB)
return false;
const keysA = Object.keys(objA);
const keysB = Object.keys(objB);
if (keysA.length !== keysB.length)
return false;
const bHasOwnProperty = Object.prototype.hasOwnProperty.bind(objB);
for (let idx = 0; idx < keysA.length; idx++) {
const key = keysA[idx];
if (!bHasOwnProperty(key))
return false;
const valueA = objA[key];
const valueB = objB[key];
ret = compare ? compare.call(compareContext, valueA, valueB, key) : void 0;
if (ret === false || ret === void 0 && !Object.is(valueA, valueB))
return false;
}
return true;
}
function isDeepEqual(objA, objB, maxDepth = 20, visited = [], depth = 0) {
if (depth > maxDepth) {
return true;
}
if (visited.includes(objA) || visited.includes(objB))
return true;
const compare = (a, b) => {
if (typeof a === "object" && a !== null && typeof b === "object" && b !== null) {
return isDeepEqual(a, b, maxDepth, [...visited, a, b], depth + 1);
}
return Object.is(a, b);
};
return isShallowEqual(objA, objB, compare);
}
function getModelConfig(modelType, key) {
const chatModelConfigMap = {
[index.ChatModelType.Anthropic]: {
config: index.AnthropicModelConfigSchema,
secrets: index.AnthropicSecretsSchema
},
[index.ChatModelType.HuggingFace]: {
config: index.HuggingFaceModelConfigSchema,
secrets: index.HuggingFaceSecretsSchema
},
[index.ChatModelType.Openai]: {
config: index.OpenaiModelConfigSchema,
secrets: index.OpenaiSecretsSchema
}
};
return chatModelConfigMap[modelType][key];
}
exports.BaseModelConfigSchema = index.BaseModelConfigSchema;
exports.BaseSecretsSchema = index.BaseSecretsSchema;
exports.ChatMessageStatus = index.ChatMessageStatus;
exports.ChatMessageStatusSchema = index.ChatMessageStatusSchema;
exports.ChatModelSchema = index.ChatModelSchema;
exports.ChatModelType = index.ChatModelType;
exports.ChatModelTypeSchema = index.ChatModelTypeSchema;
exports.ChatRole = index.ChatRole;
exports.ChatRoleSchema = index.ChatRoleSchema;
exports.ChatStreamReqParamsSchema = index.ChatStreamReqParamsSchema;
exports.ClientEventName = index.ClientEventName;
exports.ClientEventNameSchema = index.ClientEventNameSchema;
exports.CreateFilePathReqParamsSchema = index.CreateFilePathReqParamsSchema;
exports.DEFAULT_API_BASE_PATH = index.DEFAULT_API_BASE_PATH;
exports.DEFAULT_EXCLUDE_FILES = index.DEFAULT_EXCLUDE_FILES;
exports.DEFAULT_EXCLUDE_FILE_EXTS = index.DEFAULT_EXCLUDE_FILE_EXTS;
exports.DEFAULT_MODEL_NAMES_FOR_CHOOSE = index.DEFAULT_MODEL_NAMES_FOR_CHOOSE;
exports.Debug = index.Debug;
exports.DeleteFilePathReqParamsSchema = index.DeleteFilePathReqParamsSchema;
exports.EnvConfig = index.EnvConfig;
exports.FilterPatternSchema = index.FilterPatternSchema;
exports.FormCheckboxGroupConfigSchema = index.FormCheckboxGroupConfigSchema;
exports.FormFieldBaseConfigSchema = index.FormFieldBaseConfigSchema;
exports.FormInputConfigSchema = index.FormInputConfigSchema;
exports.FormItemConfigSchema = index.FormItemConfigSchema;
exports.FormOptionSchema = index.FormOptionSchema;
exports.FormRadioGroupConfigSchema = index.FormRadioGroupConfigSchema;
exports.FormSelectConfigSchema = index.FormSelectConfigSchema;
exports.FormTextareaConfigSchema = index.FormTextareaConfigSchema;
exports.GPT_RUNNER_OFFICIAL_FOLDER = index.GPT_RUNNER_OFFICIAL_FOLDER;
exports.GetAppConfigReqParamsSchema = index.GetAppConfigReqParamsSchema;
exports.GetCommonFilesReqParamsSchema = index.GetCommonFilesReqParamsSchema;
exports.GetFileInfoReqParamsSchema = index.GetFileInfoReqParamsSchema;
exports.GetGptFileInfoReqParamsSchema = index.GetGptFileInfoReqParamsSchema;
exports.GetGptFilesReqParamsSchema = index.GetGptFilesReqParamsSchema;
exports.GetModelNamesForChooseReqParamsSchema = index.GetModelNamesForChooseReqParamsSchema;
exports.GetUserConfigReqParamsSchema = index.GetUserConfigReqParamsSchema;
exports.GptFileTreeItemType = index.GptFileTreeItemType;
exports.GptFileTreeItemTypeSchema = index.GptFileTreeItemTypeSchema;
exports.InitGptFilesReqParamsSchema = index.InitGptFilesReqParamsSchema;
exports.LocaleLang = index.LocaleLang;
exports.LocaleLangSchema = index.LocaleLangSchema;
exports.MIN_NODE_VERSION = index.MIN_NODE_VERSION;
exports.MarkAsVisitedAppConfigReqParamsSchema = index.MarkAsVisitedAppConfigReqParamsSchema;
exports.OpenEditorReqParamsSchema = index.OpenEditorReqParamsSchema;
exports.OpenaiModelConfigSchema = index.OpenaiModelConfigSchema;
exports.OpenaiSecretsSchema = index.OpenaiSecretsSchema;
exports.PartialChatModelTypeMapSchema = index.PartialChatModelTypeMapSchema;
exports.RenameFilePathReqParamsSchema = index.RenameFilePathReqParamsSchema;
exports.SECRET_KEY_PLACEHOLDER = index.SECRET_KEY_PLACEHOLDER;
exports.STREAM_DONE_FLAG = index.STREAM_DONE_FLAG;
exports.SaveFileContentReqParamsSchema = index.SaveFileContentReqParamsSchema;
exports.SecretStorageKey = index.SecretStorageKey;
exports.ServerStorageName = index.ServerStorageName;
exports.ServerStorageNameSchema = index.ServerStorageNameSchema;
exports.SingleChatMessageSchema = index.SingleChatMessageSchema;
exports.SingleFileConfigSchema = index.SingleFileConfigSchema;
exports.StorageClearReqParamsSchema = index.StorageClearReqParamsSchema;
exports.StorageGetItemReqParamsSchema = index.StorageGetItemReqParamsSchema;
exports.StorageRemoveItemReqParamsSchema = index.StorageRemoveItemReqParamsSchema;
exports.StorageSetItemReqParamsSchema = index.StorageSetItemReqParamsSchema;
exports.UserConfigForUserSchema = index.UserConfigForUserSchema;
exports.UserConfigSchema = index.UserConfigSchema;
exports.VendorTag = index.VendorTag;
exports.WssActionName = index.WssActionName;
exports.WssUtils = index.WssUtils;
exports.buildFailResponse = index.buildFailResponse;
exports.buildSuccessResponse = index.buildSuccessResponse;
exports.createFilterByPattern = index.createFilterByPattern;
exports.debounce = index.debounce;
exports.formatSourceValue = index.formatSourceValue;
exports.getErrorMsg = index.getErrorMsg;
exports.getProcessCwd = index.getProcessCwd;
exports.hasOwn = index.hasOwn;
exports.isChineseCharacter = index.isChineseCharacter;
exports.objectToQueryString = index.objectToQueryString;
exports.runOnceByKey = index.runOnceByKey;
exports.singleFileJsonSchema = index.singleFileJsonSchema;
exports.sleep = index.sleep;
exports.toUnixPath = index.toUnixPath;
exports.travelTree = index.travelTree;
exports.travelTreeDeepFirst = index.travelTreeDeepFirst;
exports.tryParseJson = index.tryParseJson;
exports.tryStringifyJson = index.tryStringifyJson;
exports.urlRemoveLocalhost = index.urlRemoveLocalhost;
exports.userConfigJsonSchema = index.userConfigJsonSchema;
exports.verifyZod = index.verifyZod;
exports.waitForCondition = index.waitForCondition;
exports.getModelConfig = getModelConfig;
exports.isBoolean = isBoolean;
exports.isDeepEqual = isDeepEqual;
exports.isFunction = isFunction;
exports.isNotEmptyString = isNotEmptyString;
exports.isNumber = isNumber;
exports.isObject = isObject;
exports.isShallowEqual = isShallowEqual;
exports.isString = isString;
exports.removeUserConfigUnsafeKey = removeUserConfigUnsafeKey;
exports.resolveSingleFileConfig = resolveSingleFileConfig;
exports.singleFileConfigWithDefault = singleFileConfigWithDefault;
exports.userConfigWithDefault = userConfigWithDefault;

2183
node_modules/@nicepkg/gpt-runner-shared/dist/common.d.ts generated vendored Normal file

File diff suppressed because it is too large Load Diff

133
node_modules/@nicepkg/gpt-runner-shared/dist/common.mjs generated vendored Normal file
View File

@@ -0,0 +1,133 @@
import { C as ChatModelType, E as EnvConfig, g as getProcessCwd, D as DEFAULT_EXCLUDE_FILES, A as AnthropicModelConfigSchema, a as AnthropicSecretsSchema, H as HuggingFaceModelConfigSchema, b as HuggingFaceSecretsSchema, O as OpenaiModelConfigSchema, c as OpenaiSecretsSchema } from './shared/gpt-runner-shared.15a86815.mjs';
export { Y as BaseModelConfigSchema, X as BaseSecretsSchema, L as ChatMessageStatus, ae as ChatMessageStatusSchema, _ as ChatModelSchema, C as ChatModelType, ac as ChatModelTypeSchema, K as ChatRole, ad as ChatRoleSchema, aj as ChatStreamReqParamsSchema, N as ClientEventName, af as ClientEventNameSchema, av as CreateFilePathReqParamsSchema, p as DEFAULT_API_BASE_PATH, D as DEFAULT_EXCLUDE_FILES, v as DEFAULT_EXCLUDE_FILE_EXTS, q as DEFAULT_MODEL_NAMES_FOR_CHOOSE, y as Debug, ax as DeleteFilePathReqParamsSchema, E as EnvConfig, Z as FilterPatternSchema, a8 as FormCheckboxGroupConfigSchema, a4 as FormFieldBaseConfigSchema, a5 as FormInputConfigSchema, aa as FormItemConfigSchema, a3 as FormOptionSchema, a9 as FormRadioGroupConfigSchema, a7 as FormSelectConfigSchema, a6 as FormTextareaConfigSchema, G as GPT_RUNNER_OFFICIAL_FOLDER, aA as GetAppConfigReqParamsSchema, at as GetCommonFilesReqParamsSchema, ay as GetFileInfoReqParamsSchema, am as GetGptFileInfoReqParamsSchema, al as GetGptFilesReqParamsSchema, ak as GetModelNamesForChooseReqParamsSchema, ao as GetUserConfigReqParamsSchema, P as GptFileTreeItemType, ag as GptFileTreeItemTypeSchema, an as InitGptFilesReqParamsSchema, T as LocaleLang, ai as LocaleLangSchema, M as MIN_NODE_VERSION, aB as MarkAsVisitedAppConfigReqParamsSchema, au as OpenEditorReqParamsSchema, O as OpenaiModelConfigSchema, c as OpenaiSecretsSchema, $ as PartialChatModelTypeMapSchema, aw as RenameFilePathReqParamsSchema, S as SECRET_KEY_PLACEHOLDER, n as STREAM_DONE_FLAG, az as SaveFileContentReqParamsSchema, U as SecretStorageKey, Q as ServerStorageName, ah as ServerStorageNameSchema, a2 as SingleChatMessageSchema, ab as SingleFileConfigSchema, as as StorageClearReqParamsSchema, ap as StorageGetItemReqParamsSchema, ar as StorageRemoveItemReqParamsSchema, aq as StorageSetItemReqParamsSchema, a1 as UserConfigForUserSchema, a0 as UserConfigSchema, V as VendorTag, R as WssActionName, W as WssUtils, B as buildFailResponse, z as buildSuccessResponse, x as createFilterByPattern, j as debounce, f as formatSourceValue, l as getErrorMsg, g as getProcessCwd, h as hasOwn, m as isChineseCharacter, o as objectToQueryString, r as runOnceByKey, J as singleFileJsonSchema, s as sleep, k as toUnixPath, t as travelTree, d as travelTreeDeepFirst, e as tryParseJson, i as tryStringifyJson, u as urlRemoveLocalhost, I as userConfigJsonSchema, F as verifyZod, w as waitForCondition } from './shared/gpt-runner-shared.15a86815.mjs';
import 'minimatch';
import 'debug';
import 'zod-to-json-schema';
import 'zod';
import 'axios';
import 'jsonc-parser';
function singleFileConfigWithDefault(singleFileConfig) {
return {
...singleFileConfig
};
}
function userConfigWithDefault(userConfig) {
return {
model: {
type: ChatModelType.Openai,
modelName: "gpt-3.5-turbo-16k",
temperature: 0.9,
maxTokens: 2e3
},
rootPath: EnvConfig.get("GPTR_DEFAULT_ROOT_PATH") || getProcessCwd(),
includes: null,
excludes: DEFAULT_EXCLUDE_FILES,
exts: [".gpt.md"],
respectGitIgnore: true,
urlConfig: {},
...userConfig
};
}
function resolveSingleFileConfig(params, withDefault = true) {
let userConfig = withDefault ? userConfigWithDefault(params.userConfig) : params.userConfig;
const singleFileConfig = withDefault ? singleFileConfigWithDefault(params.singleFileConfig) : params.singleFileConfig;
userConfig = removeUserConfigUnsafeKey(userConfig);
const resolvedConfig = {
...singleFileConfig,
model: {
...userConfig.model,
...singleFileConfig.model
}
};
return resolvedConfig;
}
function removeUserConfigUnsafeKey(userConfig) {
const userConfigClone = {
...userConfig,
model: {
...userConfig.model
}
};
if (userConfigClone.model?.secrets)
delete userConfigClone.model.secrets;
return userConfigClone;
}
function isNumber(value) {
return Object.prototype.toString.call(value) === "[object Number]";
}
function isString(value) {
return Object.prototype.toString.call(value) === "[object String]";
}
function isNotEmptyString(value) {
return typeof value === "string" && value.length > 0;
}
function isBoolean(value) {
return Object.prototype.toString.call(value) === "[object Boolean]";
}
function isFunction(value) {
return Object.prototype.toString.call(value) === "[object Function]";
}
function isObject(value) {
return Object.prototype.toString.call(value) === "[object Object]";
}
function isShallowEqual(objA, objB, compare, compareContext) {
let ret = compare ? compare.call(compareContext, objA, objB) : void 0;
if (ret !== void 0)
return !!ret;
if (Object.is(objA, objB))
return true;
if (typeof objA !== "object" || !objA || typeof objB !== "object" || !objB)
return false;
const keysA = Object.keys(objA);
const keysB = Object.keys(objB);
if (keysA.length !== keysB.length)
return false;
const bHasOwnProperty = Object.prototype.hasOwnProperty.bind(objB);
for (let idx = 0; idx < keysA.length; idx++) {
const key = keysA[idx];
if (!bHasOwnProperty(key))
return false;
const valueA = objA[key];
const valueB = objB[key];
ret = compare ? compare.call(compareContext, valueA, valueB, key) : void 0;
if (ret === false || ret === void 0 && !Object.is(valueA, valueB))
return false;
}
return true;
}
function isDeepEqual(objA, objB, maxDepth = 20, visited = [], depth = 0) {
if (depth > maxDepth) {
return true;
}
if (visited.includes(objA) || visited.includes(objB))
return true;
const compare = (a, b) => {
if (typeof a === "object" && a !== null && typeof b === "object" && b !== null) {
return isDeepEqual(a, b, maxDepth, [...visited, a, b], depth + 1);
}
return Object.is(a, b);
};
return isShallowEqual(objA, objB, compare);
}
function getModelConfig(modelType, key) {
const chatModelConfigMap = {
[ChatModelType.Anthropic]: {
config: AnthropicModelConfigSchema,
secrets: AnthropicSecretsSchema
},
[ChatModelType.HuggingFace]: {
config: HuggingFaceModelConfigSchema,
secrets: HuggingFaceSecretsSchema
},
[ChatModelType.Openai]: {
config: OpenaiModelConfigSchema,
secrets: OpenaiSecretsSchema
}
};
return chatModelConfigMap[modelType][key];
}
export { getModelConfig, isBoolean, isDeepEqual, isFunction, isNotEmptyString, isNumber, isObject, isShallowEqual, isString, removeUserConfigUnsafeKey, resolveSingleFileConfig, singleFileConfigWithDefault, userConfigWithDefault };

View File

@@ -0,0 +1,632 @@
declare enum ChatModelType {
Openai = "openai",
HuggingFace = "huggingFace",
Anthropic = "anthropic"
}
declare enum ChatRole {
User = "user",
Assistant = "assistant",
System = "system"
}
declare enum ChatMessageStatus {
Pending = "pending",
Success = "success",
Error = "error"
}
declare enum ClientEventName {
InitSuccess = "initSuccess",
RefreshTree = "refreshTree",
RefreshChatTree = "refreshChatTree",
RefreshFileTree = "refreshFileTree",
InsertCodes = "insertCodes",
DiffCodes = "diffCodes",
UpdateIdeOpeningFiles = "updateIdeOpeningFiles",
UpdateIdeActiveFilePath = "updateIdeActiveFilePath",
UpdateUserSelectedText = "updateUserSelectedText",
OpenFileInIde = "openFileInIde",
OpenFileInFileEditor = "openFileInFileEditor",
GoToChatPanel = "goToChatPanel"
}
declare enum GptFileTreeItemType {
Folder = "folder",
File = "file",
Chat = "chat"
}
declare enum ServerStorageName {
FrontendState = "frontend-state",
SecretsConfig = "secrets-config",
GlobalState = "global-state",
WebPreset = "web-preset"
}
declare enum WssActionName {
Error = "error",
StorageGetItem = "storageGetItem",
StorageSetItem = "storageSetItem",
StorageRemoveItem = "storageRemoveItem",
StorageClear = "storageClear"
}
declare enum LocaleLang {
English = "en",
ChineseSimplified = "zh_CN",
ChineseTraditional = "zh_Hant",
Japanese = "ja",
German = "de"
}
declare enum SecretStorageKey {
Anthropic = "anthropic",
HuggingFace = "huggingFace",
Openai = "openai",
Proxy = "proxy"
}
declare enum VendorTag {
Free = "free",
Official = "official",
Unofficial = "unofficial",
Recommended = "recommended"
}
interface HuggingFaceSecrets extends BaseSecrets {
/**
* The API key to use for Hugging Face API requests.
*/
apiKey?: string;
}
interface HuggingFaceModelConfig extends BaseModelConfig {
/**
* mode type
*/
type: ChatModelType.HuggingFace;
/**
* huggingFace secret config
*/
secrets?: HuggingFaceSecrets;
/**
* Sampling temperature to use
*/
temperature?: number;
/**
* Maximum number of tokens to generate in the completion. -1 returns as many
* tokens as possible given the prompt and the model's maximum context size.
*/
maxTokens?: number;
/**
* Total probability mass of tokens to consider at each step
*/
topP?: number;
/**
* Integer to define the top tokens considered within the sample operation to create new text.
*/
topK?: number;
/**
* Penalizes repeated tokens according to frequency
*/
frequencyPenalty?: number;
}
interface OpenaiSecrets extends BaseSecrets {
/**
* The API key to use for OpenAI API requests.
*/
apiKey?: string;
/**
* OpenAI organization id
*/
organization?: string;
/**
* OpenAI access token
*/
accessToken?: string;
}
interface OpenaiModelConfig extends BaseModelConfig {
/**
* mode type
*/
type: ChatModelType.Openai;
/**
* openai secret config
*/
secrets?: OpenaiSecrets;
/**
* Sampling temperature to use
*/
temperature?: number;
/**
* Maximum number of tokens to generate in the completion. -1 returns as many
* tokens as possible given the prompt and the model's maximum context size.
*/
maxTokens?: number;
/**
* Total probability mass of tokens to consider at each step
*/
topP?: number;
/**
* Penalizes repeated tokens according to frequency
*/
frequencyPenalty?: number;
/**
* Penalizes repeated tokens
*/
presencePenalty?: number;
}
interface BaseSecrets {
/**
* override api request base url
*/
basePath?: string;
}
interface BaseModelConfig {
/**
* mode type
*/
type?: ChatModelType;
/**
* Model name to use
*/
modelName?: string;
/**
* some secrets config, that will not send to client
*/
secrets?: Record<string, any>;
}
interface ChatModelTypeMap {
[ChatModelType.Anthropic]: AnthropicModelConfig;
[ChatModelType.HuggingFace]: HuggingFaceModelConfig;
[ChatModelType.Openai]: OpenaiModelConfig;
}
type PartialChatModelTypeMap = Partial<ChatModelTypeMap>;
type GetModelConfigType<T extends ChatModelType, P extends 'config' | 'secrets'> = {
config: ChatModelTypeMap[T];
secrets: ChatModelTypeMap[T]['secrets'];
}[P];
type ChatModel = ChatModelTypeMap[ChatModelType];
interface AnthropicSecrets extends BaseSecrets {
/**
* The API key to use for Anthropic API requests.
*/
apiKey?: string;
}
interface AnthropicModelConfig extends BaseModelConfig {
/**
* mode type
*/
type: ChatModelType.Anthropic;
/**
* openai secret config
*/
secrets?: AnthropicSecrets;
/** Amount of randomness injected into the response. Ranges
* from 0 to 1. Use temp closer to 0 for analytical /
* multiple choice, and temp closer to 1 for creative
* and generative tasks.
*/
temperature?: number;
/**
* Maximum number of tokens to generate in the completion. -1 returns as many
* tokens as possible given the prompt and the model's maximum context size.
*/
maxTokens?: number;
/** Does nucleus sampling, in which we compute the
* cumulative distribution over all the options for each
* subsequent token in decreasing probability order and
* cut it off once it reaches a particular probability
* specified by top_p. Defaults to -1, which disables it.
* Note that you should either alter temperature or top_p,
* but not both.
*/
topP?: number;
/**
* Only sample from the top K options for each subsequent
* token. Used to remove "long tail" low probability
* responses. Defaults to -1, which disables it.
*/
topK?: number;
}
type MaybePromise<T> = T | Promise<T>;
type FilterPattern = ReadonlyArray<string | RegExp> | string | RegExp | ((source: string) => boolean) | null | undefined;
type TreeItem<T> = T & {
children?: TreeItem<T>[];
};
type ReadonlyDeep<T> = {
readonly [P in keyof T]: ReadonlyDeep<T[P]>;
};
type ValueOf<T> = T[keyof T];
type DeepRequired<T> = {
[P in keyof T]-?: DeepRequired<T[P]>;
};
type PartialKeys<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
interface UserConfig {
/**
* chat model
*/
model?: ChatModel;
/**
* @default process.cwd()
*/
rootPath?: string;
/**
* @default ['.gpt.md']
*/
exts?: string[];
/**
* @default null
*/
includes?: FilterPattern;
/**
* @default null
*/
excludes?: FilterPattern;
/**
* @default true
*/
respectGitIgnore?: boolean;
/**
* custom http request headers for specific urls
* @default {}
*
* @example
* {
* 'https://api.openai.com/*': {
* modelNames: [
* 'gpt-3.5-turbo-16k',
* 'gpt-4',
* ],
* httpRequestHeader: {
* 'host': 'api.openai.com',
* }
* }
* }
*/
urlConfig?: {
[urlMatch: string]: {
modelNames?: string[];
httpRequestHeader?: Record<string, string>;
};
};
}
type UserConfigForUser = Omit<UserConfig, 'rootPath'>;
interface SingleChatMessage {
name: ChatRole;
text: string;
}
type OmitChatModelTypeSecrets<T> = T extends ChatModel ? Omit<T, 'secrets'> : never;
interface SingleFileConfig {
model?: OmitChatModelTypeSecrets<ChatModel>;
title?: string;
userPrompt?: string;
systemPrompt?: string;
messages?: SingleChatMessage[];
forms?: Record<string, FormItemConfig & {
name: string;
}>;
}
interface FormOption {
label?: string;
value: string;
}
interface FormFieldBaseConfig<DefaultValue = string> {
type: string;
defaultValue?: DefaultValue;
description?: string;
}
interface FormInputConfig extends FormFieldBaseConfig {
type: 'input';
}
interface FormTextareaConfig extends FormFieldBaseConfig {
type: 'textarea';
row?: number;
}
interface FormSelectConfig extends FormFieldBaseConfig {
type: 'select';
options: FormOption[];
}
interface FormCheckboxGroupConfig extends FormFieldBaseConfig<string[]> {
type: 'checkbox-group';
options: FormOption[];
}
interface FormRadioGroupConfig extends FormFieldBaseConfig {
type: 'radio-group';
options: FormOption[];
}
type FormItemConfig = FormInputConfig | FormTextareaConfig | FormSelectConfig | FormCheckboxGroupConfig | FormRadioGroupConfig;
type MarkdownString = string;
interface BaseConfig {
/**
* create time like 2023-04-23 12:34:56, for diff update
*/
createAt: string;
}
interface ChangeLogConfig {
/**
* like 2023-04-23 12:34:56
*/
releaseDate: string;
version: string;
changes: MarkdownString;
}
interface ReleaseConfig extends BaseConfig {
changeLogs: ChangeLogConfig[];
}
interface NotificationConfig extends BaseConfig {
title: string;
message: MarkdownString;
}
interface BaseApiVendor {
vendorName: string;
vendorShortDescription?: string;
vendorOfficialUrl?: string;
vendorLogoUrl?: string;
vendorDescription?: MarkdownString;
vendorTags?: VendorTag[];
}
type ModelApiVendor<T extends ChatModelType> = BaseApiVendor & {
vendorSecrets?: GetModelConfigType<T, 'secrets'>;
};
type ModelTypeVendorsMap = {
[Key in ChatModelType]?: ModelApiVendor<Key>[];
};
interface VendorsConfig extends BaseConfig, ModelTypeVendorsMap {
}
interface CommonAppConfig {
notificationConfig: NotificationConfig;
releaseConfig: ReleaseConfig;
vendorsConfig: VendorsConfig;
}
type AppConfig = {
common: CommonAppConfig;
} & {
[K in LocaleLang]?: Partial<CommonAppConfig>;
};
interface CurrentAppConfig {
showNotificationModal: boolean;
showReleaseModal: boolean;
currentConfig?: CommonAppConfig;
}
interface LastVisitModalDateRecord {
notificationDate?: string;
releaseDate?: string;
}
type MarkedAsVisitedType = keyof LastVisitModalDateRecord;
interface FileBaseInfo {
id: string;
parentId: string | null;
projectRelativePath: string;
fullPath: string;
name: string;
tokenNum: number;
}
interface FileInfo extends FileBaseInfo {
isFile: true;
ext: string;
}
interface FolderInfo extends FileBaseInfo {
isFile: false;
}
type FileInfoTreeItem = TreeItem<FolderInfo | FileInfo>;
type FileInfoTree = FileInfoTreeItem[];
interface GptPathBaseInfo {
id: string;
parentId: string | null;
path: string;
name: string;
type: GptFileTreeItemType;
}
interface GptFileInfo extends GptPathBaseInfo {
type: GptFileTreeItemType.File;
content: string;
singleFileConfig: SingleFileConfig;
}
interface GptFolderInfo extends GptPathBaseInfo {
type: GptFileTreeItemType.Folder;
}
interface GptChatInfo extends GptPathBaseInfo {
type: GptFileTreeItemType.Chat;
createAt: number;
}
type GptFileInfoTreeItem = TreeItem<GptFolderInfo | GptFileInfo | GptChatInfo>;
type GptFileInfoTree = GptFileInfoTreeItem[];
interface BaseResponse<T = any> {
type: 'Success' | 'Fail';
status?: number;
message?: string;
data?: T;
}
type SuccessResponse<T = any> = Omit<BaseResponse<T>, 'type'> & {
type: 'Success';
};
type FailResponse<T = any> = Omit<BaseResponse<T>, 'type'> & {
type: 'Fail';
};
interface ProxySecrets {
proxyUrl: string;
}
type ModelTypeVendorNameMap = {
[K in ChatModelType]?: string;
};
interface ChatStreamReqParams {
messages: SingleChatMessage[];
prompt: string;
/**
* most times we don't use systemPrompt, we parse .gpt.md file
* and get the real time systemPrompt and then provide systemPrompt + appendSystemPrompt to LangchainJs
*/
systemPrompt?: string;
appendSystemPrompt?: string;
/**
* send system prompt as user prompt
* @default false
*/
systemPromptAsUserPrompt?: boolean;
singleFilePath?: string;
/**
* most times we don't use singleFileConfig, we parse .gpt.md file
* and get the real time singleFileConfig and then provide singleFileConfig to LangchainJs
*/
singleFileConfig?: SingleFileConfig;
overrideModelType?: ChatModelType;
overrideModelsConfig?: PartialChatModelTypeMap;
/**
* models type vendor name map
*/
modelTypeVendorNameMap?: ModelTypeVendorNameMap;
contextFilePaths?: string[];
editingFilePath?: string;
rootPath?: string;
}
interface GetModelNamesForChooseReqParams {
rootPath: string;
modelType: ChatModelType;
modelTypeVendorNameMap?: ModelTypeVendorNameMap;
}
interface GetModelNamesForChooseResData {
modelNames: string[];
}
interface GetGptFilesReqParams {
rootPath: string;
}
interface GetGptFilesResData {
filesInfo: GptFileInfo[];
filesInfoTree: GptFileInfoTree;
}
interface GetGptFileInfoReqParams {
rootPath: string;
filePath: string;
}
interface GetGptFileInfoResData {
userConfig: UserConfig;
singleFileConfig: SingleFileConfig;
}
interface InitGptFilesReqParams {
rootPath: string;
gptFilesNames: string[];
}
type InitGptFilesResData = null;
type GetProjectConfigReqParams = null;
interface GetProjectConfigResData {
gptRunnerVersion: string;
nodeVersion: string;
nodeVersionValidMessage: string;
}
interface GetAppConfigReqParams {
langId?: LocaleLang;
}
type GetAppConfigResData = CurrentAppConfig | null;
interface MarkAsVisitedAppConfigReqParams {
types: MarkedAsVisitedType[];
}
type MarkAsVisitedAppConfigResData = null;
interface GetUserConfigReqParams {
rootPath: string;
}
interface GetUserConfigResData {
userConfig: UserConfig;
}
interface StorageGetItemReqParams {
storageName: ServerStorageName;
key: string;
}
type ServerStorageValue = Record<string, any> | null | undefined;
interface StorageGetItemResData {
value: ServerStorageValue;
cacheDir: string;
}
interface StorageSetItemReqParams {
storageName: ServerStorageName;
key: string;
value?: ServerStorageValue;
}
type StorageSetItemResData = null;
interface StorageRemoveItemReqParams {
storageName: ServerStorageName;
key: string;
}
type StorageRemoveItemResData = null;
interface StorageClearReqParams {
storageName: ServerStorageName;
}
type StorageClearResData = null;
interface GetCommonFilesReqParams {
rootPath: string;
excludeExts?: string[];
}
interface GetCommonFilesResData {
filesInfoTree: FileInfoTree;
includeFileExts: string[];
allFileExts: string[];
}
interface OpenEditorReqParams {
rootPath?: string;
path: string;
matchContent?: string;
}
type OpenEditorResData = null;
interface CreateFilePathReqParams {
fileFullPath: string;
isDir: boolean;
}
type CreateFilePathResData = null;
interface RenameFilePathReqParams {
oldFileFullPath: string;
newFileFullPath: string;
}
type RenameFilePathResData = null;
interface DeleteFilePathReqParams {
fileFullPath: string;
}
type DeleteFilePathResData = null;
interface GetFileInfoReqParams {
fileFullPath: string;
}
interface GetFileInfoResData {
content: string;
isDir: boolean;
}
interface SaveFileContentReqParams {
fileFullPath: string;
content: string;
}
type SaveFileContentResData = null;
interface Env {
NODE_ENV?: 'development' | 'production';
OPENAI_API_KEY?: string;
GPTR_DEFAULT_ROOT_PATH?: string;
GPTR_ONLY_LOAD_CONFIG_PATH?: string;
GPTR_BASE_SERVER_URL?: string;
}
type EnvName = keyof Env;
declare class EnvConfig {
static get<T extends EnvName>(key: T): string;
/**
* get all env vars on server or client side
* @param type server or client, get all allowed env vars on that scope
* @param getWays all or process, get env vars both on process and window.__env__ or only process.env
* @returns env vars key value map
*/
static getAllEnvVarsOnScopes(type: 'client' | 'server', getWays?: 'all' | 'process'): Partial<Record<EnvName, string>>;
static logServerSideEnvVars(): void;
static logClientSideEnvVars(): void;
/**
* for /api/config
* @returns env vars key value map for window.__env__
*/
static getClientEnvVarsInServerSide(): Partial<Record<EnvName, string>>;
}
declare global {
namespace NodeJS {
interface ProcessEnv extends Env {
}
}
interface Window {
__env__?: Partial<Env>;
}
}
export { PartialKeys as $, AnthropicModelConfig as A, BaseResponse as B, ChatMessageStatus as C, LastVisitModalDateRecord as D, Env as E, FilterPattern as F, GetModelConfigType as G, HuggingFaceModelConfig as H, MarkedAsVisitedType as I, FileBaseInfo as J, FileInfo as K, LocaleLang as L, MaybePromise as M, NotificationConfig as N, OpenaiModelConfig as O, FolderInfo as P, FileInfoTreeItem as Q, ReleaseConfig as R, SingleChatMessage as S, TreeItem as T, UserConfig as U, VendorsConfig as V, WssActionName as W, FileInfoTree as X, ReadonlyDeep as Y, ValueOf as Z, DeepRequired as _, ClientEventName as a, AnthropicSecrets as a0, BaseSecrets as a1, BaseModelConfig as a2, ChatModelTypeMap as a3, PartialChatModelTypeMap as a4, ChatModel as a5, HuggingFaceSecrets as a6, OpenaiSecrets as a7, UserConfigForUser as a8, FormOption as a9, GetProjectConfigReqParams as aA, GetProjectConfigResData as aB, GetAppConfigReqParams as aC, GetAppConfigResData as aD, MarkAsVisitedAppConfigReqParams as aE, MarkAsVisitedAppConfigResData as aF, GetUserConfigReqParams as aG, GetUserConfigResData as aH, ServerStorageValue as aI, GetCommonFilesReqParams as aJ, GetCommonFilesResData as aK, OpenEditorReqParams as aL, OpenEditorResData as aM, CreateFilePathReqParams as aN, CreateFilePathResData as aO, RenameFilePathReqParams as aP, RenameFilePathResData as aQ, DeleteFilePathReqParams as aR, DeleteFilePathResData as aS, GetFileInfoReqParams as aT, GetFileInfoResData as aU, SaveFileContentReqParams as aV, SaveFileContentResData as aW, FormFieldBaseConfig as aa, FormInputConfig as ab, FormTextareaConfig as ac, FormSelectConfig as ad, FormCheckboxGroupConfig as ae, FormRadioGroupConfig as af, FormItemConfig as ag, SecretStorageKey as ah, VendorTag as ai, GptPathBaseInfo as aj, GptFileInfo as ak, GptFolderInfo as al, GptChatInfo as am, GptFileInfoTreeItem as an, GptFileInfoTree as ao, ProxySecrets as ap, ModelTypeVendorNameMap as aq, ChatStreamReqParams as ar, GetModelNamesForChooseReqParams as as, GetModelNamesForChooseResData as at, GetGptFilesReqParams as au, GetGptFilesResData as av, GetGptFileInfoReqParams as aw, GetGptFileInfoResData as ax, InitGptFilesReqParams as ay, InitGptFilesResData as az, StorageGetItemReqParams as b, StorageGetItemResData as c, StorageSetItemReqParams as d, StorageSetItemResData as e, StorageRemoveItemReqParams as f, StorageRemoveItemResData as g, StorageClearReqParams as h, StorageClearResData as i, SingleFileConfig as j, ChatModelType as k, SuccessResponse as l, FailResponse as m, ChatRole as n, GptFileTreeItemType as o, ServerStorageName as p, EnvConfig as q, MarkdownString as r, BaseConfig as s, ChangeLogConfig as t, BaseApiVendor as u, ModelApiVendor as v, ModelTypeVendorsMap as w, CommonAppConfig as x, AppConfig as y, CurrentAppConfig as z };

View File

@@ -0,0 +1,344 @@
{
"type": "object",
"properties": {
"model": {
"anyOf": [
{
"type": "object",
"properties": {
"type": {
"type": "string",
"const": "anthropic",
"description": "Use Anthropic model"
},
"modelName": {
"type": "string",
"description": "The name of the model"
},
"secrets": {
"type": "object",
"properties": {
"basePath": {
"type": "string",
"default": "https://api.anthropic.com",
"description": "The Anthropic base API url"
},
"apiKey": {
"type": "string",
"description": "The Anthropic API key"
}
},
"additionalProperties": false,
"description": "The Anthropic API secrets config"
},
"temperature": {
"type": "number",
"description": "The temperature for the Anthropic model"
},
"maxTokens": {
"type": "number",
"description": "The maximum number of tokens for the Anthropic model"
},
"topP": {
"type": "number",
"description": "The top P value for the Anthropic model"
},
"topK": {
"type": "number",
"description": "The top K value for the Anthropic model"
}
},
"required": [
"type"
],
"additionalProperties": false
},
{
"type": "object",
"properties": {
"type": {
"type": "string",
"const": "huggingFace",
"description": "Use Open AI model"
},
"modelName": {
"$ref": "#/properties/model/anyOf/0/properties/modelName"
},
"secrets": {
"type": "object",
"properties": {
"basePath": {
"type": "string",
"description": "The base API url"
},
"apiKey": {
"type": "string",
"description": "The HuggingFace API key"
}
},
"additionalProperties": false,
"description": "The HuggingFace API secrets config"
},
"temperature": {
"type": "number",
"description": "The temperature for the HuggingFace model"
},
"maxTokens": {
"type": "number",
"description": "The maximum number of tokens for the HuggingFace model"
},
"topP": {
"type": "number",
"description": "The top P value for the HuggingFace model"
},
"topK": {
"type": "number",
"description": "The top K value for the HuggingFace model"
},
"frequencyPenalty": {
"type": "number",
"description": "The frequency penalty for the HuggingFace model"
}
},
"required": [
"type"
],
"additionalProperties": false
},
{
"type": "object",
"properties": {
"type": {
"type": "string",
"const": "openai",
"description": "Use OpenAI model"
},
"modelName": {
"$ref": "#/properties/model/anyOf/0/properties/modelName"
},
"secrets": {
"type": "object",
"properties": {
"basePath": {
"type": "string",
"default": "https://api.openai.com/v1",
"description": "The OpenAI base API path"
},
"apiKey": {
"type": "string",
"description": "The OpenAI API key"
},
"organization": {
"type": "string",
"description": "The OpenAI organization"
},
"accessToken": {
"type": "string",
"description": "The OpenAI access token"
}
},
"additionalProperties": false,
"description": "The OpenAI API secrets config"
},
"temperature": {
"type": "number",
"description": "The temperature for the OpenAI model"
},
"maxTokens": {
"type": "number",
"description": "The maximum number of tokens for the OpenAI model"
},
"topP": {
"type": "number",
"description": "The top P value for the OpenAI model"
},
"frequencyPenalty": {
"type": "number",
"description": "The frequency penalty for the OpenAI model"
},
"presencePenalty": {
"type": "number",
"description": "The presence penalty for the OpenAI model"
}
},
"required": [
"type"
],
"additionalProperties": false
}
],
"description": "The LLM model configuration"
},
"title": {
"type": "string"
},
"userPrompt": {
"type": "string"
},
"systemPrompt": {
"type": "string"
},
"messages": {
"type": "array",
"items": {
"type": "object",
"properties": {
"name": {
"type": "string",
"enum": [
"user",
"assistant",
"system"
]
},
"text": {
"type": "string"
}
},
"required": [
"name",
"text"
],
"additionalProperties": false
}
},
"forms": {
"type": "object",
"additionalProperties": {
"anyOf": [
{
"type": "object",
"properties": {
"type": {
"type": "string",
"const": "input"
},
"defaultValue": {},
"description": {
"type": "string"
}
},
"required": [
"type"
],
"additionalProperties": false
},
{
"type": "object",
"properties": {
"type": {
"type": "string",
"const": "textarea"
},
"defaultValue": {
"$ref": "#/properties/forms/additionalProperties/anyOf/0/properties/defaultValue"
},
"description": {
"$ref": "#/properties/forms/additionalProperties/anyOf/0/properties/description"
},
"row": {
"type": "number"
}
},
"required": [
"type"
],
"additionalProperties": false
},
{
"type": "object",
"properties": {
"type": {
"type": "string",
"const": "select"
},
"defaultValue": {
"$ref": "#/properties/forms/additionalProperties/anyOf/0/properties/defaultValue"
},
"description": {
"$ref": "#/properties/forms/additionalProperties/anyOf/0/properties/description"
},
"options": {
"type": "array",
"items": {
"type": "object",
"properties": {
"label": {
"type": "string"
},
"value": {
"type": "string"
}
},
"required": [
"value"
],
"additionalProperties": false
}
}
},
"required": [
"type",
"options"
],
"additionalProperties": false
},
{
"type": "object",
"properties": {
"type": {
"type": "string",
"const": "checkbox-group"
},
"defaultValue": {
"$ref": "#/properties/forms/additionalProperties/anyOf/0/properties/defaultValue"
},
"description": {
"$ref": "#/properties/forms/additionalProperties/anyOf/0/properties/description"
},
"options": {
"type": "array",
"items": {
"$ref": "#/properties/forms/additionalProperties/anyOf/2/properties/options/items"
}
}
},
"required": [
"type",
"options"
],
"additionalProperties": false
},
{
"type": "object",
"properties": {
"type": {
"type": "string",
"const": "radio-group"
},
"defaultValue": {
"$ref": "#/properties/forms/additionalProperties/anyOf/0/properties/defaultValue"
},
"description": {
"$ref": "#/properties/forms/additionalProperties/anyOf/0/properties/description"
},
"options": {
"type": "array",
"items": {
"$ref": "#/properties/forms/additionalProperties/anyOf/2/properties/options/items"
}
}
},
"required": [
"type",
"options"
],
"additionalProperties": false
}
]
}
}
},
"additionalProperties": false,
"$schema": "http://json-schema.org/draft-07/schema#"
}

View File

@@ -0,0 +1,238 @@
{
"type": "object",
"properties": {
"model": {
"anyOf": [
{
"type": "object",
"properties": {
"type": {
"type": "string",
"const": "anthropic",
"description": "Use Anthropic model"
},
"modelName": {
"type": "string",
"description": "The name of the model"
},
"secrets": {
"type": "object",
"properties": {
"basePath": {
"type": "string",
"default": "https://api.anthropic.com",
"description": "The Anthropic base API url"
},
"apiKey": {
"type": "string",
"description": "The Anthropic API key"
}
},
"additionalProperties": false,
"description": "The Anthropic API secrets config"
},
"temperature": {
"type": "number",
"description": "The temperature for the Anthropic model"
},
"maxTokens": {
"type": "number",
"description": "The maximum number of tokens for the Anthropic model"
},
"topP": {
"type": "number",
"description": "The top P value for the Anthropic model"
},
"topK": {
"type": "number",
"description": "The top K value for the Anthropic model"
}
},
"required": [
"type"
],
"additionalProperties": false
},
{
"type": "object",
"properties": {
"type": {
"type": "string",
"const": "huggingFace",
"description": "Use Open AI model"
},
"modelName": {
"$ref": "#/properties/model/anyOf/0/properties/modelName"
},
"secrets": {
"type": "object",
"properties": {
"basePath": {
"type": "string",
"description": "The base API url"
},
"apiKey": {
"type": "string",
"description": "The HuggingFace API key"
}
},
"additionalProperties": false,
"description": "The HuggingFace API secrets config"
},
"temperature": {
"type": "number",
"description": "The temperature for the HuggingFace model"
},
"maxTokens": {
"type": "number",
"description": "The maximum number of tokens for the HuggingFace model"
},
"topP": {
"type": "number",
"description": "The top P value for the HuggingFace model"
},
"topK": {
"type": "number",
"description": "The top K value for the HuggingFace model"
},
"frequencyPenalty": {
"type": "number",
"description": "The frequency penalty for the HuggingFace model"
}
},
"required": [
"type"
],
"additionalProperties": false
},
{
"type": "object",
"properties": {
"type": {
"type": "string",
"const": "openai",
"description": "Use OpenAI model"
},
"modelName": {
"$ref": "#/properties/model/anyOf/0/properties/modelName"
},
"secrets": {
"type": "object",
"properties": {
"basePath": {
"type": "string",
"default": "https://api.openai.com/v1",
"description": "The OpenAI base API path"
},
"apiKey": {
"type": "string",
"description": "The OpenAI API key"
},
"organization": {
"type": "string",
"description": "The OpenAI organization"
},
"accessToken": {
"type": "string",
"description": "The OpenAI access token"
}
},
"additionalProperties": false,
"description": "The OpenAI API secrets config"
},
"temperature": {
"type": "number",
"description": "The temperature for the OpenAI model"
},
"maxTokens": {
"type": "number",
"description": "The maximum number of tokens for the OpenAI model"
},
"topP": {
"type": "number",
"description": "The top P value for the OpenAI model"
},
"frequencyPenalty": {
"type": "number",
"description": "The frequency penalty for the OpenAI model"
},
"presencePenalty": {
"type": "number",
"description": "The presence penalty for the OpenAI model"
}
},
"required": [
"type"
],
"additionalProperties": false
}
],
"description": "The LLM model configuration"
},
"includes": {
"anyOf": [
{
"type": "array",
"items": {
"anyOf": [
{
"type": "string"
},
{}
]
}
},
{
"type": "string"
},
{},
{},
{
"type": "null"
},
{
"not": {}
}
],
"default": null,
"description": "The include patterns for filtering files"
},
"excludes": {
"$ref": "#/properties/includes",
"default": null,
"description": "The exclude patterns for filtering files"
},
"respectGitIgnore": {
"type": "boolean",
"default": true,
"description": "Whether to respect .gitignore rules"
},
"urlConfig": {
"type": "object",
"additionalProperties": {
"type": "object",
"properties": {
"modelNames": {
"type": "array",
"items": {
"type": "string"
},
"description": "The model name that will be displayed in the model selector"
},
"httpRequestHeader": {
"type": "object",
"additionalProperties": {
"type": "string"
},
"description": "Additional request headers are required"
}
},
"additionalProperties": false
},
"default": {},
"description": "Custom http request headers and models names for specific urls"
}
},
"additionalProperties": false,
"$schema": "http://json-schema.org/draft-07/schema#"
}

539
node_modules/@nicepkg/gpt-runner-shared/dist/node.cjs generated vendored Normal file
View File

@@ -0,0 +1,539 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
const index = require('./shared/gpt-runner-shared.79ccd90a.cjs');
require('minimatch');
require('debug');
const axios = require('axios');
const httpProxyAgent = require('http-proxy-agent');
const httpsProxyAgent = require('https-proxy-agent');
const node_child_process = require('node:child_process');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const getCacheDir = require('cachedir');
const node_url = require('node:url');
require('jsonc-parser');
const launch = require('launch-editor');
const nodeLocalstorage = require('@kvs/node-localstorage');
const open = require('open');
const fp = require('find-free-ports');
const ip = require('ip');
const undici = require('undici');
require('web-streams-polyfill/polyfill');
require('zod-to-json-schema');
require('zod');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e["default"] : e; }
const axios__default = /*#__PURE__*/_interopDefaultLegacy(axios);
const fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
const os__default = /*#__PURE__*/_interopDefaultLegacy(os);
const path__default = /*#__PURE__*/_interopDefaultLegacy(path);
const getCacheDir__default = /*#__PURE__*/_interopDefaultLegacy(getCacheDir);
const launch__default = /*#__PURE__*/_interopDefaultLegacy(launch);
const open__default = /*#__PURE__*/_interopDefaultLegacy(open);
const fp__default = /*#__PURE__*/_interopDefaultLegacy(fp);
const ip__default = /*#__PURE__*/_interopDefaultLegacy(ip);
function initAxios() {
const httpProxyUrl = process.env.HTTP_PROXY;
const httpsProxyUrl = process.env.HTTPS_PROXY;
if (httpProxyUrl) {
const httpAgent = new httpProxyAgent.HttpProxyAgent(httpProxyUrl);
axios__default.defaults.httpAgent = httpAgent;
}
if (httpsProxyUrl) {
const httpsAgent = new httpsProxyAgent.HttpsProxyAgent(httpsProxyUrl);
axios__default.defaults.httpsAgent = httpsAgent;
}
}
let axiosInstance = null;
function getAxiosInstance() {
if (!axiosInstance) {
initAxios();
axiosInstance = axios__default.create();
}
return axiosInstance;
}
class PathUtils {
static getCurrentDirName(importMetaUrl, getDirname) {
let dirname = "";
try {
dirname = getDirname();
} catch {
}
if (!importMetaUrl)
return index.toUnixPath(dirname);
const __filename = node_url.fileURLToPath(importMetaUrl);
const __dirname = path__default.dirname(__filename);
return __dirname;
}
static join(...paths) {
return index.toUnixPath(path__default.join(...paths));
}
static resolve(...paths) {
return index.toUnixPath(path__default.resolve(...paths));
}
static relative(from, to) {
return index.toUnixPath(path__default.relative(from, to));
}
static dirname(filePath) {
return index.toUnixPath(path__default.dirname(filePath));
}
static extname(filePath) {
if (!PathUtils.isFile(filePath))
return "";
return path__default.extname(filePath);
}
static isFile(filePath) {
return fs__default.existsSync(filePath) && fs__default.statSync(filePath).isFile();
}
static isDirectory(filePath) {
return fs__default.existsSync(filePath) && fs__default.statSync(filePath).isDirectory();
}
static includeExt(filePath, exts) {
if (!exts || !Array.isArray(exts))
return false;
return exts.some((ext) => filePath.endsWith(ext));
}
static isExit(filePath) {
return fs__default.existsSync(filePath);
}
static isAccessible(filePath, mode) {
if (!PathUtils.isExit(filePath))
return false;
const modeMap = {
F: fs__default.constants.F_OK,
R: fs__default.constants.R_OK,
W: fs__default.constants.W_OK,
X: fs__default.constants.X_OK
};
const finalMode = modeMap[mode || "F"] || fs__default.constants.F_OK;
try {
fs__default.accessSync(filePath, finalMode);
return true;
} catch (err) {
return false;
}
}
static getDirPath(filePath) {
return path__default.dirname(filePath);
}
}
async function getGlobalCacheDir(name) {
const cacheDir = getCacheDir__default(name);
await createCacheDir(cacheDir);
return cacheDir;
}
async function createCacheDir(cacheDir) {
if (await PathUtils.isAccessible(cacheDir, "W"))
return;
await fs__default.promises.mkdir(cacheDir, { recursive: true });
}
const _BinaryDownloader = class {
static async getBinaryPath() {
const cacheDir = await getGlobalCacheDir("nicepkg-tunnel");
const binaryPath = path__default.join(cacheDir, _BinaryDownloader.BINARY_FILENAME);
return binaryPath;
}
static async downloadBinary() {
const debug = new index.Debug("tunnel");
const binaryPath = await _BinaryDownloader.getBinaryPath();
if (!fs__default.existsSync(binaryPath)) {
const binaryUrl = `https://cdn-media.huggingface.co/frpc-gradio-${_BinaryDownloader.VERSION}/${_BinaryDownloader.BINARY_NAME}${_BinaryDownloader.EXTENSION}`;
debug.log(`Downloading ${binaryUrl} to ${binaryPath}...`);
try {
const axios = getAxiosInstance();
const response = await axios.get(binaryUrl, {
responseType: "arraybuffer"
});
await fs__default.promises.writeFile(binaryPath, response.data, "binary");
fs__default.chmodSync(binaryPath, 493);
debug.log(`Downloaded success ${binaryUrl} to ${binaryPath}`);
} catch (err) {
debug.error(`Failed to download ${binaryUrl}: ${err}`);
if (err?.response?.status === 403) {
throw new Error(
`Cannot set up a share link as this platform is incompatible. Please create a GitHub issue with information about your platform: ${JSON.stringify(
os__default.userInfo()
)}`
);
}
throw err;
}
}
}
};
let BinaryDownloader = _BinaryDownloader;
BinaryDownloader.VERSION = "0.2";
BinaryDownloader.EXTENSION = os__default.platform() === "win32" ? ".exe" : "";
BinaryDownloader.MACHINE = os__default.arch();
BinaryDownloader.ARCH = _BinaryDownloader.MACHINE === "x64" ? "amd64" : _BinaryDownloader.MACHINE;
BinaryDownloader.BINARY_NAME = `frpc_${os__default.type().toLowerCase()}_${_BinaryDownloader.ARCH.toLowerCase()}`;
BinaryDownloader.BINARY_FILENAME = `${_BinaryDownloader.BINARY_NAME}_v${_BinaryDownloader.VERSION}`;
class TunnelProcess {
constructor(command) {
this.proc = null;
this.command = command;
}
async start() {
const binaryPath = await BinaryDownloader.getBinaryPath();
await BinaryDownloader.downloadBinary();
return this._startProcess(binaryPath);
}
kill() {
if (this.proc !== null) {
this.proc.kill("SIGTERM");
this.proc = null;
}
}
_startProcess(binary) {
return new Promise((resolve, reject) => {
this.proc = node_child_process.spawn(binary, this.command, {
stdio: ["ignore", "pipe", "pipe"]
});
process.once("exit", () => this.kill());
let output = "";
this.proc.stdout.on("data", (data) => {
output += data.toString();
const match = output.match(/start proxy success: (.+)/);
if (match) {
resolve(match[1]);
output = "";
}
});
this.proc.stderr.on("data", (data) => {
output += data.toString();
});
this.proc.on("error", (err) => {
reject(err);
});
});
}
}
class Tunnel {
constructor(options) {
this.GRADIO_API_SERVER_URL = "https://api.gradio.app/v2/tunnel-request";
const {
remoteHost,
remotePort,
localHost,
localPort,
shareToken
} = options;
this.url = null;
this.remoteHost = remoteHost || "";
this.remotePort = remotePort || 0;
this.localHost = localHost || "localhost";
this.localPort = localPort;
this.shareToken = shareToken || "";
}
async initProcess() {
if (!this.remoteHost || !this.remotePort) {
try {
const axios = getAxiosInstance();
const res = await axios.get(this.GRADIO_API_SERVER_URL);
const data = res.data;
this.remoteHost = data[0].host;
this.remotePort = data[0].port;
} catch (err) {
throw new Error(`Failed to fetch ${this.GRADIO_API_SERVER_URL}: ${index.getErrorMsg(err)}`);
}
}
const command = [
"http",
"-n",
this.shareToken,
"-l",
`${this.localPort}`,
"-i",
this.localHost,
"--uc",
"--sd",
"random",
"--ue",
"--server_addr",
`${this.remoteHost}:${this.remotePort}`,
"--disable_log_color"
];
this.tunnelProcess = new TunnelProcess(command);
}
async startTunnel() {
if (!this.tunnelProcess)
await this.initProcess();
this.url = await this.tunnelProcess.start();
return this.url;
}
kill() {
if (this.tunnelProcess) {
console.log(
`Killing tunnel ${this.localHost}:${this.localPort} <> ${this.url}`
);
this.tunnelProcess.kill();
}
}
}
function compareVersion(a, b) {
const aParts = a.split(".");
const bParts = b.split(".");
const len = Math.max(aParts.length, bParts.length);
const stringToNum = (str) => parseInt(str.match(/\d+/)?.[0] || "0") || 0;
for (let i = 0; i < len; i++) {
const aPart = stringToNum(aParts[i]) || 0;
const bPart = stringToNum(bParts[i]) || 0;
if (aPart > bPart)
return 1;
if (aPart < bPart)
return -1;
}
return 0;
}
function checkNodeVersion() {
const currentNodeVersion = process.version;
if (compareVersion(currentNodeVersion, index.MIN_NODE_VERSION) < 0)
return `You are using Node ${currentNodeVersion}, but GPT-Runner requires Node ${index.MIN_NODE_VERSION}.
Please upgrade your Node version in https://nodejs.org/en/download`;
}
function canUseNodeFetchWithoutCliFlag() {
const currentNodeVersion = process.version;
return compareVersion(currentNodeVersion, "18.0.0") > 0;
}
function getRunServerEnv() {
if (!canUseNodeFetchWithoutCliFlag()) {
return {
NODE_OPTIONS: "--experimental-fetch",
NODE_NO_WARNINGS: "1"
};
}
return {};
}
class FileUtils {
static async readFile(params) {
const { filePath, valid = true } = params;
if (typeof filePath !== "string")
return "";
if (valid && !PathUtils.isFile(filePath))
return "";
if (!filePath)
return "";
return fs.promises.readFile(filePath, { encoding: "utf8" });
}
static async writeFile(params) {
const { filePath, content, overwrite = true, valid = true } = params;
if (valid) {
if (!PathUtils.isAccessible(filePath, "W"))
return;
if (!PathUtils.isFile(filePath))
return;
}
const dir = PathUtils.getDirPath(filePath);
if (!PathUtils.isExit(dir))
await fs.promises.mkdir(dir, { recursive: true });
if (overwrite)
await fs.promises.writeFile(filePath, content, { encoding: "utf8" });
else
await fs.promises.appendFile(filePath, content, { encoding: "utf8" });
}
static async deletePath(fullPath) {
if (!PathUtils.isAccessible(fullPath, "W"))
await fs.promises.rm(fullPath, { recursive: true });
}
static async ensurePath(params) {
const { filePath } = params;
if (!PathUtils.isAccessible(filePath, "W"))
await fs.promises.mkdir(filePath, { recursive: true });
}
static async movePath(params) {
const { oldPath, newPath } = params;
if (PathUtils.isAccessible(oldPath, "W"))
await fs.promises.rename(oldPath, newPath);
}
static async travelFiles(params) {
const { isValidPath, callback } = params;
const filePath = PathUtils.resolve(params.filePath);
if (!PathUtils.isAccessible(filePath, "R"))
return;
const promises = [];
if (PathUtils.isDirectory(filePath)) {
const entries = await fs.promises.readdir(filePath);
for (const entry of entries) {
const fullPath = PathUtils.join(filePath, entry);
if (!PathUtils.isAccessible(filePath, "R"))
continue;
const isValid = await isValidPath(fullPath);
if (isValid)
promises.push(FileUtils.travelFiles({ filePath: fullPath, isValidPath, callback }));
}
} else {
const result = callback(filePath);
if (result instanceof Promise)
promises.push(result);
}
await Promise.allSettled(promises);
}
static async travelFilesByFilterPattern(params) {
const { filePath, isValidPath, callback, exts = [], includes = null, excludes = null } = params;
await FileUtils.travelFiles({
filePath,
isValidPath: async (filePath2) => {
if (exts.length > 0 && PathUtils.isFile(filePath2) && !PathUtils.includeExt(filePath2, exts))
return false;
if (!index.createFilterByPattern(includes)(filePath2))
return false;
if (index.createFilterByPattern(excludes)(filePath2))
return false;
if (!isValidPath(filePath2))
return false;
return true;
},
callback
});
}
}
async function launchEditor(params) {
return new Promise((resolve, reject) => {
const { path, lineNum, columnNum = 0, editorName, onError } = params;
const finalPath = lineNum && columnNum ? `${path}:${lineNum}:${columnNum}` : path;
launch__default(finalPath, editorName, (error) => {
if (error) {
onError?.(error);
reject(error);
}
});
resolve();
});
}
async function launchEditorByPathAndContent(params) {
const { path, matchContent, editorName, onError } = params;
const content = await FileUtils.readFile({ filePath: path });
let lineNum = 0;
let columnNum = 0;
if (matchContent) {
const matchContentStartIndex = content.indexOf(matchContent);
if (matchContentStartIndex !== -1) {
const beforeMatchContent = content.slice(0, matchContentStartIndex);
lineNum = beforeMatchContent.split("\n").length;
columnNum = matchContentStartIndex - beforeMatchContent.lastIndexOf("\n");
}
}
await launchEditor({ path, lineNum, columnNum, editorName, onError });
return { lineNum, columnNum };
}
async function getStorage(storageName) {
const cacheFolder = await getGlobalCacheDir("gpt-runner-server");
const storage = await nodeLocalstorage.kvsLocalStorage({
name: storageName,
storeFilePath: cacheFolder,
version: 1
});
return {
cacheDir: cacheFolder,
storage
};
}
function openInBrowser(props) {
const { url } = props;
try {
open__default(url);
} catch (error) {
throw new Error(`Server is started at ${url} but failed to open browser. ${error}`);
}
}
async function getPort(props) {
const { defaultPort, autoFreePort, excludePorts } = props;
if (defaultPort) {
if (!autoFreePort)
return defaultPort;
const canUseDefaultPort = await fp__default.isFreePort(defaultPort);
if (canUseDefaultPort)
return defaultPort;
}
const freePorts = await fp__default.findFreePorts(1, {
startPort: 3001,
endPort: 9999,
isFree: async (port) => {
if (excludePorts?.includes(port))
return false;
return fp__default.isFreePort(port);
}
});
return freePorts[0];
}
function getLocalHostname() {
return ip__default.address("public", "ipv4");
}
function addNodejsPolyfill() {
if (!canUseNodeFetchWithoutCliFlag()) {
console.log("GPT Runner: add polyfill for fetch", process.version);
globalThis.fetch = undici.fetch;
globalThis.Headers = undici.Headers;
globalThis.Request = undici.Request;
globalThis.Response = undici.Response;
}
}
async function getDefaultProxyUrl() {
let proxyUrl = "";
try {
const { storage } = await getStorage(index.ServerStorageName.SecretsConfig);
const proxySecret = await storage.get(index.SecretStorageKey.Proxy);
proxyUrl = proxySecret?.proxyUrl ?? "";
} catch (error) {
console.error("getDefaultProxyUrl error", error);
}
if (proxyUrl)
return proxyUrl;
["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY"].forEach((key) => {
if (proxyUrl)
return;
const upperKey = key.toUpperCase();
const lowerKey = key.toLowerCase();
const upperKeyValue = process.env[upperKey] && process.env[upperKey] !== "undefined" ? process.env[upperKey] || "" : "";
const lowerKeyValue = process.env[lowerKey] && process.env[lowerKey] !== "undefined" ? process.env[lowerKey] || "" : "";
return proxyUrl = upperKeyValue || lowerKeyValue || "";
});
return proxyUrl;
}
function sendSuccessResponse(res, options) {
return res.status(options.status || 200).json(index.buildSuccessResponse(options));
}
function sendFailResponse(res, options) {
return res.status(options.status || 400).json(index.buildFailResponse(options));
}
function verifyParamsByZod(params, schema) {
index.verifyZod(schema, params);
}
exports.FileUtils = FileUtils;
exports.PathUtils = PathUtils;
exports.Tunnel = Tunnel;
exports.addNodejsPolyfill = addNodejsPolyfill;
exports.canUseNodeFetchWithoutCliFlag = canUseNodeFetchWithoutCliFlag;
exports.checkNodeVersion = checkNodeVersion;
exports.compareVersion = compareVersion;
exports.getDefaultProxyUrl = getDefaultProxyUrl;
exports.getGlobalCacheDir = getGlobalCacheDir;
exports.getLocalHostname = getLocalHostname;
exports.getPort = getPort;
exports.getRunServerEnv = getRunServerEnv;
exports.getStorage = getStorage;
exports.launchEditor = launchEditor;
exports.launchEditorByPathAndContent = launchEditorByPathAndContent;
exports.openInBrowser = openInBrowser;
exports.sendFailResponse = sendFailResponse;
exports.sendSuccessResponse = sendSuccessResponse;
exports.verifyParamsByZod = verifyParamsByZod;

147
node_modules/@nicepkg/gpt-runner-shared/dist/node.d.ts generated vendored Normal file
View File

@@ -0,0 +1,147 @@
import { M as MaybePromise, F as FilterPattern, p as ServerStorageName, l as SuccessResponse, m as FailResponse } from './env-config-3be2ee5d.js';
import * as _kvs_storage from '@kvs/storage';
import { Response } from 'express';
import { z } from 'zod';
interface TunnelOptions {
remoteHost?: string;
remotePort?: number;
localHost?: string;
localPort: number;
shareToken?: string;
}
declare class Tunnel {
private tunnelProcess;
GRADIO_API_SERVER_URL: string;
url: string | null;
private remoteHost;
private remotePort;
private localHost;
private localPort;
private shareToken;
constructor(options: TunnelOptions);
initProcess(): Promise<void>;
startTunnel(): Promise<string>;
kill(): void;
}
declare function compareVersion(a: string, b: string): 1 | 0 | -1;
declare function checkNodeVersion(): string | undefined;
declare function canUseNodeFetchWithoutCliFlag(): boolean;
declare function getRunServerEnv(): {
NODE_OPTIONS: string;
NODE_NO_WARNINGS: string;
} | {
NODE_OPTIONS?: undefined;
NODE_NO_WARNINGS?: undefined;
};
type LaunchEditorName = 'Atom' | 'Atom Beta' | 'subl' | 'sublime' | 'sublime_text' | 'wstorm' | 'charm' | 'notepad++' | 'vim' | 'mvim' | 'joe' | 'gvim' | 'emacs' | 'emacsclient' | 'rmate' | 'mate' | 'mine' | 'Code' | 'Code - Insiders' | 'codium' | 'vscodium' | 'VSCodium' | 'appcode' | 'clion' | 'clion64' | 'idea' | 'idea64' | 'phpstorm' | 'phpstorm64' | 'pycharm' | 'pycharm64' | 'rubymine' | 'rubymine64' | 'webstorm' | 'webstorm64' | 'goland' | 'goland64' | 'rider' | 'rider64';
interface LaunchEditorParams {
path: string;
lineNum?: number;
columnNum?: number;
editorName?: LaunchEditorName;
onError?: (error: any) => void;
}
declare function launchEditor(params: LaunchEditorParams): Promise<void>;
interface LaunchEditorByPathAndContentParams {
path: string;
matchContent?: string;
editorName?: LaunchEditorName;
onError?: (error: any) => void;
}
declare function launchEditorByPathAndContent(params: LaunchEditorByPathAndContentParams): Promise<{
lineNum: number;
columnNum: number;
}>;
interface ReadFileParams {
filePath: string | undefined;
valid?: boolean;
}
interface WriteFileParams {
filePath: string;
content: string;
overwrite?: boolean;
valid?: boolean;
}
interface EnsurePathParams {
filePath: string;
}
interface MovePathParams {
oldPath: string;
newPath: string;
}
interface TravelFilesParams {
filePath: string;
isValidPath: (filePath: string) => MaybePromise<boolean>;
callback: (filePath: string) => MaybePromise<void>;
}
interface TravelFilesByFilterPatternParams extends TravelFilesParams {
/**
* @default []
*/
exts?: string[];
/**
* @default null
*/
includes?: FilterPattern;
/**
* @default null
*/
excludes?: FilterPattern;
}
declare class FileUtils {
static readFile(params: ReadFileParams): Promise<string>;
static writeFile(params: WriteFileParams): Promise<void>;
static deletePath(fullPath: string): Promise<void>;
static ensurePath(params: EnsurePathParams): Promise<void>;
static movePath(params: MovePathParams): Promise<void>;
static travelFiles(params: TravelFilesParams): Promise<void>;
static travelFilesByFilterPattern(params: TravelFilesByFilterPatternParams): Promise<void>;
}
declare function getGlobalCacheDir(name: string): Promise<string>;
declare function getStorage(storageName: ServerStorageName): Promise<{
cacheDir: string;
storage: _kvs_storage.KvsStorage<Record<string, Record<string, any> | null>>;
}>;
interface OpenInBrowserProps {
url: string;
}
declare function openInBrowser(props: OpenInBrowserProps): void;
interface GetPortProps {
defaultPort?: number;
autoFreePort?: boolean;
excludePorts?: number[];
}
declare function getPort(props: GetPortProps): Promise<number>;
declare function getLocalHostname(): string;
declare class PathUtils {
static getCurrentDirName(importMetaUrl: string, getDirname: () => string): string;
static join(...paths: string[]): string;
static resolve(...paths: string[]): string;
static relative(from: string, to: string): string;
static dirname(filePath: string): string;
static extname(filePath: string): string;
static isFile(filePath: string): boolean;
static isDirectory(filePath: string): boolean;
static includeExt(filePath: string, exts: string[] | undefined | null): boolean;
static isExit(filePath: string): boolean;
static isAccessible(filePath: string, mode?: 'F' | 'R' | 'W' | 'X'): boolean;
static getDirPath(filePath: string): string;
}
declare function addNodejsPolyfill(): void;
declare function getDefaultProxyUrl(): Promise<string>;
declare function sendSuccessResponse<T>(res: Response, options: Omit<SuccessResponse<T>, 'type'>): Response;
declare function sendFailResponse<T>(res: Response, options: Omit<FailResponse<T>, 'type'>): Response;
declare function verifyParamsByZod<T>(params: T, schema: z.ZodSchema<T>): void;
export { EnsurePathParams, FileUtils, GetPortProps, LaunchEditorByPathAndContentParams, LaunchEditorName, LaunchEditorParams, MovePathParams, OpenInBrowserProps, PathUtils, ReadFileParams, TravelFilesByFilterPatternParams, TravelFilesParams, Tunnel, WriteFileParams, addNodejsPolyfill, canUseNodeFetchWithoutCliFlag, checkNodeVersion, compareVersion, getDefaultProxyUrl, getGlobalCacheDir, getLocalHostname, getPort, getRunServerEnv, getStorage, launchEditor, launchEditorByPathAndContent, openInBrowser, sendFailResponse, sendSuccessResponse, verifyParamsByZod };

505
node_modules/@nicepkg/gpt-runner-shared/dist/node.mjs generated vendored Normal file
View File

@@ -0,0 +1,505 @@
import { k as toUnixPath, y as Debug, l as getErrorMsg, M as MIN_NODE_VERSION, x as createFilterByPattern, Q as ServerStorageName, U as SecretStorageKey, z as buildSuccessResponse, B as buildFailResponse, F as verifyZod } from './shared/gpt-runner-shared.15a86815.mjs';
import 'minimatch';
import 'debug';
import axios from 'axios';
import { HttpProxyAgent } from 'http-proxy-agent';
import { HttpsProxyAgent } from 'https-proxy-agent';
import { spawn } from 'node:child_process';
import fs, { promises } from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import getCacheDir from 'cachedir';
import { fileURLToPath } from 'node:url';
import 'jsonc-parser';
import launch from 'launch-editor';
import { kvsLocalStorage } from '@kvs/node-localstorage';
import open from 'open';
import fp from 'find-free-ports';
import ip from 'ip';
import { fetch, Headers, Request, Response } from 'undici';
import 'web-streams-polyfill/polyfill';
import 'zod-to-json-schema';
import 'zod';
function initAxios() {
const httpProxyUrl = process.env.HTTP_PROXY;
const httpsProxyUrl = process.env.HTTPS_PROXY;
if (httpProxyUrl) {
const httpAgent = new HttpProxyAgent(httpProxyUrl);
axios.defaults.httpAgent = httpAgent;
}
if (httpsProxyUrl) {
const httpsAgent = new HttpsProxyAgent(httpsProxyUrl);
axios.defaults.httpsAgent = httpsAgent;
}
}
let axiosInstance = null;
function getAxiosInstance() {
if (!axiosInstance) {
initAxios();
axiosInstance = axios.create();
}
return axiosInstance;
}
class PathUtils {
static getCurrentDirName(importMetaUrl, getDirname) {
let dirname = "";
try {
dirname = getDirname();
} catch {
}
if (!importMetaUrl)
return toUnixPath(dirname);
const __filename = fileURLToPath(importMetaUrl);
const __dirname = path.dirname(__filename);
return __dirname;
}
static join(...paths) {
return toUnixPath(path.join(...paths));
}
static resolve(...paths) {
return toUnixPath(path.resolve(...paths));
}
static relative(from, to) {
return toUnixPath(path.relative(from, to));
}
static dirname(filePath) {
return toUnixPath(path.dirname(filePath));
}
static extname(filePath) {
if (!PathUtils.isFile(filePath))
return "";
return path.extname(filePath);
}
static isFile(filePath) {
return fs.existsSync(filePath) && fs.statSync(filePath).isFile();
}
static isDirectory(filePath) {
return fs.existsSync(filePath) && fs.statSync(filePath).isDirectory();
}
static includeExt(filePath, exts) {
if (!exts || !Array.isArray(exts))
return false;
return exts.some((ext) => filePath.endsWith(ext));
}
static isExit(filePath) {
return fs.existsSync(filePath);
}
static isAccessible(filePath, mode) {
if (!PathUtils.isExit(filePath))
return false;
const modeMap = {
F: fs.constants.F_OK,
R: fs.constants.R_OK,
W: fs.constants.W_OK,
X: fs.constants.X_OK
};
const finalMode = modeMap[mode || "F"] || fs.constants.F_OK;
try {
fs.accessSync(filePath, finalMode);
return true;
} catch (err) {
return false;
}
}
static getDirPath(filePath) {
return path.dirname(filePath);
}
}
async function getGlobalCacheDir(name) {
const cacheDir = getCacheDir(name);
await createCacheDir(cacheDir);
return cacheDir;
}
async function createCacheDir(cacheDir) {
if (await PathUtils.isAccessible(cacheDir, "W"))
return;
await fs.promises.mkdir(cacheDir, { recursive: true });
}
const _BinaryDownloader = class {
static async getBinaryPath() {
const cacheDir = await getGlobalCacheDir("nicepkg-tunnel");
const binaryPath = path.join(cacheDir, _BinaryDownloader.BINARY_FILENAME);
return binaryPath;
}
static async downloadBinary() {
const debug = new Debug("tunnel");
const binaryPath = await _BinaryDownloader.getBinaryPath();
if (!fs.existsSync(binaryPath)) {
const binaryUrl = `https://cdn-media.huggingface.co/frpc-gradio-${_BinaryDownloader.VERSION}/${_BinaryDownloader.BINARY_NAME}${_BinaryDownloader.EXTENSION}`;
debug.log(`Downloading ${binaryUrl} to ${binaryPath}...`);
try {
const axios = getAxiosInstance();
const response = await axios.get(binaryUrl, {
responseType: "arraybuffer"
});
await fs.promises.writeFile(binaryPath, response.data, "binary");
fs.chmodSync(binaryPath, 493);
debug.log(`Downloaded success ${binaryUrl} to ${binaryPath}`);
} catch (err) {
debug.error(`Failed to download ${binaryUrl}: ${err}`);
if (err?.response?.status === 403) {
throw new Error(
`Cannot set up a share link as this platform is incompatible. Please create a GitHub issue with information about your platform: ${JSON.stringify(
os.userInfo()
)}`
);
}
throw err;
}
}
}
};
let BinaryDownloader = _BinaryDownloader;
BinaryDownloader.VERSION = "0.2";
BinaryDownloader.EXTENSION = os.platform() === "win32" ? ".exe" : "";
BinaryDownloader.MACHINE = os.arch();
BinaryDownloader.ARCH = _BinaryDownloader.MACHINE === "x64" ? "amd64" : _BinaryDownloader.MACHINE;
BinaryDownloader.BINARY_NAME = `frpc_${os.type().toLowerCase()}_${_BinaryDownloader.ARCH.toLowerCase()}`;
BinaryDownloader.BINARY_FILENAME = `${_BinaryDownloader.BINARY_NAME}_v${_BinaryDownloader.VERSION}`;
class TunnelProcess {
constructor(command) {
this.proc = null;
this.command = command;
}
async start() {
const binaryPath = await BinaryDownloader.getBinaryPath();
await BinaryDownloader.downloadBinary();
return this._startProcess(binaryPath);
}
kill() {
if (this.proc !== null) {
this.proc.kill("SIGTERM");
this.proc = null;
}
}
_startProcess(binary) {
return new Promise((resolve, reject) => {
this.proc = spawn(binary, this.command, {
stdio: ["ignore", "pipe", "pipe"]
});
process.once("exit", () => this.kill());
let output = "";
this.proc.stdout.on("data", (data) => {
output += data.toString();
const match = output.match(/start proxy success: (.+)/);
if (match) {
resolve(match[1]);
output = "";
}
});
this.proc.stderr.on("data", (data) => {
output += data.toString();
});
this.proc.on("error", (err) => {
reject(err);
});
});
}
}
class Tunnel {
constructor(options) {
this.GRADIO_API_SERVER_URL = "https://api.gradio.app/v2/tunnel-request";
const {
remoteHost,
remotePort,
localHost,
localPort,
shareToken
} = options;
this.url = null;
this.remoteHost = remoteHost || "";
this.remotePort = remotePort || 0;
this.localHost = localHost || "localhost";
this.localPort = localPort;
this.shareToken = shareToken || "";
}
async initProcess() {
if (!this.remoteHost || !this.remotePort) {
try {
const axios = getAxiosInstance();
const res = await axios.get(this.GRADIO_API_SERVER_URL);
const data = res.data;
this.remoteHost = data[0].host;
this.remotePort = data[0].port;
} catch (err) {
throw new Error(`Failed to fetch ${this.GRADIO_API_SERVER_URL}: ${getErrorMsg(err)}`);
}
}
const command = [
"http",
"-n",
this.shareToken,
"-l",
`${this.localPort}`,
"-i",
this.localHost,
"--uc",
"--sd",
"random",
"--ue",
"--server_addr",
`${this.remoteHost}:${this.remotePort}`,
"--disable_log_color"
];
this.tunnelProcess = new TunnelProcess(command);
}
async startTunnel() {
if (!this.tunnelProcess)
await this.initProcess();
this.url = await this.tunnelProcess.start();
return this.url;
}
kill() {
if (this.tunnelProcess) {
console.log(
`Killing tunnel ${this.localHost}:${this.localPort} <> ${this.url}`
);
this.tunnelProcess.kill();
}
}
}
function compareVersion(a, b) {
const aParts = a.split(".");
const bParts = b.split(".");
const len = Math.max(aParts.length, bParts.length);
const stringToNum = (str) => parseInt(str.match(/\d+/)?.[0] || "0") || 0;
for (let i = 0; i < len; i++) {
const aPart = stringToNum(aParts[i]) || 0;
const bPart = stringToNum(bParts[i]) || 0;
if (aPart > bPart)
return 1;
if (aPart < bPart)
return -1;
}
return 0;
}
function checkNodeVersion() {
const currentNodeVersion = process.version;
if (compareVersion(currentNodeVersion, MIN_NODE_VERSION) < 0)
return `You are using Node ${currentNodeVersion}, but GPT-Runner requires Node ${MIN_NODE_VERSION}.
Please upgrade your Node version in https://nodejs.org/en/download`;
}
function canUseNodeFetchWithoutCliFlag() {
const currentNodeVersion = process.version;
return compareVersion(currentNodeVersion, "18.0.0") > 0;
}
function getRunServerEnv() {
if (!canUseNodeFetchWithoutCliFlag()) {
return {
NODE_OPTIONS: "--experimental-fetch",
NODE_NO_WARNINGS: "1"
};
}
return {};
}
class FileUtils {
static async readFile(params) {
const { filePath, valid = true } = params;
if (typeof filePath !== "string")
return "";
if (valid && !PathUtils.isFile(filePath))
return "";
if (!filePath)
return "";
return promises.readFile(filePath, { encoding: "utf8" });
}
static async writeFile(params) {
const { filePath, content, overwrite = true, valid = true } = params;
if (valid) {
if (!PathUtils.isAccessible(filePath, "W"))
return;
if (!PathUtils.isFile(filePath))
return;
}
const dir = PathUtils.getDirPath(filePath);
if (!PathUtils.isExit(dir))
await promises.mkdir(dir, { recursive: true });
if (overwrite)
await promises.writeFile(filePath, content, { encoding: "utf8" });
else
await promises.appendFile(filePath, content, { encoding: "utf8" });
}
static async deletePath(fullPath) {
if (!PathUtils.isAccessible(fullPath, "W"))
await promises.rm(fullPath, { recursive: true });
}
static async ensurePath(params) {
const { filePath } = params;
if (!PathUtils.isAccessible(filePath, "W"))
await promises.mkdir(filePath, { recursive: true });
}
static async movePath(params) {
const { oldPath, newPath } = params;
if (PathUtils.isAccessible(oldPath, "W"))
await promises.rename(oldPath, newPath);
}
static async travelFiles(params) {
const { isValidPath, callback } = params;
const filePath = PathUtils.resolve(params.filePath);
if (!PathUtils.isAccessible(filePath, "R"))
return;
const promises$1 = [];
if (PathUtils.isDirectory(filePath)) {
const entries = await promises.readdir(filePath);
for (const entry of entries) {
const fullPath = PathUtils.join(filePath, entry);
if (!PathUtils.isAccessible(filePath, "R"))
continue;
const isValid = await isValidPath(fullPath);
if (isValid)
promises$1.push(FileUtils.travelFiles({ filePath: fullPath, isValidPath, callback }));
}
} else {
const result = callback(filePath);
if (result instanceof Promise)
promises$1.push(result);
}
await Promise.allSettled(promises$1);
}
static async travelFilesByFilterPattern(params) {
const { filePath, isValidPath, callback, exts = [], includes = null, excludes = null } = params;
await FileUtils.travelFiles({
filePath,
isValidPath: async (filePath2) => {
if (exts.length > 0 && PathUtils.isFile(filePath2) && !PathUtils.includeExt(filePath2, exts))
return false;
if (!createFilterByPattern(includes)(filePath2))
return false;
if (createFilterByPattern(excludes)(filePath2))
return false;
if (!isValidPath(filePath2))
return false;
return true;
},
callback
});
}
}
async function launchEditor(params) {
return new Promise((resolve, reject) => {
const { path, lineNum, columnNum = 0, editorName, onError } = params;
const finalPath = lineNum && columnNum ? `${path}:${lineNum}:${columnNum}` : path;
launch(finalPath, editorName, (error) => {
if (error) {
onError?.(error);
reject(error);
}
});
resolve();
});
}
async function launchEditorByPathAndContent(params) {
const { path, matchContent, editorName, onError } = params;
const content = await FileUtils.readFile({ filePath: path });
let lineNum = 0;
let columnNum = 0;
if (matchContent) {
const matchContentStartIndex = content.indexOf(matchContent);
if (matchContentStartIndex !== -1) {
const beforeMatchContent = content.slice(0, matchContentStartIndex);
lineNum = beforeMatchContent.split("\n").length;
columnNum = matchContentStartIndex - beforeMatchContent.lastIndexOf("\n");
}
}
await launchEditor({ path, lineNum, columnNum, editorName, onError });
return { lineNum, columnNum };
}
async function getStorage(storageName) {
const cacheFolder = await getGlobalCacheDir("gpt-runner-server");
const storage = await kvsLocalStorage({
name: storageName,
storeFilePath: cacheFolder,
version: 1
});
return {
cacheDir: cacheFolder,
storage
};
}
function openInBrowser(props) {
const { url } = props;
try {
open(url);
} catch (error) {
throw new Error(`Server is started at ${url} but failed to open browser. ${error}`);
}
}
async function getPort(props) {
const { defaultPort, autoFreePort, excludePorts } = props;
if (defaultPort) {
if (!autoFreePort)
return defaultPort;
const canUseDefaultPort = await fp.isFreePort(defaultPort);
if (canUseDefaultPort)
return defaultPort;
}
const freePorts = await fp.findFreePorts(1, {
startPort: 3001,
endPort: 9999,
isFree: async (port) => {
if (excludePorts?.includes(port))
return false;
return fp.isFreePort(port);
}
});
return freePorts[0];
}
function getLocalHostname() {
return ip.address("public", "ipv4");
}
function addNodejsPolyfill() {
if (!canUseNodeFetchWithoutCliFlag()) {
console.log("GPT Runner: add polyfill for fetch", process.version);
globalThis.fetch = fetch;
globalThis.Headers = Headers;
globalThis.Request = Request;
globalThis.Response = Response;
}
}
async function getDefaultProxyUrl() {
let proxyUrl = "";
try {
const { storage } = await getStorage(ServerStorageName.SecretsConfig);
const proxySecret = await storage.get(SecretStorageKey.Proxy);
proxyUrl = proxySecret?.proxyUrl ?? "";
} catch (error) {
console.error("getDefaultProxyUrl error", error);
}
if (proxyUrl)
return proxyUrl;
["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY"].forEach((key) => {
if (proxyUrl)
return;
const upperKey = key.toUpperCase();
const lowerKey = key.toLowerCase();
const upperKeyValue = process.env[upperKey] && process.env[upperKey] !== "undefined" ? process.env[upperKey] || "" : "";
const lowerKeyValue = process.env[lowerKey] && process.env[lowerKey] !== "undefined" ? process.env[lowerKey] || "" : "";
return proxyUrl = upperKeyValue || lowerKeyValue || "";
});
return proxyUrl;
}
function sendSuccessResponse(res, options) {
return res.status(options.status || 200).json(buildSuccessResponse(options));
}
function sendFailResponse(res, options) {
return res.status(options.status || 400).json(buildFailResponse(options));
}
function verifyParamsByZod(params, schema) {
verifyZod(schema, params);
}
export { FileUtils, PathUtils, Tunnel, addNodejsPolyfill, canUseNodeFetchWithoutCliFlag, checkNodeVersion, compareVersion, getDefaultProxyUrl, getGlobalCacheDir, getLocalHostname, getPort, getRunServerEnv, getStorage, launchEditor, launchEditorByPathAndContent, openInBrowser, sendFailResponse, sendSuccessResponse, verifyParamsByZod };

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

1
node_modules/@nicepkg/gpt-runner-shared/index.cjs generated vendored Normal file
View File

@@ -0,0 +1 @@
module.exports = require('./dist/common.cjs')

1
node_modules/@nicepkg/gpt-runner-shared/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1 @@
export * from './dist/common'

1
node_modules/@nicepkg/gpt-runner-shared/index.mjs generated vendored Normal file
View File

@@ -0,0 +1 @@
export * from './dist/common'

1
node_modules/@nicepkg/gpt-runner-shared/node.cjs generated vendored Normal file
View File

@@ -0,0 +1 @@
module.exports = require('./dist/node.cjs')

1
node_modules/@nicepkg/gpt-runner-shared/node.d.ts generated vendored Normal file
View File

@@ -0,0 +1 @@
export * from './dist/node'

1
node_modules/@nicepkg/gpt-runner-shared/node.mjs generated vendored Normal file
View File

@@ -0,0 +1 @@
export * from './dist/node'

123
node_modules/@nicepkg/gpt-runner-shared/package.json generated vendored Normal file
View File

@@ -0,0 +1,123 @@
{
"name": "@nicepkg/gpt-runner-shared",
"version": "1.2.9",
"description": "Provides shared code for GPT-Runner, featuring reusable common, browser, and server elements across all packages.",
"author": "Jinming Yang <2214962083@qq.com>",
"license": "MIT",
"funding": "https://github.com/sponsors/2214962083",
"homepage": "https://github.com/nicepkg/gpt-runner/tree/main/packages/gpt-runner-shared#readme",
"repository": {
"type": "git",
"url": "https://github.com/nicepkg/gpt-runner",
"directory": "packages/gpt-runner-shared"
},
"bugs": {
"url": "https://github.com/nicepkg/gpt-runner/issues"
},
"keywords": [
"gpt-runner",
"langchain",
"chatgpt",
"prompt",
"ai",
"storybook",
"openai",
"huggingFace",
"anthropic"
],
"sideEffects": false,
"exports": {
".": {
"types": "./dist/common.d.ts",
"import": "./dist/common.mjs",
"require": "./dist/common.cjs"
},
"./*": "./*",
"./browser": {
"types": "./dist/browser.d.ts",
"import": "./dist/browser.mjs",
"require": "./dist/browser.cjs"
},
"./common": {
"types": "./dist/common.d.ts",
"import": "./dist/common.mjs",
"require": "./dist/common.cjs"
},
"./node": {
"types": "./dist/node.d.ts",
"import": "./dist/node.mjs",
"require": "./dist/node.cjs"
}
},
"main": "dist/common.cjs",
"module": "dist/common.mjs",
"types": "dist/common.d.ts",
"files": [
"dist/",
"LICENSE",
"*.md",
"browser.cjs",
"browser.d.ts",
"browser.mjs",
"common.cjs",
"common.d.ts",
"common.mjs",
"index.cjs",
"index.d.ts",
"index.mjs",
"node.cjs",
"node.d.ts",
"node.mjs"
],
"peerDependencies": {
"@kvs/node-localstorage": "*",
"@kvs/storage": "*",
"axios": "*",
"cachedir": "*",
"debug": "*",
"find-free-ports": "*",
"http-proxy-agent": "*",
"https-proxy-agent": "*",
"ip": "*",
"jsonc-parser": "*",
"launch-editor": "*",
"minimatch": "*",
"socket.io": "*",
"socket.io-client": "*",
"undici": "*",
"web-streams-polyfill": "*",
"zod": "*",
"zod-to-json-schema": "*"
},
"dependencies": {
"@kvs/node-localstorage": "^2.1.5",
"@kvs/storage": "^2.1.4",
"axios": "1.3.4",
"cachedir": "^2.4.0",
"debug": "^4.3.4",
"find-free-ports": "^3.1.1",
"http-proxy-agent": "^7.0.0",
"https-proxy-agent": "^7.0.1",
"ip": "^1.1.8",
"jsonc-parser": "^3.2.0",
"launch-editor": "^2.6.0",
"minimatch": "^9.0.3",
"open": "^8.4.2",
"socket.io": "^4.7.2",
"socket.io-client": "^4.7.2",
"undici": "^5.23.0",
"web-streams-polyfill": "^4.0.0-beta.3",
"zod": "^3.22.0",
"zod-to-json-schema": "^3.21.4"
},
"devDependencies": {
"@types/express": "^4.17.17",
"@types/ip": "^1.1.0",
"express": "^4.18.2"
},
"scripts": {
"build": "unbuild && pnpm build:json-schema",
"build:json-schema": "pnpm esno ./scripts/zod-to-json-schema.ts",
"stub": "unbuild --stub && pnpm build:json-schema"
}
}

21
node_modules/@nicepkg/gpt-runner/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2023-PRESENT Jinming Yang <https://github.com/2214962083>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

5
node_modules/@nicepkg/gpt-runner/README.md generated vendored Normal file
View File

@@ -0,0 +1,5 @@
# GPT-Runner
It contains `defineConfig` function and `UserConfig` type.
It's helpful to config `gptr.config.ts` file with type checking.

18
node_modules/@nicepkg/gpt-runner/dist/index.cjs generated vendored Normal file
View File

@@ -0,0 +1,18 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
const common = require('@nicepkg/gpt-runner-shared/common');
const node = require('@nicepkg/gpt-runner-shared/node');
function defineConfig(config) {
return config;
}
exports.defineConfig = defineConfig;
for (const k in common) {
if (k !== 'default' && !exports.hasOwnProperty(k)) exports[k] = common[k];
}
for (const k in node) {
if (k !== 'default' && !exports.hasOwnProperty(k)) exports[k] = node[k];
}

13
node_modules/@nicepkg/gpt-runner/dist/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,13 @@
import { UserConfig as UserConfig$1, ChatModelType } from '@nicepkg/gpt-runner-shared/common';
export * from '@nicepkg/gpt-runner-shared/common';
export * from '@nicepkg/gpt-runner-shared/node';
type GetStaticValueFromChatModelType<T extends ChatModelType> = T extends ChatModelType ? `${T}` : never;
type UserConfig = {
[Key in keyof Omit<UserConfig$1, 'rootPath' | 'exts'>]: Key extends 'model' ? Omit<NonNullable<UserConfig$1[Key]>, 'type'> & {
type: GetStaticValueFromChatModelType<NonNullable<UserConfig$1[Key]>['type']>;
} : UserConfig$1[Key];
};
declare function defineConfig(config: UserConfig): UserConfig;
export { UserConfig, defineConfig };

8
node_modules/@nicepkg/gpt-runner/dist/index.mjs generated vendored Normal file
View File

@@ -0,0 +1,8 @@
export * from '@nicepkg/gpt-runner-shared/common';
export * from '@nicepkg/gpt-runner-shared/node';
function defineConfig(config) {
return config;
}
export { defineConfig };

56
node_modules/@nicepkg/gpt-runner/package.json generated vendored Normal file
View File

@@ -0,0 +1,56 @@
{
"name": "@nicepkg/gpt-runner",
"version": "1.2.9",
"description": "Provides the defineConfig function and UserConfig type to enable type-checked configuration of the gptr.config.ts file, forming a crucial part of the GPT-Runner package designed to enhance AI-driven development workflows.",
"author": "Jinming Yang <2214962083@qq.com>",
"license": "MIT",
"funding": "https://github.com/sponsors/2214962083",
"homepage": "https://github.com/nicepkg/gpt-runner#readme",
"repository": {
"type": "git",
"url": "https://github.com/nicepkg/gpt-runner"
},
"sponsor": {
"url": "https://github.com/sponsors/2214962083"
},
"bugs": {
"url": "https://github.com/nicepkg/gpt-runner/issues"
},
"keywords": [
"gpt-runner",
"langchain",
"chatgpt",
"prompt",
"ai",
"storybook",
"openai",
"huggingFace",
"anthropic"
],
"sideEffects": false,
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.mjs",
"require": "./dist/index.cjs"
}
},
"main": "./dist/index.cjs",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"files": [
"dist/",
"LICENSE",
"*.md"
],
"engines": {
"node": ">=16.15.0"
},
"dependencies": {
"@nicepkg/gpt-runner-shared": "1.2.9"
},
"scripts": {
"build": "unbuild",
"stub": "unbuild --stub"
}
}