@h-ai/ai 1.0.0-beta.27 → 1.0.0-beta.29
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 +3 -1
- package/README.ja.md +3 -1
- package/README.md +3 -1
- package/dist/{ai-acp-types-DZQuumPs.d.ts → ai-acp-types-BTVshtKX.d.ts} +20 -10
- package/dist/browser.d.ts +1 -1
- package/dist/browser.js +1 -1
- package/dist/{chunk-VEWBD2J4.js → chunk-W44R24T2.js} +16 -2
- package/dist/chunk-W44R24T2.js.map +1 -0
- package/dist/index.d.ts +2 -2
- package/dist/index.js +422 -208
- 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-W44R24T2.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-W44R24T2.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(core35) {
|
|
|
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,14 +14306,17 @@ 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" });
|
|
14188
14310
|
var checkpointId = "scan";
|
|
14189
|
-
var
|
|
14311
|
+
var pageSize2 = 64;
|
|
14190
14312
|
var pollMs = 1e3;
|
|
14313
|
+
var wakeMs = 250;
|
|
14314
|
+
var pagesPerBatch = 32;
|
|
14315
|
+
var batchWorkMs = 750;
|
|
14191
14316
|
var roundPauseMs = 5e3;
|
|
14192
14317
|
var failureRetryMs = 2e3;
|
|
14193
|
-
var
|
|
14194
|
-
function createMemoryVectorScan(memory, state, vectors) {
|
|
14318
|
+
var leaseMs2 = 9e4;
|
|
14319
|
+
function createMemoryVectorScan(memory, state, vectors, collection) {
|
|
14195
14320
|
const currentIds = memory.getMemoryVectorIds?.bind(memory);
|
|
14196
14321
|
const scan = vectors.scan?.bind(vectors);
|
|
14197
14322
|
const remove = vectors.removeMany?.bind(vectors);
|
|
@@ -14205,22 +14330,28 @@ function createMemoryVectorScan(memory, state, vectors) {
|
|
|
14205
14330
|
const run = async () => {
|
|
14206
14331
|
const now = await state.currentTime();
|
|
14207
14332
|
const record = await state.readVersioned(checkpointId);
|
|
14208
|
-
if (record && record.data.updatedAt > now) {
|
|
14209
|
-
nextCheck = performance.now() + Math.min(record.data.updatedAt - now, roundPauseMs);
|
|
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);
|
|
14210
14335
|
return;
|
|
14211
14336
|
}
|
|
14212
14337
|
const claim = await write(async (checkpoint) => {
|
|
14213
14338
|
const current = lockedWrite ? await checkpoint.readVersioned(checkpointId) : record;
|
|
14214
14339
|
const claimedAt = lockedWrite ? await checkpoint.currentTime() : now;
|
|
14215
|
-
|
|
14216
|
-
|
|
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);
|
|
14217
14343
|
return void 0;
|
|
14218
14344
|
}
|
|
14219
|
-
const cursor2 = current?.data.cursor;
|
|
14220
|
-
const deadline2 = claimedAt +
|
|
14345
|
+
const cursor2 = matches ? current?.data.cursor : void 0;
|
|
14346
|
+
const deadline2 = claimedAt + leaseMs2;
|
|
14221
14347
|
const version2 = await checkpoint.compareAndSwap(checkpointId, {
|
|
14222
14348
|
expectedVersion: current?.version,
|
|
14223
|
-
data: {
|
|
14349
|
+
data: {
|
|
14350
|
+
collection,
|
|
14351
|
+
cursor: cursor2,
|
|
14352
|
+
updatedAt: deadline2,
|
|
14353
|
+
leased: true
|
|
14354
|
+
}
|
|
14224
14355
|
});
|
|
14225
14356
|
return version2 ? { cursor: cursor2, version: version2, deadline: deadline2 } : void 0;
|
|
14226
14357
|
});
|
|
@@ -14228,32 +14359,58 @@ function createMemoryVectorScan(memory, state, vectors) {
|
|
|
14228
14359
|
nextCheck = Math.max(nextCheck, performance.now() + pollMs);
|
|
14229
14360
|
return;
|
|
14230
14361
|
}
|
|
14231
|
-
|
|
14232
|
-
|
|
14233
|
-
|
|
14234
|
-
|
|
14235
|
-
|
|
14236
|
-
if (
|
|
14237
|
-
|
|
14238
|
-
|
|
14239
|
-
|
|
14240
|
-
|
|
14241
|
-
|
|
14242
|
-
|
|
14243
|
-
const
|
|
14244
|
-
|
|
14245
|
-
|
|
14246
|
-
|
|
14247
|
-
|
|
14248
|
-
|
|
14249
|
-
|
|
14250
|
-
|
|
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
|
+
}
|
|
14251
14407
|
}
|
|
14252
14408
|
await write(async (checkpoint) => {
|
|
14253
14409
|
const completedAt = await checkpoint.currentTime();
|
|
14410
|
+
const nextBatchAt = retryIn === 0 && timer !== void 0 ? Math.max(completedAt, deadline - leaseMs2 + pollMs) : completedAt + retryIn;
|
|
14254
14411
|
await checkpoint.compareAndSwap(checkpointId, {
|
|
14255
14412
|
expectedVersion: version,
|
|
14256
|
-
data: { cursor
|
|
14413
|
+
data: { collection, cursor, updatedAt: nextBatchAt },
|
|
14257
14414
|
notAfter: deadline
|
|
14258
14415
|
});
|
|
14259
14416
|
});
|
|
@@ -14264,14 +14421,14 @@ function createMemoryVectorScan(memory, state, vectors) {
|
|
|
14264
14421
|
return;
|
|
14265
14422
|
active = run().catch(() => {
|
|
14266
14423
|
nextCheck = performance.now() + failureRetryMs;
|
|
14267
|
-
|
|
14424
|
+
logger25.warn("Memory vector scan checkpoint unavailable");
|
|
14268
14425
|
}).finally(() => {
|
|
14269
14426
|
active = void 0;
|
|
14270
14427
|
});
|
|
14271
14428
|
}
|
|
14272
14429
|
return {
|
|
14273
14430
|
start() {
|
|
14274
|
-
timer ??= setInterval(kick,
|
|
14431
|
+
timer ??= setInterval(kick, wakeMs);
|
|
14275
14432
|
timer.unref();
|
|
14276
14433
|
kick();
|
|
14277
14434
|
},
|
|
@@ -14284,7 +14441,7 @@ function createMemoryVectorScan(memory, state, vectors) {
|
|
|
14284
14441
|
}
|
|
14285
14442
|
|
|
14286
14443
|
// src/memory/ai-memory-vector-sync.ts
|
|
14287
|
-
var
|
|
14444
|
+
var logger26 = core.logger.child({ module: "ai", scope: "memory-vector-sync" });
|
|
14288
14445
|
var pollMs2 = 1e3;
|
|
14289
14446
|
var inFlightRetryMs = 45e3;
|
|
14290
14447
|
var lateWriteWindowMs = 6e4;
|
|
@@ -14295,11 +14452,11 @@ function backoff(attempts) {
|
|
|
14295
14452
|
function vectorId(memory) {
|
|
14296
14453
|
return memory.vectorId ?? memory.id;
|
|
14297
14454
|
}
|
|
14298
|
-
function createMemoryVectorSync(store, queue, vectors, scanStore) {
|
|
14455
|
+
function createMemoryVectorSync(store, queue, vectors, scanStore, collection) {
|
|
14299
14456
|
const lock = store.withRelatedWriteLock?.bind(store);
|
|
14300
14457
|
if (!lock || !queue.queryKeys)
|
|
14301
14458
|
return void 0;
|
|
14302
|
-
const scan = scanStore && createMemoryVectorScan(store, scanStore, vectors);
|
|
14459
|
+
const scan = scanStore && createMemoryVectorScan(store, scanStore, vectors, collection);
|
|
14303
14460
|
function write(run) {
|
|
14304
14461
|
return lock(queue, run);
|
|
14305
14462
|
}
|
|
@@ -14343,7 +14500,7 @@ function createMemoryVectorSync(store, queue, vectors, scanStore) {
|
|
|
14343
14500
|
}
|
|
14344
14501
|
succeeded = true;
|
|
14345
14502
|
} catch {
|
|
14346
|
-
|
|
14503
|
+
logger26.debug("Memory vector sync will retry", {
|
|
14347
14504
|
operation: claimed.entry ? "upsert" : "delete"
|
|
14348
14505
|
});
|
|
14349
14506
|
}
|
|
@@ -14389,7 +14546,7 @@ function createMemoryVectorSync(store, queue, vectors, scanStore) {
|
|
|
14389
14546
|
function kick() {
|
|
14390
14547
|
if (timer && !active) {
|
|
14391
14548
|
active = drain().catch(() => {
|
|
14392
|
-
|
|
14549
|
+
logger26.warn("Memory vector compensation storage unavailable");
|
|
14393
14550
|
}).finally(() => {
|
|
14394
14551
|
active = void 0;
|
|
14395
14552
|
});
|
|
@@ -14437,7 +14594,7 @@ function createMemoryVectorSync(store, queue, vectors, scanStore) {
|
|
|
14437
14594
|
}
|
|
14438
14595
|
|
|
14439
14596
|
// src/memory/providers/ai-memory-provider-native.ts
|
|
14440
|
-
var
|
|
14597
|
+
var logger27 = core.logger.child({ module: "ai", scope: "memory-native" });
|
|
14441
14598
|
var EVICTION_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1e3;
|
|
14442
14599
|
var EVICTION_CANDIDATES = 64;
|
|
14443
14600
|
function generateId() {
|
|
@@ -14465,8 +14622,8 @@ function matchScope2(entry, scope) {
|
|
|
14465
14622
|
return false;
|
|
14466
14623
|
return Object.entries(scope).every(([k, v]) => entry.scope[k] === v);
|
|
14467
14624
|
}
|
|
14468
|
-
function assembleNativeMemory(config, llm, embedding, store, vectorStore, vectorQueue, vectorScan) {
|
|
14469
|
-
const sync = vectorQueue && createMemoryVectorSync(store, vectorQueue, vectorStore, vectorScan);
|
|
14625
|
+
function assembleNativeMemory(config, llm, embedding, store, vectorStore, vectorQueue, vectorScan, vectorCollection) {
|
|
14626
|
+
const sync = vectorQueue && createMemoryVectorSync(store, vectorQueue, vectorStore, vectorScan, vectorCollection);
|
|
14470
14627
|
const maxPending = Math.max(1024, config.maxEntriesGlobal * 2);
|
|
14471
14628
|
async function ensureVectorCapacity(pending) {
|
|
14472
14629
|
if (pending && await pending.count() >= maxPending)
|
|
@@ -14485,7 +14642,7 @@ function assembleNativeMemory(config, llm, embedding, store, vectorStore, vector
|
|
|
14485
14642
|
try {
|
|
14486
14643
|
return await operation();
|
|
14487
14644
|
} catch (error) {
|
|
14488
|
-
|
|
14645
|
+
logger27.error("Memory storage operation failed", {
|
|
14489
14646
|
error: core.sanitize.sanitizeSensitiveFields(error)
|
|
14490
14647
|
});
|
|
14491
14648
|
return err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryOperationFailed"));
|
|
@@ -14517,7 +14674,7 @@ function assembleNativeMemory(config, llm, embedding, store, vectorStore, vector
|
|
|
14517
14674
|
const result = await embedding.embedText(text);
|
|
14518
14675
|
if (result.success)
|
|
14519
14676
|
return result.data;
|
|
14520
|
-
|
|
14677
|
+
logger27.warn("Failed to compute embedding for memory", { error: result.error });
|
|
14521
14678
|
return void 0;
|
|
14522
14679
|
}
|
|
14523
14680
|
async function evictLowest(activeStore, candidates, count, pending) {
|
|
@@ -14654,10 +14811,10 @@ function assembleNativeMemory(config, llm, embedding, store, vectorStore, vector
|
|
|
14654
14811
|
params: { id: memoryId }
|
|
14655
14812
|
}));
|
|
14656
14813
|
}
|
|
14657
|
-
|
|
14814
|
+
logger27.trace("Memory updated", { id: memoryId });
|
|
14658
14815
|
return ok(existing);
|
|
14659
14816
|
} catch (error) {
|
|
14660
|
-
|
|
14817
|
+
logger27.error("Memory update failed", {
|
|
14661
14818
|
id: memoryId,
|
|
14662
14819
|
error: core.sanitize.sanitizeSensitiveFields(error)
|
|
14663
14820
|
});
|
|
@@ -14668,7 +14825,7 @@ function assembleNativeMemory(config, llm, embedding, store, vectorStore, vector
|
|
|
14668
14825
|
const topK = options?.topK ?? config.defaultTopK;
|
|
14669
14826
|
const recencyWeight = options?.recencyWeight ?? 1 - config.recencyDecay;
|
|
14670
14827
|
const candidateMultiplier = Math.max(1, options?.candidateMultiplier ?? config.candidateMultiplier);
|
|
14671
|
-
|
|
14828
|
+
logger27.trace("Recalling memories", {
|
|
14672
14829
|
query: query.slice(0, 100),
|
|
14673
14830
|
topK,
|
|
14674
14831
|
updateAccessStats
|
|
@@ -14712,7 +14869,7 @@ function assembleNativeMemory(config, llm, embedding, store, vectorStore, vector
|
|
|
14712
14869
|
} catch (error) {
|
|
14713
14870
|
if (!sync)
|
|
14714
14871
|
throw error;
|
|
14715
|
-
|
|
14872
|
+
logger27.debug("Memory vector search unavailable; using persisted embeddings");
|
|
14716
14873
|
}
|
|
14717
14874
|
}
|
|
14718
14875
|
const now = Date.now();
|
|
@@ -14742,14 +14899,14 @@ function assembleNativeMemory(config, llm, embedding, store, vectorStore, vector
|
|
|
14742
14899
|
}
|
|
14743
14900
|
results.push(publicEntry(entry));
|
|
14744
14901
|
}
|
|
14745
|
-
|
|
14902
|
+
logger27.trace("Memory recall completed", {
|
|
14746
14903
|
query: query.slice(0, 50),
|
|
14747
14904
|
resultCount: results.length,
|
|
14748
14905
|
updateAccessStats
|
|
14749
14906
|
});
|
|
14750
14907
|
return ok(results);
|
|
14751
14908
|
} catch (error) {
|
|
14752
|
-
|
|
14909
|
+
logger27.error("Memory recall failed", {
|
|
14753
14910
|
error: core.sanitize.sanitizeSensitiveFields(error)
|
|
14754
14911
|
});
|
|
14755
14912
|
return err(HaiAIError.MEMORY_RECALL_FAILED, aiM("ai_memoryOperationFailed"));
|
|
@@ -14801,10 +14958,10 @@ function assembleNativeMemory(config, llm, embedding, store, vectorStore, vector
|
|
|
14801
14958
|
const stored = await saveEntry(entry, vector);
|
|
14802
14959
|
if (!stored)
|
|
14803
14960
|
return err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryOperationFailed"));
|
|
14804
|
-
|
|
14961
|
+
logger27.trace("Memory added", { id: stored.id, type: stored.type });
|
|
14805
14962
|
return ok(stored);
|
|
14806
14963
|
} catch (error) {
|
|
14807
|
-
|
|
14964
|
+
logger27.error("Memory add failed", {
|
|
14808
14965
|
error: core.sanitize.sanitizeSensitiveFields(error)
|
|
14809
14966
|
});
|
|
14810
14967
|
return err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryOperationFailed"));
|
|
@@ -14851,7 +15008,7 @@ function assembleNativeMemory(config, llm, embedding, store, vectorStore, vector
|
|
|
14851
15008
|
params: { id: memoryId }
|
|
14852
15009
|
}));
|
|
14853
15010
|
}
|
|
14854
|
-
|
|
15011
|
+
logger27.trace("Memory removed", { id: memoryId });
|
|
14855
15012
|
return ok(void 0);
|
|
14856
15013
|
},
|
|
14857
15014
|
/**
|
|
@@ -14937,7 +15094,7 @@ function assembleNativeMemory(config, llm, embedding, store, vectorStore, vector
|
|
|
14937
15094
|
if (!sync && !options?.types && !options?.objectId && !options?.scope) {
|
|
14938
15095
|
await vectorStore.clear();
|
|
14939
15096
|
await store.clear();
|
|
14940
|
-
|
|
15097
|
+
logger27.debug("All memories cleared");
|
|
14941
15098
|
return ok(void 0);
|
|
14942
15099
|
}
|
|
14943
15100
|
const where = {};
|
|
@@ -14968,7 +15125,7 @@ function assembleNativeMemory(config, llm, embedding, store, vectorStore, vector
|
|
|
14968
15125
|
throw new Error("Memory store did not advance the primary-key cursor");
|
|
14969
15126
|
afterId = batch.nextId;
|
|
14970
15127
|
}
|
|
14971
|
-
|
|
15128
|
+
logger27.debug("Memories cleared", {
|
|
14972
15129
|
removed: removed2,
|
|
14973
15130
|
objectId: options?.objectId,
|
|
14974
15131
|
types: options?.types,
|
|
@@ -14989,7 +15146,7 @@ function assembleNativeMemory(config, llm, embedding, store, vectorStore, vector
|
|
|
14989
15146
|
}
|
|
14990
15147
|
};
|
|
14991
15148
|
}
|
|
14992
|
-
var
|
|
15149
|
+
var logger28 = core.logger.child({ module: "ai", scope: "persona" });
|
|
14993
15150
|
var DEFAULT_OBJECT_ID2 = "system";
|
|
14994
15151
|
function personaKey(objectId, id3) {
|
|
14995
15152
|
return JSON.stringify([objectId, id3]);
|
|
@@ -15008,7 +15165,7 @@ function createPersonaOperations(store) {
|
|
|
15008
15165
|
try {
|
|
15009
15166
|
return await operation();
|
|
15010
15167
|
} catch (error) {
|
|
15011
|
-
|
|
15168
|
+
logger28.error("Persona storage operation failed", {
|
|
15012
15169
|
error: core.sanitize.sanitizeSensitiveFields(error)
|
|
15013
15170
|
});
|
|
15014
15171
|
return err(HaiAIError.PERSONA_SAVE_FAILED, aiM("ai_personaOperationFailed"));
|
|
@@ -15032,10 +15189,10 @@ function createPersonaOperations(store) {
|
|
|
15032
15189
|
updatedAt: now
|
|
15033
15190
|
};
|
|
15034
15191
|
await store.save(key, profile, { objectId });
|
|
15035
|
-
|
|
15192
|
+
logger28.trace("Persona saved", { id: profile.id, objectId });
|
|
15036
15193
|
return ok(profile);
|
|
15037
15194
|
} catch (error) {
|
|
15038
|
-
|
|
15195
|
+
logger28.error("Persona save failed", {
|
|
15039
15196
|
error: core.sanitize.sanitizeSensitiveFields(error)
|
|
15040
15197
|
});
|
|
15041
15198
|
return err(HaiAIError.PERSONA_SAVE_FAILED, aiM("ai_personaOperationFailed"));
|
|
@@ -15072,7 +15229,7 @@ function createPersonaOperations(store) {
|
|
|
15072
15229
|
await store.save(key, profile, { objectId });
|
|
15073
15230
|
return ok(profile);
|
|
15074
15231
|
} catch (error) {
|
|
15075
|
-
|
|
15232
|
+
logger28.error("Persona update failed", {
|
|
15076
15233
|
error: core.sanitize.sanitizeSensitiveFields(error)
|
|
15077
15234
|
});
|
|
15078
15235
|
return err(HaiAIError.PERSONA_SAVE_FAILED, aiM("ai_personaOperationFailed"));
|
|
@@ -15111,7 +15268,7 @@ function createPersonaOperations(store) {
|
|
|
15111
15268
|
compose: (id3, options) => protect(() => operations2.compose(id3, options))
|
|
15112
15269
|
};
|
|
15113
15270
|
}
|
|
15114
|
-
var
|
|
15271
|
+
var logger29 = core.logger.child({ module: "ai", scope: "rag" });
|
|
15115
15272
|
var DEFAULT_RAG_SYSTEM_PROMPT = `You are a helpful assistant. Answer the user's question based on the provided context.
|
|
15116
15273
|
If the context doesn't contain relevant information, say so honestly.
|
|
15117
15274
|
When using information from the context, cite the source by its number, e.g. [1] or [2].`;
|
|
@@ -15140,7 +15297,7 @@ function createRagOperations(llm, retrieval) {
|
|
|
15140
15297
|
* @returns `ok(RagResult)` 含 answer、context 列表与引用信源;检索或生成失败时返回错误
|
|
15141
15298
|
*/
|
|
15142
15299
|
async query(query, options) {
|
|
15143
|
-
|
|
15300
|
+
logger29.trace("Starting RAG query", {
|
|
15144
15301
|
query: query.slice(0, 100)
|
|
15145
15302
|
});
|
|
15146
15303
|
try {
|
|
@@ -15195,7 +15352,7 @@ ${contextText}
|
|
|
15195
15352
|
}
|
|
15196
15353
|
const choice = chatResult.data.choices[0];
|
|
15197
15354
|
const answer = choice?.message?.content ?? "";
|
|
15198
|
-
|
|
15355
|
+
logger29.trace("RAG query completed", {
|
|
15199
15356
|
contextCount: contextItems.length,
|
|
15200
15357
|
model: chatResult.data.model
|
|
15201
15358
|
});
|
|
@@ -15222,7 +15379,7 @@ ${contextText}
|
|
|
15222
15379
|
} : void 0
|
|
15223
15380
|
});
|
|
15224
15381
|
} catch (error) {
|
|
15225
|
-
|
|
15382
|
+
logger29.error("RAG query failed", { error });
|
|
15226
15383
|
return err(HaiAIError.RAG_FAILED, aiM("ai_internalError", {
|
|
15227
15384
|
params: {
|
|
15228
15385
|
error: String(error)
|
|
@@ -15234,7 +15391,7 @@ ${contextText}
|
|
|
15234
15391
|
* 流式 RAG 查询:先产出 context,再逐 chunk 产出 delta,最后 done
|
|
15235
15392
|
*/
|
|
15236
15393
|
async *queryStream(query, options) {
|
|
15237
|
-
|
|
15394
|
+
logger29.trace("Starting RAG stream", {
|
|
15238
15395
|
query: query.slice(0, 100)
|
|
15239
15396
|
});
|
|
15240
15397
|
const retrieveResult = await retrieval.retrieve({
|
|
@@ -15318,7 +15475,7 @@ ${contextText}
|
|
|
15318
15475
|
}
|
|
15319
15476
|
};
|
|
15320
15477
|
}
|
|
15321
|
-
var
|
|
15478
|
+
var logger30 = core.logger.child({ module: "ai", scope: "reasoning" });
|
|
15322
15479
|
var REACT_SYSTEM_PROMPT = `You are a reasoning agent that follows the ReAct (Reasoning and Acting) framework.
|
|
15323
15480
|
For each step:
|
|
15324
15481
|
1. Think: Analyze what you know and what you need to find out.
|
|
@@ -15568,7 +15725,7 @@ ${query}` }
|
|
|
15568
15725
|
return {
|
|
15569
15726
|
async run(query, options) {
|
|
15570
15727
|
const strategy = options?.strategy ?? "react";
|
|
15571
|
-
|
|
15728
|
+
logger30.trace("Starting reasoning", { strategy, maxRounds: options?.maxRounds });
|
|
15572
15729
|
try {
|
|
15573
15730
|
switch (strategy) {
|
|
15574
15731
|
case "react":
|
|
@@ -15583,7 +15740,7 @@ ${query}` }
|
|
|
15583
15740
|
}));
|
|
15584
15741
|
}
|
|
15585
15742
|
} catch (error) {
|
|
15586
|
-
|
|
15743
|
+
logger30.error("Reasoning failed", { error });
|
|
15587
15744
|
return err(HaiAIError.REASONING_FAILED, aiM("ai_internalError", {
|
|
15588
15745
|
params: {
|
|
15589
15746
|
error: String(error)
|
|
@@ -15615,7 +15772,7 @@ ${query}` }
|
|
|
15615
15772
|
}
|
|
15616
15773
|
};
|
|
15617
15774
|
}
|
|
15618
|
-
var
|
|
15775
|
+
var logger31 = core.logger.child({ module: "ai", scope: "rerank" });
|
|
15619
15776
|
function createRerankOperations(config, loadModels = () => config.llm) {
|
|
15620
15777
|
function normalizeDocuments(documents) {
|
|
15621
15778
|
if (documents.length === 0) {
|
|
@@ -15660,7 +15817,7 @@ function createRerankOperations(config, loadModels = () => config.llm) {
|
|
|
15660
15817
|
if (request2.returnDocuments) {
|
|
15661
15818
|
body.return_documents = true;
|
|
15662
15819
|
}
|
|
15663
|
-
|
|
15820
|
+
logger31.trace("Calling rerank API", { model: resolved.model, documentCount: texts.length, topN: request2.topN });
|
|
15664
15821
|
try {
|
|
15665
15822
|
const response = await fetch(`${resolved.baseUrl}/v1/rerank`, {
|
|
15666
15823
|
method: "POST",
|
|
@@ -15675,7 +15832,7 @@ function createRerankOperations(config, loadModels = () => config.llm) {
|
|
|
15675
15832
|
const requestId = response.headers.get("x-request-id");
|
|
15676
15833
|
await response.body?.cancel().catch(() => {
|
|
15677
15834
|
});
|
|
15678
|
-
|
|
15835
|
+
logger31.error("Rerank API request failed", {
|
|
15679
15836
|
status: response.status,
|
|
15680
15837
|
providerRequestId: requestId && /^[\w.:-]{1,128}$/.test(requestId) ? requestId : void 0
|
|
15681
15838
|
});
|
|
@@ -15690,11 +15847,11 @@ function createRerankOperations(config, loadModels = () => config.llm) {
|
|
|
15690
15847
|
relevanceScore: item2.relevance_score,
|
|
15691
15848
|
document: item2.document?.text
|
|
15692
15849
|
}));
|
|
15693
|
-
|
|
15850
|
+
logger31.trace("Rerank completed", { resultCount: results.length });
|
|
15694
15851
|
return ok({ model: resolved.model, results });
|
|
15695
15852
|
} catch (error) {
|
|
15696
15853
|
const causeName = error instanceof Error ? error.name : void 0;
|
|
15697
|
-
|
|
15854
|
+
logger31.error("Rerank API call failed", { causeName });
|
|
15698
15855
|
return err(HaiAIError.RERANK_API_ERROR, aiM("ai_rerankApiFailed", {
|
|
15699
15856
|
params: {
|
|
15700
15857
|
error: causeName ?? core.i18n.coreM("core_errorInternal")
|
|
@@ -15730,7 +15887,7 @@ function createRerankOperations(config, loadModels = () => config.llm) {
|
|
|
15730
15887
|
}
|
|
15731
15888
|
};
|
|
15732
15889
|
}
|
|
15733
|
-
var
|
|
15890
|
+
var logger32 = core.logger.child({ module: "ai", scope: "retrieval" });
|
|
15734
15891
|
function createRetrievalOperations(embeddingOps, storeProvider, sourceStore, rerankOps, registry) {
|
|
15735
15892
|
const vectorStoreCache = /* @__PURE__ */ new Map();
|
|
15736
15893
|
function getVectorStore(collection) {
|
|
@@ -15763,7 +15920,7 @@ function createRetrievalOperations(embeddingOps, storeProvider, sourceStore, rer
|
|
|
15763
15920
|
}));
|
|
15764
15921
|
}
|
|
15765
15922
|
await sourceStore.save(source.id, source);
|
|
15766
|
-
|
|
15923
|
+
logger32.debug("Retrieval source added", { sourceId: source.id, collection: source.collection });
|
|
15767
15924
|
return ok(void 0);
|
|
15768
15925
|
},
|
|
15769
15926
|
/**
|
|
@@ -15784,7 +15941,7 @@ function createRetrievalOperations(embeddingOps, storeProvider, sourceStore, rer
|
|
|
15784
15941
|
}));
|
|
15785
15942
|
}
|
|
15786
15943
|
await sourceStore.remove(sourceId);
|
|
15787
|
-
|
|
15944
|
+
logger32.debug("Retrieval source removed", { sourceId });
|
|
15788
15945
|
return ok(void 0);
|
|
15789
15946
|
},
|
|
15790
15947
|
/**
|
|
@@ -15871,21 +16028,21 @@ function createRetrievalOperations(embeddingOps, storeProvider, sourceStore, rer
|
|
|
15871
16028
|
allItems.length = 0;
|
|
15872
16029
|
allItems.push(...reranked);
|
|
15873
16030
|
} else {
|
|
15874
|
-
|
|
16031
|
+
logger32.warn("Rerank failed, falling back to vector scores", { error: rerankResult.error });
|
|
15875
16032
|
}
|
|
15876
16033
|
}
|
|
15877
16034
|
allItems.sort((a, b) => b.score - a.score);
|
|
15878
16035
|
const topK = request2.topK ?? 10;
|
|
15879
16036
|
const limitedItems = allItems.slice(0, topK);
|
|
15880
16037
|
const duration = Date.now() - startTime;
|
|
15881
|
-
|
|
16038
|
+
logger32.trace("Retrieval completed", { queryLength: request2.query.length, resultCount: limitedItems.length, duration });
|
|
15882
16039
|
return ok({
|
|
15883
16040
|
items: limitedItems,
|
|
15884
16041
|
query: request2.query,
|
|
15885
16042
|
duration
|
|
15886
16043
|
});
|
|
15887
16044
|
} catch (error) {
|
|
15888
|
-
|
|
16045
|
+
logger32.error("Retrieval failed", { error });
|
|
15889
16046
|
return err(HaiAIError.RETRIEVAL_FAILED, aiM("ai_internalError", {
|
|
15890
16047
|
params: {
|
|
15891
16048
|
error: String(error)
|
|
@@ -15895,7 +16052,7 @@ function createRetrievalOperations(embeddingOps, storeProvider, sourceStore, rer
|
|
|
15895
16052
|
}
|
|
15896
16053
|
};
|
|
15897
16054
|
}
|
|
15898
|
-
var
|
|
16055
|
+
var logger33 = core.logger.child({ module: "ai", scope: "summary" });
|
|
15899
16056
|
var SUMMARIZE_SYSTEM_PROMPT = `You are a conversation summarizer. Create a concise summary of the conversation that preserves:
|
|
15900
16057
|
1. Key facts and decisions made
|
|
15901
16058
|
2. Important context and background information
|
|
@@ -15953,7 +16110,7 @@ ${INCREMENTAL_SUMMARIZE_SUFFIX.replace("{previousSummary}", options.previousSumm
|
|
|
15953
16110
|
return ok(chatResult.data.choices[0]?.message?.content ?? "");
|
|
15954
16111
|
}
|
|
15955
16112
|
async function summarize(messages, options) {
|
|
15956
|
-
|
|
16113
|
+
logger33.trace("Summarizing messages", { messageCount: messages.length });
|
|
15957
16114
|
try {
|
|
15958
16115
|
const result = await generate(messages, options);
|
|
15959
16116
|
if (!result.success)
|
|
@@ -15965,7 +16122,7 @@ ${INCREMENTAL_SUMMARIZE_SUFFIX.replace("{previousSummary}", options.previousSumm
|
|
|
15965
16122
|
coveredMessages: messages.filter((m) => m.role !== "system").length
|
|
15966
16123
|
});
|
|
15967
16124
|
} catch (error) {
|
|
15968
|
-
|
|
16125
|
+
logger33.error("Context summarization failed", { error });
|
|
15969
16126
|
return err(HaiAIError.CONTEXT_SUMMARIZE_FAILED, aiM("ai_contextSummarizeFailed", {
|
|
15970
16127
|
params: {
|
|
15971
16128
|
error: String(error)
|
|
@@ -16044,8 +16201,8 @@ async function createAISubsystems(config, deps) {
|
|
|
16044
16201
|
{ hasObjectId: true }
|
|
16045
16202
|
);
|
|
16046
16203
|
const a2aStores = config.a2a ? createA2AStores(storeProvider) : null;
|
|
16047
|
-
const
|
|
16048
|
-
const memoryVectorScan = memoryStore?.getMemoryVectorIds
|
|
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;
|
|
16049
16206
|
let registriesOpen = true;
|
|
16050
16207
|
const isOpen = () => registriesOpen;
|
|
16051
16208
|
const llmModels = createResourceRegistry(
|
|
@@ -16155,6 +16312,9 @@ async function createAISubsystems(config, deps) {
|
|
|
16155
16312
|
deps.acpPolicy
|
|
16156
16313
|
);
|
|
16157
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;
|
|
16158
16318
|
const llmFunctions = createAILLMFunctions(config, {
|
|
16159
16319
|
recordStore: chatRecordStore,
|
|
16160
16320
|
sessionStore,
|
|
@@ -16210,7 +16370,7 @@ async function createAISubsystems(config, deps) {
|
|
|
16210
16370
|
datapipeDep,
|
|
16211
16371
|
knowledgeStore
|
|
16212
16372
|
);
|
|
16213
|
-
const nativeMemory = memoryStore && memoryVectorStore ? assembleNativeMemory(memoryParsed, llm, embedding, memoryStore, memoryVectorStore, memoryVectorQueue, memoryVectorScan) : void 0;
|
|
16373
|
+
const nativeMemory = memoryStore && memoryVectorStore ? assembleNativeMemory(memoryParsed, llm, embedding, memoryStore, memoryVectorStore, memoryVectorQueue, memoryVectorScan, memoryCollection) : void 0;
|
|
16214
16374
|
const memoryCore = nativeMemory?.operations ?? await createMem0MemoryOperations({
|
|
16215
16375
|
config: memoryParsed,
|
|
16216
16376
|
embedding,
|
|
@@ -16319,11 +16479,15 @@ async function createAISubsystems(config, deps) {
|
|
|
16319
16479
|
services: mcpServices.operations
|
|
16320
16480
|
});
|
|
16321
16481
|
nativeMemory?.sync?.start();
|
|
16482
|
+
memoryVectorRebuild?.start();
|
|
16322
16483
|
return {
|
|
16323
16484
|
closeRegistries: async () => {
|
|
16324
16485
|
mcpServices.close();
|
|
16325
16486
|
registriesOpen = false;
|
|
16326
|
-
await
|
|
16487
|
+
await Promise.all([
|
|
16488
|
+
nativeMemory?.sync?.close(),
|
|
16489
|
+
memoryVectorRebuild?.close()
|
|
16490
|
+
]);
|
|
16327
16491
|
},
|
|
16328
16492
|
a2aStores,
|
|
16329
16493
|
llm,
|
|
@@ -16720,13 +16884,14 @@ function documentInfo(document) {
|
|
|
16720
16884
|
}
|
|
16721
16885
|
|
|
16722
16886
|
// src/store/providers/ai-store-provider-db.ts
|
|
16723
|
-
var
|
|
16887
|
+
var logger34 = core.logger.child({ module: "ai", scope: "store-provider-db" });
|
|
16724
16888
|
function requireSqlSuccess(result) {
|
|
16725
16889
|
if (!result.success)
|
|
16726
16890
|
throw new Error(result.error.message, { cause: result.error });
|
|
16727
16891
|
return result;
|
|
16728
16892
|
}
|
|
16729
16893
|
var MAX_BATCH_SQL_PARAMS = 900;
|
|
16894
|
+
var POSTGRES_SCHEMA_LOCK = "hai:ai:store-schema";
|
|
16730
16895
|
function dataTimestamp(data, field, fallback) {
|
|
16731
16896
|
if (typeof data !== "object" || data === null)
|
|
16732
16897
|
return fallback;
|
|
@@ -16769,6 +16934,7 @@ var ReldbAIRelStore = class _ReldbAIRelStore {
|
|
|
16769
16934
|
withWriteLock;
|
|
16770
16935
|
withRelatedWriteLock;
|
|
16771
16936
|
getMemoryVectorIds;
|
|
16937
|
+
readMemoryVectorPage;
|
|
16772
16938
|
constructor(sql, table, jsonOps, dbType, options, tx) {
|
|
16773
16939
|
this.connection = sql;
|
|
16774
16940
|
this.sql = {
|
|
@@ -16802,6 +16968,17 @@ var ReldbAIRelStore = class _ReldbAIRelStore {
|
|
|
16802
16968
|
return requireSqlSuccess(await tx.wrap(readIds)).data;
|
|
16803
16969
|
return readIds(this.sql);
|
|
16804
16970
|
};
|
|
16971
|
+
this.readMemoryVectorPage = async (afterId, limit) => {
|
|
16972
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > 128)
|
|
16973
|
+
throw new RangeError("Invalid memory vector rebuild page size");
|
|
16974
|
+
const readPage = async (connection) => requireSqlSuccess(await connection.query(
|
|
16975
|
+
`SELECT data FROM ${table} WHERE id > ? AND ${key} IS NOT NULL ORDER BY id ASC LIMIT ?`,
|
|
16976
|
+
[afterId, limit]
|
|
16977
|
+
)).data.map((row) => this.decodeData(row.data));
|
|
16978
|
+
if (dbType === "sqlite" && tx)
|
|
16979
|
+
return requireSqlSuccess(await tx.wrap(readPage)).data;
|
|
16980
|
+
return readPage(this.sql);
|
|
16981
|
+
};
|
|
16805
16982
|
}
|
|
16806
16983
|
if (options?.serializeWrites && tx) {
|
|
16807
16984
|
const gate = `${table}_write_gate`;
|
|
@@ -16831,9 +17008,10 @@ var ReldbAIRelStore = class _ReldbAIRelStore {
|
|
|
16831
17008
|
}
|
|
16832
17009
|
}
|
|
16833
17010
|
/** 创建表及索引(幂等) */
|
|
16834
|
-
async createTable() {
|
|
17011
|
+
async createTable(connection = this.connection) {
|
|
16835
17012
|
const t = this.table;
|
|
16836
17013
|
const db = this.dbType;
|
|
17014
|
+
const execute2 = async (statement) => requireSqlSuccess(await connection.execute(statement));
|
|
16837
17015
|
const idType = db === "mysql" ? "VARCHAR(512)" : "TEXT";
|
|
16838
17016
|
const scopeType = db === "mysql" ? "VARCHAR(255)" : "TEXT";
|
|
16839
17017
|
const dataType = db === "postgresql" ? "JSONB" : db === "mysql" ? "JSON" : "TEXT";
|
|
@@ -16849,28 +17027,51 @@ var ReldbAIRelStore = class _ReldbAIRelStore {
|
|
|
16849
17027
|
cols.push("version VARCHAR(36) NOT NULL", `data ${dataType} NOT NULL`, `created_at BIGINT NOT NULL`, `updated_at BIGINT NOT NULL`);
|
|
16850
17028
|
if (db === "mysql" && this.memoryVectorKey)
|
|
16851
17029
|
cols.push(this.mysqlMemoryVectorColumn(this.memoryVectorKey));
|
|
16852
|
-
await
|
|
17030
|
+
await execute2(`CREATE TABLE IF NOT EXISTS ${t} (${cols.join(", ")})`);
|
|
16853
17031
|
if (this.gate) {
|
|
16854
|
-
await
|
|
17032
|
+
await execute2(`CREATE TABLE IF NOT EXISTS ${this.gate} (id INTEGER PRIMARY KEY, marker INTEGER NOT NULL)`);
|
|
16855
17033
|
const conflict = db === "mysql" ? "ON DUPLICATE KEY UPDATE id = id" : "ON CONFLICT(id) DO NOTHING";
|
|
16856
|
-
await
|
|
17034
|
+
await execute2(`INSERT INTO ${this.gate} (id, marker) VALUES (1, 0) ${conflict}`);
|
|
16857
17035
|
}
|
|
17036
|
+
const indexes = [];
|
|
16858
17037
|
if (this.hasObjectId)
|
|
16859
|
-
|
|
17038
|
+
indexes.push(["object_id", "object_id"]);
|
|
16860
17039
|
if (this.hasSessionId)
|
|
16861
|
-
|
|
17040
|
+
indexes.push(["session_id", "session_id"]);
|
|
16862
17041
|
if (this.hasObjectId && this.hasSessionId)
|
|
16863
|
-
|
|
17042
|
+
indexes.push(["object_session", "object_id, session_id"]);
|
|
16864
17043
|
if (this.hasStatus)
|
|
16865
|
-
|
|
17044
|
+
indexes.push(["status", "status"]);
|
|
16866
17045
|
if (this.hasRefId)
|
|
16867
|
-
|
|
17046
|
+
indexes.push(["ref_id", "ref_id"]);
|
|
16868
17047
|
if (this.hasUpdatedAtIndex)
|
|
16869
|
-
|
|
16870
|
-
if (this.memoryVectorKey)
|
|
16871
|
-
|
|
17048
|
+
indexes.push(["updated_at", "updated_at, id"]);
|
|
17049
|
+
if (this.memoryVectorKey && db !== "mysql")
|
|
17050
|
+
indexes.push(["vector_key", `(${this.memoryVectorKey})`]);
|
|
16872
17051
|
if (this.hasScopeIndex && db === "postgresql")
|
|
16873
|
-
|
|
17052
|
+
indexes.push(["data_gin", "data jsonb_path_ops", "GIN"]);
|
|
17053
|
+
const existing = db === "postgresql" && indexes.length > 0 ? requireSqlSuccess(await connection.query(`
|
|
17054
|
+
SELECT c.relname AS name, i.indisvalid AS valid FROM pg_catalog.pg_index AS i
|
|
17055
|
+
JOIN pg_catalog.pg_class AS c ON c.oid = i.indexrelid
|
|
17056
|
+
WHERE i.indrelid = pg_catalog.to_regclass(?)
|
|
17057
|
+
`, [t])).data : [];
|
|
17058
|
+
const existingIndexes = new Map(existing.map((row) => [row.name, row.valid]));
|
|
17059
|
+
for (const [suffix, columns, method] of indexes) {
|
|
17060
|
+
const name = `idx_${t}_${suffix}`;
|
|
17061
|
+
if (db === "mysql") {
|
|
17062
|
+
await this.createMysqlIndex(name, columns);
|
|
17063
|
+
continue;
|
|
17064
|
+
}
|
|
17065
|
+
if (existingIndexes.get(name) === false)
|
|
17066
|
+
throw new Error(aiM("ai_storeIndexMismatch"));
|
|
17067
|
+
if (existingIndexes.has(name))
|
|
17068
|
+
continue;
|
|
17069
|
+
const ifMissing = db === "sqlite" ? "IF NOT EXISTS " : "";
|
|
17070
|
+
const using = method ? ` USING ${method}` : "";
|
|
17071
|
+
await execute2(`CREATE INDEX ${ifMissing}${name} ON ${t}${using} (${columns})`);
|
|
17072
|
+
}
|
|
17073
|
+
if (db === "mysql" && this.memoryVectorKey)
|
|
17074
|
+
await this.createMysqlMemoryVectorIndex(this.memoryVectorKey);
|
|
16874
17075
|
}
|
|
16875
17076
|
/** MySQL 在新表中直接创建生成列,已有表在首次升级时添加该列。 */
|
|
16876
17077
|
mysqlMemoryVectorColumn(key) {
|
|
@@ -16880,12 +17081,8 @@ var ReldbAIRelStore = class _ReldbAIRelStore {
|
|
|
16880
17081
|
) VIRTUAL`;
|
|
16881
17082
|
}
|
|
16882
17083
|
/** 索引覆盖旧记录,无需逐条回写。MySQL 查询使用命名生成列以命中索引。 */
|
|
16883
|
-
async
|
|
17084
|
+
async createMysqlMemoryVectorIndex(key) {
|
|
16884
17085
|
const name = `idx_${this.table}_vector_key`;
|
|
16885
|
-
if (this.dbType !== "mysql") {
|
|
16886
|
-
await this.sql.execute(`CREATE INDEX IF NOT EXISTS ${name} ON ${this.table}((${key}))`);
|
|
16887
|
-
return;
|
|
16888
|
-
}
|
|
16889
17086
|
const read = async () => requireSqlSuccess(await this.sql.get(
|
|
16890
17087
|
"SELECT EXTRA AS extra FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = ?",
|
|
16891
17088
|
[this.table, key]
|
|
@@ -16900,36 +17097,32 @@ var ReldbAIRelStore = class _ReldbAIRelStore {
|
|
|
16900
17097
|
}
|
|
16901
17098
|
if ((await read())?.extra !== "VIRTUAL GENERATED")
|
|
16902
17099
|
throw new Error(aiM("ai_storeIndexMismatch"));
|
|
16903
|
-
await this.
|
|
17100
|
+
await this.createMysqlIndex(name, key);
|
|
16904
17101
|
}
|
|
16905
17102
|
/**
|
|
16906
17103
|
* MySQL 并发首次创建只接受明确的重复名称错误,并重读结构,权限/DDL/不匹配仍失败。
|
|
16907
17104
|
*/
|
|
16908
|
-
async
|
|
16909
|
-
|
|
16910
|
-
|
|
16911
|
-
|
|
16912
|
-
|
|
16913
|
-
|
|
16914
|
-
|
|
16915
|
-
|
|
16916
|
-
|
|
16917
|
-
if (existing
|
|
16918
|
-
|
|
16919
|
-
throw new Error(aiM("ai_storeIndexMismatch"));
|
|
16920
|
-
return;
|
|
16921
|
-
}
|
|
16922
|
-
try {
|
|
16923
|
-
await this.sql.execute(`CREATE INDEX ${name} ON ${this.table}(${columns})`);
|
|
16924
|
-
} catch (error) {
|
|
16925
|
-
if (!isMysqlError(error, "ER_DUP_KEYNAME", 1061))
|
|
16926
|
-
throw error;
|
|
16927
|
-
if (!matches(await read()))
|
|
16928
|
-
throw new Error(aiM("ai_storeIndexMismatch"), { cause: error });
|
|
16929
|
-
}
|
|
17105
|
+
async createMysqlIndex(name, columns) {
|
|
17106
|
+
const read = async () => requireSqlSuccess(await this.sql.query(
|
|
17107
|
+
"SELECT COLUMN_NAME AS column_name, SEQ_IN_INDEX AS seq_in_index, NON_UNIQUE AS non_unique, SUB_PART AS sub_part, INDEX_TYPE AS index_type, COLLATION AS collation, IS_VISIBLE AS is_visible, EXPRESSION AS expression FROM information_schema.STATISTICS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND INDEX_NAME = ? ORDER BY SEQ_IN_INDEX",
|
|
17108
|
+
[this.table, name]
|
|
17109
|
+
)).data;
|
|
17110
|
+
const expected = columns.split(",").map((column) => column.trim());
|
|
17111
|
+
const matches = (definition) => definition.length === expected.length && definition.every((column, index) => column.column_name === expected[index] && Number(column.seq_in_index) === index + 1 && Number(column.non_unique) === 1 && column.sub_part === null && column.index_type === "BTREE" && column.collation === "A" && column.is_visible === "YES" && column.expression === null);
|
|
17112
|
+
const existing = await read();
|
|
17113
|
+
if (existing.length > 0) {
|
|
17114
|
+
if (!matches(existing))
|
|
17115
|
+
throw new Error(aiM("ai_storeIndexMismatch"));
|
|
16930
17116
|
return;
|
|
16931
17117
|
}
|
|
16932
|
-
|
|
17118
|
+
try {
|
|
17119
|
+
await this.sql.execute(`CREATE INDEX ${name} ON ${this.table}(${columns})`);
|
|
17120
|
+
} catch (error) {
|
|
17121
|
+
if (!isMysqlError(error, "ER_DUP_KEYNAME", 1061))
|
|
17122
|
+
throw error;
|
|
17123
|
+
if (!matches(await read()))
|
|
17124
|
+
throw new Error(aiM("ai_storeIndexMismatch"), { cause: error });
|
|
17125
|
+
}
|
|
16933
17126
|
}
|
|
16934
17127
|
/** 普通写入也更换版本,使并发条件写入识别所有较新修改。 */
|
|
16935
17128
|
async save(id3, data, scope) {
|
|
@@ -17340,6 +17533,9 @@ var VecdbAIVectorStore = class {
|
|
|
17340
17533
|
collection;
|
|
17341
17534
|
scan;
|
|
17342
17535
|
constructor(vecdb2, collection) {
|
|
17536
|
+
const config = vecdb2.config;
|
|
17537
|
+
if (config?.type === "pgvector" && Buffer.byteLength(`${config.tablePrefix}${collection}`) > 63)
|
|
17538
|
+
throw new Error(aiM("ai_storeVectorCollectionNameTooLong"));
|
|
17343
17539
|
this.vecdb = vecdb2;
|
|
17344
17540
|
this.collection = collection;
|
|
17345
17541
|
const scan = vecdb2.vector.scan?.bind(vecdb2.vector);
|
|
@@ -17353,10 +17549,15 @@ var VecdbAIVectorStore = class {
|
|
|
17353
17549
|
}
|
|
17354
17550
|
}
|
|
17355
17551
|
async upsert(id3, vector, metadata) {
|
|
17356
|
-
await
|
|
17357
|
-
requireVecdbSuccess(await this.vecdb.vector.upsert(this.collection, [
|
|
17552
|
+
await this.upsertMany([
|
|
17358
17553
|
{ id: id3, vector, metadata }
|
|
17359
|
-
])
|
|
17554
|
+
]);
|
|
17555
|
+
}
|
|
17556
|
+
async upsertMany(entries) {
|
|
17557
|
+
if (!entries.length)
|
|
17558
|
+
return;
|
|
17559
|
+
await ensureVecdbCollection(this.vecdb, this.collection, entries[0].vector.length);
|
|
17560
|
+
requireVecdbSuccess(await this.vecdb.vector.upsert(this.collection, entries));
|
|
17360
17561
|
}
|
|
17361
17562
|
async search(vector, options) {
|
|
17362
17563
|
return requireVecdbSuccess(await this.vecdb.vector.search(this.collection, vector, options));
|
|
@@ -17378,9 +17579,32 @@ var VecdbAIVectorStore = class {
|
|
|
17378
17579
|
}
|
|
17379
17580
|
};
|
|
17380
17581
|
function createDbStoreProvider(deps) {
|
|
17381
|
-
const { sql, jsonOps, vecdb: vecdbDep } = deps;
|
|
17582
|
+
const { sql, tx, jsonOps, vecdb: vecdbDep } = deps;
|
|
17382
17583
|
const dbType = deps.dbType ?? "sqlite";
|
|
17383
17584
|
const relStores = /* @__PURE__ */ new Map();
|
|
17585
|
+
async function prepareTables(groups) {
|
|
17586
|
+
if (dbType === "postgresql") {
|
|
17587
|
+
if (!tx)
|
|
17588
|
+
throw new TypeError(aiM("ai_storeTransactionRequired"));
|
|
17589
|
+
requireSqlSuccess(await tx.wrap(async (connection) => {
|
|
17590
|
+
requireSqlSuccess(await connection.execute("SET TRANSACTION ISOLATION LEVEL READ COMMITTED"));
|
|
17591
|
+
requireSqlSuccess(await connection.execute("SELECT pg_catalog.pg_advisory_xact_lock(pg_catalog.hashtextextended(?, 0))", [POSTGRES_SCHEMA_LOCK]));
|
|
17592
|
+
for (const stores of groups) {
|
|
17593
|
+
for (const store of stores)
|
|
17594
|
+
await store.createTable(connection);
|
|
17595
|
+
}
|
|
17596
|
+
}));
|
|
17597
|
+
return;
|
|
17598
|
+
}
|
|
17599
|
+
const results = await Promise.allSettled(Array.from(groups, async (stores) => {
|
|
17600
|
+
for (const store of stores)
|
|
17601
|
+
await store.createTable();
|
|
17602
|
+
}));
|
|
17603
|
+
for (const result of results) {
|
|
17604
|
+
if (result.status === "rejected")
|
|
17605
|
+
throw result.reason;
|
|
17606
|
+
}
|
|
17607
|
+
}
|
|
17384
17608
|
return {
|
|
17385
17609
|
name: "db",
|
|
17386
17610
|
get stateScope() {
|
|
@@ -17389,7 +17613,7 @@ function createDbStoreProvider(deps) {
|
|
|
17389
17613
|
return dbType !== "sqlite" && sharedVector ? "shared" : "local";
|
|
17390
17614
|
},
|
|
17391
17615
|
createRelStore(name, options) {
|
|
17392
|
-
const store = new ReldbAIRelStore(sql, name, jsonOps, dbType, options,
|
|
17616
|
+
const store = new ReldbAIRelStore(sql, name, jsonOps, dbType, options, tx);
|
|
17393
17617
|
const stores = relStores.get(name) ?? [];
|
|
17394
17618
|
stores.push(store);
|
|
17395
17619
|
relStores.set(name, stores);
|
|
@@ -17409,25 +17633,15 @@ function createDbStoreProvider(deps) {
|
|
|
17409
17633
|
documents,
|
|
17410
17634
|
collections,
|
|
17411
17635
|
vecdb: vecdbDep,
|
|
17412
|
-
prepare:
|
|
17413
|
-
|
|
17414
|
-
|
|
17415
|
-
}
|
|
17636
|
+
prepare: () => prepareTables([
|
|
17637
|
+
[documents, collections]
|
|
17638
|
+
])
|
|
17416
17639
|
});
|
|
17417
17640
|
},
|
|
17418
17641
|
async initialize() {
|
|
17419
17642
|
if (relStores.size > 0) {
|
|
17420
|
-
|
|
17421
|
-
|
|
17422
|
-
].map(async (stores) => {
|
|
17423
|
-
for (const store of stores)
|
|
17424
|
-
await store.createTable();
|
|
17425
|
-
}));
|
|
17426
|
-
for (const result of results) {
|
|
17427
|
-
if (result.status === "rejected")
|
|
17428
|
-
throw result.reason;
|
|
17429
|
-
}
|
|
17430
|
-
logger33.debug("DB store provider initialized", { tableCount: relStores.size });
|
|
17643
|
+
await prepareTables(relStores.values());
|
|
17644
|
+
logger34.debug("DB store provider initialized", { tableCount: relStores.size });
|
|
17431
17645
|
}
|
|
17432
17646
|
},
|
|
17433
17647
|
async close() {
|
|
@@ -17707,7 +17921,7 @@ function createMemoryStoreProvider() {
|
|
|
17707
17921
|
}
|
|
17708
17922
|
|
|
17709
17923
|
// src/ai-main.ts
|
|
17710
|
-
var
|
|
17924
|
+
var logger35 = core.logger.child({ module: "ai", scope: "main" });
|
|
17711
17925
|
var initInProgress = false;
|
|
17712
17926
|
var initCompletion = null;
|
|
17713
17927
|
var closingPromise = null;
|
|
@@ -17886,7 +18100,7 @@ async function resetAllState() {
|
|
|
17886
18100
|
try {
|
|
17887
18101
|
await storeProvider.close();
|
|
17888
18102
|
} catch (error) {
|
|
17889
|
-
|
|
18103
|
+
logger35.error("AI store provider close failed", { error });
|
|
17890
18104
|
}
|
|
17891
18105
|
}
|
|
17892
18106
|
}
|
|
@@ -17903,7 +18117,7 @@ var streamOperations = {
|
|
|
17903
18117
|
var ai = {
|
|
17904
18118
|
async init(config, options) {
|
|
17905
18119
|
if (initInProgress || closingPromise) {
|
|
17906
|
-
|
|
18120
|
+
logger35.warn("AI init already in progress, skipping concurrent call");
|
|
17907
18121
|
return err(HaiAIError.INIT_IN_PROGRESS, aiM("ai_initInProgress"));
|
|
17908
18122
|
}
|
|
17909
18123
|
initInProgress = true;
|
|
@@ -17914,15 +18128,15 @@ var ai = {
|
|
|
17914
18128
|
let closingPrevious = false;
|
|
17915
18129
|
try {
|
|
17916
18130
|
if (currentConfig) {
|
|
17917
|
-
|
|
18131
|
+
logger35.warn("AI module is already initialized, reinitializing");
|
|
17918
18132
|
closingPrevious = true;
|
|
17919
18133
|
await resetAllState();
|
|
17920
18134
|
closingPrevious = false;
|
|
17921
18135
|
}
|
|
17922
|
-
|
|
18136
|
+
logger35.info("Initializing AI module");
|
|
17923
18137
|
const parseResult = AIConfigSchema.safeParse(config ?? {});
|
|
17924
18138
|
if (!parseResult.success) {
|
|
17925
|
-
|
|
18139
|
+
logger35.error("AI config validation failed", { error: parseResult.error.message });
|
|
17926
18140
|
return err(
|
|
17927
18141
|
HaiAIError.CONFIGURATION_ERROR,
|
|
17928
18142
|
aiM("ai_configError", {
|
|
@@ -17939,7 +18153,7 @@ var ai = {
|
|
|
17939
18153
|
storeProvider = createDbStoreProviderFromModules();
|
|
17940
18154
|
} else {
|
|
17941
18155
|
storeProvider = createMemoryStoreProvider();
|
|
17942
|
-
|
|
18156
|
+
logger35.warn("AI is using the ephemeral in-memory store; initialize reldb and vecdb before ai.init() for persistent data");
|
|
17943
18157
|
}
|
|
17944
18158
|
if (core.module.requiresSharedState(process2.env) && storeProvider.stateScope !== "shared")
|
|
17945
18159
|
return err(HaiAIError.CONFIGURATION_ERROR, aiM("ai_sharedBackendRequired"));
|
|
@@ -17975,17 +18189,17 @@ var ai = {
|
|
|
17975
18189
|
currentA2AConfig = parsed.a2a;
|
|
17976
18190
|
currentA2AStores = subs.a2aStores;
|
|
17977
18191
|
currentConfig = parsed;
|
|
17978
|
-
|
|
18192
|
+
logger35.info("AI module initialized", { model: parsed.llm?.model });
|
|
17979
18193
|
return ok(void 0);
|
|
17980
18194
|
} catch (error) {
|
|
17981
18195
|
if (!closingPrevious) {
|
|
17982
18196
|
try {
|
|
17983
18197
|
await resetAllState();
|
|
17984
18198
|
} catch (cleanupError) {
|
|
17985
|
-
|
|
18199
|
+
logger35.error("AI initialization cleanup failed", { error: cleanupError });
|
|
17986
18200
|
}
|
|
17987
18201
|
}
|
|
17988
|
-
|
|
18202
|
+
logger35.error("AI module initialization failed", { error });
|
|
17989
18203
|
return err(
|
|
17990
18204
|
HaiAIError.CONFIGURATION_ERROR,
|
|
17991
18205
|
aiM("ai_initFailed", {
|
|
@@ -18075,9 +18289,9 @@ var ai = {
|
|
|
18075
18289
|
closingPromise = (async () => {
|
|
18076
18290
|
if (initCompletion)
|
|
18077
18291
|
await initCompletion;
|
|
18078
|
-
|
|
18292
|
+
logger35.info("Closing AI module");
|
|
18079
18293
|
await resetAllState();
|
|
18080
|
-
|
|
18294
|
+
logger35.info("AI module closed");
|
|
18081
18295
|
})().finally(() => {
|
|
18082
18296
|
closingPromise = null;
|
|
18083
18297
|
});
|