nolo-cli 0.1.9 → 0.1.11

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 (240) hide show
  1. package/README.md +0 -32
  2. package/agentRuntimeCommands.ts +3 -3
  3. package/commandRegistry.ts +2 -2
  4. package/machineCommands.ts +31 -6
  5. package/package.json +6 -8
  6. package/ai/agent/_executeModel.ts +0 -118
  7. package/ai/agent/agentSlice.ts +0 -525
  8. package/ai/agent/appWorkingMemory.ts +0 -126
  9. package/ai/agent/avatarUtils.ts +0 -24
  10. package/ai/agent/buildEditingContext.ts +0 -373
  11. package/ai/agent/buildSystemPrompt.ts +0 -532
  12. package/ai/agent/cleanAgentMessages.ts +0 -140
  13. package/ai/agent/cliChatClient.ts +0 -119
  14. package/ai/agent/cliExecutor.ts +0 -733
  15. package/ai/agent/cliPrompt.ts +0 -10
  16. package/ai/agent/contextCompiler.ts +0 -107
  17. package/ai/agent/contextLayerContract.ts +0 -44
  18. package/ai/agent/createAgentSchema.ts +0 -234
  19. package/ai/agent/executeToolCall.ts +0 -58
  20. package/ai/agent/fetchAgentContexts.ts +0 -42
  21. package/ai/agent/generatePrompt.ts +0 -3
  22. package/ai/agent/getFullChatContextKeys.ts +0 -168
  23. package/ai/agent/hooks/fetchPublicAgents.ts +0 -133
  24. package/ai/agent/hooks/useAgentConfig.ts +0 -61
  25. package/ai/agent/hooks/useAgentDialog.ts +0 -35
  26. package/ai/agent/hooks/useAgentFormValidation.ts +0 -202
  27. package/ai/agent/hooks/usePublicAgents.ts +0 -473
  28. package/ai/agent/machineRunPermissions.ts +0 -95
  29. package/ai/agent/persistMessageWithFixedId.ts +0 -37
  30. package/ai/agent/planSlice.ts +0 -259
  31. package/ai/agent/referenceUtils.ts +0 -229
  32. package/ai/agent/runAgentBackground.ts +0 -238
  33. package/ai/agent/runAgentClientLoop.ts +0 -138
  34. package/ai/agent/runtimeGuidance.ts +0 -97
  35. package/ai/agent/runtimeServerBase.ts +0 -37
  36. package/ai/agent/server/fetchPublicAgents.ts +0 -128
  37. package/ai/agent/startParallelAgentStreams.ts +0 -424
  38. package/ai/agent/startupProtocol.ts +0 -53
  39. package/ai/agent/streamAgentChatTurn.ts +0 -1278
  40. package/ai/agent/streamAgentChatTurnUtils.ts +0 -738
  41. package/ai/agent/types.ts +0 -71
  42. package/ai/agent/utils/imageOutput.ts +0 -33
  43. package/ai/agent/utils/sortUtils.ts +0 -250
  44. package/ai/agent/web/referencePickerUtils.ts +0 -146
  45. package/ai/ai.locale.ts +0 -1075
  46. package/ai/chat/accumulateToolCallChunks.ts +0 -95
  47. package/ai/chat/fetchUtils.native.ts +0 -276
  48. package/ai/chat/fetchUtils.ts +0 -153
  49. package/ai/chat/parseApiError.ts +0 -64
  50. package/ai/chat/parseMultilineSSE.ts +0 -95
  51. package/ai/chat/sendOpenAICompletionsRequest.native.ts +0 -682
  52. package/ai/chat/sendOpenAICompletionsRequest.ts +0 -703
  53. package/ai/chat/sendOpenAIResponseRequest.ts +0 -491
  54. package/ai/chat/shouldUseServerProxy.ts +0 -18
  55. package/ai/chat/sseClient.native.ts +0 -91
  56. package/ai/chat/sseClient.ts +0 -67
  57. package/ai/chat/streamReader.native.ts +0 -31
  58. package/ai/chat/streamReader.ts +0 -62
  59. package/ai/chat/updateTotalUsage.ts +0 -72
  60. package/ai/context/buildReferenceContext.ts +0 -437
  61. package/ai/context/calculateContextUsage.ts +0 -133
  62. package/ai/context/retention.ts +0 -165
  63. package/ai/context/tokenUtils.ts +0 -78
  64. package/ai/index.ts +0 -1
  65. package/ai/llm/calculateGeminiImageTokens.ts +0 -57
  66. package/ai/llm/deepinfra.ts +0 -28
  67. package/ai/llm/fireworks.ts +0 -50
  68. package/ai/llm/generateRequestBody.ts +0 -165
  69. package/ai/llm/getModelContextWindow.ts +0 -84
  70. package/ai/llm/getNoloKey.ts +0 -31
  71. package/ai/llm/getPricing.ts +0 -199
  72. package/ai/llm/hooks/useModelPricing.ts +0 -75
  73. package/ai/llm/imagePricing.ts +0 -40
  74. package/ai/llm/isResponseAPIModel.ts +0 -13
  75. package/ai/llm/mimo.ts +0 -71
  76. package/ai/llm/mistral.ts +0 -22
  77. package/ai/llm/modelAvatar.ts +0 -427
  78. package/ai/llm/models.ts +0 -45
  79. package/ai/llm/openrouterModels.ts +0 -269
  80. package/ai/llm/providers.ts +0 -306
  81. package/ai/llm/reasoningModels.ts +0 -28
  82. package/ai/llm/types.ts +0 -59
  83. package/ai/llm/usageRequestOptions.ts +0 -59
  84. package/ai/memory/capture.ts +0 -148
  85. package/ai/memory/consolidate.ts +0 -104
  86. package/ai/memory/delete.ts +0 -147
  87. package/ai/memory/overlay.ts +0 -84
  88. package/ai/memory/query.ts +0 -38
  89. package/ai/memory/queryShared.ts +0 -160
  90. package/ai/memory/rank.ts +0 -105
  91. package/ai/memory/recentRelationshipRecap.ts +0 -249
  92. package/ai/memory/remember.ts +0 -167
  93. package/ai/memory/runtime.ts +0 -76
  94. package/ai/memory/store.ts +0 -20
  95. package/ai/memory/storeShared.ts +0 -76
  96. package/ai/memory/types.ts +0 -46
  97. package/ai/memory/understanding.ts +0 -349
  98. package/ai/memory/understandingGreeting.ts +0 -264
  99. package/ai/messages/type.ts +0 -20
  100. package/ai/policy/personalizationDialog.ts +0 -333
  101. package/ai/policy/runtimePolicy.ts +0 -440
  102. package/ai/policy/selfUpdateFields.ts +0 -48
  103. package/ai/policy/types.ts +0 -64
  104. package/ai/skills/referenceRuntime.ts +0 -274
  105. package/ai/skills/skillDiagnostics.ts +0 -251
  106. package/ai/skills/skillDocBuilder.ts +0 -139
  107. package/ai/skills/skillDocProtocol.ts +0 -434
  108. package/ai/skills/skillReferenceSummary.ts +0 -63
  109. package/ai/skills/skillSummaryMarker.ts +0 -26
  110. package/ai/token/calculatePrice.ts +0 -544
  111. package/ai/token/db.ts +0 -98
  112. package/ai/token/externalToolCost.ts +0 -330
  113. package/ai/token/hooks/useRecords.ts +0 -65
  114. package/ai/token/missingUsageEstimate.ts +0 -42
  115. package/ai/token/modelUsageQuery.ts +0 -252
  116. package/ai/token/normalizeUsage.ts +0 -84
  117. package/ai/token/openaiImageGenerationUsage.ts +0 -56
  118. package/ai/token/prepareTokenUsageData.ts +0 -88
  119. package/ai/token/query.ts +0 -88
  120. package/ai/token/queryUserTokens.ts +0 -59
  121. package/ai/token/resolveBillingTarget.ts +0 -52
  122. package/ai/token/saveTokenRecord.ts +0 -53
  123. package/ai/token/serverDialogProjection.ts +0 -78
  124. package/ai/token/serverTokenWriter.ts +0 -143
  125. package/ai/token/stats.ts +0 -21
  126. package/ai/token/tokenThunks.ts +0 -24
  127. package/ai/token/types.ts +0 -93
  128. package/ai/tools/agent/agentTools.ts +0 -176
  129. package/ai/tools/agent/agentUpdateShared.ts +0 -311
  130. package/ai/tools/agent/callAgentTool.ts +0 -139
  131. package/ai/tools/agent/createAgentTool.ts +0 -512
  132. package/ai/tools/agent/createDialogTool.ts +0 -69
  133. package/ai/tools/agent/createSkillAgentTool.ts +0 -62
  134. package/ai/tools/agent/parallelBudget.ts +0 -221
  135. package/ai/tools/agent/presets/appBuilderPreset.ts +0 -145
  136. package/ai/tools/agent/runLlmTool.ts +0 -96
  137. package/ai/tools/agent/runStreamingAgentTool.ts +0 -73
  138. package/ai/tools/agent/skillAgentArgs.ts +0 -106
  139. package/ai/tools/agent/skillAgentPreset.ts +0 -89
  140. package/ai/tools/agent/streamParallelAgentsTool.ts +0 -122
  141. package/ai/tools/agent/updateAgentTool.ts +0 -96
  142. package/ai/tools/agent/updateSelfTool.ts +0 -113
  143. package/ai/tools/amazonProductScraperTool.ts +0 -86
  144. package/ai/tools/apifyActorClient.ts +0 -45
  145. package/ai/tools/appEditGuard.ts +0 -372
  146. package/ai/tools/appReadSnapshot.ts +0 -153
  147. package/ai/tools/appTools.ts +0 -1549
  148. package/ai/tools/applyEditTool.ts +0 -256
  149. package/ai/tools/applyLineEditsTool.ts +0 -312
  150. package/ai/tools/browserTools/click.ts +0 -33
  151. package/ai/tools/browserTools/closeSession.ts +0 -29
  152. package/ai/tools/browserTools/common.ts +0 -27
  153. package/ai/tools/browserTools/openSession.ts +0 -48
  154. package/ai/tools/browserTools/readContent.ts +0 -38
  155. package/ai/tools/browserTools/selectOption.ts +0 -46
  156. package/ai/tools/browserTools/typeText.ts +0 -42
  157. package/ai/tools/category/createCategoryTool.ts +0 -66
  158. package/ai/tools/category/queryContentsByCategoryTool.ts +0 -69
  159. package/ai/tools/category/updateContentCategoryTool.ts +0 -75
  160. package/ai/tools/cfBrowserTools.ts +0 -319
  161. package/ai/tools/cfSpeechToTextTool.ts +0 -49
  162. package/ai/tools/checkEnvTool.ts +0 -65
  163. package/ai/tools/cloudflareCrawlTool.ts +0 -289
  164. package/ai/tools/codeSearchTool.ts +0 -111
  165. package/ai/tools/codeTools.ts +0 -101
  166. package/ai/tools/createDocTool.ts +0 -132
  167. package/ai/tools/createPlanTool.ts +0 -999
  168. package/ai/tools/createSkillDocTool.ts +0 -155
  169. package/ai/tools/createWorkflowTool.ts +0 -154
  170. package/ai/tools/deepseekOcrTool.ts +0 -34
  171. package/ai/tools/delayTool.ts +0 -31
  172. package/ai/tools/deleteSpacesTool.ts +0 -325
  173. package/ai/tools/deleteSpacesToolModel.ts +0 -159
  174. package/ai/tools/devReloadUtils.ts +0 -29
  175. package/ai/tools/dialogMessageSearch.ts +0 -137
  176. package/ai/tools/doctorSkillTool.ts +0 -72
  177. package/ai/tools/ecommerceScraperTool.ts +0 -86
  178. package/ai/tools/emailTools.ts +0 -549
  179. package/ai/tools/evalSkillTool.ts +0 -92
  180. package/ai/tools/exaSearchTool.ts +0 -64
  181. package/ai/tools/execBashTool.ts +0 -379
  182. package/ai/tools/executeSqlTool.ts +0 -192
  183. package/ai/tools/fetchWebpageSupport.ts +0 -309
  184. package/ai/tools/fetchWebpageTool.ts +0 -84
  185. package/ai/tools/geminiImagePreviewTool.ts +0 -361
  186. package/ai/tools/generateDocxTool.ts +0 -215
  187. package/ai/tools/googleSearchScraperTool.ts +0 -106
  188. package/ai/tools/importDataTool.ts +0 -133
  189. package/ai/tools/importSkillTool.ts +0 -162
  190. package/ai/tools/index.ts +0 -1858
  191. package/ai/tools/listFilesTool.ts +0 -82
  192. package/ai/tools/listUserSpacesTool.ts +0 -113
  193. package/ai/tools/modelUsageTools.ts +0 -142
  194. package/ai/tools/olmOcrTool.ts +0 -34
  195. package/ai/tools/openaiImageTool.ts +0 -218
  196. package/ai/tools/paddleOcrTool.ts +0 -34
  197. package/ai/tools/prepareTools.ts +0 -23
  198. package/ai/tools/readDocTool.ts +0 -84
  199. package/ai/tools/readFileTool.ts +0 -211
  200. package/ai/tools/readTool.ts +0 -163
  201. package/ai/tools/readXPostTool.ts +0 -233
  202. package/ai/tools/rememberMemoryTool.ts +0 -84
  203. package/ai/tools/remotionVideoTool.ts +0 -151
  204. package/ai/tools/searchDialogMessagesTool.ts +0 -222
  205. package/ai/tools/searchRepoTool.ts +0 -115
  206. package/ai/tools/searchWorkspaceTool.ts +0 -259
  207. package/ai/tools/skillFollowup.ts +0 -86
  208. package/ai/tools/surfWeatherTool.ts +0 -169
  209. package/ai/tools/table/addTableRowTool.ts +0 -217
  210. package/ai/tools/table/createTableTool.ts +0 -315
  211. package/ai/tools/table/rowTools.ts +0 -366
  212. package/ai/tools/table/schemaTools.ts +0 -244
  213. package/ai/tools/table/shareTableTool.ts +0 -148
  214. package/ai/tools/table/toolShared.ts +0 -129
  215. package/ai/tools/toolApiClient.ts +0 -198
  216. package/ai/tools/toolNameAliases.ts +0 -57
  217. package/ai/tools/toolResultError.ts +0 -42
  218. package/ai/tools/toolRunSlice.ts +0 -303
  219. package/ai/tools/toolSchemaCompatibility.ts +0 -53
  220. package/ai/tools/toolVisibility.ts +0 -4
  221. package/ai/tools/types.ts +0 -20
  222. package/ai/tools/uiAskChoiceTool.ts +0 -104
  223. package/ai/tools/updateContentTitleTool.ts +0 -84
  224. package/ai/tools/updateDocTool.ts +0 -105
  225. package/ai/tools/updateUserPreferenceProfileTool.ts +0 -145
  226. package/ai/tools/whisperTool.ts +0 -77
  227. package/ai/tools/writeFileTool.ts +0 -210
  228. package/ai/tools/youtubeScraperTool.ts +0 -116
  229. package/ai/tools/ziweiChartTool.ts +0 -678
  230. package/ai/types.ts +0 -55
  231. package/ai/workflow/workflowExecutor.ts +0 -323
  232. package/ai/workflow/workflowSlice.ts +0 -73
  233. package/ai/workflow/workflowTypes.ts +0 -106
  234. package/client/compactDialog.ts +0 -222
  235. package/connector-experimental/capabilities.ts +0 -73
  236. package/connector-experimental/codexBinary.ts +0 -41
  237. package/connector-experimental/heartbeatLoop.ts +0 -22
  238. package/connector-experimental/index.ts +0 -5
  239. package/connector-experimental/machineInfo.ts +0 -46
  240. package/connector-experimental/protocol.ts +0 -54
