mtxuilib 0.1.124 → 0.1.126

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/dist/components/AiTypes.d.ts +9 -0
  2. package/dist/components/AiTypes.js +1 -0
  3. package/dist/components/chat-share-dialog.js +1 -1
  4. package/dist/components/dev-bot/DevBotActions.d.ts +2 -9
  5. package/dist/components/dev-bot/DevBotActions.js +5 -3
  6. package/dist/components/dev-bot/chat-list.d.ts +1 -1
  7. package/dist/lib/componentHelper.d.ts +5 -5
  8. package/dist/lib/componentHelper.js +2 -2
  9. package/dist/lib/errors.js +1 -1
  10. package/dist/lib/highlight-code.js +2 -2
  11. package/dist/lib/types.d.ts +3 -3
  12. package/dist/lib/utils.d.ts +2 -5
  13. package/dist/lib/utils.js +19 -57
  14. package/dist/lib/zustand.d.ts +7 -3
  15. package/dist/lib/zustand.js +3 -3
  16. package/dist/tools/devTools/dpMtCfWorkerTool.js +1 -1
  17. package/dist/tools/devTools/dpMtxedge.js +2 -2
  18. package/dist/tools/devTools/ollamaService.d.ts +14 -0
  19. package/dist/tools/devTools/ollamaService.js +28 -0
  20. package/dist/tools/hello1Tool.d.ts +9 -3
  21. package/dist/tools/hello1Tool.js +9 -8
  22. package/dist/tools/rag/RagHello.d.ts +8 -0
  23. package/dist/tools/rag/RagHello.js +14 -0
  24. package/dist/tools/rag/addResoure.d.ts +18 -0
  25. package/dist/tools/rag/addResoure.js +27 -0
  26. package/dist/tools/rag/getInformation.d.ts +20 -0
  27. package/dist/tools/rag/getInformation.js +15 -0
  28. package/dist/tools/rag/ui/RagInput.d.ts +2 -0
  29. package/dist/tools/rag/ui/RagInput.js +29 -0
  30. package/dist/tools/webbot/callAdminBot.d.ts +1 -1
  31. package/dist/tools/webbot/callAdminBot.js +1 -1
  32. package/package.json +1 -2
  33. package/dist/components/chat.d.ts +0 -8
  34. package/dist/components/chat.js +0 -50
  35. package/dist/lib/reactqueryGraphql/fetcher.d.ts +0 -9
  36. package/dist/lib/reactqueryGraphql/fetcher.js +0 -30
  37. package/dist/lib/reactqueryGraphql/query-utils.d.ts +0 -26
  38. package/dist/lib/reactqueryGraphql/query-utils.js +0 -49
  39. package/dist/lib/selectPath.d.ts +0 -4
  40. package/dist/lib/selectPath.js +0 -44
  41. package/dist/tailwind copy.cjs +0 -76
  42. package/dist/tailwind copy.d.cts +0 -2
  43. package/dist/tools/ui/Hello1.d.ts +0 -1
  44. package/dist/tools/ui/Hello1.js +0 -17
