nolo-cli 0.1.13 → 0.1.14

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 (320) hide show
  1. package/README.md +9 -2
  2. package/agent-runtime/hostAdapter.ts +53 -0
  3. package/agent-runtime/index.ts +28 -0
  4. package/agent-runtime/localLoop.ts +62 -0
  5. package/agent-runtime/runtimeDecision.ts +70 -0
  6. package/agent-runtime/types.ts +87 -0
  7. package/agentRuntimeCommands.ts +139 -22
  8. package/agentRuntimeLocal.ts +7 -0
  9. package/ai/agent/_executeModel.ts +118 -0
  10. package/ai/agent/agentSlice.ts +544 -1
  11. package/ai/agent/appWorkingMemory.ts +126 -0
  12. package/ai/agent/avatarUtils.ts +24 -0
  13. package/ai/agent/buildEditingContext.ts +373 -0
  14. package/ai/agent/buildSystemPrompt.ts +532 -0
  15. package/ai/agent/cleanAgentMessages.ts +140 -0
  16. package/ai/agent/cliChatClient.ts +119 -0
  17. package/ai/agent/contextCompiler.ts +107 -0
  18. package/ai/agent/contextLayerContract.ts +44 -0
  19. package/ai/agent/createAgentSchema.ts +234 -0
  20. package/ai/agent/executeToolCall.ts +58 -0
  21. package/ai/agent/fetchAgentContexts.ts +42 -0
  22. package/ai/agent/generatePrompt.ts +3 -0
  23. package/ai/agent/getFullChatContextKeys.ts +168 -0
  24. package/ai/agent/hooks/fetchPublicAgents.ts +133 -0
  25. package/ai/agent/hooks/useAgentConfig.ts +61 -0
  26. package/ai/agent/hooks/useAgentDialog.ts +35 -0
  27. package/ai/agent/hooks/useAgentFormValidation.ts +202 -0
  28. package/ai/agent/hooks/usePublicAgents.ts +473 -0
  29. package/ai/agent/persistMessageWithFixedId.ts +37 -0
  30. package/ai/agent/planSlice.ts +259 -0
  31. package/ai/agent/referenceUtils.ts +229 -0
  32. package/ai/agent/runAgentBackground.ts +238 -0
  33. package/ai/agent/runAgentClientLoop.ts +138 -0
  34. package/ai/agent/runtimeGuidance.ts +97 -0
  35. package/ai/agent/runtimeServerBase.ts +37 -0
  36. package/ai/agent/server/fetchPublicAgents.ts +128 -0
  37. package/ai/agent/startParallelAgentStreams.ts +424 -0
  38. package/ai/agent/startupProtocol.ts +53 -0
  39. package/ai/agent/streamAgentChatTurn.ts +1299 -0
  40. package/ai/agent/streamAgentChatTurnUtils.ts +738 -0
  41. package/ai/agent/types.ts +71 -0
  42. package/ai/agent/utils/imageOutput.ts +39 -0
  43. package/ai/agent/utils/publicImageAgentMode.ts +26 -0
  44. package/ai/agent/utils/sortUtils.ts +250 -0
  45. package/ai/agent/web/referencePickerUtils.ts +146 -0
  46. package/ai/ai.locale.ts +1083 -0
  47. package/ai/chat/accumulateToolCallChunks.ts +95 -0
  48. package/ai/chat/fetchUtils.native.ts +276 -0
  49. package/ai/chat/fetchUtils.ts +153 -0
  50. package/ai/chat/inlineImageUrlsForCustomProvider.ts +117 -0
  51. package/ai/chat/parseApiError.ts +64 -0
  52. package/ai/chat/parseMultilineSSE.ts +95 -0
  53. package/ai/chat/sendOpenAICompletionsRequest.native.ts +682 -0
  54. package/ai/chat/sendOpenAICompletionsRequest.ts +712 -0
  55. package/ai/chat/sendOpenAIResponseRequest.ts +512 -0
  56. package/ai/chat/shouldUseServerProxy.ts +18 -0
  57. package/ai/chat/sseClient.native.ts +91 -0
  58. package/ai/chat/sseClient.ts +67 -0
  59. package/ai/chat/streamReader.native.ts +31 -0
  60. package/ai/chat/streamReader.ts +62 -0
  61. package/ai/chat/updateTotalUsage.ts +72 -0
  62. package/ai/context/buildReferenceContext.ts +437 -0
  63. package/ai/context/calculateContextUsage.ts +133 -0
  64. package/ai/context/retention.ts +165 -0
  65. package/ai/context/tokenUtils.ts +78 -0
  66. package/ai/index.ts +1 -1
  67. package/ai/llm/agentCapabilities.ts +74 -0
  68. package/ai/llm/calculateGeminiImageTokens.ts +57 -0
  69. package/ai/llm/deepinfra.ts +28 -0
  70. package/ai/llm/fireworks.ts +68 -0
  71. package/ai/llm/generateRequestBody.ts +165 -0
  72. package/ai/llm/getModelContextWindow.ts +84 -0
  73. package/ai/llm/getNoloKey.ts +37 -0
  74. package/ai/llm/getPricing.ts +232 -0
  75. package/ai/llm/hooks/useModelPricing.ts +75 -0
  76. package/ai/llm/imagePricing.ts +66 -0
  77. package/ai/llm/isResponseAPIModel.ts +13 -0
  78. package/ai/llm/kimi.ts +18 -0
  79. package/ai/llm/mimo.ts +71 -0
  80. package/ai/llm/mistral.ts +22 -0
  81. package/ai/llm/modelAvatar.ts +427 -0
  82. package/ai/llm/models.ts +45 -0
  83. package/ai/llm/openrouterModels.ts +141 -0
  84. package/ai/llm/providers.ts +307 -0
  85. package/ai/llm/reasoningModels.ts +28 -0
  86. package/ai/llm/types.ts +59 -0
  87. package/ai/llm/usageRequestOptions.ts +59 -0
  88. package/ai/memory/capture.ts +148 -0
  89. package/ai/memory/consolidate.ts +104 -0
  90. package/ai/memory/delete.ts +147 -0
  91. package/ai/memory/overlay.ts +84 -0
  92. package/ai/memory/query.ts +38 -0
  93. package/ai/memory/queryShared.ts +160 -0
  94. package/ai/memory/rank.ts +105 -0
  95. package/ai/memory/recentRelationshipRecap.ts +247 -0
  96. package/ai/memory/remember.ts +167 -0
  97. package/ai/memory/runtime.ts +76 -0
  98. package/ai/memory/store.ts +20 -0
  99. package/ai/memory/storeShared.ts +76 -0
  100. package/ai/memory/types.ts +46 -0
  101. package/ai/memory/understanding.ts +349 -0
  102. package/ai/memory/understandingGreeting.ts +264 -0
  103. package/ai/messages/type.ts +20 -0
  104. package/ai/policy/personalizationDialog.ts +333 -0
  105. package/ai/policy/runtimePolicy.ts +440 -0
  106. package/ai/policy/selfUpdateFields.ts +48 -0
  107. package/ai/policy/types.ts +64 -0
  108. package/ai/skills/referenceRuntime.ts +274 -0
  109. package/ai/skills/skillDiagnostics.ts +251 -0
  110. package/ai/skills/skillDocBuilder.ts +139 -0
  111. package/ai/skills/skillDocProtocol.ts +434 -0
  112. package/ai/skills/skillReferenceSummary.ts +63 -0
  113. package/ai/skills/skillSummaryMarker.ts +26 -0
  114. package/ai/token/calculatePrice.ts +546 -0
  115. package/ai/token/db.ts +98 -0
  116. package/ai/token/externalToolCost.ts +321 -0
  117. package/ai/token/hooks/useRecords.ts +65 -0
  118. package/ai/token/missingUsageEstimate.ts +42 -0
  119. package/ai/token/modelUsageQuery.ts +252 -0
  120. package/ai/token/normalizeUsage.ts +84 -0
  121. package/ai/token/openaiImageGenerationUsage.ts +56 -0
  122. package/ai/token/prepareTokenUsageData.ts +88 -0
  123. package/ai/token/query.ts +88 -0
  124. package/ai/token/queryUserTokens.ts +59 -0
  125. package/ai/token/resolveBillingTarget.ts +52 -0
  126. package/ai/token/saveTokenRecord.ts +53 -0
  127. package/ai/token/serverDialogProjection.ts +78 -0
  128. package/ai/token/serverTokenWriter.ts +143 -0
  129. package/ai/token/stats.ts +21 -0
  130. package/ai/token/tokenThunks.ts +24 -0
  131. package/ai/token/types.ts +93 -0
  132. package/ai/tools/agent/agentTools.ts +176 -0
  133. package/ai/tools/agent/agentUpdateShared.ts +311 -0
  134. package/ai/tools/agent/callAgentTool.ts +139 -0
  135. package/ai/tools/agent/createAgentTool.ts +512 -0
  136. package/ai/tools/agent/createDialogTool.ts +69 -0
  137. package/ai/tools/agent/createSkillAgentTool.ts +62 -0
  138. package/ai/tools/agent/parallelBudget.ts +221 -0
  139. package/ai/tools/agent/presets/appBuilderPreset.ts +147 -0
  140. package/ai/tools/agent/runLlmTool.ts +96 -0
  141. package/ai/tools/agent/runStreamingAgentTool.ts +73 -0
  142. package/ai/tools/agent/skillAgentArgs.ts +106 -0
  143. package/ai/tools/agent/skillAgentPreset.ts +89 -0
  144. package/ai/tools/agent/streamParallelAgentsTool.ts +122 -0
  145. package/ai/tools/agent/updateAgentTool.ts +96 -0
  146. package/ai/tools/agent/updateSelfTool.ts +113 -0
  147. package/ai/tools/amazonProductScraperTool.ts +86 -0
  148. package/ai/tools/apifyActorClient.ts +45 -0
  149. package/ai/tools/appEditGuard.ts +372 -0
  150. package/ai/tools/appReadSnapshot.ts +153 -0
  151. package/ai/tools/appTools.ts +1549 -0
  152. package/ai/tools/applyEditTool.ts +256 -0
  153. package/ai/tools/applyLineEditsTool.ts +312 -0
  154. package/ai/tools/browserTools/click.ts +33 -0
  155. package/ai/tools/browserTools/closeSession.ts +29 -0
  156. package/ai/tools/browserTools/common.ts +27 -0
  157. package/ai/tools/browserTools/openSession.ts +48 -0
  158. package/ai/tools/browserTools/readContent.ts +38 -0
  159. package/ai/tools/browserTools/selectOption.ts +46 -0
  160. package/ai/tools/browserTools/typeText.ts +42 -0
  161. package/ai/tools/category/createCategoryTool.ts +66 -0
  162. package/ai/tools/category/queryContentsByCategoryTool.ts +69 -0
  163. package/ai/tools/category/updateContentCategoryTool.ts +75 -0
  164. package/ai/tools/cfBrowserTools.ts +319 -0
  165. package/ai/tools/cfSpeechToTextTool.ts +49 -0
  166. package/ai/tools/checkEnvTool.ts +65 -0
  167. package/ai/tools/cloudflareCrawlTool.ts +289 -0
  168. package/ai/tools/codeSearchTool.ts +111 -0
  169. package/ai/tools/codeTools.ts +101 -0
  170. package/ai/tools/createDocTool.ts +132 -0
  171. package/ai/tools/createPlanTool.ts +999 -0
  172. package/ai/tools/createSkillDocTool.ts +155 -0
  173. package/ai/tools/createWorkflowTool.ts +154 -0
  174. package/ai/tools/deepseekOcrTool.ts +34 -0
  175. package/ai/tools/delayTool.ts +31 -0
  176. package/ai/tools/deleteSpacesTool.ts +325 -0
  177. package/ai/tools/deleteSpacesToolModel.ts +159 -0
  178. package/ai/tools/devReloadUtils.ts +29 -0
  179. package/ai/tools/dialogMessageSearch.ts +137 -0
  180. package/ai/tools/doctorSkillTool.ts +72 -0
  181. package/ai/tools/ecommerceScraperTool.ts +86 -0
  182. package/ai/tools/emailTools.ts +549 -0
  183. package/ai/tools/evalSkillTool.ts +92 -0
  184. package/ai/tools/exaSearchTool.ts +64 -0
  185. package/ai/tools/execBashTool.ts +379 -0
  186. package/ai/tools/executeSqlTool.ts +192 -0
  187. package/ai/tools/fetchWebpageSupport.ts +309 -0
  188. package/ai/tools/fetchWebpageTool.ts +84 -0
  189. package/ai/tools/geminiImagePreviewTool.ts +361 -0
  190. package/ai/tools/generateDocxTool.ts +215 -0
  191. package/ai/tools/googleSearchScraperTool.ts +106 -0
  192. package/ai/tools/importDataTool.ts +133 -0
  193. package/ai/tools/importSkillTool.ts +162 -0
  194. package/ai/tools/index.ts +1927 -0
  195. package/ai/tools/listFilesTool.ts +82 -0
  196. package/ai/tools/listUserSpacesTool.ts +113 -0
  197. package/ai/tools/modelUsageTools.ts +199 -0
  198. package/ai/tools/olmOcrTool.ts +34 -0
  199. package/ai/tools/openaiImageTool.ts +267 -0
  200. package/ai/tools/prepareTools.ts +23 -0
  201. package/ai/tools/readDocTool.ts +84 -0
  202. package/ai/tools/readFileTool.ts +211 -0
  203. package/ai/tools/readTool.ts +163 -0
  204. package/ai/tools/readXPostTool.ts +233 -0
  205. package/ai/tools/rememberMemoryTool.ts +84 -0
  206. package/ai/tools/remotionVideoTool.ts +151 -0
  207. package/ai/tools/searchDialogMessagesTool.ts +222 -0
  208. package/ai/tools/searchRepoTool.ts +115 -0
  209. package/ai/tools/searchWorkspaceTool.ts +259 -0
  210. package/ai/tools/skillFollowup.ts +86 -0
  211. package/ai/tools/surfWeatherTool.ts +169 -0
  212. package/ai/tools/table/addTableRowTool.ts +217 -0
  213. package/ai/tools/table/createTableTool.ts +315 -0
  214. package/ai/tools/table/rowTools.ts +366 -0
  215. package/ai/tools/table/schemaTools.ts +244 -0
  216. package/ai/tools/table/shareTableTool.ts +148 -0
  217. package/ai/tools/table/toolShared.ts +129 -0
  218. package/ai/tools/toolApiClient.ts +198 -0
  219. package/ai/tools/toolNameAliases.ts +57 -0
  220. package/ai/tools/toolResultError.ts +42 -0
  221. package/ai/tools/toolRunSlice.ts +303 -0
  222. package/ai/tools/toolSchemaCompatibility.ts +53 -0
  223. package/ai/tools/toolVisibility.ts +4 -0
  224. package/ai/tools/types.ts +20 -0
  225. package/ai/tools/uiAskChoiceTool.ts +104 -0
  226. package/ai/tools/updateContentTitleTool.ts +84 -0
  227. package/ai/tools/updateDocTool.ts +105 -0
  228. package/ai/tools/updateUserPreferenceProfileTool.ts +145 -0
  229. package/ai/tools/whisperTool.ts +77 -0
  230. package/ai/tools/writeFileTool.ts +210 -0
  231. package/ai/tools/youtubeScraperTool.ts +116 -0
  232. package/ai/tools/ziweiChartTool.ts +678 -0
  233. package/ai/types.ts +55 -0
  234. package/ai/workflow/workflowExecutor.ts +323 -0
  235. package/ai/workflow/workflowSlice.ts +73 -0
  236. package/ai/workflow/workflowTypes.ts +106 -0
  237. package/client/agentRun.test.ts +240 -0
  238. package/client/agentRun.ts +182 -19
  239. package/client/compactDialog.test.ts +238 -0
  240. package/client/localRuntimeAdapter.test.ts +135 -0
  241. package/client/localRuntimeAdapter.ts +244 -0
  242. package/client/profileConfig.test.ts +40 -0
  243. package/client/streamingOutput.test.ts +22 -0
  244. package/client/streamingOutput.ts +38 -0
  245. package/commandRegistry.ts +9 -2
  246. package/connector-experimental/index.ts +5 -0
  247. package/database/actions/cacheMergedUserData.ts +64 -0
  248. package/database/actions/common.ts +242 -0
  249. package/database/actions/deleteFile.ts +40 -0
  250. package/database/actions/fetchUserData.ts +16 -0
  251. package/database/actions/fileContent.ts +125 -0
  252. package/database/actions/patch.ts +155 -0
  253. package/database/actions/read.ts +337 -0
  254. package/database/actions/readAndWait.ts +224 -0
  255. package/database/actions/readRequestManager.ts +120 -0
  256. package/database/actions/remove.ts +94 -0
  257. package/database/actions/replication.ts +366 -0
  258. package/database/actions/upload.ts +174 -0
  259. package/database/actions/upsert.ts +56 -0
  260. package/database/actions/write.ts +126 -0
  261. package/database/client/db.native.ts +73 -0
  262. package/database/client/db.ts +51 -0
  263. package/database/client/fetchUserData.ts +61 -0
  264. package/database/client/handleError.ts +19 -0
  265. package/database/client/queryRequest.ts +21 -0
  266. package/database/config.ts +21 -0
  267. package/database/dbActionThunks.ts +1 -0
  268. package/database/dbSlice.ts +149 -0
  269. package/database/email.ts +42 -0
  270. package/database/fileRing.ts +51 -0
  271. package/database/fileSharding.ts +70 -0
  272. package/database/fileStorage.native.ts +92 -0
  273. package/database/fileStorage.ts +232 -0
  274. package/database/fileUrl.ts +34 -0
  275. package/database/hooks/useUserData.ts +489 -0
  276. package/database/index.ts +1 -0
  277. package/database/keys.ts +765 -0
  278. package/database/queryPrefixes.ts +14 -0
  279. package/database/requests.ts +443 -0
  280. package/database/runtimeServerContext.ts +35 -0
  281. package/database/server/MemoryDB.ts +76 -0
  282. package/database/server/actorAccess.ts +76 -0
  283. package/database/server/agentDelegation.ts +124 -0
  284. package/database/server/coreDataOwnership.ts +13 -0
  285. package/database/server/coreDataProxy.ts +76 -0
  286. package/database/server/cybotReadonly.ts +18 -0
  287. package/database/server/dataHandlers.ts +111 -0
  288. package/database/server/db.ts +118 -0
  289. package/database/server/dbPath.ts +20 -0
  290. package/database/server/delete.ts +499 -0
  291. package/database/server/emailRepository.ts +1480 -0
  292. package/database/server/ensureDbOpen.ts +12 -0
  293. package/database/server/fileRead.ts +337 -0
  294. package/database/server/fileService.ts +436 -0
  295. package/database/server/handleTransaction.ts +86 -0
  296. package/database/server/patch.ts +282 -0
  297. package/database/server/query.ts +138 -0
  298. package/database/server/read.ts +325 -0
  299. package/database/server/resourceAccess.ts +211 -0
  300. package/database/server/routes.ts +110 -0
  301. package/database/server/spaceMemberAuthority.ts +67 -0
  302. package/database/server/upload.ts +159 -0
  303. package/database/server/write.ts +494 -0
  304. package/database/server/writeAuthority.ts +133 -0
  305. package/database/sqliteDb.ts +46 -0
  306. package/database/table/deleteTable.ts +120 -0
  307. package/database/tenantPlacement.ts +57 -0
  308. package/database/tombstones.ts +52 -0
  309. package/database/userDataLoadDecision.ts +17 -0
  310. package/database/userDataMerge.ts +95 -0
  311. package/database/userPreferenceRegister.ts +108 -0
  312. package/database/utils/dbPath.ts +47 -0
  313. package/database/utils/ulid.native.ts +6 -0
  314. package/database/utils/ulid.ts +1 -0
  315. package/index.ts +25 -15
  316. package/localRuntimeDb.ts +28 -0
  317. package/package.json +16 -4
  318. package/runtimeModeArgs.ts +33 -0
  319. package/tui/readlineWorkspace.ts +1 -0
  320. package/tui/session.ts +22 -0