@@ -1,59 +0,0 @@
1
- export interface UsageRequestOptions {
2
- stream_options?: {
3
- include_usage: true;
4
- };
5
- usage?: {
6
- include: true;
7
- };
8
- }
9
-
10
- export type UsageRequestApi = "chat-completions" | "responses";
11
-
12
- const STREAM_USAGE_PROVIDERS = new Set([
13
- "google",
14
- "openrouter",
15
- "xai",
16
- "openai",
17
- "fireworks",
18
- "mistral",
19
- ]);
20
-
21
- const EXTRA_USAGE_FIELD_PROVIDERS = new Set(["openrouter"]);
22
-
23
- const normalizeProviderName = (providerName?: string | null) =>
24
- typeof providerName === "string" ? providerName.trim().toLowerCase() : "";
25
-
26
- export const getUsageRequestOptions = (
27
- providerName?: string | null,
28
- options?: { api?: UsageRequestApi }
29
- ): UsageRequestOptions => {
30
- const normalizedProvider = normalizeProviderName(providerName);
31
- const api = options?.api ?? "chat-completions";
32
-
33
- if (api === "responses") {
34
- return EXTRA_USAGE_FIELD_PROVIDERS.has(normalizedProvider)
35
- ? {
36
- usage: {
37
- include: true as const,
38
- },
39
- }
40
- : {};
41
- }
42
-
43
- return {
44
- ...(STREAM_USAGE_PROVIDERS.has(normalizedProvider)
45
- ? {
46
- stream_options: {
47
- include_usage: true as const,
48
- },
49
- }
50
- : {}),
51
- ...(EXTRA_USAGE_FIELD_PROVIDERS.has(normalizedProvider)
52
- ? {
53
- usage: {
54
- include: true as const,
55
- },
56
- }
57
- : {}),
58
- };
59
- };
@@ -1,148 +0,0 @@
1
- import serverDb from "database/server/db";
2
- import { maybeConsolidateExplicitRemember } from "./consolidate";
3
- import { createMemoryItem, writeMemoryItemWithIndexesToDb } from "./store";
4
- import type { MemoryOwnerType, MemorySubjectType, MemoryVisibility } from "./types";
5
-
6
- const EXPLICIT_REMEMBER_PATTERNS = [
7
- "记住",
8
- "你要记住",
9
- "请记住",
10
- "以后记住",
11
- ];
12
-
13
- export const shouldCaptureExplicitMemory = (userInput: string): boolean => {
14
- const text = userInput.trim();
15
- if (!text) return false;
16
- return EXPLICIT_REMEMBER_PATTERNS.some((pattern) => {
17
- const index = text.indexOf(pattern);
18
- if (index < 0) return false;
19
-
20
- const prefix = text.slice(0, index).trim();
21
- const suffix = text.slice(index + pattern.length).trim();
22
- if (!suffix) return false;
23
- if (!prefix) return true;
24
-
25
- return /^(这个|这件事|这一点|这点|请你|你)?$/u.test(prefix);
26
- });
27
- };
28
-
29
- const buildExplicitMemoryTargets = (input: {
30
- userId?: string | null;
31
- spaceId?: string | null;
32
- }): Array<{
33
- ownerType: MemoryOwnerType;
34
- ownerId: string;
35
- visibility: MemoryVisibility;
36
- subjectType: MemorySubjectType;
37
- subjectId: string;
38
- importance: number;
39
- confidence: number;
40
- tags: string[];
41
- }> => {
42
- if (input.userId) {
43
- return [
44
- {
45
- ownerType: "user",
46
- ownerId: input.userId,
47
- visibility: "private",
48
- subjectType: "user",
49
- subjectId: input.userId,
50
- importance: 0.95,
51
- confidence: 0.95,
52
- tags: ["explicit-memory"],
53
- },
54
- ];
55
- }
56
-
57
- if (input.spaceId) {
58
- return [
59
- {
60
- ownerType: "space",
61
- ownerId: input.spaceId,
62
- visibility: "shared",
63
- subjectType: "space",
64
- subjectId: input.spaceId,
65
- importance: 0.85,
66
- confidence: 0.9,
67
- tags: ["explicit-memory", "space-context"],
68
- },
69
- ];
70
- }
71
-
72
- return [];
73
- };
74
-
75
- export const captureExplicitMemoryEpisode = async (input: {
76
- db?: any;
77
- userId?: string | null;
78
- spaceId?: string | null;
79
- agentKey: string;
80
- dialogId: string;
81
- userInput: string;
82
- }): Promise<void> => {
83
- if (!shouldCaptureExplicitMemory(input.userInput)) return;
84
- const db = input.db ?? serverDb;
85
- const targets = buildExplicitMemoryTargets(input);
86
-
87
- for (const target of targets) {
88
- const item = createMemoryItem({
89
- ownerType: target.ownerType,
90
- ownerId: target.ownerId,
91
- visibility: target.visibility,
92
- subjectType: target.subjectType,
93
- subjectId: target.subjectId,
94
- kind: "episodic",
95
- content: input.userInput.trim(),
96
- importance: target.importance,
97
- confidence: target.confidence,
98
- tags: target.tags,
99
- patternKey: "explicit-remember",
100
- sourceDialogId: input.dialogId,
101
- });
102
- await writeMemoryItemWithIndexesToDb(db, item);
103
- }
104
- };
105
-
106
- export const consolidateExplicitMemoryAfterDialog = async (input: {
107
- db?: any;
108
- userId?: string | null;
109
- spaceId?: string | null;
110
- agentKey: string;
111
- dialogId: string;
112
- userInput: string;
113
- }): Promise<void> => {
114
- if (!shouldCaptureExplicitMemory(input.userInput)) return;
115
- const db = input.db ?? serverDb;
116
- const targets = buildExplicitMemoryTargets(input);
117
-
118
- for (const target of targets) {
119
- await maybeConsolidateExplicitRemember({
120
- db,
121
- owner: { ownerType: target.ownerType, ownerId: target.ownerId },
122
- subjectType: target.subjectType,
123
- subjectId: target.subjectId,
124
- visibility: target.visibility,
125
- content: input.userInput.trim(),
126
- });
127
- }
128
- };
129
-
130
- export const scheduleExplicitMemoryConsolidation = (input: {
131
- db?: any;
132
- userId?: string | null;
133
- spaceId?: string | null;
134
- agentKey: string;
135
- dialogId: string;
136
- userInput: string;
137
- }): void => {
138
- queueMicrotask(() => {
139
- void consolidateExplicitMemoryAfterDialog(input).catch((error) => {
140
- console.warn("[memory] explicit post-dialog consolidation failed", {
141
- dialogId: input.dialogId,
142
- userId: input.userId ?? null,
143
- spaceId: input.spaceId ?? null,
144
- error,
145
- });
146
- });
147
- });
148
- };
@@ -1,104 +0,0 @@
1
- import serverDb from "database/server/db";
2
- import { loadMemoryCandidatesFromDb } from "./query";
3
- import { createMemoryItem, writeMemoryItemWithIndexesToDb } from "./store";
4
- import type { MemoryItem, MemoryOwnerRef, MemorySubjectType } from "./types";
5
-
6
- const EXPLICIT_REMEMBER_PREFIXES = [
7
- "你要记住",
8
- "请记住",
9
- "以后记住",
10
- "记住",
11
- ];
12
-
13
- const normalizeExplicitRememberContent = (text: string): string => {
14
- let normalized = text.trim();
15
- for (const prefix of EXPLICIT_REMEMBER_PREFIXES) {
16
- if (normalized.startsWith(prefix)) {
17
- normalized = normalized.slice(prefix.length).trim();
18
- break;
19
- }
20
- }
21
-
22
- normalized = normalized
23
- .replace(/^[,,。.\s::]+/, "")
24
- .replace(/[。!?!?]+$/g, "")
25
- .trim();
26
-
27
- return normalized;
28
- };
29
-
30
- const buildSemanticPatternKey = (normalizedContent: string): string =>
31
- `semantic-explicit:${normalizedContent.toLowerCase()}`;
32
-
33
- const shouldKeepAsSemanticCandidate = (normalizedContent: string): boolean =>
34
- normalizedContent.length >= 6;
35
-
36
- const findMatchingExplicitEpisodes = (
37
- items: MemoryItem[],
38
- normalizedContent: string,
39
- subjectId: string
40
- ): MemoryItem[] =>
41
- items.filter((item) => {
42
- if (item.kind !== "episodic") return false;
43
- if (item.patternKey !== "explicit-remember") return false;
44
- if (item.subjectId !== subjectId) return false;
45
- return normalizeExplicitRememberContent(item.content) === normalizedContent;
46
- });
47
-
48
- export const maybeConsolidateExplicitRemember = async (input: {
49
- db?: any;
50
- owner: MemoryOwnerRef;
51
- subjectType: MemorySubjectType;
52
- subjectId: string;
53
- visibility: "private" | "shared" | "public";
54
- content: string;
55
- }): Promise<void> => {
56
- const normalizedContent = normalizeExplicitRememberContent(input.content);
57
- if (!shouldKeepAsSemanticCandidate(normalizedContent)) return;
58
-
59
- const db = input.db ?? serverDb;
60
- const items = await loadMemoryCandidatesFromDb(db, {
61
- owners: [input.owner],
62
- subjects: [{ subjectType: input.subjectType, subjectId: input.subjectId }],
63
- kinds: ["episodic", "semantic"],
64
- ownerLimit: 50,
65
- });
66
-
67
- const matchingEpisodes = findMatchingExplicitEpisodes(
68
- items,
69
- normalizedContent,
70
- input.subjectId
71
- );
72
- if (matchingEpisodes.length < 2) return;
73
-
74
- const semanticPatternKey = buildSemanticPatternKey(normalizedContent);
75
- const existingSemantic = items.find(
76
- (item) =>
77
- item.kind === "semantic" &&
78
- item.subjectId === input.subjectId &&
79
- item.patternKey === semanticPatternKey
80
- );
81
- if (existingSemantic) return;
82
-
83
- const semantic = createMemoryItem({
84
- ownerType: input.owner.ownerType,
85
- ownerId: input.owner.ownerId,
86
- visibility: input.visibility,
87
- subjectType: input.subjectType,
88
- subjectId: input.subjectId,
89
- kind: "semantic",
90
- content: normalizedContent,
91
- importance: 0.92,
92
- confidence: 0.72,
93
- tags: ["explicit-memory", "consolidated"],
94
- patternKey: semanticPatternKey,
95
- sourceDialogId: matchingEpisodes[matchingEpisodes.length - 1]?.sourceDialogId,
96
- });
97
-
98
- await writeMemoryItemWithIndexesToDb(db, semantic);
99
- };
100
-
101
- export const __test__ = {
102
- normalizeExplicitRememberContent,
103
- buildSemanticPatternKey,
104
- };
@@ -1,147 +0,0 @@
1
- import serverDb from "database/server/db";
2
- import {
3
- createMemoryKey,
4
- createMemoryOwnerIndexKey,
5
- createMemorySubjectKindIndexKey,
6
- memoryOwnerRange,
7
- } from "database/keys";
8
- import type {
9
- MemoryFacet,
10
- MemoryItem,
11
- MemoryKind,
12
- MemoryOwnerRef,
13
- MemorySubjectType,
14
- } from "./types";
15
-
16
- interface DeleteMemoryFilters {
17
- ids?: string[];
18
- kinds?: MemoryKind[];
19
- facets?: MemoryFacet[];
20
- subjectType?: MemorySubjectType;
21
- subjectId?: string;
22
- patternKeyPrefix?: string;
23
- sourceDialogId?: string;
24
- tags?: string[];
25
- limit?: number;
26
- }
27
-
28
- export interface DeleteMemoryResult {
29
- deletedCount: number;
30
- deletedIds: string[];
31
- matchedItems: MemoryItem[];
32
- }
33
-
34
- const normalizeSet = (values?: string[]): Set<string> | null => {
35
- if (!Array.isArray(values) || values.length === 0) return null;
36
- const normalized = values
37
- .map((value) => value.trim())
38
- .filter(Boolean);
39
- return normalized.length > 0 ? new Set(normalized) : null;
40
- };
41
-
42
- const matchesFilters = (item: MemoryItem, filters: DeleteMemoryFilters): boolean => {
43
- const idSet = normalizeSet(filters.ids);
44
- if (idSet && !idSet.has(item.id)) return false;
45
-
46
- const kindSet = normalizeSet(filters.kinds);
47
- if (kindSet && !kindSet.has(item.kind)) return false;
48
-
49
- const facetSet = normalizeSet(filters.facets);
50
- if (facetSet && (!item.facet || !facetSet.has(item.facet))) return false;
51
-
52
- if (filters.subjectType && item.subjectType !== filters.subjectType) return false;
53
- if (filters.subjectId && item.subjectId !== filters.subjectId) return false;
54
-
55
- const prefix = typeof filters.patternKeyPrefix === "string"
56
- ? filters.patternKeyPrefix.trim()
57
- : "";
58
- if (prefix && !(item.patternKey ?? "").startsWith(prefix)) return false;
59
-
60
- if (filters.sourceDialogId && item.sourceDialogId !== filters.sourceDialogId) {
61
- return false;
62
- }
63
-
64
- const tagSet = normalizeSet(filters.tags);
65
- if (tagSet) {
66
- const itemTags = new Set((item.tags ?? []).map((tag) => tag.trim()).filter(Boolean));
67
- for (const tag of tagSet) {
68
- if (!itemTags.has(tag)) return false;
69
- }
70
- }
71
-
72
- return true;
73
- };
74
-
75
- const deleteMemoryItemWithIndexesInBatch = (
76
- batch: any,
77
- item: MemoryItem
78
- ) => {
79
- batch.del(createMemoryKey(item.ownerType, item.ownerId, item.id));
80
- batch.del(
81
- createMemoryOwnerIndexKey(
82
- item.ownerType,
83
- item.ownerId,
84
- item.createdAt,
85
- item.id
86
- )
87
- );
88
- batch.del(
89
- createMemorySubjectKindIndexKey(
90
- item.subjectType,
91
- item.subjectId,
92
- item.kind,
93
- item.createdAt,
94
- item.id
95
- )
96
- );
97
- };
98
-
99
- export const deleteMemoriesForOwnerFromDb = async (
100
- db: any,
101
- owner: MemoryOwnerRef,
102
- filters: DeleteMemoryFilters = {}
103
- ): Promise<DeleteMemoryResult> => {
104
- const range = memoryOwnerRange(owner.ownerType, owner.ownerId);
105
- const matchedItems: MemoryItem[] = [];
106
- const limit = typeof filters.limit === "number" && filters.limit > 0
107
- ? filters.limit
108
- : Number.POSITIVE_INFINITY;
109
-
110
- for await (const [, value] of db.iterator({
111
- gte: range.start,
112
- lte: range.end,
113
- reverse: true,
114
- })) {
115
- const memoryId = typeof value?.memoryId === "string" ? value.memoryId : "";
116
- if (!memoryId) continue;
117
- const item = (await db
118
- .get(createMemoryKey(owner.ownerType, owner.ownerId, memoryId))
119
- .catch(() => null)) as MemoryItem | null;
120
- if (!item) continue;
121
- if (!matchesFilters(item, filters)) continue;
122
- matchedItems.push(item);
123
- if (matchedItems.length >= limit) break;
124
- }
125
-
126
- if (matchedItems.length === 0) {
127
- return { deletedCount: 0, deletedIds: [], matchedItems: [] };
128
- }
129
-
130
- const batch = db.batch();
131
- for (const item of matchedItems) {
132
- deleteMemoryItemWithIndexesInBatch(batch, item);
133
- }
134
- await batch.write();
135
-
136
- return {
137
- deletedCount: matchedItems.length,
138
- deletedIds: matchedItems.map((item) => item.id),
139
- matchedItems,
140
- };
141
- };
142
-
143
- export const deleteMemoriesForOwner = async (
144
- owner: MemoryOwnerRef,
145
- filters: DeleteMemoryFilters = {}
146
- ): Promise<DeleteMemoryResult> =>
147
- deleteMemoriesForOwnerFromDb(serverDb, owner, filters);
@@ -1,84 +0,0 @@
1
- import type { MemoryItem } from "./types";
2
-
3
- const KIND_TITLES: Record<MemoryItem["kind"], string> = {
4
- episodic: "Episodic",
5
- semantic: "Semantic",
6
- procedural: "Procedural",
7
- };
8
-
9
- const normalizeDisplayContent = (item: MemoryItem): string => {
10
- const normalized = item.content
11
- .trim()
12
- .replace(/^(你要记住|请记住|以后记住|记住)[,,。.\s::]*/u, "")
13
- .replace(/[。!?!?]+$/u, "")
14
- .trim();
15
- const stripPrefix = (prefix: string) =>
16
- normalized.startsWith(prefix) ? normalized.slice(prefix.length).trim() : normalized;
17
-
18
- if (item.kind === "semantic") {
19
- if (item.tags?.includes("understanding-memory")) {
20
- switch (item.facet) {
21
- case "unfinished":
22
- return `用户仍未定下:${stripPrefix("还没决定")}`;
23
- case "tension":
24
- return `用户当前在权衡:${stripPrefix("在权衡")}`;
25
- case "preference":
26
- return `用户当前更在意:${stripPrefix("更在意")}`;
27
- case "style":
28
- return `用户互动偏好:${stripPrefix("更喜欢")}`;
29
- case "goal":
30
- return `用户当前目标:${stripPrefix("想推进")}`;
31
- }
32
- }
33
- return `用户长期偏好/事实:${normalized}`;
34
- }
35
-
36
- if (item.kind === "episodic" && item.patternKey === "explicit-remember") {
37
- return `用户明确要求你记住:${normalized}`;
38
- }
39
-
40
- if (item.kind === "episodic" && item.tags?.includes("understanding-memory")) {
41
- switch (item.facet) {
42
- case "unfinished":
43
- return `最近一次对话显示:用户还没定下 ${stripPrefix("还没决定")}`;
44
- case "tension":
45
- return `最近一次对话显示:用户还在权衡 ${stripPrefix("在权衡")}`;
46
- case "preference":
47
- return `最近一次对话显示:用户更在意 ${stripPrefix("更在意")}`;
48
- case "style":
49
- return `最近一次对话显示:用户更偏好 ${stripPrefix("更喜欢")}`;
50
- case "goal":
51
- return `最近一次对话显示:用户想推进 ${stripPrefix("想推进")}`;
52
- }
53
- }
54
-
55
- return normalized;
56
- };
57
-
58
- export const buildMemoryOverlay = (items: MemoryItem[]): string | null => {
59
- if (items.length === 0) return null;
60
-
61
- const byKind: Record<string, MemoryItem[]> = {
62
- episodic: [],
63
- semantic: [],
64
- procedural: [],
65
- };
66
- for (const item of items) {
67
- byKind[item.kind].push(item);
68
- }
69
-
70
- const sections = Object.entries(byKind)
71
- .filter(([, list]) => list.length > 0)
72
- .map(([kind, list]) => {
73
- const lines = list.slice(0, 3).map((item) => `- ${normalizeDisplayContent(item)}`);
74
- return [`[${KIND_TITLES[kind as MemoryItem["kind"]]}]`, ...lines].join("\n");
75
- });
76
-
77
- return [
78
- "--- Memory Overlay ---",
79
- "以下是当前请求可用的记忆事实;相关时直接基于这些记忆回答。",
80
- "用户当前输入优先于记忆;记忆只辅助理解,不要求迎合。",
81
- "",
82
- ...sections,
83
- ].join("\n");
84
- };
@@ -1,38 +0,0 @@
1
- import serverDb from "database/server/db";
2
- import type {
3
- MemoryItem,
4
- MemoryKind,
5
- MemoryOwnerRef,
6
- MemorySubjectRef,
7
- } from "./types";
8
- import {
9
- buildDefaultSubjects,
10
- chooseMemoryOwners,
11
- loadMemoryCandidatesFromDb,
12
- loadOwnerItemsFromDb,
13
- loadSubjectKindItemsFromDb,
14
- } from "./queryShared";
15
-
16
- export {
17
- buildDefaultSubjects,
18
- chooseMemoryOwners,
19
- loadMemoryCandidatesFromDb,
20
- loadOwnerItemsFromDb,
21
- loadSubjectKindItemsFromDb,
22
- };
23
-
24
- export const loadOwnerItems = async (
25
- owner: MemoryOwnerRef,
26
- limit: number
27
- ): Promise<MemoryItem[]> => {
28
- return loadOwnerItemsFromDb(serverDb, owner, limit);
29
- };
30
-
31
- export const loadMemoryCandidates = async (input: {
32
- owners: MemoryOwnerRef[];
33
- subjects: MemorySubjectRef[];
34
- kinds?: MemoryKind[];
35
- ownerLimit?: number;
36
- }): Promise<MemoryItem[]> => {
37
- return loadMemoryCandidatesFromDb(serverDb, input);
38
- };