@h-ai/ai 1.0.0-beta.26 → 1.0.0-beta.28
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.
- package/README.en.md +2 -0
- package/README.ja.md +2 -0
- package/README.md +2 -0
- package/dist/{ai-acp-types-BYUy6Tyx.d.ts → ai-acp-types-BTVshtKX.d.ts} +28 -2
- package/dist/browser.d.ts +1 -1
- package/dist/browser.js +1 -1
- package/dist/{chunk-VEWBD2J4.js → chunk-EENBKRIH.js} +13 -2
- package/dist/chunk-EENBKRIH.js.map +1 -0
- package/dist/index.d.ts +2 -2
- package/dist/index.js +492 -122
- package/dist/index.js.map +1 -1
- package/package.json +7 -7
- package/dist/chunk-VEWBD2J4.js.map +0 -1
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { platformOptionsSchema, aiM, AIConfigSchema, MemoryConfigSchema, ModelEntrySchema, AudioModelEntrySchema, ImageModelEntrySchema, MCPExternalServerSchema, RetrievalSourceSchema, KnowledgeConfigSchema, TokenConfigSchema, SummaryConfigSchema, CompressConfigSchema, ACPConfigSchema, ACPAgentSchema, ACPWorkspaceSchema, AudioConfigSchema, resolveModelEntry, resolveAudioModel, ensureAudioCredential, platformScopeSchema, resolveModelApi, platformRequestSchema, platformRunSchema, sessionIdentitySchema, branchNameSchema, ImageConfigSchema, resolveImageModel, ACPPublishSchema } from './chunk-
|
|
2
|
-
export { A2AConfigSchema, A2ASkillConfigSchema, ACPAgentSchema, ACPConfigSchema, ACPPublishSchema, ACPRepositorySchema, ACPWorkspaceSchema, AIConfigSchema, AUDIO_WS_PATH, ApiTypeSchema, AudioConfigSchema, AudioFormatSchema, AudioModelEntrySchema, AudioOperationSchema, AudioOperationsSchema, AudioProviderSchema, AudioWsClientMessageSchema, AudioWsDoneMessageSchema, AudioWsStartMessageSchema, AudioWsTextMessageSchema, CompressConfigSchema, CompressionStrategySchema, EmbeddingConfigSchema, EntityTypeSchema, FileConfigSchema, ImageConfigSchema, ImageModelEntrySchema, ImageProviderSchema, KnowledgeConfigSchema, LLMConfigSchema, MCPConfigSchema, MCPExternalServerSchema, MCPServerCapabilitiesSchema, MCPServerConfigSchema, MemoryConfigSchema, MemoryTypeSchema, ModelCapabilitiesSchema, ModelEntrySchema, ModelScenarioSchema, OptionalSecretSchema, RetrievalConfigSchema, RetrievalSourceSchema, SummaryConfigSchema, TokenConfigSchema, ensureAudioCredential, resolveAudioModel, resolveImageModel, resolveModelApi, resolveModelEntry, serializePlayableAudio } from './chunk-
|
|
1
|
+
import { platformOptionsSchema, aiM, AIConfigSchema, MemoryConfigSchema, ModelEntrySchema, AudioModelEntrySchema, ImageModelEntrySchema, MCPExternalServerSchema, RetrievalSourceSchema, KnowledgeConfigSchema, TokenConfigSchema, SummaryConfigSchema, CompressConfigSchema, ACPConfigSchema, ACPAgentSchema, ACPWorkspaceSchema, AudioConfigSchema, resolveModelEntry, resolveAudioModel, ensureAudioCredential, platformScopeSchema, resolveModelApi, platformRequestSchema, platformRunSchema, sessionIdentitySchema, branchNameSchema, ImageConfigSchema, resolveImageModel, ACPPublishSchema } from './chunk-EENBKRIH.js';
|
|
2
|
+
export { A2AConfigSchema, A2ASkillConfigSchema, ACPAgentSchema, ACPConfigSchema, ACPPublishSchema, ACPRepositorySchema, ACPWorkspaceSchema, AIConfigSchema, AUDIO_WS_PATH, ApiTypeSchema, AudioConfigSchema, AudioFormatSchema, AudioModelEntrySchema, AudioOperationSchema, AudioOperationsSchema, AudioProviderSchema, AudioWsClientMessageSchema, AudioWsDoneMessageSchema, AudioWsStartMessageSchema, AudioWsTextMessageSchema, CompressConfigSchema, CompressionStrategySchema, EmbeddingConfigSchema, EntityTypeSchema, FileConfigSchema, ImageConfigSchema, ImageModelEntrySchema, ImageProviderSchema, KnowledgeConfigSchema, LLMConfigSchema, MCPConfigSchema, MCPExternalServerSchema, MCPServerCapabilitiesSchema, MCPServerConfigSchema, MemoryConfigSchema, MemoryTypeSchema, ModelCapabilitiesSchema, ModelEntrySchema, ModelScenarioSchema, OptionalSecretSchema, RetrievalConfigSchema, RetrievalSourceSchema, SummaryConfigSchema, TokenConfigSchema, ensureAudioCredential, resolveAudioModel, resolveImageModel, resolveModelApi, resolveModelEntry, serializePlayableAudio } from './chunk-EENBKRIH.js';
|
|
3
3
|
import { HaiAIError } from './chunk-NRDLMUSY.js';
|
|
4
4
|
export { HaiAIError } from './chunk-NRDLMUSY.js';
|
|
5
5
|
import { TaskState, SendMessageRequest, Message, Role, AgentCard, TaskStatus, Task } from '@a2a-js/sdk';
|
|
@@ -11,7 +11,7 @@ import { core, err, ok } from '@h-ai/core';
|
|
|
11
11
|
import { datapipe } from '@h-ai/datapipe';
|
|
12
12
|
import { JsonRpcTransportFactory, ClientFactory } from '@a2a-js/sdk/client';
|
|
13
13
|
import { Buffer } from 'buffer';
|
|
14
|
-
import {
|
|
14
|
+
import { randomUUID, createHash, randomBytes } from 'crypto';
|
|
15
15
|
import { setTimeout as setTimeout$1 } from 'timers/promises';
|
|
16
16
|
import { ExtendedAgentCardNotConfiguredError, PushNotificationNotSupportedError, UnsupportedOperationError, A2AError, TaskNotFoundError, RequestMalformedError, TaskNotCancelableError } from '@a2a-js/sdk/errors';
|
|
17
17
|
import { z, ZodError } from 'zod';
|
|
@@ -12915,27 +12915,27 @@ function createMCPServiceOperations(read, runner, files, configuredServices = []
|
|
|
12915
12915
|
}
|
|
12916
12916
|
};
|
|
12917
12917
|
}
|
|
12918
|
-
function createScopedMemory(
|
|
12918
|
+
function createScopedMemory(core36, binding) {
|
|
12919
12919
|
if (typeof binding.objectId !== "string" || !binding.objectId.trim())
|
|
12920
12920
|
throw new TypeError(aiM("ai_memoryScopeInvalid"));
|
|
12921
12921
|
const { objectId, scope } = binding;
|
|
12922
12922
|
const accessScope = { objectId, scope };
|
|
12923
12923
|
return {
|
|
12924
|
-
extract: (messages, options) =>
|
|
12925
|
-
recall: (query, options) =>
|
|
12926
|
-
injectMemories: (messages, options) =>
|
|
12927
|
-
add: (entry) =>
|
|
12928
|
-
update: (memoryId, updates) =>
|
|
12929
|
-
get: (memoryId) =>
|
|
12930
|
-
remove: (memoryId) =>
|
|
12931
|
-
list: (options) =>
|
|
12932
|
-
listPage: (options) =>
|
|
12933
|
-
clear: (options) =>
|
|
12924
|
+
extract: (messages, options) => core36.extract(messages, { ...options, objectId, scope }),
|
|
12925
|
+
recall: (query, options) => core36.recall(query, { ...options, objectId, scope }),
|
|
12926
|
+
injectMemories: (messages, options) => core36.injectMemories(messages, { ...options, objectId, scope }),
|
|
12927
|
+
add: (entry) => core36.add({ ...entry, objectId, scope }),
|
|
12928
|
+
update: (memoryId, updates) => core36.update(memoryId, updates, accessScope),
|
|
12929
|
+
get: (memoryId) => core36.get(memoryId, accessScope),
|
|
12930
|
+
remove: (memoryId) => core36.remove(memoryId, accessScope),
|
|
12931
|
+
list: (options) => core36.list({ ...options, objectId, scope }),
|
|
12932
|
+
listPage: (options) => core36.listPage({ ...options, objectId, scope }),
|
|
12933
|
+
clear: (options) => core36.clear({ ...options, objectId, scope })
|
|
12934
12934
|
};
|
|
12935
12935
|
}
|
|
12936
|
-
function createMemoryOperations(
|
|
12936
|
+
function createMemoryOperations(core36) {
|
|
12937
12937
|
return {
|
|
12938
|
-
...
|
|
12938
|
+
...core36,
|
|
12939
12939
|
/**
|
|
12940
12940
|
* 清空记忆(空过滤保护)。
|
|
12941
12941
|
*
|
|
@@ -12949,20 +12949,142 @@ function createMemoryOperations(core34) {
|
|
|
12949
12949
|
if (!hasFilter) {
|
|
12950
12950
|
return err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryClearRequiresFilter"));
|
|
12951
12951
|
}
|
|
12952
|
-
return
|
|
12952
|
+
return core36.clear(options);
|
|
12953
12953
|
},
|
|
12954
|
-
scoped: (binding) => createScopedMemory(
|
|
12954
|
+
scoped: (binding) => createScopedMemory(core36, binding),
|
|
12955
12955
|
admin: {
|
|
12956
12956
|
async clearAll(options) {
|
|
12957
12957
|
if (options?.confirm !== true) {
|
|
12958
12958
|
return err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryClearAllUnconfirmed"));
|
|
12959
12959
|
}
|
|
12960
|
-
return
|
|
12960
|
+
return core36.clear();
|
|
12961
12961
|
}
|
|
12962
12962
|
}
|
|
12963
12963
|
};
|
|
12964
12964
|
}
|
|
12965
|
-
var logger20 = core.logger.child({ module: "ai", scope: "memory-
|
|
12965
|
+
var logger20 = core.logger.child({ module: "ai", scope: "memory-vector-namespace" });
|
|
12966
|
+
var bindingId = "namespace";
|
|
12967
|
+
var leaseMs = 9e4;
|
|
12968
|
+
var tickMs = 1e3;
|
|
12969
|
+
var pagesPerTick = 8;
|
|
12970
|
+
var pageSize = 64;
|
|
12971
|
+
async function bindMemoryVectorNamespace(state, namespace) {
|
|
12972
|
+
const readBinding = async (store) => {
|
|
12973
|
+
let current = (await store.readVersioned(bindingId))?.data;
|
|
12974
|
+
if (!current) {
|
|
12975
|
+
const proposed = {
|
|
12976
|
+
namespace,
|
|
12977
|
+
owner: randomUUID().replaceAll("-", ""),
|
|
12978
|
+
updatedAt: 0
|
|
12979
|
+
};
|
|
12980
|
+
const created = await store.compareAndSwap(bindingId, { expectedVersion: void 0, data: proposed });
|
|
12981
|
+
current = created ? proposed : (await store.readVersioned(bindingId))?.data;
|
|
12982
|
+
}
|
|
12983
|
+
if (!current || current.namespace !== namespace || !/^[a-f0-9]{32}$/.test(current.owner))
|
|
12984
|
+
throw new Error(aiM("ai_memoryVectorNamespaceMismatch"));
|
|
12985
|
+
return `hai_m_${namespace}_${current.owner}`;
|
|
12986
|
+
};
|
|
12987
|
+
return state.withWriteLock ? state.withWriteLock(readBinding) : readBinding(state);
|
|
12988
|
+
}
|
|
12989
|
+
function createMemoryVectorRebuild(memory, state, vectors) {
|
|
12990
|
+
const readPage = memory.readMemoryVectorPage?.bind(memory);
|
|
12991
|
+
if (!readPage)
|
|
12992
|
+
return void 0;
|
|
12993
|
+
const lockedWrite = state.withWriteLock?.bind(state);
|
|
12994
|
+
const write = lockedWrite ?? ((operation) => operation(state));
|
|
12995
|
+
let timer;
|
|
12996
|
+
let active;
|
|
12997
|
+
let done = false;
|
|
12998
|
+
let nextCheck = 0;
|
|
12999
|
+
const rebuildPage = async () => {
|
|
13000
|
+
const snapshot2 = await state.readVersioned(bindingId);
|
|
13001
|
+
if (!snapshot2)
|
|
13002
|
+
throw new Error("Missing native memory vector binding");
|
|
13003
|
+
if (snapshot2.data.migrated) {
|
|
13004
|
+
done = true;
|
|
13005
|
+
clearInterval(timer);
|
|
13006
|
+
timer = void 0;
|
|
13007
|
+
return false;
|
|
13008
|
+
}
|
|
13009
|
+
const now = await state.currentTime();
|
|
13010
|
+
if (snapshot2.data.updatedAt > now) {
|
|
13011
|
+
nextCheck = performance.now() + Math.min(5e3, snapshot2.data.updatedAt - now);
|
|
13012
|
+
return false;
|
|
13013
|
+
}
|
|
13014
|
+
const deadline = now + leaseMs;
|
|
13015
|
+
const lease = await write((checkpoint) => checkpoint.compareAndSwap(bindingId, {
|
|
13016
|
+
expectedVersion: snapshot2.version,
|
|
13017
|
+
data: { ...snapshot2.data, updatedAt: deadline }
|
|
13018
|
+
}));
|
|
13019
|
+
if (!lease)
|
|
13020
|
+
return false;
|
|
13021
|
+
let progress = snapshot2.data;
|
|
13022
|
+
try {
|
|
13023
|
+
const rows = await readPage(progress.cursor ?? "", pageSize);
|
|
13024
|
+
const batch = rows.flatMap((entry) => entry.vector ? [
|
|
13025
|
+
{
|
|
13026
|
+
id: entry.vectorId ?? entry.id,
|
|
13027
|
+
vector: entry.vector,
|
|
13028
|
+
metadata: { objectId: entry.objectId, type: entry.type }
|
|
13029
|
+
}
|
|
13030
|
+
] : []);
|
|
13031
|
+
if (batch.length) {
|
|
13032
|
+
if (vectors.upsertMany) {
|
|
13033
|
+
await vectors.upsertMany(batch);
|
|
13034
|
+
} else {
|
|
13035
|
+
for (const { id: id3, vector, metadata } of batch)
|
|
13036
|
+
await vectors.upsert(id3, vector, metadata);
|
|
13037
|
+
}
|
|
13038
|
+
}
|
|
13039
|
+
progress = rows.length < pageSize ? {
|
|
13040
|
+
...progress,
|
|
13041
|
+
cursor: void 0,
|
|
13042
|
+
migrated: true,
|
|
13043
|
+
updatedAt: 0
|
|
13044
|
+
} : { ...progress, cursor: rows.at(-1).id, updatedAt: 0 };
|
|
13045
|
+
} catch {
|
|
13046
|
+
nextCheck = performance.now() + 2e3;
|
|
13047
|
+
logger20.warn("Memory vector rebuild page will retry");
|
|
13048
|
+
progress = { ...progress, updatedAt: await state.currentTime() + 2e3 };
|
|
13049
|
+
}
|
|
13050
|
+
const version = await write((checkpoint) => checkpoint.compareAndSwap(bindingId, {
|
|
13051
|
+
expectedVersion: lease,
|
|
13052
|
+
data: progress,
|
|
13053
|
+
notAfter: deadline
|
|
13054
|
+
}));
|
|
13055
|
+
return Boolean(version && !progress.updatedAt);
|
|
13056
|
+
};
|
|
13057
|
+
function kick() {
|
|
13058
|
+
if (done || active || performance.now() < nextCheck)
|
|
13059
|
+
return;
|
|
13060
|
+
active = (async () => {
|
|
13061
|
+
for (let page = 0; page < pagesPerTick; page++) {
|
|
13062
|
+
if (!timer || !await rebuildPage())
|
|
13063
|
+
break;
|
|
13064
|
+
}
|
|
13065
|
+
})().catch(() => {
|
|
13066
|
+
nextCheck = performance.now() + 2e3;
|
|
13067
|
+
logger20.warn("Memory vector namespace checkpoint unavailable");
|
|
13068
|
+
}).finally(() => {
|
|
13069
|
+
active = void 0;
|
|
13070
|
+
});
|
|
13071
|
+
}
|
|
13072
|
+
return {
|
|
13073
|
+
start() {
|
|
13074
|
+
if (done || timer)
|
|
13075
|
+
return;
|
|
13076
|
+
timer = setInterval(kick, tickMs);
|
|
13077
|
+
timer.unref();
|
|
13078
|
+
kick();
|
|
13079
|
+
},
|
|
13080
|
+
async close() {
|
|
13081
|
+
clearInterval(timer);
|
|
13082
|
+
timer = void 0;
|
|
13083
|
+
await active;
|
|
13084
|
+
}
|
|
13085
|
+
};
|
|
13086
|
+
}
|
|
13087
|
+
var logger21 = core.logger.child({ module: "ai", scope: "memory-extractor" });
|
|
12966
13088
|
var LEADING_MARKDOWN_FENCE_REGEX2 = /^```(?:json)?\n?/;
|
|
12967
13089
|
var TRAILING_MARKDOWN_FENCE_REGEX2 = /\n?```$/;
|
|
12968
13090
|
var MEMORY_EXTRACTION_SYSTEM_PROMPT = `You are a memory extraction assistant. Analyze the conversation and extract important information worth remembering for future interactions.
|
|
@@ -13015,7 +13137,7 @@ Only extract memories of these types: ${options.types.join(", ")}`;
|
|
|
13015
13137
|
signal: options?.signal
|
|
13016
13138
|
});
|
|
13017
13139
|
if (!chatResult.success) {
|
|
13018
|
-
|
|
13140
|
+
logger21.warn("Memory extraction LLM call failed", { error: chatResult.error });
|
|
13019
13141
|
return err(HaiAIError.MEMORY_EXTRACT_FAILED, aiM("ai_memoryExtractFailed", {
|
|
13020
13142
|
params: {
|
|
13021
13143
|
error: String(chatResult.error.message)
|
|
@@ -13034,10 +13156,10 @@ Only extract memories of these types: ${options.types.join(", ")}`;
|
|
|
13034
13156
|
if (options?.objectId) {
|
|
13035
13157
|
entries = entries.map((e) => ({ ...e, objectId: options.objectId }));
|
|
13036
13158
|
}
|
|
13037
|
-
|
|
13159
|
+
logger21.trace("Memory extraction completed", { messageCount: messages.length, extractedCount: entries.length });
|
|
13038
13160
|
return ok(entries);
|
|
13039
13161
|
} catch (error) {
|
|
13040
|
-
|
|
13162
|
+
logger21.error("Memory extraction failed", { error });
|
|
13041
13163
|
return err(HaiAIError.MEMORY_EXTRACT_FAILED, aiM("ai_memoryExtractFailed", {
|
|
13042
13164
|
params: {
|
|
13043
13165
|
error: String(error)
|
|
@@ -13068,12 +13190,12 @@ function parseMemoryResponse(content) {
|
|
|
13068
13190
|
return memories.filter(isValidMemoryItem).map(normalizeMemoryItem);
|
|
13069
13191
|
}
|
|
13070
13192
|
}
|
|
13071
|
-
|
|
13193
|
+
logger21.warn("Memory extraction returned unexpected format", {
|
|
13072
13194
|
content: content.slice(0, 200)
|
|
13073
13195
|
});
|
|
13074
13196
|
return [];
|
|
13075
13197
|
} catch {
|
|
13076
|
-
|
|
13198
|
+
logger21.warn("Memory extraction returned invalid JSON", {
|
|
13077
13199
|
content: content.slice(0, 200)
|
|
13078
13200
|
});
|
|
13079
13201
|
return [];
|
|
@@ -13094,7 +13216,7 @@ function normalizeMemoryItem(item2) {
|
|
|
13094
13216
|
importance
|
|
13095
13217
|
};
|
|
13096
13218
|
}
|
|
13097
|
-
var
|
|
13219
|
+
var logger22 = core.logger.child({ module: "ai", scope: "memory" });
|
|
13098
13220
|
function isMemoryAccessDenied(entry, accessScope) {
|
|
13099
13221
|
if (!accessScope)
|
|
13100
13222
|
return false;
|
|
@@ -13182,10 +13304,10 @@ ${memoryText}
|
|
|
13182
13304
|
});
|
|
13183
13305
|
}
|
|
13184
13306
|
}
|
|
13185
|
-
|
|
13307
|
+
logger22.trace("Memories enriched", { count: recallResult.data.length, position });
|
|
13186
13308
|
return ok(result);
|
|
13187
13309
|
} catch (error) {
|
|
13188
|
-
|
|
13310
|
+
logger22.error("Memory enrichment failed", { error });
|
|
13189
13311
|
return err(HaiAIError.MEMORY_ENRICH_FAILED, aiM("ai_memoryEnrichFailed", {
|
|
13190
13312
|
params: {
|
|
13191
13313
|
error: String(error)
|
|
@@ -13502,7 +13624,7 @@ async function createMem0Store(options) {
|
|
|
13502
13624
|
}
|
|
13503
13625
|
|
|
13504
13626
|
// src/memory/providers/ai-memory-provider-mem0.ts
|
|
13505
|
-
var
|
|
13627
|
+
var logger23 = core.logger.child({ module: "ai", scope: "memory-mem0" });
|
|
13506
13628
|
var DEFAULT_IMPORTANCE = 0.5;
|
|
13507
13629
|
var DEFAULT_OBJECT_ID = "hai-global";
|
|
13508
13630
|
var MEM0_LIST_CANDIDATE_LIMIT = 1e3;
|
|
@@ -13618,7 +13740,7 @@ function buildVectorStoreConfig(deps) {
|
|
|
13618
13740
|
);
|
|
13619
13741
|
}
|
|
13620
13742
|
if (backend)
|
|
13621
|
-
|
|
13743
|
+
logger23.warn("Mem0 format falls back to in-memory vector store (allowEphemeralFallback=true); data will not survive restart", { backend: backend.type });
|
|
13622
13744
|
return ok({
|
|
13623
13745
|
provider: "memory",
|
|
13624
13746
|
persistent: false
|
|
@@ -13659,7 +13781,7 @@ async function extractMemories2(context, messages, options) {
|
|
|
13659
13781
|
throw failed.reason;
|
|
13660
13782
|
return ok(stored.flatMap((result) => result.status === "fulfilled" ? [result.value] : []));
|
|
13661
13783
|
} catch (error) {
|
|
13662
|
-
|
|
13784
|
+
logger23.error("Mem0 format extract failed", {
|
|
13663
13785
|
error: core.sanitize.sanitizeSensitiveFields(error)
|
|
13664
13786
|
});
|
|
13665
13787
|
return memoryWriteFailure(HaiAIError.MEMORY_EXTRACT_FAILED, aiM("ai_memoryOperationFailed"), memoryIds);
|
|
@@ -13686,7 +13808,7 @@ async function recallMemories(context, query, options) {
|
|
|
13686
13808
|
}
|
|
13687
13809
|
return ok(entries.slice(0, topK));
|
|
13688
13810
|
} catch (error) {
|
|
13689
|
-
|
|
13811
|
+
logger23.error("Mem0 format recall failed", {
|
|
13690
13812
|
error: core.sanitize.sanitizeSensitiveFields(error)
|
|
13691
13813
|
});
|
|
13692
13814
|
return err(HaiAIError.MEMORY_RECALL_FAILED, aiM("ai_memoryOperationFailed"));
|
|
@@ -13703,7 +13825,7 @@ async function addMemory(context, entry) {
|
|
|
13703
13825
|
throw new Error("Mem0 format stored memory could not be read back");
|
|
13704
13826
|
return ok(toMemoryEntry(persisted, objectId));
|
|
13705
13827
|
} catch (error) {
|
|
13706
|
-
|
|
13828
|
+
logger23.error("Mem0 format add failed", {
|
|
13707
13829
|
error: core.sanitize.sanitizeSensitiveFields(error)
|
|
13708
13830
|
});
|
|
13709
13831
|
return memoryWriteFailure(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryOperationFailed"), memoryIds);
|
|
@@ -13741,7 +13863,7 @@ async function updateMemory(context, memoryId, updates, accessScope) {
|
|
|
13741
13863
|
}
|
|
13742
13864
|
return ok(toMemoryEntry(refreshed, objectId));
|
|
13743
13865
|
} catch (error) {
|
|
13744
|
-
|
|
13866
|
+
logger23.error("Mem0 format update failed", {
|
|
13745
13867
|
id: memoryId,
|
|
13746
13868
|
error: core.sanitize.sanitizeSensitiveFields(error)
|
|
13747
13869
|
});
|
|
@@ -13764,7 +13886,7 @@ async function getMemory(context, memoryId, accessScope) {
|
|
|
13764
13886
|
}
|
|
13765
13887
|
return ok(entry);
|
|
13766
13888
|
} catch (error) {
|
|
13767
|
-
|
|
13889
|
+
logger23.error("Mem0 format read failed", {
|
|
13768
13890
|
error: core.sanitize.sanitizeSensitiveFields(error)
|
|
13769
13891
|
});
|
|
13770
13892
|
return err(HaiAIError.MEMORY_RECALL_FAILED, aiM("ai_memoryOperationFailed"));
|
|
@@ -13783,7 +13905,7 @@ async function removeMemory(context, memoryId, accessScope) {
|
|
|
13783
13905
|
await context.memory.remove(memoryId);
|
|
13784
13906
|
return ok(void 0);
|
|
13785
13907
|
} catch (error) {
|
|
13786
|
-
|
|
13908
|
+
logger23.error("Mem0 format delete failed", {
|
|
13787
13909
|
error: core.sanitize.sanitizeSensitiveFields(error)
|
|
13788
13910
|
});
|
|
13789
13911
|
return err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryOperationFailed"));
|
|
@@ -13832,7 +13954,7 @@ async function createMem0MemoryOperations(deps) {
|
|
|
13832
13954
|
backend: configResult.data.backend
|
|
13833
13955
|
});
|
|
13834
13956
|
} catch (error) {
|
|
13835
|
-
|
|
13957
|
+
logger23.error("Mem0 data storage initialization failed", {
|
|
13836
13958
|
error: core.sanitize.sanitizeSensitiveFields(error)
|
|
13837
13959
|
});
|
|
13838
13960
|
const failure = err(HaiAIError.CONFIGURATION_ERROR, aiM("ai_memoryOperationFailed"));
|
|
@@ -13840,7 +13962,7 @@ async function createMem0MemoryOperations(deps) {
|
|
|
13840
13962
|
throw failure.error;
|
|
13841
13963
|
throw new Error("Unreachable memory initialization state");
|
|
13842
13964
|
}
|
|
13843
|
-
|
|
13965
|
+
logger23.info("Mem0 format memory initialized", {
|
|
13844
13966
|
vectorProvider: configResult.data.provider,
|
|
13845
13967
|
persistent: configResult.data.persistent
|
|
13846
13968
|
});
|
|
@@ -13873,7 +13995,7 @@ async function createMem0MemoryOperations(deps) {
|
|
|
13873
13995
|
try {
|
|
13874
13996
|
return ok(await listMemories(context, options));
|
|
13875
13997
|
} catch (error) {
|
|
13876
|
-
|
|
13998
|
+
logger23.error("Mem0 data list failed", {
|
|
13877
13999
|
operation: "list",
|
|
13878
14000
|
...core.context.get(),
|
|
13879
14001
|
error: core.sanitize.sanitizeSensitiveFields(error)
|
|
@@ -13893,7 +14015,7 @@ async function createMem0MemoryOperations(deps) {
|
|
|
13893
14015
|
total: all.length
|
|
13894
14016
|
});
|
|
13895
14017
|
} catch (error) {
|
|
13896
|
-
|
|
14018
|
+
logger23.error("Mem0 data page failed", {
|
|
13897
14019
|
operation: "page",
|
|
13898
14020
|
...core.context.get(),
|
|
13899
14021
|
error: core.sanitize.sanitizeSensitiveFields(error)
|
|
@@ -13924,7 +14046,7 @@ async function createMem0MemoryOperations(deps) {
|
|
|
13924
14046
|
const matched = await listMemories(context, { objectId: options?.objectId, types: options?.types, scope: options?.scope });
|
|
13925
14047
|
for (const entry of matched)
|
|
13926
14048
|
await context.memory.remove(entry.id);
|
|
13927
|
-
|
|
14049
|
+
logger23.debug("Mem0 format memories cleared", {
|
|
13928
14050
|
removed: matched.length,
|
|
13929
14051
|
objectId: options?.objectId,
|
|
13930
14052
|
types: options?.types,
|
|
@@ -13932,7 +14054,7 @@ async function createMem0MemoryOperations(deps) {
|
|
|
13932
14054
|
});
|
|
13933
14055
|
return ok(void 0);
|
|
13934
14056
|
} catch (error) {
|
|
13935
|
-
|
|
14057
|
+
logger23.error("Mem0 data clear failed", {
|
|
13936
14058
|
operation: "clear",
|
|
13937
14059
|
...core.context.get(),
|
|
13938
14060
|
error: core.sanitize.sanitizeSensitiveFields(error)
|
|
@@ -13944,7 +14066,7 @@ async function createMem0MemoryOperations(deps) {
|
|
|
13944
14066
|
}
|
|
13945
14067
|
};
|
|
13946
14068
|
}
|
|
13947
|
-
var
|
|
14069
|
+
var logger24 = core.logger.child({ module: "ai", scope: "memory-consolidation" });
|
|
13948
14070
|
var DEFAULT_IMPORTANCE2 = 0.5;
|
|
13949
14071
|
var MEMORY_TYPES2 = /* @__PURE__ */ new Set([
|
|
13950
14072
|
"fact",
|
|
@@ -14075,7 +14197,7 @@ async function applyConsolidationOps(deps, ops, options) {
|
|
|
14075
14197
|
if (op.event === "DELETE" && op.id) {
|
|
14076
14198
|
const removeResult = await deps.remove(op.id);
|
|
14077
14199
|
if (!removeResult.success)
|
|
14078
|
-
|
|
14200
|
+
logger24.warn("Consolidation delete skipped", { id: op.id, error: removeResult.error.message });
|
|
14079
14201
|
continue;
|
|
14080
14202
|
}
|
|
14081
14203
|
if (op.event === "UPDATE" && op.id) {
|
|
@@ -14105,7 +14227,7 @@ async function applyConsolidationOps(deps, ops, options) {
|
|
|
14105
14227
|
return ok(entries);
|
|
14106
14228
|
}
|
|
14107
14229
|
async function extractAndConsolidate(deps, messages, options) {
|
|
14108
|
-
|
|
14230
|
+
logger24.trace("Consolidation extract", { messageCount: messages.length });
|
|
14109
14231
|
const extractResult = await extractMemories(deps.llm, messages, {
|
|
14110
14232
|
types: options?.types,
|
|
14111
14233
|
model: options?.model,
|
|
@@ -14163,7 +14285,7 @@ async function extractAndConsolidate(deps, messages, options) {
|
|
|
14163
14285
|
try {
|
|
14164
14286
|
ops = parseConsolidationOps(rawContent, candidates, relatedIds);
|
|
14165
14287
|
} catch {
|
|
14166
|
-
|
|
14288
|
+
logger24.warn("Consolidation returned invalid JSON, falling back to ADD-all", {
|
|
14167
14289
|
content: rawContent.slice(0, 200)
|
|
14168
14290
|
});
|
|
14169
14291
|
ops = candidates.map((candidate) => ({
|
|
@@ -14176,7 +14298,7 @@ async function extractAndConsolidate(deps, messages, options) {
|
|
|
14176
14298
|
const applyResult = await applyConsolidationOps(deps, ops, options);
|
|
14177
14299
|
if (!applyResult.success)
|
|
14178
14300
|
return applyResult;
|
|
14179
|
-
|
|
14301
|
+
logger24.trace("Consolidation completed", {
|
|
14180
14302
|
candidates: candidates.length,
|
|
14181
14303
|
related: related.length,
|
|
14182
14304
|
ops: ops.length,
|
|
@@ -14184,8 +14306,143 @@ async function extractAndConsolidate(deps, messages, options) {
|
|
|
14184
14306
|
});
|
|
14185
14307
|
return ok(applyResult.data);
|
|
14186
14308
|
}
|
|
14187
|
-
var
|
|
14309
|
+
var logger25 = core.logger.child({ module: "ai", scope: "memory-vector-scan" });
|
|
14310
|
+
var checkpointId = "scan";
|
|
14311
|
+
var pageSize2 = 64;
|
|
14188
14312
|
var pollMs = 1e3;
|
|
14313
|
+
var wakeMs = 250;
|
|
14314
|
+
var pagesPerBatch = 32;
|
|
14315
|
+
var batchWorkMs = 750;
|
|
14316
|
+
var roundPauseMs = 5e3;
|
|
14317
|
+
var failureRetryMs = 2e3;
|
|
14318
|
+
var leaseMs2 = 9e4;
|
|
14319
|
+
function createMemoryVectorScan(memory, state, vectors, collection) {
|
|
14320
|
+
const currentIds = memory.getMemoryVectorIds?.bind(memory);
|
|
14321
|
+
const scan = vectors.scan?.bind(vectors);
|
|
14322
|
+
const remove = vectors.removeMany?.bind(vectors);
|
|
14323
|
+
if (!currentIds || !scan || !remove)
|
|
14324
|
+
return void 0;
|
|
14325
|
+
const lockedWrite = state.withWriteLock?.bind(state);
|
|
14326
|
+
const write = lockedWrite ?? ((update) => update(state));
|
|
14327
|
+
let timer;
|
|
14328
|
+
let active;
|
|
14329
|
+
let nextCheck = 0;
|
|
14330
|
+
const run = async () => {
|
|
14331
|
+
const now = await state.currentTime();
|
|
14332
|
+
const record = await state.readVersioned(checkpointId);
|
|
14333
|
+
if (record && record.data.collection === collection && record.data.updatedAt > now) {
|
|
14334
|
+
nextCheck = performance.now() + Math.min(record.data.updatedAt - now, record.data.leased ? pollMs : roundPauseMs);
|
|
14335
|
+
return;
|
|
14336
|
+
}
|
|
14337
|
+
const claim = await write(async (checkpoint) => {
|
|
14338
|
+
const current = lockedWrite ? await checkpoint.readVersioned(checkpointId) : record;
|
|
14339
|
+
const claimedAt = lockedWrite ? await checkpoint.currentTime() : now;
|
|
14340
|
+
const matches = current?.data.collection === collection;
|
|
14341
|
+
if (current && matches && current.data.updatedAt > claimedAt) {
|
|
14342
|
+
nextCheck = performance.now() + Math.min(current.data.updatedAt - claimedAt, current.data.leased ? pollMs : roundPauseMs);
|
|
14343
|
+
return void 0;
|
|
14344
|
+
}
|
|
14345
|
+
const cursor2 = matches ? current?.data.cursor : void 0;
|
|
14346
|
+
const deadline2 = claimedAt + leaseMs2;
|
|
14347
|
+
const version2 = await checkpoint.compareAndSwap(checkpointId, {
|
|
14348
|
+
expectedVersion: current?.version,
|
|
14349
|
+
data: {
|
|
14350
|
+
collection,
|
|
14351
|
+
cursor: cursor2,
|
|
14352
|
+
updatedAt: deadline2,
|
|
14353
|
+
leased: true
|
|
14354
|
+
}
|
|
14355
|
+
});
|
|
14356
|
+
return version2 ? { cursor: cursor2, version: version2, deadline: deadline2 } : void 0;
|
|
14357
|
+
});
|
|
14358
|
+
if (!claim) {
|
|
14359
|
+
nextCheck = Math.max(nextCheck, performance.now() + pollMs);
|
|
14360
|
+
return;
|
|
14361
|
+
}
|
|
14362
|
+
let { cursor, version } = claim;
|
|
14363
|
+
const { deadline } = claim;
|
|
14364
|
+
const stopBy = performance.now() + batchWorkMs;
|
|
14365
|
+
let retryIn = 0;
|
|
14366
|
+
for (let processed = 0; processed < pagesPerBatch && performance.now() < stopBy; processed++) {
|
|
14367
|
+
if (timer === void 0)
|
|
14368
|
+
break;
|
|
14369
|
+
let nextCursor;
|
|
14370
|
+
try {
|
|
14371
|
+
const page = await scan({ cursor, limit: pageSize2 });
|
|
14372
|
+
if (page.items.length > pageSize2 || cursor !== void 0 && page.nextCursor === cursor)
|
|
14373
|
+
throw new Error("Invalid memory vector scan page");
|
|
14374
|
+
const ids = [
|
|
14375
|
+
...new Set(page.items.map((point) => point.id))
|
|
14376
|
+
];
|
|
14377
|
+
if (ids.length) {
|
|
14378
|
+
const current = new Set(await currentIds(ids));
|
|
14379
|
+
const obsolete = ids.filter((id3) => !current.has(id3));
|
|
14380
|
+
if (obsolete.length)
|
|
14381
|
+
await remove(obsolete);
|
|
14382
|
+
}
|
|
14383
|
+
nextCursor = page.nextCursor;
|
|
14384
|
+
} catch {
|
|
14385
|
+
retryIn = failureRetryMs;
|
|
14386
|
+
logger25.warn("Memory vector scan page will retry");
|
|
14387
|
+
break;
|
|
14388
|
+
}
|
|
14389
|
+
const saved = await write((checkpoint) => checkpoint.compareAndSwap(checkpointId, {
|
|
14390
|
+
expectedVersion: version,
|
|
14391
|
+
data: {
|
|
14392
|
+
collection,
|
|
14393
|
+
cursor: nextCursor,
|
|
14394
|
+
updatedAt: deadline,
|
|
14395
|
+
leased: true
|
|
14396
|
+
},
|
|
14397
|
+
notAfter: deadline
|
|
14398
|
+
}));
|
|
14399
|
+
if (!saved)
|
|
14400
|
+
return;
|
|
14401
|
+
version = saved;
|
|
14402
|
+
cursor = nextCursor;
|
|
14403
|
+
if (cursor === void 0) {
|
|
14404
|
+
retryIn = roundPauseMs;
|
|
14405
|
+
break;
|
|
14406
|
+
}
|
|
14407
|
+
}
|
|
14408
|
+
await write(async (checkpoint) => {
|
|
14409
|
+
const completedAt = await checkpoint.currentTime();
|
|
14410
|
+
const nextBatchAt = retryIn === 0 && timer !== void 0 ? Math.max(completedAt, deadline - leaseMs2 + pollMs) : completedAt + retryIn;
|
|
14411
|
+
await checkpoint.compareAndSwap(checkpointId, {
|
|
14412
|
+
expectedVersion: version,
|
|
14413
|
+
data: { collection, cursor, updatedAt: nextBatchAt },
|
|
14414
|
+
notAfter: deadline
|
|
14415
|
+
});
|
|
14416
|
+
});
|
|
14417
|
+
nextCheck = performance.now() + retryIn;
|
|
14418
|
+
};
|
|
14419
|
+
function kick() {
|
|
14420
|
+
if (active || performance.now() < nextCheck)
|
|
14421
|
+
return;
|
|
14422
|
+
active = run().catch(() => {
|
|
14423
|
+
nextCheck = performance.now() + failureRetryMs;
|
|
14424
|
+
logger25.warn("Memory vector scan checkpoint unavailable");
|
|
14425
|
+
}).finally(() => {
|
|
14426
|
+
active = void 0;
|
|
14427
|
+
});
|
|
14428
|
+
}
|
|
14429
|
+
return {
|
|
14430
|
+
start() {
|
|
14431
|
+
timer ??= setInterval(kick, wakeMs);
|
|
14432
|
+
timer.unref();
|
|
14433
|
+
kick();
|
|
14434
|
+
},
|
|
14435
|
+
async close() {
|
|
14436
|
+
clearInterval(timer);
|
|
14437
|
+
timer = void 0;
|
|
14438
|
+
await active;
|
|
14439
|
+
}
|
|
14440
|
+
};
|
|
14441
|
+
}
|
|
14442
|
+
|
|
14443
|
+
// src/memory/ai-memory-vector-sync.ts
|
|
14444
|
+
var logger26 = core.logger.child({ module: "ai", scope: "memory-vector-sync" });
|
|
14445
|
+
var pollMs2 = 1e3;
|
|
14189
14446
|
var inFlightRetryMs = 45e3;
|
|
14190
14447
|
var lateWriteWindowMs = 6e4;
|
|
14191
14448
|
var batchSize2 = 16;
|
|
@@ -14195,10 +14452,11 @@ function backoff(attempts) {
|
|
|
14195
14452
|
function vectorId(memory) {
|
|
14196
14453
|
return memory.vectorId ?? memory.id;
|
|
14197
14454
|
}
|
|
14198
|
-
function createMemoryVectorSync(store, queue, vectors) {
|
|
14455
|
+
function createMemoryVectorSync(store, queue, vectors, scanStore, collection) {
|
|
14199
14456
|
const lock = store.withRelatedWriteLock?.bind(store);
|
|
14200
14457
|
if (!lock || !queue.queryKeys)
|
|
14201
14458
|
return void 0;
|
|
14459
|
+
const scan = scanStore && createMemoryVectorScan(store, scanStore, vectors, collection);
|
|
14202
14460
|
function write(run) {
|
|
14203
14461
|
return lock(queue, run);
|
|
14204
14462
|
}
|
|
@@ -14242,7 +14500,7 @@ function createMemoryVectorSync(store, queue, vectors) {
|
|
|
14242
14500
|
}
|
|
14243
14501
|
succeeded = true;
|
|
14244
14502
|
} catch {
|
|
14245
|
-
|
|
14503
|
+
logger26.debug("Memory vector sync will retry", {
|
|
14246
14504
|
operation: claimed.entry ? "upsert" : "delete"
|
|
14247
14505
|
});
|
|
14248
14506
|
}
|
|
@@ -14251,7 +14509,11 @@ function createMemoryVectorSync(store, queue, vectors) {
|
|
|
14251
14509
|
if (!job || job.token !== claimed.token)
|
|
14252
14510
|
return;
|
|
14253
14511
|
const now = await pending.currentTime();
|
|
14254
|
-
if (
|
|
14512
|
+
if (scan && !claimed.entry) {
|
|
14513
|
+
await pending.remove(id3);
|
|
14514
|
+
return;
|
|
14515
|
+
}
|
|
14516
|
+
if (!scan && succeeded && claimed.entry && job.attempts > 1) {
|
|
14255
14517
|
await pending.save(id3, {
|
|
14256
14518
|
...job,
|
|
14257
14519
|
token: void 0,
|
|
@@ -14260,7 +14522,7 @@ function createMemoryVectorSync(store, queue, vectors) {
|
|
|
14260
14522
|
});
|
|
14261
14523
|
return;
|
|
14262
14524
|
}
|
|
14263
|
-
if (succeeded && (!job.retireUntil || job.retireUntil <= now)) {
|
|
14525
|
+
if (succeeded && (scan || !job.retireUntil || job.retireUntil <= now)) {
|
|
14264
14526
|
await pending.remove(id3);
|
|
14265
14527
|
return;
|
|
14266
14528
|
}
|
|
@@ -14284,7 +14546,7 @@ function createMemoryVectorSync(store, queue, vectors) {
|
|
|
14284
14546
|
function kick() {
|
|
14285
14547
|
if (timer && !active) {
|
|
14286
14548
|
active = drain().catch(() => {
|
|
14287
|
-
|
|
14549
|
+
logger26.warn("Memory vector compensation storage unavailable");
|
|
14288
14550
|
}).finally(() => {
|
|
14289
14551
|
active = void 0;
|
|
14290
14552
|
});
|
|
@@ -14295,15 +14557,19 @@ function createMemoryVectorSync(store, queue, vectors) {
|
|
|
14295
14557
|
kick,
|
|
14296
14558
|
start() {
|
|
14297
14559
|
if (!timer) {
|
|
14298
|
-
timer = setInterval(kick,
|
|
14560
|
+
timer = setInterval(kick, pollMs2);
|
|
14299
14561
|
timer.unref();
|
|
14300
14562
|
kick();
|
|
14563
|
+
scan?.start();
|
|
14301
14564
|
}
|
|
14302
14565
|
},
|
|
14303
14566
|
async close() {
|
|
14304
14567
|
clearInterval(timer);
|
|
14305
14568
|
timer = void 0;
|
|
14306
|
-
await
|
|
14569
|
+
await Promise.all([
|
|
14570
|
+
active,
|
|
14571
|
+
scan?.close()
|
|
14572
|
+
]);
|
|
14307
14573
|
},
|
|
14308
14574
|
async enqueue(pending, entry) {
|
|
14309
14575
|
const now = await pending.currentTime();
|
|
@@ -14321,14 +14587,14 @@ function createMemoryVectorSync(store, queue, vectors) {
|
|
|
14321
14587
|
memoryId: entry.id,
|
|
14322
14588
|
updatedAt: now,
|
|
14323
14589
|
attempts: 0,
|
|
14324
|
-
|
|
14590
|
+
...!scan && prior && { retireUntil: now + lateWriteWindowMs }
|
|
14325
14591
|
});
|
|
14326
14592
|
}
|
|
14327
14593
|
};
|
|
14328
14594
|
}
|
|
14329
14595
|
|
|
14330
14596
|
// src/memory/providers/ai-memory-provider-native.ts
|
|
14331
|
-
var
|
|
14597
|
+
var logger27 = core.logger.child({ module: "ai", scope: "memory-native" });
|
|
14332
14598
|
var EVICTION_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1e3;
|
|
14333
14599
|
var EVICTION_CANDIDATES = 64;
|
|
14334
14600
|
function generateId() {
|
|
@@ -14356,8 +14622,8 @@ function matchScope2(entry, scope) {
|
|
|
14356
14622
|
return false;
|
|
14357
14623
|
return Object.entries(scope).every(([k, v]) => entry.scope[k] === v);
|
|
14358
14624
|
}
|
|
14359
|
-
function assembleNativeMemory(config, llm, embedding, store, vectorStore, vectorQueue) {
|
|
14360
|
-
const sync = vectorQueue && createMemoryVectorSync(store, vectorQueue, vectorStore);
|
|
14625
|
+
function assembleNativeMemory(config, llm, embedding, store, vectorStore, vectorQueue, vectorScan, vectorCollection) {
|
|
14626
|
+
const sync = vectorQueue && createMemoryVectorSync(store, vectorQueue, vectorStore, vectorScan, vectorCollection);
|
|
14361
14627
|
const maxPending = Math.max(1024, config.maxEntriesGlobal * 2);
|
|
14362
14628
|
async function ensureVectorCapacity(pending) {
|
|
14363
14629
|
if (pending && await pending.count() >= maxPending)
|
|
@@ -14376,7 +14642,7 @@ function assembleNativeMemory(config, llm, embedding, store, vectorStore, vector
|
|
|
14376
14642
|
try {
|
|
14377
14643
|
return await operation();
|
|
14378
14644
|
} catch (error) {
|
|
14379
|
-
|
|
14645
|
+
logger27.error("Memory storage operation failed", {
|
|
14380
14646
|
error: core.sanitize.sanitizeSensitiveFields(error)
|
|
14381
14647
|
});
|
|
14382
14648
|
return err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryOperationFailed"));
|
|
@@ -14408,7 +14674,7 @@ function assembleNativeMemory(config, llm, embedding, store, vectorStore, vector
|
|
|
14408
14674
|
const result = await embedding.embedText(text);
|
|
14409
14675
|
if (result.success)
|
|
14410
14676
|
return result.data;
|
|
14411
|
-
|
|
14677
|
+
logger27.warn("Failed to compute embedding for memory", { error: result.error });
|
|
14412
14678
|
return void 0;
|
|
14413
14679
|
}
|
|
14414
14680
|
async function evictLowest(activeStore, candidates, count, pending) {
|
|
@@ -14545,10 +14811,10 @@ function assembleNativeMemory(config, llm, embedding, store, vectorStore, vector
|
|
|
14545
14811
|
params: { id: memoryId }
|
|
14546
14812
|
}));
|
|
14547
14813
|
}
|
|
14548
|
-
|
|
14814
|
+
logger27.trace("Memory updated", { id: memoryId });
|
|
14549
14815
|
return ok(existing);
|
|
14550
14816
|
} catch (error) {
|
|
14551
|
-
|
|
14817
|
+
logger27.error("Memory update failed", {
|
|
14552
14818
|
id: memoryId,
|
|
14553
14819
|
error: core.sanitize.sanitizeSensitiveFields(error)
|
|
14554
14820
|
});
|
|
@@ -14559,7 +14825,7 @@ function assembleNativeMemory(config, llm, embedding, store, vectorStore, vector
|
|
|
14559
14825
|
const topK = options?.topK ?? config.defaultTopK;
|
|
14560
14826
|
const recencyWeight = options?.recencyWeight ?? 1 - config.recencyDecay;
|
|
14561
14827
|
const candidateMultiplier = Math.max(1, options?.candidateMultiplier ?? config.candidateMultiplier);
|
|
14562
|
-
|
|
14828
|
+
logger27.trace("Recalling memories", {
|
|
14563
14829
|
query: query.slice(0, 100),
|
|
14564
14830
|
topK,
|
|
14565
14831
|
updateAccessStats
|
|
@@ -14603,7 +14869,7 @@ function assembleNativeMemory(config, llm, embedding, store, vectorStore, vector
|
|
|
14603
14869
|
} catch (error) {
|
|
14604
14870
|
if (!sync)
|
|
14605
14871
|
throw error;
|
|
14606
|
-
|
|
14872
|
+
logger27.debug("Memory vector search unavailable; using persisted embeddings");
|
|
14607
14873
|
}
|
|
14608
14874
|
}
|
|
14609
14875
|
const now = Date.now();
|
|
@@ -14633,14 +14899,14 @@ function assembleNativeMemory(config, llm, embedding, store, vectorStore, vector
|
|
|
14633
14899
|
}
|
|
14634
14900
|
results.push(publicEntry(entry));
|
|
14635
14901
|
}
|
|
14636
|
-
|
|
14902
|
+
logger27.trace("Memory recall completed", {
|
|
14637
14903
|
query: query.slice(0, 50),
|
|
14638
14904
|
resultCount: results.length,
|
|
14639
14905
|
updateAccessStats
|
|
14640
14906
|
});
|
|
14641
14907
|
return ok(results);
|
|
14642
14908
|
} catch (error) {
|
|
14643
|
-
|
|
14909
|
+
logger27.error("Memory recall failed", {
|
|
14644
14910
|
error: core.sanitize.sanitizeSensitiveFields(error)
|
|
14645
14911
|
});
|
|
14646
14912
|
return err(HaiAIError.MEMORY_RECALL_FAILED, aiM("ai_memoryOperationFailed"));
|
|
@@ -14692,10 +14958,10 @@ function assembleNativeMemory(config, llm, embedding, store, vectorStore, vector
|
|
|
14692
14958
|
const stored = await saveEntry(entry, vector);
|
|
14693
14959
|
if (!stored)
|
|
14694
14960
|
return err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryOperationFailed"));
|
|
14695
|
-
|
|
14961
|
+
logger27.trace("Memory added", { id: stored.id, type: stored.type });
|
|
14696
14962
|
return ok(stored);
|
|
14697
14963
|
} catch (error) {
|
|
14698
|
-
|
|
14964
|
+
logger27.error("Memory add failed", {
|
|
14699
14965
|
error: core.sanitize.sanitizeSensitiveFields(error)
|
|
14700
14966
|
});
|
|
14701
14967
|
return err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryOperationFailed"));
|
|
@@ -14742,7 +15008,7 @@ function assembleNativeMemory(config, llm, embedding, store, vectorStore, vector
|
|
|
14742
15008
|
params: { id: memoryId }
|
|
14743
15009
|
}));
|
|
14744
15010
|
}
|
|
14745
|
-
|
|
15011
|
+
logger27.trace("Memory removed", { id: memoryId });
|
|
14746
15012
|
return ok(void 0);
|
|
14747
15013
|
},
|
|
14748
15014
|
/**
|
|
@@ -14828,7 +15094,7 @@ function assembleNativeMemory(config, llm, embedding, store, vectorStore, vector
|
|
|
14828
15094
|
if (!sync && !options?.types && !options?.objectId && !options?.scope) {
|
|
14829
15095
|
await vectorStore.clear();
|
|
14830
15096
|
await store.clear();
|
|
14831
|
-
|
|
15097
|
+
logger27.debug("All memories cleared");
|
|
14832
15098
|
return ok(void 0);
|
|
14833
15099
|
}
|
|
14834
15100
|
const where = {};
|
|
@@ -14859,7 +15125,7 @@ function assembleNativeMemory(config, llm, embedding, store, vectorStore, vector
|
|
|
14859
15125
|
throw new Error("Memory store did not advance the primary-key cursor");
|
|
14860
15126
|
afterId = batch.nextId;
|
|
14861
15127
|
}
|
|
14862
|
-
|
|
15128
|
+
logger27.debug("Memories cleared", {
|
|
14863
15129
|
removed: removed2,
|
|
14864
15130
|
objectId: options?.objectId,
|
|
14865
15131
|
types: options?.types,
|
|
@@ -14880,7 +15146,7 @@ function assembleNativeMemory(config, llm, embedding, store, vectorStore, vector
|
|
|
14880
15146
|
}
|
|
14881
15147
|
};
|
|
14882
15148
|
}
|
|
14883
|
-
var
|
|
15149
|
+
var logger28 = core.logger.child({ module: "ai", scope: "persona" });
|
|
14884
15150
|
var DEFAULT_OBJECT_ID2 = "system";
|
|
14885
15151
|
function personaKey(objectId, id3) {
|
|
14886
15152
|
return JSON.stringify([objectId, id3]);
|
|
@@ -14899,7 +15165,7 @@ function createPersonaOperations(store) {
|
|
|
14899
15165
|
try {
|
|
14900
15166
|
return await operation();
|
|
14901
15167
|
} catch (error) {
|
|
14902
|
-
|
|
15168
|
+
logger28.error("Persona storage operation failed", {
|
|
14903
15169
|
error: core.sanitize.sanitizeSensitiveFields(error)
|
|
14904
15170
|
});
|
|
14905
15171
|
return err(HaiAIError.PERSONA_SAVE_FAILED, aiM("ai_personaOperationFailed"));
|
|
@@ -14923,10 +15189,10 @@ function createPersonaOperations(store) {
|
|
|
14923
15189
|
updatedAt: now
|
|
14924
15190
|
};
|
|
14925
15191
|
await store.save(key, profile, { objectId });
|
|
14926
|
-
|
|
15192
|
+
logger28.trace("Persona saved", { id: profile.id, objectId });
|
|
14927
15193
|
return ok(profile);
|
|
14928
15194
|
} catch (error) {
|
|
14929
|
-
|
|
15195
|
+
logger28.error("Persona save failed", {
|
|
14930
15196
|
error: core.sanitize.sanitizeSensitiveFields(error)
|
|
14931
15197
|
});
|
|
14932
15198
|
return err(HaiAIError.PERSONA_SAVE_FAILED, aiM("ai_personaOperationFailed"));
|
|
@@ -14963,7 +15229,7 @@ function createPersonaOperations(store) {
|
|
|
14963
15229
|
await store.save(key, profile, { objectId });
|
|
14964
15230
|
return ok(profile);
|
|
14965
15231
|
} catch (error) {
|
|
14966
|
-
|
|
15232
|
+
logger28.error("Persona update failed", {
|
|
14967
15233
|
error: core.sanitize.sanitizeSensitiveFields(error)
|
|
14968
15234
|
});
|
|
14969
15235
|
return err(HaiAIError.PERSONA_SAVE_FAILED, aiM("ai_personaOperationFailed"));
|
|
@@ -15002,7 +15268,7 @@ function createPersonaOperations(store) {
|
|
|
15002
15268
|
compose: (id3, options) => protect(() => operations2.compose(id3, options))
|
|
15003
15269
|
};
|
|
15004
15270
|
}
|
|
15005
|
-
var
|
|
15271
|
+
var logger29 = core.logger.child({ module: "ai", scope: "rag" });
|
|
15006
15272
|
var DEFAULT_RAG_SYSTEM_PROMPT = `You are a helpful assistant. Answer the user's question based on the provided context.
|
|
15007
15273
|
If the context doesn't contain relevant information, say so honestly.
|
|
15008
15274
|
When using information from the context, cite the source by its number, e.g. [1] or [2].`;
|
|
@@ -15031,7 +15297,7 @@ function createRagOperations(llm, retrieval) {
|
|
|
15031
15297
|
* @returns `ok(RagResult)` 含 answer、context 列表与引用信源;检索或生成失败时返回错误
|
|
15032
15298
|
*/
|
|
15033
15299
|
async query(query, options) {
|
|
15034
|
-
|
|
15300
|
+
logger29.trace("Starting RAG query", {
|
|
15035
15301
|
query: query.slice(0, 100)
|
|
15036
15302
|
});
|
|
15037
15303
|
try {
|
|
@@ -15086,7 +15352,7 @@ ${contextText}
|
|
|
15086
15352
|
}
|
|
15087
15353
|
const choice = chatResult.data.choices[0];
|
|
15088
15354
|
const answer = choice?.message?.content ?? "";
|
|
15089
|
-
|
|
15355
|
+
logger29.trace("RAG query completed", {
|
|
15090
15356
|
contextCount: contextItems.length,
|
|
15091
15357
|
model: chatResult.data.model
|
|
15092
15358
|
});
|
|
@@ -15113,7 +15379,7 @@ ${contextText}
|
|
|
15113
15379
|
} : void 0
|
|
15114
15380
|
});
|
|
15115
15381
|
} catch (error) {
|
|
15116
|
-
|
|
15382
|
+
logger29.error("RAG query failed", { error });
|
|
15117
15383
|
return err(HaiAIError.RAG_FAILED, aiM("ai_internalError", {
|
|
15118
15384
|
params: {
|
|
15119
15385
|
error: String(error)
|
|
@@ -15125,7 +15391,7 @@ ${contextText}
|
|
|
15125
15391
|
* 流式 RAG 查询:先产出 context,再逐 chunk 产出 delta,最后 done
|
|
15126
15392
|
*/
|
|
15127
15393
|
async *queryStream(query, options) {
|
|
15128
|
-
|
|
15394
|
+
logger29.trace("Starting RAG stream", {
|
|
15129
15395
|
query: query.slice(0, 100)
|
|
15130
15396
|
});
|
|
15131
15397
|
const retrieveResult = await retrieval.retrieve({
|
|
@@ -15209,7 +15475,7 @@ ${contextText}
|
|
|
15209
15475
|
}
|
|
15210
15476
|
};
|
|
15211
15477
|
}
|
|
15212
|
-
var
|
|
15478
|
+
var logger30 = core.logger.child({ module: "ai", scope: "reasoning" });
|
|
15213
15479
|
var REACT_SYSTEM_PROMPT = `You are a reasoning agent that follows the ReAct (Reasoning and Acting) framework.
|
|
15214
15480
|
For each step:
|
|
15215
15481
|
1. Think: Analyze what you know and what you need to find out.
|
|
@@ -15459,7 +15725,7 @@ ${query}` }
|
|
|
15459
15725
|
return {
|
|
15460
15726
|
async run(query, options) {
|
|
15461
15727
|
const strategy = options?.strategy ?? "react";
|
|
15462
|
-
|
|
15728
|
+
logger30.trace("Starting reasoning", { strategy, maxRounds: options?.maxRounds });
|
|
15463
15729
|
try {
|
|
15464
15730
|
switch (strategy) {
|
|
15465
15731
|
case "react":
|
|
@@ -15474,7 +15740,7 @@ ${query}` }
|
|
|
15474
15740
|
}));
|
|
15475
15741
|
}
|
|
15476
15742
|
} catch (error) {
|
|
15477
|
-
|
|
15743
|
+
logger30.error("Reasoning failed", { error });
|
|
15478
15744
|
return err(HaiAIError.REASONING_FAILED, aiM("ai_internalError", {
|
|
15479
15745
|
params: {
|
|
15480
15746
|
error: String(error)
|
|
@@ -15506,7 +15772,7 @@ ${query}` }
|
|
|
15506
15772
|
}
|
|
15507
15773
|
};
|
|
15508
15774
|
}
|
|
15509
|
-
var
|
|
15775
|
+
var logger31 = core.logger.child({ module: "ai", scope: "rerank" });
|
|
15510
15776
|
function createRerankOperations(config, loadModels = () => config.llm) {
|
|
15511
15777
|
function normalizeDocuments(documents) {
|
|
15512
15778
|
if (documents.length === 0) {
|
|
@@ -15551,7 +15817,7 @@ function createRerankOperations(config, loadModels = () => config.llm) {
|
|
|
15551
15817
|
if (request2.returnDocuments) {
|
|
15552
15818
|
body.return_documents = true;
|
|
15553
15819
|
}
|
|
15554
|
-
|
|
15820
|
+
logger31.trace("Calling rerank API", { model: resolved.model, documentCount: texts.length, topN: request2.topN });
|
|
15555
15821
|
try {
|
|
15556
15822
|
const response = await fetch(`${resolved.baseUrl}/v1/rerank`, {
|
|
15557
15823
|
method: "POST",
|
|
@@ -15566,7 +15832,7 @@ function createRerankOperations(config, loadModels = () => config.llm) {
|
|
|
15566
15832
|
const requestId = response.headers.get("x-request-id");
|
|
15567
15833
|
await response.body?.cancel().catch(() => {
|
|
15568
15834
|
});
|
|
15569
|
-
|
|
15835
|
+
logger31.error("Rerank API request failed", {
|
|
15570
15836
|
status: response.status,
|
|
15571
15837
|
providerRequestId: requestId && /^[\w.:-]{1,128}$/.test(requestId) ? requestId : void 0
|
|
15572
15838
|
});
|
|
@@ -15581,11 +15847,11 @@ function createRerankOperations(config, loadModels = () => config.llm) {
|
|
|
15581
15847
|
relevanceScore: item2.relevance_score,
|
|
15582
15848
|
document: item2.document?.text
|
|
15583
15849
|
}));
|
|
15584
|
-
|
|
15850
|
+
logger31.trace("Rerank completed", { resultCount: results.length });
|
|
15585
15851
|
return ok({ model: resolved.model, results });
|
|
15586
15852
|
} catch (error) {
|
|
15587
15853
|
const causeName = error instanceof Error ? error.name : void 0;
|
|
15588
|
-
|
|
15854
|
+
logger31.error("Rerank API call failed", { causeName });
|
|
15589
15855
|
return err(HaiAIError.RERANK_API_ERROR, aiM("ai_rerankApiFailed", {
|
|
15590
15856
|
params: {
|
|
15591
15857
|
error: causeName ?? core.i18n.coreM("core_errorInternal")
|
|
@@ -15621,7 +15887,7 @@ function createRerankOperations(config, loadModels = () => config.llm) {
|
|
|
15621
15887
|
}
|
|
15622
15888
|
};
|
|
15623
15889
|
}
|
|
15624
|
-
var
|
|
15890
|
+
var logger32 = core.logger.child({ module: "ai", scope: "retrieval" });
|
|
15625
15891
|
function createRetrievalOperations(embeddingOps, storeProvider, sourceStore, rerankOps, registry) {
|
|
15626
15892
|
const vectorStoreCache = /* @__PURE__ */ new Map();
|
|
15627
15893
|
function getVectorStore(collection) {
|
|
@@ -15654,7 +15920,7 @@ function createRetrievalOperations(embeddingOps, storeProvider, sourceStore, rer
|
|
|
15654
15920
|
}));
|
|
15655
15921
|
}
|
|
15656
15922
|
await sourceStore.save(source.id, source);
|
|
15657
|
-
|
|
15923
|
+
logger32.debug("Retrieval source added", { sourceId: source.id, collection: source.collection });
|
|
15658
15924
|
return ok(void 0);
|
|
15659
15925
|
},
|
|
15660
15926
|
/**
|
|
@@ -15675,7 +15941,7 @@ function createRetrievalOperations(embeddingOps, storeProvider, sourceStore, rer
|
|
|
15675
15941
|
}));
|
|
15676
15942
|
}
|
|
15677
15943
|
await sourceStore.remove(sourceId);
|
|
15678
|
-
|
|
15944
|
+
logger32.debug("Retrieval source removed", { sourceId });
|
|
15679
15945
|
return ok(void 0);
|
|
15680
15946
|
},
|
|
15681
15947
|
/**
|
|
@@ -15762,21 +16028,21 @@ function createRetrievalOperations(embeddingOps, storeProvider, sourceStore, rer
|
|
|
15762
16028
|
allItems.length = 0;
|
|
15763
16029
|
allItems.push(...reranked);
|
|
15764
16030
|
} else {
|
|
15765
|
-
|
|
16031
|
+
logger32.warn("Rerank failed, falling back to vector scores", { error: rerankResult.error });
|
|
15766
16032
|
}
|
|
15767
16033
|
}
|
|
15768
16034
|
allItems.sort((a, b) => b.score - a.score);
|
|
15769
16035
|
const topK = request2.topK ?? 10;
|
|
15770
16036
|
const limitedItems = allItems.slice(0, topK);
|
|
15771
16037
|
const duration = Date.now() - startTime;
|
|
15772
|
-
|
|
16038
|
+
logger32.trace("Retrieval completed", { queryLength: request2.query.length, resultCount: limitedItems.length, duration });
|
|
15773
16039
|
return ok({
|
|
15774
16040
|
items: limitedItems,
|
|
15775
16041
|
query: request2.query,
|
|
15776
16042
|
duration
|
|
15777
16043
|
});
|
|
15778
16044
|
} catch (error) {
|
|
15779
|
-
|
|
16045
|
+
logger32.error("Retrieval failed", { error });
|
|
15780
16046
|
return err(HaiAIError.RETRIEVAL_FAILED, aiM("ai_internalError", {
|
|
15781
16047
|
params: {
|
|
15782
16048
|
error: String(error)
|
|
@@ -15786,7 +16052,7 @@ function createRetrievalOperations(embeddingOps, storeProvider, sourceStore, rer
|
|
|
15786
16052
|
}
|
|
15787
16053
|
};
|
|
15788
16054
|
}
|
|
15789
|
-
var
|
|
16055
|
+
var logger33 = core.logger.child({ module: "ai", scope: "summary" });
|
|
15790
16056
|
var SUMMARIZE_SYSTEM_PROMPT = `You are a conversation summarizer. Create a concise summary of the conversation that preserves:
|
|
15791
16057
|
1. Key facts and decisions made
|
|
15792
16058
|
2. Important context and background information
|
|
@@ -15844,7 +16110,7 @@ ${INCREMENTAL_SUMMARIZE_SUFFIX.replace("{previousSummary}", options.previousSumm
|
|
|
15844
16110
|
return ok(chatResult.data.choices[0]?.message?.content ?? "");
|
|
15845
16111
|
}
|
|
15846
16112
|
async function summarize(messages, options) {
|
|
15847
|
-
|
|
16113
|
+
logger33.trace("Summarizing messages", { messageCount: messages.length });
|
|
15848
16114
|
try {
|
|
15849
16115
|
const result = await generate(messages, options);
|
|
15850
16116
|
if (!result.success)
|
|
@@ -15856,7 +16122,7 @@ ${INCREMENTAL_SUMMARIZE_SUFFIX.replace("{previousSummary}", options.previousSumm
|
|
|
15856
16122
|
coveredMessages: messages.filter((m) => m.role !== "system").length
|
|
15857
16123
|
});
|
|
15858
16124
|
} catch (error) {
|
|
15859
|
-
|
|
16125
|
+
logger33.error("Context summarization failed", { error });
|
|
15860
16126
|
return err(HaiAIError.CONTEXT_SUMMARIZE_FAILED, aiM("ai_contextSummarizeFailed", {
|
|
15861
16127
|
params: {
|
|
15862
16128
|
error: String(error)
|
|
@@ -15922,6 +16188,7 @@ async function createAISubsystems(config, deps) {
|
|
|
15922
16188
|
const memoryStore = useMem0Oss ? null : storeProvider.createRelStore("hai_ai_memory", {
|
|
15923
16189
|
hasObjectId: true,
|
|
15924
16190
|
hasScopeIndex: true,
|
|
16191
|
+
hasMemoryVectorIndex: true,
|
|
15925
16192
|
serializeWrites: true
|
|
15926
16193
|
});
|
|
15927
16194
|
const memoryVectorQueue = memoryStore?.withRelatedWriteLock ? storeProvider.createRelStore("hai_ai_memory_vector_outbox", { hasUpdatedAtIndex: true }) : void 0;
|
|
@@ -15934,7 +16201,8 @@ async function createAISubsystems(config, deps) {
|
|
|
15934
16201
|
{ hasObjectId: true }
|
|
15935
16202
|
);
|
|
15936
16203
|
const a2aStores = config.a2a ? createA2AStores(storeProvider) : null;
|
|
15937
|
-
const
|
|
16204
|
+
const memoryNamespace = memoryStore ? storeProvider.createRelStore("hai_ai_memory_vector_namespace", { serializeWrites: true }) : void 0;
|
|
16205
|
+
const memoryVectorScan = memoryStore?.getMemoryVectorIds ? storeProvider.createRelStore("hai_ai_memory_vector_scan", { serializeWrites: true }) : void 0;
|
|
15938
16206
|
let registriesOpen = true;
|
|
15939
16207
|
const isOpen = () => registriesOpen;
|
|
15940
16208
|
const llmModels = createResourceRegistry(
|
|
@@ -16044,6 +16312,9 @@ async function createAISubsystems(config, deps) {
|
|
|
16044
16312
|
deps.acpPolicy
|
|
16045
16313
|
);
|
|
16046
16314
|
await storeProvider.initialize();
|
|
16315
|
+
const memoryCollection = memoryNamespace && await bindMemoryVectorNamespace(memoryNamespace, memoryParsed.vectorNamespace);
|
|
16316
|
+
const memoryVectorStore = memoryCollection ? storeProvider.createVectorStore(memoryCollection) : void 0;
|
|
16317
|
+
const memoryVectorRebuild = memoryStore && memoryNamespace && memoryVectorQueue?.queryKeys && memoryVectorScan && memoryVectorStore?.scan && memoryVectorStore.removeMany ? createMemoryVectorRebuild(memoryStore, memoryNamespace, memoryVectorStore) : void 0;
|
|
16047
16318
|
const llmFunctions = createAILLMFunctions(config, {
|
|
16048
16319
|
recordStore: chatRecordStore,
|
|
16049
16320
|
sessionStore,
|
|
@@ -16099,7 +16370,7 @@ async function createAISubsystems(config, deps) {
|
|
|
16099
16370
|
datapipeDep,
|
|
16100
16371
|
knowledgeStore
|
|
16101
16372
|
);
|
|
16102
|
-
const nativeMemory = memoryStore && memoryVectorStore ? assembleNativeMemory(memoryParsed, llm, embedding, memoryStore, memoryVectorStore, memoryVectorQueue) : void 0;
|
|
16373
|
+
const nativeMemory = memoryStore && memoryVectorStore ? assembleNativeMemory(memoryParsed, llm, embedding, memoryStore, memoryVectorStore, memoryVectorQueue, memoryVectorScan, memoryCollection) : void 0;
|
|
16103
16374
|
const memoryCore = nativeMemory?.operations ?? await createMem0MemoryOperations({
|
|
16104
16375
|
config: memoryParsed,
|
|
16105
16376
|
embedding,
|
|
@@ -16208,11 +16479,15 @@ async function createAISubsystems(config, deps) {
|
|
|
16208
16479
|
services: mcpServices.operations
|
|
16209
16480
|
});
|
|
16210
16481
|
nativeMemory?.sync?.start();
|
|
16482
|
+
memoryVectorRebuild?.start();
|
|
16211
16483
|
return {
|
|
16212
16484
|
closeRegistries: async () => {
|
|
16213
16485
|
mcpServices.close();
|
|
16214
16486
|
registriesOpen = false;
|
|
16215
|
-
await
|
|
16487
|
+
await Promise.all([
|
|
16488
|
+
nativeMemory?.sync?.close(),
|
|
16489
|
+
memoryVectorRebuild?.close()
|
|
16490
|
+
]);
|
|
16216
16491
|
},
|
|
16217
16492
|
a2aStores,
|
|
16218
16493
|
llm,
|
|
@@ -16609,7 +16884,7 @@ function documentInfo(document) {
|
|
|
16609
16884
|
}
|
|
16610
16885
|
|
|
16611
16886
|
// src/store/providers/ai-store-provider-db.ts
|
|
16612
|
-
var
|
|
16887
|
+
var logger34 = core.logger.child({ module: "ai", scope: "store-provider-db" });
|
|
16613
16888
|
function requireSqlSuccess(result) {
|
|
16614
16889
|
if (!result.success)
|
|
16615
16890
|
throw new Error(result.error.message, { cause: result.error });
|
|
@@ -16622,18 +16897,25 @@ function dataTimestamp(data, field, fallback) {
|
|
|
16622
16897
|
const value = data[field];
|
|
16623
16898
|
return typeof value === "number" && Number.isFinite(value) ? value : fallback;
|
|
16624
16899
|
}
|
|
16625
|
-
function
|
|
16900
|
+
function isMysqlError(error, code, errno) {
|
|
16626
16901
|
const seen = /* @__PURE__ */ new Set();
|
|
16627
16902
|
let current = error;
|
|
16628
16903
|
while (current !== null && typeof current === "object" && !seen.has(current)) {
|
|
16629
16904
|
seen.add(current);
|
|
16630
16905
|
const details = current;
|
|
16631
|
-
if (details.code ===
|
|
16906
|
+
if (details.code === code && details.errno === errno)
|
|
16632
16907
|
return true;
|
|
16633
16908
|
current = details.cause;
|
|
16634
16909
|
}
|
|
16635
16910
|
return false;
|
|
16636
16911
|
}
|
|
16912
|
+
function memoryVectorKey(type) {
|
|
16913
|
+
if (type === "postgresql")
|
|
16914
|
+
return `(CASE WHEN jsonb_typeof(data->'vector') = 'array' THEN COALESCE(data->>'vectorId', id) END)`;
|
|
16915
|
+
if (type === "mysql")
|
|
16916
|
+
return "memory_vector_key";
|
|
16917
|
+
return `(CASE WHEN json_type(data, '$.vector') = 'array' THEN COALESCE(json_extract(data, '$.vectorId'), id) END)`;
|
|
16918
|
+
}
|
|
16637
16919
|
var ReldbAIRelStore = class _ReldbAIRelStore {
|
|
16638
16920
|
sql;
|
|
16639
16921
|
connection;
|
|
@@ -16647,8 +16929,11 @@ var ReldbAIRelStore = class _ReldbAIRelStore {
|
|
|
16647
16929
|
hasScopeIndex;
|
|
16648
16930
|
hasUpdatedAtIndex;
|
|
16649
16931
|
gate;
|
|
16932
|
+
memoryVectorKey;
|
|
16650
16933
|
withWriteLock;
|
|
16651
16934
|
withRelatedWriteLock;
|
|
16935
|
+
getMemoryVectorIds;
|
|
16936
|
+
readMemoryVectorPage;
|
|
16652
16937
|
constructor(sql, table, jsonOps, dbType, options, tx) {
|
|
16653
16938
|
this.connection = sql;
|
|
16654
16939
|
this.sql = {
|
|
@@ -16666,6 +16951,34 @@ var ReldbAIRelStore = class _ReldbAIRelStore {
|
|
|
16666
16951
|
this.hasRefId = options?.hasRefId ?? false;
|
|
16667
16952
|
this.hasScopeIndex = options?.hasScopeIndex ?? false;
|
|
16668
16953
|
this.hasUpdatedAtIndex = options?.hasUpdatedAtIndex ?? false;
|
|
16954
|
+
if (options?.hasMemoryVectorIndex) {
|
|
16955
|
+
const key = memoryVectorKey(dbType);
|
|
16956
|
+
this.memoryVectorKey = key;
|
|
16957
|
+
this.getMemoryVectorIds = async (ids) => {
|
|
16958
|
+
if (!ids.length)
|
|
16959
|
+
return [];
|
|
16960
|
+
if (ids.length > 128)
|
|
16961
|
+
throw new RangeError("Too many memory vector keys");
|
|
16962
|
+
const readIds = async (connection) => requireSqlSuccess(await connection.query(
|
|
16963
|
+
`SELECT ${key} AS vector_id FROM ${table} WHERE ${key} IN (${ids.map(() => "?").join(", ")})`,
|
|
16964
|
+
ids
|
|
16965
|
+
)).data.map((row) => row.vector_id);
|
|
16966
|
+
if (dbType === "sqlite" && tx)
|
|
16967
|
+
return requireSqlSuccess(await tx.wrap(readIds)).data;
|
|
16968
|
+
return readIds(this.sql);
|
|
16969
|
+
};
|
|
16970
|
+
this.readMemoryVectorPage = async (afterId, limit) => {
|
|
16971
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > 128)
|
|
16972
|
+
throw new RangeError("Invalid memory vector rebuild page size");
|
|
16973
|
+
const readPage = async (connection) => requireSqlSuccess(await connection.query(
|
|
16974
|
+
`SELECT data FROM ${table} WHERE id > ? AND ${key} IS NOT NULL ORDER BY id ASC LIMIT ?`,
|
|
16975
|
+
[afterId, limit]
|
|
16976
|
+
)).data.map((row) => this.decodeData(row.data));
|
|
16977
|
+
if (dbType === "sqlite" && tx)
|
|
16978
|
+
return requireSqlSuccess(await tx.wrap(readPage)).data;
|
|
16979
|
+
return readPage(this.sql);
|
|
16980
|
+
};
|
|
16981
|
+
}
|
|
16669
16982
|
if (options?.serializeWrites && tx) {
|
|
16670
16983
|
const gate = `${table}_write_gate`;
|
|
16671
16984
|
this.gate = gate;
|
|
@@ -16710,6 +17023,8 @@ var ReldbAIRelStore = class _ReldbAIRelStore {
|
|
|
16710
17023
|
if (this.hasRefId)
|
|
16711
17024
|
cols.push(`ref_id ${scopeType}`);
|
|
16712
17025
|
cols.push("version VARCHAR(36) NOT NULL", `data ${dataType} NOT NULL`, `created_at BIGINT NOT NULL`, `updated_at BIGINT NOT NULL`);
|
|
17026
|
+
if (db === "mysql" && this.memoryVectorKey)
|
|
17027
|
+
cols.push(this.mysqlMemoryVectorColumn(this.memoryVectorKey));
|
|
16713
17028
|
await this.sql.execute(`CREATE TABLE IF NOT EXISTS ${t} (${cols.join(", ")})`);
|
|
16714
17029
|
if (this.gate) {
|
|
16715
17030
|
await this.sql.execute(`CREATE TABLE IF NOT EXISTS ${this.gate} (id INTEGER PRIMARY KEY, marker INTEGER NOT NULL)`);
|
|
@@ -16728,9 +17043,41 @@ var ReldbAIRelStore = class _ReldbAIRelStore {
|
|
|
16728
17043
|
await this.createIndex(`idx_${t}_ref_id`, "ref_id");
|
|
16729
17044
|
if (this.hasUpdatedAtIndex)
|
|
16730
17045
|
await this.createIndex(`idx_${t}_updated_at`, "updated_at, id");
|
|
17046
|
+
if (this.memoryVectorKey)
|
|
17047
|
+
await this.createMemoryVectorIndex(this.memoryVectorKey);
|
|
16731
17048
|
if (this.hasScopeIndex && db === "postgresql")
|
|
16732
17049
|
await this.sql.execute(`CREATE INDEX IF NOT EXISTS idx_${t}_data_gin ON ${t} USING GIN (data jsonb_path_ops)`);
|
|
16733
17050
|
}
|
|
17051
|
+
/** MySQL 在新表中直接创建生成列,已有表在首次升级时添加该列。 */
|
|
17052
|
+
mysqlMemoryVectorColumn(key) {
|
|
17053
|
+
return `${key} VARCHAR(512) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin GENERATED ALWAYS AS (
|
|
17054
|
+
CASE WHEN JSON_TYPE(JSON_EXTRACT(data, '$.vector')) = 'ARRAY'
|
|
17055
|
+
THEN COALESCE(NULLIF(JSON_UNQUOTE(JSON_EXTRACT(data, '$.vectorId')), 'null'), id) END
|
|
17056
|
+
) VIRTUAL`;
|
|
17057
|
+
}
|
|
17058
|
+
/** 索引覆盖旧记录,无需逐条回写。MySQL 查询使用命名生成列以命中索引。 */
|
|
17059
|
+
async createMemoryVectorIndex(key) {
|
|
17060
|
+
const name = `idx_${this.table}_vector_key`;
|
|
17061
|
+
if (this.dbType !== "mysql") {
|
|
17062
|
+
await this.sql.execute(`CREATE INDEX IF NOT EXISTS ${name} ON ${this.table}((${key}))`);
|
|
17063
|
+
return;
|
|
17064
|
+
}
|
|
17065
|
+
const read = async () => requireSqlSuccess(await this.sql.get(
|
|
17066
|
+
"SELECT EXTRA AS extra FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = ?",
|
|
17067
|
+
[this.table, key]
|
|
17068
|
+
)).data;
|
|
17069
|
+
if (!await read()) {
|
|
17070
|
+
try {
|
|
17071
|
+
await this.sql.execute(`ALTER TABLE ${this.table} ADD COLUMN ${this.mysqlMemoryVectorColumn(key)}`);
|
|
17072
|
+
} catch (error) {
|
|
17073
|
+
if (!isMysqlError(error, "ER_DUP_FIELDNAME", 1060))
|
|
17074
|
+
throw error;
|
|
17075
|
+
}
|
|
17076
|
+
}
|
|
17077
|
+
if ((await read())?.extra !== "VIRTUAL GENERATED")
|
|
17078
|
+
throw new Error(aiM("ai_storeIndexMismatch"));
|
|
17079
|
+
await this.createIndex(name, key);
|
|
17080
|
+
}
|
|
16734
17081
|
/**
|
|
16735
17082
|
* MySQL 并发首次创建只接受明确的重复名称错误,并重读结构,权限/DDL/不匹配仍失败。
|
|
16736
17083
|
*/
|
|
@@ -16751,7 +17098,7 @@ var ReldbAIRelStore = class _ReldbAIRelStore {
|
|
|
16751
17098
|
try {
|
|
16752
17099
|
await this.sql.execute(`CREATE INDEX ${name} ON ${this.table}(${columns})`);
|
|
16753
17100
|
} catch (error) {
|
|
16754
|
-
if (!
|
|
17101
|
+
if (!isMysqlError(error, "ER_DUP_KEYNAME", 1061))
|
|
16755
17102
|
throw error;
|
|
16756
17103
|
if (!matches(await read()))
|
|
16757
17104
|
throw new Error(aiM("ai_storeIndexMismatch"), { cause: error });
|
|
@@ -17167,15 +17514,33 @@ async function ensureVecdbCollection(database, name, dimension) {
|
|
|
17167
17514
|
var VecdbAIVectorStore = class {
|
|
17168
17515
|
vecdb;
|
|
17169
17516
|
collection;
|
|
17517
|
+
scan;
|
|
17170
17518
|
constructor(vecdb2, collection) {
|
|
17519
|
+
const config = vecdb2.config;
|
|
17520
|
+
if (config?.type === "pgvector" && Buffer.byteLength(`${config.tablePrefix}${collection}`) > 63)
|
|
17521
|
+
throw new Error(aiM("ai_storeVectorCollectionNameTooLong"));
|
|
17171
17522
|
this.vecdb = vecdb2;
|
|
17172
17523
|
this.collection = collection;
|
|
17524
|
+
const scan = vecdb2.vector.scan?.bind(vecdb2.vector);
|
|
17525
|
+
if (scan) {
|
|
17526
|
+
this.scan = async (options) => {
|
|
17527
|
+
const result = await scan(collection, options);
|
|
17528
|
+
if (!result.success && result.error.code === HaiVecdbError.COLLECTION_NOT_FOUND.code)
|
|
17529
|
+
return { items: [] };
|
|
17530
|
+
return requireVecdbSuccess(result);
|
|
17531
|
+
};
|
|
17532
|
+
}
|
|
17173
17533
|
}
|
|
17174
17534
|
async upsert(id3, vector, metadata) {
|
|
17175
|
-
await
|
|
17176
|
-
requireVecdbSuccess(await this.vecdb.vector.upsert(this.collection, [
|
|
17535
|
+
await this.upsertMany([
|
|
17177
17536
|
{ id: id3, vector, metadata }
|
|
17178
|
-
])
|
|
17537
|
+
]);
|
|
17538
|
+
}
|
|
17539
|
+
async upsertMany(entries) {
|
|
17540
|
+
if (!entries.length)
|
|
17541
|
+
return;
|
|
17542
|
+
await ensureVecdbCollection(this.vecdb, this.collection, entries[0].vector.length);
|
|
17543
|
+
requireVecdbSuccess(await this.vecdb.vector.upsert(this.collection, entries));
|
|
17179
17544
|
}
|
|
17180
17545
|
async search(vector, options) {
|
|
17181
17546
|
return requireVecdbSuccess(await this.vecdb.vector.search(this.collection, vector, options));
|
|
@@ -17185,6 +17550,11 @@ var VecdbAIVectorStore = class {
|
|
|
17185
17550
|
return;
|
|
17186
17551
|
requireVecdbSuccess(await this.vecdb.vector.delete(this.collection, [id3]));
|
|
17187
17552
|
}
|
|
17553
|
+
async removeMany(ids) {
|
|
17554
|
+
const result = await this.vecdb.vector.delete(this.collection, ids);
|
|
17555
|
+
if (!result.success && result.error.code !== HaiVecdbError.COLLECTION_NOT_FOUND.code)
|
|
17556
|
+
requireVecdbSuccess(result);
|
|
17557
|
+
}
|
|
17188
17558
|
async clear(_filter) {
|
|
17189
17559
|
const exists = requireVecdbSuccess(await this.vecdb.collection.exists(this.collection));
|
|
17190
17560
|
if (exists)
|
|
@@ -17241,7 +17611,7 @@ function createDbStoreProvider(deps) {
|
|
|
17241
17611
|
if (result.status === "rejected")
|
|
17242
17612
|
throw result.reason;
|
|
17243
17613
|
}
|
|
17244
|
-
|
|
17614
|
+
logger34.debug("DB store provider initialized", { tableCount: relStores.size });
|
|
17245
17615
|
}
|
|
17246
17616
|
},
|
|
17247
17617
|
async close() {
|
|
@@ -17521,7 +17891,7 @@ function createMemoryStoreProvider() {
|
|
|
17521
17891
|
}
|
|
17522
17892
|
|
|
17523
17893
|
// src/ai-main.ts
|
|
17524
|
-
var
|
|
17894
|
+
var logger35 = core.logger.child({ module: "ai", scope: "main" });
|
|
17525
17895
|
var initInProgress = false;
|
|
17526
17896
|
var initCompletion = null;
|
|
17527
17897
|
var closingPromise = null;
|
|
@@ -17700,7 +18070,7 @@ async function resetAllState() {
|
|
|
17700
18070
|
try {
|
|
17701
18071
|
await storeProvider.close();
|
|
17702
18072
|
} catch (error) {
|
|
17703
|
-
|
|
18073
|
+
logger35.error("AI store provider close failed", { error });
|
|
17704
18074
|
}
|
|
17705
18075
|
}
|
|
17706
18076
|
}
|
|
@@ -17717,7 +18087,7 @@ var streamOperations = {
|
|
|
17717
18087
|
var ai = {
|
|
17718
18088
|
async init(config, options) {
|
|
17719
18089
|
if (initInProgress || closingPromise) {
|
|
17720
|
-
|
|
18090
|
+
logger35.warn("AI init already in progress, skipping concurrent call");
|
|
17721
18091
|
return err(HaiAIError.INIT_IN_PROGRESS, aiM("ai_initInProgress"));
|
|
17722
18092
|
}
|
|
17723
18093
|
initInProgress = true;
|
|
@@ -17728,15 +18098,15 @@ var ai = {
|
|
|
17728
18098
|
let closingPrevious = false;
|
|
17729
18099
|
try {
|
|
17730
18100
|
if (currentConfig) {
|
|
17731
|
-
|
|
18101
|
+
logger35.warn("AI module is already initialized, reinitializing");
|
|
17732
18102
|
closingPrevious = true;
|
|
17733
18103
|
await resetAllState();
|
|
17734
18104
|
closingPrevious = false;
|
|
17735
18105
|
}
|
|
17736
|
-
|
|
18106
|
+
logger35.info("Initializing AI module");
|
|
17737
18107
|
const parseResult = AIConfigSchema.safeParse(config ?? {});
|
|
17738
18108
|
if (!parseResult.success) {
|
|
17739
|
-
|
|
18109
|
+
logger35.error("AI config validation failed", { error: parseResult.error.message });
|
|
17740
18110
|
return err(
|
|
17741
18111
|
HaiAIError.CONFIGURATION_ERROR,
|
|
17742
18112
|
aiM("ai_configError", {
|
|
@@ -17753,7 +18123,7 @@ var ai = {
|
|
|
17753
18123
|
storeProvider = createDbStoreProviderFromModules();
|
|
17754
18124
|
} else {
|
|
17755
18125
|
storeProvider = createMemoryStoreProvider();
|
|
17756
|
-
|
|
18126
|
+
logger35.warn("AI is using the ephemeral in-memory store; initialize reldb and vecdb before ai.init() for persistent data");
|
|
17757
18127
|
}
|
|
17758
18128
|
if (core.module.requiresSharedState(process2.env) && storeProvider.stateScope !== "shared")
|
|
17759
18129
|
return err(HaiAIError.CONFIGURATION_ERROR, aiM("ai_sharedBackendRequired"));
|
|
@@ -17789,17 +18159,17 @@ var ai = {
|
|
|
17789
18159
|
currentA2AConfig = parsed.a2a;
|
|
17790
18160
|
currentA2AStores = subs.a2aStores;
|
|
17791
18161
|
currentConfig = parsed;
|
|
17792
|
-
|
|
18162
|
+
logger35.info("AI module initialized", { model: parsed.llm?.model });
|
|
17793
18163
|
return ok(void 0);
|
|
17794
18164
|
} catch (error) {
|
|
17795
18165
|
if (!closingPrevious) {
|
|
17796
18166
|
try {
|
|
17797
18167
|
await resetAllState();
|
|
17798
18168
|
} catch (cleanupError) {
|
|
17799
|
-
|
|
18169
|
+
logger35.error("AI initialization cleanup failed", { error: cleanupError });
|
|
17800
18170
|
}
|
|
17801
18171
|
}
|
|
17802
|
-
|
|
18172
|
+
logger35.error("AI module initialization failed", { error });
|
|
17803
18173
|
return err(
|
|
17804
18174
|
HaiAIError.CONFIGURATION_ERROR,
|
|
17805
18175
|
aiM("ai_initFailed", {
|
|
@@ -17889,9 +18259,9 @@ var ai = {
|
|
|
17889
18259
|
closingPromise = (async () => {
|
|
17890
18260
|
if (initCompletion)
|
|
17891
18261
|
await initCompletion;
|
|
17892
|
-
|
|
18262
|
+
logger35.info("Closing AI module");
|
|
17893
18263
|
await resetAllState();
|
|
17894
|
-
|
|
18264
|
+
logger35.info("AI module closed");
|
|
17895
18265
|
})().finally(() => {
|
|
17896
18266
|
closingPromise = null;
|
|
17897
18267
|
});
|