@@ -0,0 +1,9 @@
1
+ import type { Message } from "mtxuilib/lib/types";
2
+ export type AIState = {
3
+ chatId: string;
4
+ messages: Message[];
5
+ };
6
+ export type UIState = {
7
+ id: string;
8
+ display: React.ReactNode;
9
+ }[];
@@ -0,0 +1 @@
1
+ export {};
@@ -24,7 +24,7 @@ export function ChatShareDialog({ chat, shareChat, onCopy, ...props }) {
24
24
  startShareTransition(async () => {
25
25
  const result = await shareChat(chat.id);
26
26
  if (result && "error" in result) {
27
- toast.error(result.error);
27
+ toast.error(result.error?.toString());
28
28
  return;
29
29
  }
30
30
  copyShareLink(result);
@@ -1,13 +1,6 @@
1
1
  import "server-only";
2
- import type { Chat, Message } from "mtxuilib/lib/types";
3
- export type AIState = {
4
- chatId: string;
5
- messages: Message[];
6
- };
7
- export type UIState = {
8
- id: string;
9
- display: React.ReactNode;
10
- }[];
2
+ import type { Chat } from "mtxuilib/lib/types";
3
+ import { AIState, UIState } from "../AiTypes";
11
4
  export declare const AIDev: (props: {
12
5
  children: React.ReactNode;
13
6
  initialAIState?: AIState | undefined;
@@ -2,7 +2,6 @@ import { jsx as _jsx } from "react/jsx-runtime";
2
2
  import "server-only";
3
3
  import { createOpenAI } from "@ai-sdk/openai";
4
4
  import { createAI, createStreamableValue, getAIState, getMutableAIState, streamUI, } from "ai/rsc";
5
- import { nanoid } from "mtxuilib/lib/utils";
6
5
  import { auth } from "../../lib/auth/auth";
7
6
  import { saveChat } from "../../lib/chat/chatActions";
8
7
  import { countDownTool } from "../../tools/countDown";
@@ -19,9 +18,11 @@ import { releasePackagesTool } from "../../tools/devTools/packageRelease";
19
18
  import { vcDeployTool } from "../../tools/devTools/vcDeploytool";
20
19
  import { vncServerTool } from "../../tools/devTools/vncServer";
21
20
  import { genSiteHeaderBarsTool } from "../../tools/genSiteHeaderBarsTool";
22
- import { helloTool } from "../../tools/hello1Tool";
21
+ import { welcomeTool } from "../../tools/hello1Tool";
23
22
  import { welcomeAdminUser } from "../../tools/welcomeAdminTool";
24
23
  import { BotCard, BotMessage, SpinnerMessage, UserMessage } from "../message";
24
+ import { ollamaServiceTool } from "../../tools/devTools/ollamaService";
25
+ import { nanoid } from "mtxlib/lib/utils";
25
26
  async function submitUserMessage(content) {
26
27
  "use server";
27
28
  const aiState = getMutableAIState();
@@ -82,7 +83,7 @@ async function submitUserMessage(content) {
82
83
  return textNode;
83
84
  },
84
85
  tools: {
85
- ...helloTool,
86
+ ...welcomeTool,
86
87
  ...welcomeAdminUser,
87
88
  ...vcDeployTool,
88
89
  ...dockerComposeTool,
@@ -98,6 +99,7 @@ async function submitUserMessage(content) {
98
99
  ...vncServerTool,
99
100
  ...getExternalIpTool,
100
101
  ...installOsPackagesTool,
102
+ ...ollamaServiceTool,
101
103
  },
102
104
  });
103
105
  return {
@@ -1,5 +1,5 @@
1
1
  import type { Session } from "mtxuilib/lib/types";
2
- import type { UIState } from "./DevBotActions";
2
+ import { UIState } from "../AiTypes";
3
3
  export interface ChatList {
4
4
  messages: UIState;
5
5
  session?: Session;
@@ -1,7 +1,7 @@
1
- import { ComponentType } from "react";
2
- export declare const RegisterView: (Component: ComponentType<any>, name: string | null) => void;
1
+ import type { ComponentType } from "react";
2
+ export declare const RegisterView: (Component: ComponentType<unknown>, name: string | null) => void;
3
3
  export declare const getComponentProps: (comp: any) => any;
4
- export declare const getRenderableComponent: (comp: any) => any;
4
+ export declare const getRenderableComponent: (comp: any) => undefined;
5
5
  export declare const getBlockEditorComponent: (comp: any) => any;
6
- export declare function getDynComponent(name: string): ComponentType<any>;
7
- export declare const blocks: Record<string, ComponentType<any>>;
6
+ export declare function getDynComponent(name: string): ComponentType<unknown>;
7
+ export declare const blocks: Record<string, ComponentType<unknown>>;
@@ -16,7 +16,7 @@ export const getComponentProps = (comp) => {
16
16
  };
17
17
  export const getRenderableComponent = (comp) => {
18
18
  let _comp = undefined;
19
- if (comp.$$typeof == Symbol.for('react.element')) {
19
+ if (comp.$$typeof === Symbol.for('react.element')) {
20
20
  _comp = comp.type;
21
21
  }
22
22
  if (!_comp) {
@@ -27,7 +27,7 @@ export const getRenderableComponent = (comp) => {
27
27
  export const getBlockEditorComponent = (comp) => {
28
28
  let editorComp = comp.type?._payload?.value?.Editor;
29
29
  if (!editorComp) {
30
- if (comp.type?.$$typeof == Symbol.for('react.lazy')) {
30
+ if (comp.type?.$$typeof === Symbol.for('react.lazy')) {
31
31
  editorComp = comp.type?._payload?.value?.Editor;
32
32
  }
33
33
  else {
@@ -4,5 +4,5 @@ export class RequiresProPlanError extends Error {
4
4
  }
5
5
  }
6
6
  export const MakeErrorString = (e) => {
7
- return "error:" + e.message + ", stack:" + e.stack;
7
+ return `error:${e.message}, stack:${e.stack}`;
8
8
  };
@@ -1,6 +1,6 @@
1
1
  "use server";
2
- import { promises as fs } from "fs";
3
- import path from "path";
2
+ import { promises as fs } from "node:fs";
3
+ import path from "node:path";
4
4
  import { getHighlighter } from "shiki";
5
5
  export async function highlightCode(code) {
6
6
  if (process.env.NODE_ENV === "development") {
@@ -1,8 +1,8 @@
1
- import { CoreMessage } from 'ai';
1
+ import type { CoreMessage } from "ai";
2
2
  export type Message = CoreMessage & {
3
3
  id: string;
4
4
  };
5
- export interface Chat extends Record<string, any> {
5
+ export interface Chat extends Record<string, unknown> {
6
6
  id: string;
7
7
  title: string;
8
8
  createdAt: Date;
@@ -24,7 +24,7 @@ export interface AuthResult {
24
24
  type: string;
25
25
  message: string;
26
26
  }
27
- export interface User extends Record<string, any> {
27
+ export interface User extends Record<string, unknown> {
28
28
  id: string;
29
29
  email: string;
30
30
  password: string;
@@ -14,8 +14,6 @@ export declare function ReadFileBase64Str(file: Blob): Promise<unknown>;
14
14
  export declare function ReadFileStr(file: Blob): Promise<string>;
15
15
  export declare const DataFormat: (date: number) => string;
16
16
  export declare const DataFormatWithSeconds: (date: number) => string;
17
- export declare function stringify(obj: any): string;
18
- export declare function stringifyV2(obj: any): string;
19
17
  export declare const isEdgeRuntime: () => boolean;
20
18
  export declare function isWebWorker(): boolean;
21
19
  export declare const convertToArray: <T>(maybeArray: T | T[]) => T[];
@@ -25,10 +23,9 @@ export declare function transUrlLink(url: string): string;
25
23
  export declare const isJsonResponse: (res: Response) => boolean;
26
24
  export declare function humanize(input: string): string;
27
25
  export declare function stringsRemovePrefix(inputString: string, prefix: string): string;
28
- export declare const nanoid: (size?: number) => string;
29
- export declare function fetcher<JSON = any>(input: RequestInfo, init?: RequestInit): Promise<JSON>;
26
+ export declare function fetcher<JSON>(input: RequestInfo, init?: RequestInit): Promise<JSON>;
30
27
  export declare const formatNumber: (value: number) => string;
31
- export declare const runAsyncFnWithoutBlocking: (fn: (...args: any) => Promise<any>) => void;
28
+ export declare const runAsyncFnWithoutBlocking: (fn: (...args: any) => Promise) => void;
32
29
  export declare const getStringFromBuffer: (buffer: ArrayBuffer) => string;
33
30
  export declare enum ResultCode {
34
31
  InvalidCredentials = "INVALID_CREDENTIALS",
package/dist/lib/utils.js CHANGED
@@ -1,7 +1,5 @@
1
1
  import { clsx } from "clsx";
2
- import { isFunction, isNumber, isString, omitBy, toPlainObject } from "lodash";
3
- import stableHash from "stable-hash";
4
- import { customAlphabet } from 'nanoid';
2
+ import { isNumber, isString } from "lodash";
5
3
  import { twMerge } from "tailwind-merge";
6
4
  export function cn(...inputs) {
7
5
  return twMerge(clsx(inputs));
@@ -33,7 +31,7 @@ export function cleanSearchParams(urlSearchParams) {
33
31
  const cleanedParams = urlSearchParams;
34
32
  const keysForDel = [];
35
33
  urlSearchParams.forEach((value, key) => {
36
- if (value == "null" || value === "undefined" || !value) {
34
+ if (value === "null" || value === "undefined" || !value) {
37
35
  keysForDel.push(key);
38
36
  }
39
37
  });
@@ -103,37 +101,6 @@ export const DataFormatWithSeconds = (date) => {
103
101
  const _date = new Date(date);
104
102
  return `${_date.getFullYear()}-${_date.getMonth() + 1}-${_date.getDate()}-${_date.getHours()}-${_date.getMinutes()}-${_date.getSeconds()}`;
105
103
  };
106
- export function stringify(obj) {
107
- if (typeof obj == "string") {
108
- return obj;
109
- }
110
- let _obj = omitBy(obj, isFunction);
111
- _obj = toPlainObject(_obj);
112
- let cache = [];
113
- try {
114
- const str = JSON.stringify(_obj, function (key, value) {
115
- if (typeof value === "object" && value !== null) {
116
- if (cache.indexOf(value) !== -1) {
117
- return;
118
- }
119
- cache.push(value);
120
- }
121
- if (typeof value === "bigint") {
122
- return value.toString();
123
- }
124
- return value;
125
- }, 2);
126
- cache = [];
127
- return str;
128
- }
129
- catch (e) {
130
- console.error(e);
131
- return JSON.stringify({ jsonErr: "see console" });
132
- }
133
- }
134
- export function stringifyV2(obj) {
135
- return stableHash(obj);
136
- }
137
104
  export const isEdgeRuntime = () => {
138
105
  return typeof EdgeRuntime === "string";
139
106
  };
@@ -151,7 +118,7 @@ export const ConvertToSearchParams = (value) => {
151
118
  if (isNumber(v) && v > 0) {
152
119
  return { ...pre, [k]: value[k].toString() };
153
120
  }
154
- else if (isString(v) && v != "0" && v != "false") {
121
+ if (isString(v) && v !== "0" && v !== "false") {
155
122
  return { ...pre, [k]: value[k].toString() };
156
123
  }
157
124
  }
@@ -168,8 +135,8 @@ export const splitMethodsParts = (methodName) => {
168
135
  export function transUrlLink(url) {
169
136
  try {
170
137
  const uri = new URL(url);
171
- if (uri.host == "localhost") {
172
- return uri.pathname + "?" + uri.searchParams.toString();
138
+ if (uri.host === "localhost") {
139
+ return `${uri.pathname}?${uri.searchParams.toString()}`;
173
140
  }
174
141
  return url;
175
142
  }
@@ -187,36 +154,31 @@ export function stringsRemovePrefix(inputString, prefix) {
187
154
  if (inputString.startsWith(prefix)) {
188
155
  return inputString.substring(prefix.length);
189
156
  }
190
- else {
191
- return inputString;
192
- }
157
+ return inputString;
193
158
  }
194
- export const nanoid = customAlphabet('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', 7);
195
159
  export async function fetcher(input, init) {
196
160
  const res = await fetch(input, init);
197
161
  if (!res.ok) {
198
- const json = await res.json();
162
+ const json = (await res.json());
199
163
  if (json.error) {
200
164
  const error = new Error(json.error);
201
165
  error.status = res.status;
202
166
  throw error;
203
167
  }
204
- else {
205
- throw new Error('An unexpected error occurred');
206
- }
168
+ throw new Error("An unexpected error occurred");
207
169
  }
208
170
  return res.json();
209
171
  }
210
- export const formatNumber = (value) => new Intl.NumberFormat('en-US', {
211
- style: 'currency',
212
- currency: 'USD'
172
+ export const formatNumber = (value) => new Intl.NumberFormat("en-US", {
173
+ style: "currency",
174
+ currency: "USD",
213
175
  }).format(value);
214
176
  export const runAsyncFnWithoutBlocking = (fn) => {
215
177
  fn();
216
178
  };
217
179
  export const getStringFromBuffer = (buffer) => Array.from(new Uint8Array(buffer))
218
- .map(b => b.toString(16).padStart(2, '0'))
219
- .join('');
180
+ .map((b) => b.toString(16).padStart(2, "0"))
181
+ .join("");
220
182
  export var ResultCode;
221
183
  (function (ResultCode) {
222
184
  ResultCode["InvalidCredentials"] = "INVALID_CREDENTIALS";
@@ -229,16 +191,16 @@ export var ResultCode;
229
191
  export const getMessageFromCode = (resultCode) => {
230
192
  switch (resultCode) {
231
193
  case ResultCode.InvalidCredentials:
232
- return 'Invalid credentials!';
194
+ return "Invalid credentials!";
233
195
  case ResultCode.InvalidSubmission:
234
- return 'Invalid submission, please try again!';
196
+ return "Invalid submission, please try again!";
235
197
  case ResultCode.UserAlreadyExists:
236
- return 'User already exists, please log in!';
198
+ return "User already exists, please log in!";
237
199
  case ResultCode.UserCreated:
238
- return 'User created, welcome!';
200
+ return "User created, welcome!";
239
201
  case ResultCode.UnknownError:
240
- return 'Something went wrong, please try again!';
202
+ return "Something went wrong, please try again!";
241
203
  case ResultCode.UserLoggedIn:
242
- return 'Logged in!';
204
+ return "Logged in!";
243
205
  }
244
206
  };
@@ -1,5 +1,9 @@
1
- import { StateStorage } from 'zustand/middleware';
2
- import { StateCreator, StoreMutatorIdentifier } from 'zustand/vanilla';
1
+ import type { StateStorage } from "zustand/middleware";
2
+ import type { StateCreator, StoreMutatorIdentifier } from "zustand/vanilla";
3
3
  export declare const customCookieStorage: StateStorage;
4
4
  export declare const hashStorage: StateStorage;
5
- export type ImmerStateCreator<T, Mps extends [StoreMutatorIdentifier, unknown][] = [], Mcs extends [StoreMutatorIdentifier, unknown][] = [], U = T> = StateCreator<T, [...Mps, ['zustand/immer', never], ["zustand/devtools", never]], Mcs, U>;
5
+ export type ImmerStateCreator<T, Mps extends [StoreMutatorIdentifier, unknown][] = [], Mcs extends [StoreMutatorIdentifier, unknown][] = [], U = T> = StateCreator<T, [
6
+ ...Mps,
7
+ ["zustand/immer", never],
8
+ ["zustand/devtools", never]
9
+ ], Mcs, U>;
@@ -1,5 +1,5 @@
1
- 'use client';
2
- import { deleteCookie, getCookie, setCookie } from 'mtxlib/clientlib';
1
+ "use client";
2
+ import { deleteCookie, getCookie, setCookie } from "mtxlib/clientlib";
3
3
  export const customCookieStorage = {
4
4
  getItem: async (name) => {
5
5
  return getCookie(name) || null;
@@ -26,5 +26,5 @@ export const hashStorage = {
26
26
  const searchParams = new URLSearchParams(window.location.hash.slice(1));
27
27
  searchParams.delete(key);
28
28
  window.location.hash = searchParams.toString();
29
- }
29
+ },
30
30
  };
@@ -4,7 +4,7 @@ import { BotCard } from "../../components/message";
4
4
  import { DpMtCfWorker } from "../../components/tool-ui/DpCfWorker";
5
5
  export const deployMtcfWorkerTool = {
6
6
  deployMtcfWorker: {
7
- description: "调用本地脚本,将 mtcf 项目部署到 cloudflared worker",
7
+ description: "调用本地脚本,将 mtcf 项目部署到 cloudflare worker",
8
8
  parameters: z.any(),
9
9
  generate: async function* (params) {
10
10
  yield _jsx(BotCard, { children: "\u52A0\u8F7D\u4E2D" });
@@ -11,7 +11,7 @@ export const deployMtxEdgeTool = {
11
11
  generate: async function* (params) {
12
12
  yield _jsx(BotCard, { children: "\u52A0\u8F7D\u4E2D" });
13
13
  try {
14
- const cloudflaredPageProjectName = "mtxedge";
14
+ const cfPageProjectName = "mtxedge";
15
15
  const projectDir = projectRoot();
16
16
  const vercelToken = process.env.VERCEL_TOKEN;
17
17
  yield (_jsx(BotCard, { children: _jsx("div", { children: "\u5F00\u59CB\u90E8\u7F72mtxedge" }) }));
@@ -54,7 +54,7 @@ export const deployMtxEdgeTool = {
54
54
  cwd: projectDir,
55
55
  });
56
56
  yield (_jsx(BotCard, { children: _jsx("div", { children: "\u8BBE\u7F6E\u5B8C\u6210\uFF0C\u5F00\u59CB\u90E8\u7F72\u5230 cloudfalre page \u4E2D" }) }));
57
- await exec(`bunx wrangler pages deploy .vercel/output/static --project-name=${cloudflaredPageProjectName} `, {
57
+ await exec(`bunx wrangler pages deploy .vercel/output/static --project-name=${cfPageProjectName} `, {
58
58
  shell: true,
59
59
  cwd: projectDir,
60
60
  env: process.env,
@@ -0,0 +1,14 @@
1
+ import { z } from "zod";
2
+ export declare const ollamaServiceTool: {
3
+ ollamaService: {
4
+ description: string;
5
+ parameters: z.ZodObject<{
6
+ action: z.ZodEnum<["start", "stop"]>;
7
+ }, "strip", z.ZodTypeAny, {
8
+ action: "stop" | "start";
9
+ }, {
10
+ action: "stop" | "start";
11
+ }>;
12
+ generate: (params: any) => AsyncGenerator<import("react/jsx-runtime").JSX.Element, import("react/jsx-runtime").JSX.Element, unknown>;
13
+ };
14
+ };
@@ -0,0 +1,28 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { z } from "zod";
3
+ import { BotCard } from "../../components/message";
4
+ import { exec } from "mtxlib/exec";
5
+ export const ollamaServiceTool = {
6
+ ollamaService: {
7
+ description: "启动或通知本地ollama服务",
8
+ parameters: z.object({
9
+ action: z
10
+ .enum(["start", "stop"])
11
+ .describe("动作类型,启动或停止"),
12
+ }),
13
+ generate: async function* (params) {
14
+ yield _jsx(BotCard, { children: "loading" });
15
+ try {
16
+ const a = await exec("ollama ", { shell: true });
17
+ return (_jsx(BotCard, { children: "\u5B8C\u6210" }));
18
+ }
19
+ catch (e) {
20
+ return (_jsxs(BotCard, { children: [_jsx("h3", { children: "\u9519\u8BEF\u6458\u8981\uFF1A" }), _jsx("pre", { children: e.toString() }), _jsx("div", { children: "\u66F4\u5177\u4F53\u7684\u9519\u8BEF\u4FE1\u606F\uFF0C\u8BF7\u5230\u540E\u53F0\u67E5\u770B" })] }));
21
+ }
22
+ },
23
+ },
24
+ };
25
+ async function getIp() {
26
+ const ipInfo = await fetch("https://ifconfig.me/all.json").then((x) => x.json());
27
+ return ipInfo;
28
+ }
@@ -1,8 +1,14 @@
1
1
  import { z } from "zod";
2
- export declare const helloTool: {
3
- hello1: {
2
+ export declare const welcomeTool: {
3
+ welcome: {
4
4
  description: string;
5
- parameters: z.ZodAny;
5
+ parameters: z.ZodObject<{
6
+ message: z.ZodString;
7
+ }, "strip", z.ZodTypeAny, {
8
+ message: string;
9
+ }, {
10
+ message: string;
11
+ }>;
6
12
  generate: (params: any) => AsyncGenerator<import("react/jsx-runtime").JSX.Element, import("react/jsx-runtime").JSX.Element, unknown>;
7
13
  };
8
14
  };
@@ -1,14 +1,15 @@
1
- import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
2
  import { z } from "zod";
3
3
  import { BotCard } from "../components/message";
4
- import { Hello1UI } from "./ui/Hello1";
5
- export const helloTool = {
6
- hello1: {
7
- description: "hello1 测试工具,供开发者练习ai ui 的相关操作",
8
- parameters: z.any(),
4
+ export const welcomeTool = {
5
+ welcome: {
6
+ description: "welcome screen",
7
+ parameters: z.object({
8
+ message: z.string().describe("show some message to user"),
9
+ }),
9
10
  generate: async function* (params) {
10
- yield _jsx(BotCard, { children: "\u52A0\u8F7D\u4E2D" });
11
- return (_jsx(BotCard, { children: _jsxs("div", { className: "bg-blue-100 p-2 flex gap-2 prose", children: [_jsx("h1", { children: "hello1" }), _jsx(Hello1UI, {})] }) }));
11
+ yield _jsx(BotCard, { children: "loading" });
12
+ return (_jsx(BotCard, { children: _jsx("div", { className: "bg-blue-100 p-2 flex gap-2 prose", children: _jsx("h1", { children: params.params }) }) }));
12
13
  },
13
14
  },
14
15
  };
@@ -0,0 +1,8 @@
1
+ import { z } from "zod";
2
+ export declare const ragHelloTool: {
3
+ ragHello: {
4
+ description: string;
5
+ parameters: z.ZodOptional<z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>>;
6
+ generate: (params: any) => AsyncGenerator<import("react/jsx-runtime").JSX.Element, import("react/jsx-runtime").JSX.Element, unknown>;
7
+ };
8
+ };
@@ -0,0 +1,14 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { z } from "zod";
3
+ import { BotCard } from "../../components/message";
4
+ import { RagInputDlg } from "./ui/RagInput";
5
+ export const ragHelloTool = {
6
+ ragHello: {
7
+ description: "测试用途的Rag知识库输入界面, 当用户 提问 包含 rag hello 相关字眼时,优先调用这个工具",
8
+ parameters: z.object({}).optional(),
9
+ generate: async function* (params) {
10
+ yield _jsx(BotCard, { children: "\u52A0\u8F7D\u4E2D" });
11
+ return (_jsx(BotCard, { children: _jsx(RagInputDlg, {}) }));
12
+ },
13
+ },
14
+ };
@@ -0,0 +1,18 @@
1
+ import { z } from "zod";
2
+ export declare const addResourceTool: {
3
+ addResource: import("ai").CoreTool<z.ZodObject<{
4
+ content: z.ZodString;
5
+ }, "strip", z.ZodTypeAny, {
6
+ content: string;
7
+ }, {
8
+ content: string;
9
+ }>, string | {
10
+ message: string;
11
+ }> & {
12
+ execute: (args: {
13
+ content: string;
14
+ }) => PromiseLike<string | {
15
+ message: string;
16
+ }>;
17
+ };
18
+ };
@@ -0,0 +1,27 @@
1
+ import { tool } from "ai";
2
+ import { createResource } from "mtxlib/lib/ai/actions/resources";
3
+ import { z } from "zod";
4
+ export const addResourceTool = {
5
+ addResource: tool({
6
+ description: `add a resource to your knowledge base.
7
+ If the user provides a random piece of knowledge unprompted, use this tool without asking for confirmation.`,
8
+ parameters: z.object({
9
+ content: z
10
+ .string()
11
+ .describe("the content or resource to add to the knowledge base"),
12
+ }),
13
+ execute: async ({ content }) => {
14
+ try {
15
+ console.log("添加 content 到 resource 表");
16
+ const result = await createResource({ content });
17
+ return result;
18
+ }
19
+ catch (e) {
20
+ console.log("调用工具失败 findRelevantContent", e);
21
+ return {
22
+ message: `调用工具失败${e.toString()}`,
23
+ };
24
+ }
25
+ },
26
+ }),
27
+ };
@@ -0,0 +1,20 @@
1
+ import { z } from "zod";
2
+ export declare const getInformationTool: {
3
+ getInformation: import("ai").CoreTool<z.ZodObject<{
4
+ question: z.ZodString;
5
+ }, "strip", z.ZodTypeAny, {
6
+ question: string;
7
+ }, {
8
+ question: string;
9
+ }>, {
10
+ name: string;
11
+ similarity: number;
12
+ }[]> & {
13
+ execute: (args: {
14
+ question: string;
15
+ }) => PromiseLike<{
16
+ name: string;
17
+ similarity: number;
18
+ }[]>;
19
+ };
20
+ };
@@ -0,0 +1,15 @@
1
+ import { tool } from "ai";
2
+ import { findRelevantContent } from "mtxlib/lib/ai/embedding";
3
+ import { z } from "zod";
4
+ export const getInformationTool = {
5
+ getInformation: tool({
6
+ description: "get information from your knowledge base to answer questions.",
7
+ parameters: z.object({
8
+ question: z.string().describe("the users question"),
9
+ }),
10
+ execute: async ({ question }) => {
11
+ const result = await findRelevantContent(question);
12
+ return result;
13
+ },
14
+ }),
15
+ };
@@ -0,0 +1,2 @@
1
+ export declare const RagInputDlg: () => import("react/jsx-runtime").JSX.Element;
2
+ export declare const RagInputForm: () => import("react/jsx-runtime").JSX.Element;
@@ -0,0 +1,29 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
3
+ import router from "next/router";
4
+ import Textarea from "react-textarea-autosize";
5
+ import { z } from "zod";
6
+ import { EditFormToolbar } from "../../../form/EditFormToolbar";
7
+ import { ZForm, useZodForm } from "../../../form/ZodForm";
8
+ import { MtButton } from "../../../ui-mt/Button";
9
+ import { MtInput } from "../../../ui-mt/inputs/input";
10
+ import { Dialog, DialogContent, DialogTrigger } from "../../../ui/dialog";
11
+ import { useRef, useState } from "react";
12
+ import { FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage, } from "../../../ui/form";
13
+ export const RagInputDlg = () => {
14
+ return (_jsx(_Fragment, { children: _jsxs(Dialog, { children: [_jsx(DialogTrigger, { asChild: true, children: _jsx(MtButton, { children: "\u8F93\u5165\u77E5\u8BC6\u5E93\u5185\u5BB9" }) }), _jsx(DialogContent, { children: _jsx(RagInputForm, {}) })] }) }));
15
+ };
16
+ export const RagInputForm = () => {
17
+ const inputRef = useRef(null);
18
+ const [content, setContent] = useState("");
19
+ const form = useZodForm({
20
+ schema: z.any(),
21
+ });
22
+ const handleSubmit = async (values) => {
23
+ const finnalContent = { ...values, content: content };
24
+ console.log("提交", finnalContent);
25
+ };
26
+ return (_jsxs(_Fragment, { children: [_jsxs(ZForm, { form: form, handleSubmit: handleSubmit, className: "space-y-2", children: [_jsx(FormField, { control: form.control, name: "title", render: ({ field }) => (_jsxs(FormItem, { children: [_jsx(FormLabel, { children: "title" }), _jsx(FormControl, { children: _jsx(MtInput, { placeholder: "title", ...form.register("title") }) }), _jsx(FormDescription, { children: "\u6807\u9898\uFF0C\u7528\u4E8E\u5217\u8868\u4E2D\u663E\u793A" }), _jsx(FormMessage, {})] })) }), _jsx(Textarea, { ref: inputRef, tabIndex: 0, placeholder: "Send a message.", className: "min-h-[60px] w-full resize-none bg-transparent px-4 py-[1.3rem] focus-within:outline-none sm:text-sm", autoFocus: true, spellCheck: false, autoComplete: "off", autoCorrect: "off", name: "message", rows: 1, value: content, onChange: (e) => setContent(e.target.value) })] }), _jsx(EditFormToolbar, { form: form, onCancel: () => {
27
+ router.back();
28
+ }, className: "bg-primary-500 border p-2 font-bold text-white" })] }));
29
+ };
@@ -1,6 +1,6 @@
1
1
  import { z } from "zod";
2
2
  export declare const callAdminBotTool: {
3
- callAdminBot: {
3
+ adminBot: {
4
4
  description: string;
5
5
  parameters: z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>;
6
6
  generate: (params: any) => AsyncGenerator<import("react/jsx-runtime").JSX.Element, import("react/jsx-runtime").JSX.Element, unknown>;
@@ -3,7 +3,7 @@ import { z } from "zod";
3
3
  import { BotCard } from "../../components/message";
4
4
  import { MtButton } from "../../ui-mt/Button";
5
5
  export const callAdminBotTool = {
6
- callAdminBot: {
6
+ adminBot: {
7
7
  description: "调用“高级机器人”,能让用户在界面上看到具有更高前线的机器人的按钮",
8
8
  parameters: z.object({}),
9
9
  generate: async function* (params) {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "mtxuilib",
3
3
  "private": false,
4
- "version": "0.1.124",
4
+ "version": "0.1.126",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },
@@ -185,7 +185,6 @@
185
185
  "rehype-external-links": "^3.0.0",
186
186
  "rehype-sanitize": "^6.0.0",
187
187
  "remark-gfm": "^4.0.0",
188
- "stable-hash": "^0.0.4",
189
188
  "superjson": "^2.2.1",
190
189
  "tippy.js": "^6.3.7",
191
190
  "tiptap-extension-auto-joiner": "^0.1.1",
@@ -1,8 +0,0 @@
1
- import type { Session } from "../lib/types";
2
- export interface ChatProps extends React.ComponentProps<"div"> {
3
- initialMessages?: Message[];
4
- id?: string;
5
- session?: Session;
6
- missingKeys: string[];
7
- }
8
- export declare function Chat({ id, className, session, missingKeys }: ChatProps): import("react/jsx-runtime").JSX.Element;
@@ -1,50 +0,0 @@
1
- "use client";
2
- import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
- import { useAIState, useUIState } from "ai/rsc";
4
- import { useEffect, useState } from "react";
5
- import { ChatList } from "./chat-list";
6
- import dynamic from "next/dynamic";
7
- import { usePathname, useRouter } from "next/navigation";
8
- import { toast } from "sonner";
9
- import { useLocalStorage } from "usehooks-ts";
10
- import { useScrollAnchor } from "../hooks/use-scroll-anchor";
11
- import { cn } from "../lib/utils";
12
- import { ChatPanel } from "./chat-panel";
13
- import { EmptyScreen } from "./empty-screen";
14
- const LzChatPanel = dynamic(() => import("./chat-panel").then((x) => x.ChatPanel), {
15
- ssr: false,
16
- });
17
- const LzChatList = dynamic(() => import("./chat-list").then((x) => x.ChatList), {
18
- ssr: false,
19
- });
20
- export function Chat({ id, className, session, missingKeys }) {
21
- const router = useRouter();
22
- const path = usePathname();
23
- const [input, setInput] = useState("");
24
- const [messages] = useUIState();
25
- const [aiState] = useAIState();
26
- const [_, setNewChatId] = useLocalStorage("newChatId", id);
27
- useEffect(() => {
28
- if (session?.user) {
29
- if (!path.includes("chat") && messages.length === 1) {
30
- window.history.replaceState({}, "", `/chat/${id}`);
31
- }
32
- }
33
- }, [id, path, session?.user, messages]);
34
- useEffect(() => {
35
- const messagesLength = aiState.messages?.length;
36
- if (messagesLength === 2) {
37
- router.refresh();
38
- }
39
- }, [aiState.messages, router]);
40
- useEffect(() => {
41
- setNewChatId(id);
42
- });
43
- useEffect(() => {
44
- missingKeys.map((key) => {
45
- toast.error(`Missing ${key} environment variable!`);
46
- });
47
- }, [missingKeys]);
48
- const { messagesRef, scrollRef, visibilityRef, isAtBottom, scrollToBottom } = useScrollAnchor();
49
- return (_jsxs("div", { className: "group w-full overflow-auto pl-0 peer-[[data-state=open]]:lg:pl-[250px] peer-[[data-state=open]]:xl:pl-[300px]", ref: scrollRef, children: [_jsxs("div", { className: cn("pb-[200px] pt-4 md:pt-10", className), ref: messagesRef, children: [messages.length ? (_jsx(ChatList, { messages: messages, isShared: false, session: session })) : (_jsx(EmptyScreen, {})), _jsx("div", { className: "w-full h-px", ref: visibilityRef })] }), _jsx(ChatPanel, { id: id, input: input, setInput: setInput, isAtBottom: isAtBottom, scrollToBottom: scrollToBottom })] }));
50
- }
@@ -1,9 +0,0 @@
1
- type FetchOptions = {
2
- cache?: RequestCache;
3
- next?: NextFetchRequestConfig;
4
- };
5
- type RequestInit = {
6
- headers: (HeadersInit & FetchOptions) | FetchOptions;
7
- };
8
- export declare const useGqlFetcher: <TData, TVariables>(query: string, options?: RequestInit["headers"]) => ((variables?: TVariables) => Promise<TData>);
9
- export {};
@@ -1,30 +0,0 @@
1
- import { MTM_COOKIE_TOKEN_NAME } from "@/consts";
2
- import { useMtmapi } from "@/providers/MtmapiProvider";
3
- export const useGqlFetcher = (query, options) => {
4
- const backendUrl = useMtmapi((x) => x.backendUrl);
5
- const url = `${backendUrl}/api.ent/gql`;
6
- return async (variables) => {
7
- let token = "";
8
- if (typeof window == "undefined") {
9
- const cookies = await import("next/headers").then((x) => x.cookies);
10
- token = cookies().get(MTM_COOKIE_TOKEN_NAME)?.value || "";
11
- }
12
- const res = await fetch(url, {
13
- method: "POST",
14
- headers: {
15
- "Content-Type": "application/json",
16
- ...(token && { Authorization: `Bearer ${token}` }),
17
- },
18
- body: JSON.stringify({
19
- query,
20
- variables,
21
- }),
22
- });
23
- const json = (await res.json());
24
- if (json.errors) {
25
- const { message } = json.errors[0] || {};
26
- throw new Error(message || "Error…");
27
- }
28
- return json.data;
29
- };
30
- };
@@ -1,26 +0,0 @@
1
- import { QueryClient, QueryKey, UseQueryOptions, UseQueryResult } from "@tanstack/react-query";
2
- type Exact<T extends {
3
- [key: string]: unknown;
4
- }> = {
5
- [K in keyof T]: T[K];
6
- };
7
- interface QueryWithKey<TData = any, TVariables = any> {
8
- (variables?: TVariables, options?: Omit<UseQueryOptions<TData, unknown, TData>, "queryKey"> & {
9
- queryKey?: UseQueryOptions<TData, unknown, TData>["queryKey"];
10
- }): UseQueryResult<TData, unknown>;
11
- getKey: (variables?: any) => QueryKey;
12
- fetcher: (variables?: any, options?: any) => () => Promise<TData>;
13
- }
14
- export type ServerFetchOptions<TQuery extends QueryWithKey> = Parameters<TQuery>[0] extends Exact<{
15
- [key: string]: never;
16
- }> | undefined ? {
17
- next?: NextFetchRequestConfig;
18
- cache?: RequestCache;
19
- } : {
20
- variables?: Parameters<TQuery>[0];
21
- next?: NextFetchRequestConfig;
22
- cache?: RequestCache;
23
- };
24
- export declare const serverPreFetch: <TQuery extends QueryWithKey>(useQuery: TQuery, queryOptions?: ServerFetchOptions<TQuery>) => Promise<QueryClient>;
25
- export declare const serverFetch: <TQuery extends QueryWithKey>(useQuery: TQuery, queryOptions?: ServerFetchOptions<TQuery>) => Promise<ReturnType<ReturnType<TQuery["fetcher"]>>>;
26
- export {};
@@ -1,49 +0,0 @@
1
- import { QueryClient } from "@tanstack/react-query";
2
- import { cache } from "react";
3
- const hasVariablesTypeGuard = (variables) => !!Object.keys(variables || {}).length;
4
- const cachedServerPreFetch = cache(async (useQuery, stringifiedQueryOptions) => {
5
- const queryOptions = stringifiedQueryOptions ? JSON.parse(stringifiedQueryOptions) : undefined;
6
- const hasVariables = hasVariablesTypeGuard(queryOptions);
7
- let variables;
8
- if (hasVariables) {
9
- variables = queryOptions.variables;
10
- }
11
- const queryClient = new QueryClient();
12
- await queryClient.prefetchQuery({
13
- queryKey: useQuery.getKey(variables),
14
- queryFn: useQuery.fetcher(variables, {
15
- next: queryOptions?.next,
16
- cache: queryOptions?.cache,
17
- }),
18
- });
19
- return queryClient;
20
- });
21
- export const serverPreFetch = async (useQuery, queryOptions) => {
22
- let stringifiedQueryOptions;
23
- if (queryOptions)
24
- stringifiedQueryOptions = JSON.stringify(queryOptions);
25
- return cachedServerPreFetch(useQuery, stringifiedQueryOptions);
26
- };
27
- const cachedServerFetch = cache(async (useQuery, stringifiedQueryOptions) => {
28
- const queryOptions = stringifiedQueryOptions ? JSON.parse(stringifiedQueryOptions) : undefined;
29
- const hasVariables = hasVariablesTypeGuard(queryOptions);
30
- let variables;
31
- if (hasVariables) {
32
- variables = queryOptions.variables;
33
- }
34
- const queryClient = new QueryClient();
35
- const data = await queryClient.fetchQuery({
36
- queryKey: useQuery.getKey(variables),
37
- queryFn: useQuery.fetcher(variables, {
38
- next: queryOptions?.next,
39
- cache: queryOptions?.cache,
40
- }),
41
- });
42
- return data;
43
- });
44
- export const serverFetch = async (useQuery, queryOptions) => {
45
- let stringifiedQueryOptions;
46
- if (queryOptions)
47
- stringifiedQueryOptions = JSON.stringify(queryOptions);
48
- return cachedServerFetch(useQuery, stringifiedQueryOptions);
49
- };
@@ -1,4 +0,0 @@
1
- export declare function getSelectorPath(e: any): {
2
- text: string;
3
- path: never[];
4
- };
@@ -1,44 +0,0 @@
1
- 'use client';
2
- const DomLists = [];
3
- export function getSelectorPath(e) {
4
- window.event ? window.event.cancelBubble = true : e.stopPropagation();
5
- const domPath = [];
6
- let domText = "";
7
- if (e.innerText) {
8
- domText = e.innerText;
9
- }
10
- else {
11
- domText = e.nodeName.toLocaleLowerCase();
12
- }
13
- if (e.id) {
14
- domPath.unshift('#' + e.id.toLocaleLowerCase());
15
- }
16
- else {
17
- while (e.nodeName.toLowerCase() !== "html") {
18
- if (e.id) {
19
- domPath.unshift('#' + e.id.toLocaleLowerCase());
20
- break;
21
- }
22
- else if (e.tagName.toLocaleLowerCase() == "body") {
23
- domPath.unshift(e.tagName.toLocaleLowerCase());
24
- }
25
- else {
26
- for (let i = 0; i < e.parentNode.childElementCount; i++) {
27
- if (e.parentNode.children[i] == e) {
28
- domPath.unshift(e.tagName.toLocaleLowerCase() + ':nth-child(' + (i + 1) + ')');
29
- }
30
- }
31
- }
32
- e = e.parentNode;
33
- }
34
- }
35
- DomLists.push({
36
- "text": domText,
37
- "path": domPath,
38
- });
39
- console.log('元素文本: ' + domText + ' 路径: ' + domPath);
40
- return {
41
- "text": domText,
42
- "path": domPath,
43
- };
44
- }
@@ -1,76 +0,0 @@
1
- const path = require("path");
2
- console.log("tailwindcss[mtxuilib]", path.dirname(require.resolve("mtxuilib")));
3
- module.exports = {
4
- content: [
5
- path.join(path.dirname(require.resolve("mtxuilib")), "**/*.{js,ts,jsx,tsx}"),
6
- path.join(path.dirname(require.resolve("mtxuilib")), "../../src/**/*.{js,ts,jsx,tsx}"),
7
- ],
8
- darkMode: ["class"],
9
- theme: {
10
- container: {
11
- center: true,
12
- padding: "2rem",
13
- screens: {
14
- "2xl": "1400px",
15
- },
16
- },
17
- extend: {
18
- colors: {
19
- border: "hsl(var(--border))",
20
- input: "hsl(var(--input))",
21
- ring: "hsl(var(--ring))",
22
- background: "hsl(var(--background))",
23
- foreground: "hsl(var(--foreground))",
24
- primary: {
25
- DEFAULT: "hsl(var(--primary))",
26
- foreground: "hsl(var(--primary-foreground))",
27
- },
28
- secondary: {
29
- DEFAULT: "hsl(var(--secondary))",
30
- foreground: "hsl(var(--secondary-foreground))",
31
- },
32
- destructive: {
33
- DEFAULT: "hsl(var(--destructive))",
34
- foreground: "hsl(var(--destructive-foreground))",
35
- },
36
- muted: {
37
- DEFAULT: "hsl(var(--muted))",
38
- foreground: "hsl(var(--muted-foreground))",
39
- },
40
- accent: {
41
- DEFAULT: "hsl(var(--accent))",
42
- foreground: "hsl(var(--accent-foreground))",
43
- },
44
- popover: {
45
- DEFAULT: "hsl(var(--popover))",
46
- foreground: "hsl(var(--popover-foreground))",
47
- },
48
- card: {
49
- DEFAULT: "hsl(var(--card))",
50
- foreground: "hsl(var(--card-foreground))",
51
- },
52
- },
53
- borderRadius: {
54
- lg: "var(--radius)",
55
- md: "calc(var(--radius) - 2px)",
56
- sm: "calc(var(--radius) - 4px)",
57
- },
58
- keyframes: {
59
- "accordion-down": {
60
- from: { height: 0 },
61
- to: { height: "var(--radix-accordion-content-height)" },
62
- },
63
- "accordion-up": {
64
- from: { height: "var(--radix-accordion-content-height)" },
65
- to: { height: 0 },
66
- },
67
- },
68
- animation: {
69
- "accordion-down": "accordion-down 0.2s ease-out",
70
- "accordion-up": "accordion-up 0.2s ease-out",
71
- },
72
- },
73
- },
74
- plugins: [require("tailwindcss-animate"), require("@tailwindcss/typography")],
75
- };
76
- export {};
@@ -1,2 +0,0 @@
1
- declare const _exports: import("tailwindcss").Config;
2
- export = _exports;
@@ -1 +0,0 @@
1
- export declare const Hello1UI: () => import("react/jsx-runtime").JSX.Element;
@@ -1,17 +0,0 @@
1
- "use client";
2
- import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
- import { useAIState, useActions, useUIState } from "ai/rsc";
4
- import { MtButton } from "../../ui-mt/Button";
5
- export const Hello1UI = () => {
6
- const [aiState, setAIState] = useAIState();
7
- const [aaa, setMessages] = useUIState();
8
- const { confirmPurchase } = useActions();
9
- const handleClick = () => {
10
- console.log("点击", aiState);
11
- };
12
- return (_jsxs("div", { children: [_jsx(MtButton, { onClick: () => {
13
- handleClick();
14
- }, children: "\u663E\u793A\u57FA\u672C\u4FE1\u606F(console)" }), _jsx(MtButton, { onClick: () => {
15
- console.log("aaa", aaa);
16
- }, children: "\u64CD\u4F5C2" })] }));
17
- };