@@ -0,0 +1,21 @@
1
+ export function createInitialDayStats(
2
+ userId: string,
3
+ dateKey: string
4
+ ): DayStats {
5
+ const initial = {
6
+ userId,
7
+ period: "day",
8
+ timeKey: dateKey,
9
+ total: {
10
+ count: 0,
11
+ tokens: {
12
+ input: 0,
13
+ output: 0,
14
+ },
15
+ cost: 0,
16
+ },
17
+ models: {},
18
+ providers: {},
19
+ };
20
+ return initial;
21
+ }
@@ -0,0 +1,24 @@
1
+ import { createAsyncThunk } from "@reduxjs/toolkit";
2
+ import { AppThunkApi } from "app/store";
3
+ import { getTokenStats, StatsParams, TokenStats } from "./query";
4
+ import { queryUserTokens, QueryParams, QueryResult } from "./queryUserTokens";
5
+
6
+ export const getTokenStatsThunk = createAsyncThunk<
7
+ TokenStats[],
8
+ StatsParams,
9
+ AppThunkApi
10
+ >("token/getStats", async (params, { extra }) => {
11
+ const { db } = extra;
12
+ if (!db) throw new Error("Database not available");
13
+ return await getTokenStats(db, params);
14
+ });
15
+
16
+ export const queryUserTokensThunk = createAsyncThunk<
17
+ QueryResult,
18
+ QueryParams,
19
+ AppThunkApi
20
+ >("token/queryUserTokens", async (params, { extra }) => {
21
+ const { db } = extra;
22
+ if (!db) throw new Error("Database not available");
23
+ return await queryUserTokens(db, params);
24
+ });
@@ -0,0 +1,93 @@
1
+ // ai/token/types.ts
2
+
3
+ export const DEFAULT_QUERY_LIMIT = 100;
4
+
5
+ export const TOKEN_PERIODS = {
6
+ DAY: "day",
7
+ WEEK: "week",
8
+ MONTH: "month",
9
+ } as const;
10
+
11
+ export const TOKEN_SCOPES = {
12
+ USER: "user",
13
+ CYBOT: "cybot",
14
+ SITE: "site",
15
+ } as const;
16
+
17
+ interface BillingUsageMetadata {
18
+ cost?: number;
19
+ billing_provider?: string;
20
+ billing_model?: string;
21
+ billing_service_tier?: string;
22
+ billing_estimated?: boolean;
23
+ image_generation_count?: number;
24
+ }
25
+
26
+ // 原始用量类型
27
+ export interface RawUsageType1 extends BillingUsageMetadata {
28
+ output_tokens?: number;
29
+ input_tokens?: number;
30
+ cache_creation_input_tokens?: number;
31
+ cache_read_input_tokens?: number;
32
+ }
33
+
34
+ export interface RawUsageType2 extends BillingUsageMetadata {
35
+ prompt_tokens: number;
36
+ completion_tokens: number;
37
+ total_tokens: number;
38
+ prompt_cache_hit_tokens: number;
39
+ prompt_cache_miss_tokens: number;
40
+ }
41
+
42
+ export type RawUsage = RawUsageType1 | RawUsageType2;
43
+
44
+ // 标准化后的用量数据
45
+ export interface NormalizedUsage extends BillingUsageMetadata {
46
+ input_tokens: number;
47
+ output_tokens: number;
48
+ cache_creation_input_tokens: number;
49
+ cache_read_input_tokens: number;
50
+ cost: number;
51
+ }
52
+
53
+ // Token使用数据
54
+ export interface TokenUsageData extends NormalizedUsage {
55
+ userId?: string;
56
+ cybotId: string;
57
+ model: string;
58
+ provider: string;
59
+ dialogId: string;
60
+ pay: any; // TODO: 明确支付数据类型
61
+ }
62
+
63
+ // Token记录
64
+ export interface TokenRecord {
65
+ id: string;
66
+ userId: string;
67
+ username: string;
68
+ cybotId: string;
69
+ model: string;
70
+ provider: string;
71
+ dialogId: string;
72
+ cache_creation_input_tokens: number;
73
+ cache_read_input_tokens: number;
74
+ output_tokens: number;
75
+ input_tokens: number;
76
+ cost: number;
77
+ image_generation_count?: number;
78
+ pay: any;
79
+ createdAt: number; // UTC timestamp
80
+ type: string;
81
+ }
82
+
83
+ // Token统计数据
84
+ export interface TokenStats {
85
+ total: number;
86
+ date: string; // YYYY-MM-DD in UTC
87
+ inputTokens: number;
88
+ outputTokens: number;
89
+ cost: number;
90
+ userId: string;
91
+ createdAt: number; // UTC timestamp
92
+ type: string;
93
+ }
@@ -0,0 +1,176 @@
1
+ // 文件路径: ai/tools/agent/agentTools.ts
2
+
3
+ import {
4
+ callAgentFunctionSchema,
5
+ callAgentFunc,
6
+ } from "./callAgentTool";
7
+ import {
8
+ createAgentToolFunctionSchema,
9
+ createAgentToolFunc,
10
+ } from "./createAgentTool";
11
+ import {
12
+ createSkillAgentToolFunctionSchema,
13
+ createSkillAgentToolFunc,
14
+ } from "./createSkillAgentTool";
15
+ import {
16
+ updateAgentToolFunctionSchema,
17
+ updateAgentToolFunc,
18
+ } from "./updateAgentTool";
19
+ import {
20
+ updateSelfToolFunctionSchema,
21
+ updateSelfToolFunc,
22
+ } from "./updateSelfTool";
23
+ import {
24
+ runStreamingAgentFunctionSchema,
25
+ runStreamingAgentFunc,
26
+ } from "./runStreamingAgentTool";
27
+ import {
28
+ streamParallelAgentsFunctionSchema,
29
+ streamParallelAgentsFunc,
30
+ } from "./streamParallelAgentsTool";
31
+ import {
32
+ createDialogFunctionSchema,
33
+ createDialogFunc,
34
+ } from "./createDialogTool";
35
+ import {
36
+ runLlmFunctionSchema,
37
+ runLlmToolFunc,
38
+ } from "./runLlmTool";
39
+
40
+ import type { ToolDefinition } from "../index";
41
+
42
+ export const agentToolDefinitions: ToolDefinition[] = [
43
+ {
44
+ id: "createAgent",
45
+ schema: createAgentToolFunctionSchema,
46
+ executor: createAgentToolFunc,
47
+ description: {
48
+ name: "createAgent",
49
+ description:
50
+ "根据给定配置创建一个新的 Agent(智能体 / 应用),并返回其详细信息。",
51
+ category: "计划与编排",
52
+ },
53
+ behavior: "action",
54
+ uiGroup: "agent",
55
+ capability: "self_evolution",
56
+ riskLevel: "high",
57
+ costLevel: "low",
58
+ defaultConsent: "ask",
59
+ },
60
+ {
61
+ id: "createSkillAgent",
62
+ schema: createSkillAgentToolFunctionSchema,
63
+ executor: createSkillAgentToolFunc,
64
+ description: {
65
+ name: "createSkillAgent",
66
+ description:
67
+ "创建专门用于创建/评估 skill 文档协议的 Agent。",
68
+ category: "计划与编排",
69
+ },
70
+ behavior: "action",
71
+ uiGroup: "agent",
72
+ capability: "self_evolution",
73
+ riskLevel: "high",
74
+ costLevel: "low",
75
+ defaultConsent: "ask",
76
+ },
77
+ {
78
+ id: "updateSelf",
79
+ schema: updateSelfToolFunctionSchema,
80
+ executor: updateSelfToolFunc,
81
+ description: {
82
+ name: "updateSelf",
83
+ description:
84
+ "更新当前正在运行的 Agent 自己。低风险字段可直接更新,高影响字段会先请求确认。",
85
+ category: "计划与编排",
86
+ },
87
+ behavior: "action",
88
+ uiGroup: "agent",
89
+ capability: "self_evolution",
90
+ riskLevel: "high",
91
+ costLevel: "low",
92
+ defaultConsent: "ask",
93
+ },
94
+ {
95
+ id: "updateAgent",
96
+ schema: updateAgentToolFunctionSchema,
97
+ executor: updateAgentToolFunc,
98
+ description: {
99
+ name: "updateAgent",
100
+ description:
101
+ "根据给定配置更新已经存在的 Agent。只会修改参数中出现的字段,未提供的字段保持不变。",
102
+ category: "计划与编排",
103
+ },
104
+ behavior: "action",
105
+ uiGroup: "agent",
106
+ capability: "self_evolution",
107
+ riskLevel: "high",
108
+ costLevel: "low",
109
+ defaultConsent: "ask",
110
+ },
111
+ {
112
+ id: "callAgent",
113
+ schema: callAgentFunctionSchema,
114
+ executor: callAgentFunc,
115
+ description: {
116
+ name: "callAgent",
117
+ description:
118
+ "调用一个指定的 Agent 执行一次子任务,可用于多 Agent 编排、自动评测、自动对比等场景。",
119
+ category: "计划与编排",
120
+ },
121
+ behavior: "orchestrator",
122
+ uiGroup: "agent",
123
+ },
124
+ {
125
+ id: "runStreamingAgent",
126
+ schema: runStreamingAgentFunctionSchema,
127
+ executor: runStreamingAgentFunc,
128
+ description: {
129
+ name: "runStreamingAgent",
130
+ description:
131
+ "将本轮回答交由指定的 Agent 以流式方式输出,常用于从通用助手切换到某个专用应用。",
132
+ category: "计划与编排",
133
+ },
134
+ behavior: "orchestrator",
135
+ uiGroup: "agent",
136
+ },
137
+ {
138
+ id: "streamParallelAgents",
139
+ schema: streamParallelAgentsFunctionSchema,
140
+ executor: streamParallelAgentsFunc,
141
+ description: {
142
+ name: "streamParallelAgents",
143
+ description:
144
+ "并行调用多个 Agent,并让它们分别以流式方式输出结果。",
145
+ category: "计划与编排",
146
+ },
147
+ behavior: "orchestrator",
148
+ uiGroup: "agent",
149
+ },
150
+ {
151
+ id: "createDialog",
152
+ schema: createDialogFunctionSchema,
153
+ executor: createDialogFunc,
154
+ description: {
155
+ name: "createDialog",
156
+ description:
157
+ "创建一个新的对话,指定 Agent 响应,可选发送第一条消息触发执行。返回 dialogId 可随时查看结果。",
158
+ category: "计划与编排",
159
+ },
160
+ behavior: "action",
161
+ uiGroup: "agent",
162
+ },
163
+ {
164
+ id: "runLlm",
165
+ schema: runLlmFunctionSchema,
166
+ executor: runLlmToolFunc,
167
+ description: {
168
+ name: "runLlm",
169
+ description:
170
+ "对指定模型发起一次单轮 LLM 调用,不加载知识库也不调用工具。适合摘要、分类、格式化等纯文本处理任务。",
171
+ category: "计划与编排",
172
+ },
173
+ behavior: "action",
174
+ uiGroup: "agent",
175
+ },
176
+ ];
@@ -0,0 +1,311 @@
1
+ import type { Agent } from "app/types";
2
+ import type { FormData as AgentFormData } from "ai/agent/createAgentSchema";
3
+ import {
4
+ type AgentUpdateField,
5
+ AGENT_UPDATE_FIELD_NAMES,
6
+ } from "ai/policy/selfUpdateFields";
7
+ import { ToolResultError } from "ai/tools/toolResultError";
8
+
9
+ type ReasoningEffort = "low" | "medium" | "high";
10
+
11
+ export type ReferenceArg = {
12
+ dbKey: string;
13
+ title?: string;
14
+ type?: "knowledge" | "instruction" | "page";
15
+ };
16
+
17
+ export type GreetingMenuItemArg = {
18
+ id: string;
19
+ label: string;
20
+ userMessage?: string;
21
+ };
22
+
23
+ export type GreetingConfigArg = {
24
+ text?: string;
25
+ menu?: GreetingMenuItemArg[];
26
+ };
27
+
28
+ export type AgentUpdateArgsShape = {
29
+ __confirmedSelfEvolution?: boolean;
30
+ name?: string;
31
+ model?: string;
32
+ provider?: string;
33
+ prompt?: string;
34
+ introduction?: string;
35
+ greeting?: string | GreetingConfigArg;
36
+ isPublic?: boolean;
37
+ tags?: string[] | string;
38
+ tools?: string[];
39
+ references?: ReferenceArg[];
40
+ temperature?: number;
41
+ top_p?: number;
42
+ frequency_penalty?: number;
43
+ presence_penalty?: number;
44
+ max_tokens?: number;
45
+ reasoning_effort?: ReasoningEffort;
46
+ };
47
+
48
+ export type UpdateAgentToolArgs = AgentUpdateArgsShape & {
49
+ agentId: string;
50
+ };
51
+
52
+ export type UpdateSelfToolArgs = AgentUpdateArgsShape;
53
+
54
+ export const agentUpdateFieldSchemaProperties = {
55
+ name: { type: "string", description: "Agent 的新名称。" },
56
+ model: { type: "string", description: "模型名称,例如 'gpt-4o-mini'。" },
57
+ provider: { type: "string", description: "模型提供方,例如 'openai'。若不确定可留空。" },
58
+ prompt: { type: "string", description: "系统提示词,描述 Agent 的角色和行为。" },
59
+ introduction: { type: "string", description: "面向终端用户的简介文案。" },
60
+ greeting: {
61
+ description: "欢迎配置:纯文本字符串,或包含欢迎语 + 菜单的对象。",
62
+ anyOf: [
63
+ { type: "string", description: "纯文本欢迎语。" },
64
+ {
65
+ type: "object",
66
+ description: "结构化欢迎配置。",
67
+ properties: {
68
+ text: { type: "string", description: "欢迎语文本。" },
69
+ menu: {
70
+ type: "array",
71
+ description: "快捷菜单项。",
72
+ items: {
73
+ type: "object",
74
+ properties: {
75
+ id: { type: "string", description: "菜单项唯一标识。" },
76
+ label: { type: "string", description: "按钮显示文案。" },
77
+ userMessage: { type: "string", description: "点击后发送给 Agent 的消息。" },
78
+ },
79
+ required: ["id", "label"],
80
+ },
81
+ },
82
+ },
83
+ },
84
+ ],
85
+ },
86
+ isPublic: { type: "boolean", description: "是否公开到应用市场。" },
87
+ tags: {
88
+ type: "array",
89
+ items: { type: "string" },
90
+ description: "标签列表;传空数组 [] 表示清空。",
91
+ },
92
+ tools: {
93
+ type: "array",
94
+ items: { type: "string" },
95
+ description: "允许调用的工具名称数组。",
96
+ },
97
+ references: {
98
+ type: "array",
99
+ description: "引用集合;传空数组 [] 表示清空。",
100
+ items: {
101
+ type: "object",
102
+ properties: {
103
+ dbKey: { type: "string", description: "引用条目的数据库键。" },
104
+ title: { type: "string", description: "引用在 UI 中展示的标题。" },
105
+ type: {
106
+ type: "string",
107
+ enum: ["knowledge", "instruction", "page"],
108
+ description: "引用类型。",
109
+ },
110
+ },
111
+ required: ["dbKey"],
112
+ },
113
+ },
114
+ temperature: { type: "number", description: "采样温度,0~2。" },
115
+ top_p: { type: "number", description: "nucleus sampling,0~1。" },
116
+ frequency_penalty: { type: "number", description: "重复惩罚,-2~2。" },
117
+ presence_penalty: { type: "number", description: "新话题激励,-2~2。" },
118
+ max_tokens: { type: "number", description: "单次回答最大 token 数。" },
119
+ reasoning_effort: {
120
+ type: "string",
121
+ enum: ["low", "medium", "high"],
122
+ description: "推理强度。",
123
+ },
124
+ } as const;
125
+
126
+ type AgentPatch = Partial<AgentFormData> & {
127
+ greeting?: string | GreetingConfigArg;
128
+ tags?: string[] | string;
129
+ references?: ReferenceArg[];
130
+ };
131
+
132
+ export const validateUpdateArgs = (
133
+ userId: string | undefined,
134
+ options?: { requireAgentId?: boolean; agentId?: string },
135
+ ): void => {
136
+ if (!userId) throw new Error("更新 Agent 失败:当前未登录或缺少 userId。");
137
+ if (options?.requireAgentId && !options?.agentId?.trim()) {
138
+ throw new Error("更新 Agent 失败:必须提供非空的 agentId。");
139
+ }
140
+ };
141
+
142
+ export const fetchAgentByDbKey = async (
143
+ dbKey: string,
144
+ db: any,
145
+ ): Promise<Agent | undefined> => {
146
+ if (!db) return undefined;
147
+ return db.get(dbKey).catch(() => undefined);
148
+ };
149
+
150
+ export const extractAgentId = (dbKey: string): string => {
151
+ const parts = dbKey.trim().split("-");
152
+ return parts.length >= 3 ? parts[parts.length - 1] : dbKey.trim();
153
+ };
154
+
155
+ export const buildPatch = (args: AgentUpdateArgsShape): AgentPatch => {
156
+ const patch: AgentPatch = {};
157
+ const {
158
+ name,
159
+ model,
160
+ provider,
161
+ prompt,
162
+ introduction,
163
+ greeting,
164
+ isPublic,
165
+ tags,
166
+ tools,
167
+ references,
168
+ temperature,
169
+ top_p,
170
+ frequency_penalty,
171
+ presence_penalty,
172
+ max_tokens,
173
+ reasoning_effort,
174
+ } = args;
175
+
176
+ if (name !== undefined) patch.name = String(name).trim();
177
+ if (model !== undefined) patch.model = String(model).trim();
178
+ if (provider !== undefined) patch.provider = String(provider).trim();
179
+ if (prompt !== undefined) patch.prompt = prompt;
180
+ if (introduction !== undefined) patch.introduction = introduction;
181
+ if (greeting !== undefined) patch.greeting = greeting;
182
+ if (isPublic !== undefined) patch.isPublic = isPublic;
183
+ if (tags !== undefined) patch.tags = tags as any;
184
+ if (tools !== undefined) patch.tools = tools ?? [];
185
+ if (references !== undefined) patch.references = references as any;
186
+ if (temperature !== undefined) patch.temperature = temperature;
187
+ if (top_p !== undefined) patch.top_p = top_p;
188
+ if (frequency_penalty !== undefined) patch.frequency_penalty = frequency_penalty;
189
+ if (presence_penalty !== undefined) patch.presence_penalty = presence_penalty;
190
+ if (max_tokens !== undefined) patch.max_tokens = max_tokens;
191
+ if (reasoning_effort !== undefined) patch.reasoning_effort = reasoning_effort;
192
+
193
+ return patch;
194
+ };
195
+
196
+ const AGENT_UPDATE_FIELD_NAME_SET = new Set<string>(AGENT_UPDATE_FIELD_NAMES);
197
+
198
+ export const listRequestedFields = (
199
+ args: Record<string, unknown>,
200
+ ): AgentUpdateField[] =>
201
+ Object.keys(args).filter(
202
+ (key): key is AgentUpdateField =>
203
+ key !== "agentId" &&
204
+ key !== "__confirmedSelfEvolution" &&
205
+ AGENT_UPDATE_FIELD_NAME_SET.has(key) &&
206
+ args[key] !== undefined,
207
+ );
208
+
209
+ export const assertAgentUpdateConfirmation = ({
210
+ scope,
211
+ requestedFields,
212
+ confirmed,
213
+ autoApprovedFields = [],
214
+ }: {
215
+ scope: "self" | "generic";
216
+ requestedFields: AgentUpdateField[];
217
+ confirmed?: boolean;
218
+ autoApprovedFields?: AgentUpdateField[];
219
+ }): void => {
220
+ if (requestedFields.length === 0 || confirmed) return;
221
+
222
+ const allowedFields =
223
+ scope === "self"
224
+ ? requestedFields.filter((field) => autoApprovedFields.includes(field))
225
+ : [];
226
+ const blockedFields =
227
+ scope === "self"
228
+ ? requestedFields.filter((field) => !autoApprovedFields.includes(field))
229
+ : requestedFields;
230
+
231
+ if (blockedFields.length === 0) return;
232
+
233
+ const displayPrefix = scope === "self" ? "updateSelf" : "updateAgent";
234
+ throw new ToolResultError(
235
+ scope === "self"
236
+ ? `当前自我更新字段需要先确认:${blockedFields.join(", ")}`
237
+ : `当前通用 Agent 更新需要先确认:${blockedFields.join(", ")}`,
238
+ {
239
+ code: "agent_update_requires_confirmation",
240
+ retryable: false,
241
+ displayData: `${displayPrefix} 需要先确认:${blockedFields.join(", ")}`,
242
+ rawData: {
243
+ error: "agent_update_requires_confirmation",
244
+ message:
245
+ scope === "self"
246
+ ? "当前自我更新包含需要用户确认的字段。"
247
+ : "当前通用 Agent 更新默认要求用户确认。",
248
+ policy: {
249
+ capability: scope === "self" ? "self_update" : "agent_update",
250
+ scope,
251
+ decision: "ask",
252
+ requestedFields,
253
+ allowedFields,
254
+ blockedFields,
255
+ autoApprovedFields,
256
+ },
257
+ },
258
+ },
259
+ );
260
+ };
261
+
262
+ export const buildRawDataWithUpdateInfo = (
263
+ agent: Agent,
264
+ previousAgent: Agent,
265
+ requestedFields: AgentUpdateField[],
266
+ ) => {
267
+ const changes: Record<string, { o: any; n: any }> = {};
268
+ for (const key of requestedFields) {
269
+ const newVal = (agent as any)[key];
270
+ const oldVal = (previousAgent as any)[key];
271
+ if (JSON.stringify(newVal) !== JSON.stringify(oldVal)) {
272
+ changes[key] = { o: oldVal, n: newVal };
273
+ }
274
+ }
275
+
276
+ return {
277
+ ...agent,
278
+ _isUpdate: true,
279
+ _changes: Object.keys(changes).length > 0 ? changes : undefined,
280
+ };
281
+ };
282
+
283
+ export const formatUpdatedAgentOutput = (agent: Agent): string =>
284
+ [
285
+ `✅ 已更新 Agent:${agent.name ?? "(名称未变)"}`,
286
+ `- ID: ${agent.id}`,
287
+ `- 是否公开: ${agent.isPublic ? "是" : "否"}`,
288
+ agent.model && `- 模型: ${agent.model}`,
289
+ (agent as any).provider && `- Provider: ${(agent as any).provider}`,
290
+ agent.tags?.length && `- 标签: ${agent.tags.join(", ")}`,
291
+ typeof agent.temperature === "number" && `- temperature: ${agent.temperature}`,
292
+ ]
293
+ .filter(Boolean)
294
+ .join("\n");
295
+
296
+ export const buildUpdateThunkPreviousAgent = (
297
+ previousAgent: Agent,
298
+ userId: string,
299
+ ): Agent => {
300
+ const ownerUserId = String(previousAgent.userId ?? "").trim();
301
+ if (previousAgent.isPublic && ownerUserId !== userId) {
302
+ return {
303
+ ...previousAgent,
304
+ isPublic: false,
305
+ };
306
+ }
307
+ return previousAgent;
308
+ };
309
+
310
+ // TODO: Persist lightweight audit events for updateSelf/updateAgent so version history
311
+ // and future rollback can inspect who changed what without rebuilding it from dialogs.