@h-ai/ai 1.0.0-beta.24 → 1.0.0-beta.26
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 +168 -3
- package/README.ja.md +168 -3
- package/README.md +168 -3
- package/dist/{ai-acp-types-B99Oa7WD.d.ts → ai-acp-types-BYUy6Tyx.d.ts} +33 -3
- package/dist/browser.d.ts +1 -1
- package/dist/browser.js +1 -1
- package/dist/{chunk-3G4ZLXH4.js → chunk-VEWBD2J4.js} +5 -2
- package/dist/chunk-VEWBD2J4.js.map +1 -0
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1008 -437
- package/dist/index.js.map +1 -1
- package/package.json +7 -7
- package/tools/README.md +43 -6
- package/dist/chunk-3G4ZLXH4.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, resolveAudioModel, ensureAudioCredential, platformScopeSchema, resolveModelApi, platformRequestSchema,
|
|
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-VEWBD2J4.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-VEWBD2J4.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';
|
|
@@ -24,6 +24,7 @@ import { createHttpStream } from '@agentclientprotocol/sdk/experimental/http-cli
|
|
|
24
24
|
import { createWebSocketStream } from '@agentclientprotocol/sdk/experimental/ws-client';
|
|
25
25
|
import WebSocket2, { WebSocket } from 'ws';
|
|
26
26
|
import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv';
|
|
27
|
+
import { HaiRunnerError } from '@h-ai/runner';
|
|
27
28
|
import { gunzipSync } from 'zlib';
|
|
28
29
|
import { FormData as FormData$1, Agent, fetch as fetch$1 } from 'undici';
|
|
29
30
|
import OpenAI3, { toFile } from 'openai';
|
|
@@ -896,6 +897,12 @@ function acpError(error) {
|
|
|
896
897
|
}
|
|
897
898
|
|
|
898
899
|
// src/acp/ai-acp-adapters.ts
|
|
900
|
+
var deepSeekChatModels = /* @__PURE__ */ new Set([
|
|
901
|
+
"deepseek-flash",
|
|
902
|
+
"deepseek-v4-pro",
|
|
903
|
+
"deepseek-v4-flash",
|
|
904
|
+
"deepseek-v4-flash-vision-exp"
|
|
905
|
+
]);
|
|
899
906
|
function resolveAgentModels(agent, config) {
|
|
900
907
|
return agent.modelIds.map((id3) => {
|
|
901
908
|
const entry = config.llm?.models?.find((model) => model.id === id3);
|
|
@@ -963,6 +970,7 @@ var nativeAdapters = {
|
|
|
963
970
|
throw new ACPFailure("model", { modelId });
|
|
964
971
|
}
|
|
965
972
|
const key = "HAI_ACP_MODEL_0";
|
|
973
|
+
const deepSeekChat = model.protocol === "chat" && (URL.parse(model.baseUrl)?.hostname === "api.deepseek.com" || deepSeekChatModels.has(model.model));
|
|
966
974
|
const providers = {
|
|
967
975
|
"hai-0": {
|
|
968
976
|
apiKeyEnv: key,
|
|
@@ -972,6 +980,15 @@ var nativeAdapters = {
|
|
|
972
980
|
responses: "openai-responses",
|
|
973
981
|
anthropic: "anthropic-messages"
|
|
974
982
|
}[model.protocol],
|
|
983
|
+
...deepSeekChat && {
|
|
984
|
+
compat: {
|
|
985
|
+
supportsDeveloperRole: false,
|
|
986
|
+
supportsStore: false,
|
|
987
|
+
maxTokensField: "max_tokens",
|
|
988
|
+
thinkingFormat: "deepseek",
|
|
989
|
+
requiresReasoningContentOnAssistantMessages: true
|
|
990
|
+
}
|
|
991
|
+
},
|
|
975
992
|
// 输出容量是能力声明;单轮预算沿用 Hai 模型的 maxTokens。
|
|
976
993
|
defaultMaxTokens: Math.min(model.maxTokens, caps.maxOutputTokens),
|
|
977
994
|
defaultContextWindow: caps.contextWindow,
|
|
@@ -2583,6 +2600,42 @@ function createGitOperations(workspace, runtime) {
|
|
|
2583
2600
|
})
|
|
2584
2601
|
};
|
|
2585
2602
|
}
|
|
2603
|
+
var batchSize = 64;
|
|
2604
|
+
var retentionMs = 7 * 24 * 60 * 60 * 1e3;
|
|
2605
|
+
function removed(result) {
|
|
2606
|
+
return !result.success && result.error.code === HaiRunnerError.NOT_FOUND.code;
|
|
2607
|
+
}
|
|
2608
|
+
function createACPMaintenance(runner, stores) {
|
|
2609
|
+
const { bindings, intents, receipts } = stores;
|
|
2610
|
+
function scan(store, consider) {
|
|
2611
|
+
let cursor;
|
|
2612
|
+
return async (updatedBefore) => {
|
|
2613
|
+
if (!store.queryKeys || !store.removeIfUnchanged)
|
|
2614
|
+
return;
|
|
2615
|
+
const page = await store.queryKeys({ updatedBefore, limit: batchSize }, cursor);
|
|
2616
|
+
for (const key of page) {
|
|
2617
|
+
if (await consider(key))
|
|
2618
|
+
await store.removeIfUnchanged(key.id, key.version);
|
|
2619
|
+
}
|
|
2620
|
+
cursor = page.length === batchSize ? page.at(-1) : void 0;
|
|
2621
|
+
};
|
|
2622
|
+
}
|
|
2623
|
+
const pruneBindings = scan(bindings, async ({ id: id3, version }) => {
|
|
2624
|
+
const record = await bindings.readVersioned(id3);
|
|
2625
|
+
return record?.version === version && removed(await runner.get(record.data.workerScope, record.data.workerId));
|
|
2626
|
+
});
|
|
2627
|
+
const pruneIntents = scan(intents, async ({ id: id3 }) => !await bindings.get(id3));
|
|
2628
|
+
const pruneReceipts = scan(receipts, async ({ id: id3, version }) => {
|
|
2629
|
+
const record = await receipts.readVersioned(id3);
|
|
2630
|
+
return record?.version === version && removed(await runner.get(record.data.workerScope, id3));
|
|
2631
|
+
});
|
|
2632
|
+
return async () => {
|
|
2633
|
+
const cutoff = await bindings.currentTime() - retentionMs;
|
|
2634
|
+
await pruneBindings(cutoff);
|
|
2635
|
+
await pruneIntents(cutoff);
|
|
2636
|
+
await pruneReceipts(cutoff);
|
|
2637
|
+
};
|
|
2638
|
+
}
|
|
2586
2639
|
function encodeWorkspaceSnapshot(snapshot2, scratchMiB) {
|
|
2587
2640
|
const files = Object.entries(snapshot2);
|
|
2588
2641
|
const maxBytes = Math.min(16, scratchMiB) * 1024 * 1024;
|
|
@@ -2600,9 +2653,24 @@ var workerKind = "hai.acp.worker.v1";
|
|
|
2600
2653
|
var controlKind = "hai.acp.control.v1";
|
|
2601
2654
|
var turnSchema = platformOptionsSchema.pick({ limits: true, output: true });
|
|
2602
2655
|
var historySummaryMaxBytes = 8192;
|
|
2656
|
+
var maxPermissionCalls = 64;
|
|
2657
|
+
var maxPermissionInputBytes = 8192;
|
|
2658
|
+
var maintenanceIntervalMs = 3e4;
|
|
2659
|
+
var logger3 = core.logger.child({ module: "ai", scope: "acp-maintenance" });
|
|
2603
2660
|
function hash(value) {
|
|
2604
2661
|
return createHash("sha256").update(value).digest("hex");
|
|
2605
2662
|
}
|
|
2663
|
+
function canonicalToolInput(value) {
|
|
2664
|
+
if (value === void 0 || value === null)
|
|
2665
|
+
return void 0;
|
|
2666
|
+
const sorted = JSON.stringify(value, (_key, item2) => {
|
|
2667
|
+
if (item2 && typeof item2 === "object" && !Array.isArray(item2)) {
|
|
2668
|
+
return Object.fromEntries(Object.entries(item2).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0));
|
|
2669
|
+
}
|
|
2670
|
+
return item2;
|
|
2671
|
+
});
|
|
2672
|
+
return Buffer.byteLength(sorted) <= maxPermissionInputBytes ? sorted : void 0;
|
|
2673
|
+
}
|
|
2606
2674
|
function json(value) {
|
|
2607
2675
|
return JSON.parse(JSON.stringify(value));
|
|
2608
2676
|
}
|
|
@@ -2661,16 +2729,44 @@ function turnRequest(base, options) {
|
|
|
2661
2729
|
}
|
|
2662
2730
|
function createACPPlatform(deps) {
|
|
2663
2731
|
const { limits, runner, policy } = deps;
|
|
2664
|
-
const
|
|
2665
|
-
const
|
|
2666
|
-
const
|
|
2667
|
-
const
|
|
2668
|
-
const
|
|
2732
|
+
const maintenanceIndex = { hasUpdatedAtIndex: true };
|
|
2733
|
+
const bindings = deps.store.createRelStore("hai_ai_acp_managed_sessions", maintenanceIndex);
|
|
2734
|
+
const intents = deps.store.createRelStore("hai_ai_acp_managed_requests", maintenanceIndex);
|
|
2735
|
+
const approvals = deps.store.createRelStore("hai_ai_acp_managed_approvals", maintenanceIndex);
|
|
2736
|
+
const grants = deps.store.createRelStore("hai_ai_acp_managed_grants", maintenanceIndex);
|
|
2737
|
+
const receipts = deps.store.createRelStore("hai_ai_acp_managed_receipts", maintenanceIndex);
|
|
2669
2738
|
const workers = /* @__PURE__ */ new Map();
|
|
2670
2739
|
const localWorkers = /* @__PURE__ */ new Map();
|
|
2671
2740
|
const owned = /* @__PURE__ */ new Map();
|
|
2672
2741
|
const unregister = [];
|
|
2673
2742
|
let closed = false;
|
|
2743
|
+
let maintenanceTimer;
|
|
2744
|
+
let maintenancePending;
|
|
2745
|
+
async function maintainApprovals() {
|
|
2746
|
+
if (!approvals.queryKeys || !approvals.removeIfUnchanged || !grants.queryKeys || !grants.removeIfUnchanged)
|
|
2747
|
+
return;
|
|
2748
|
+
const now = await approvals.currentTime();
|
|
2749
|
+
const [expiredApprovals, expiredGrants] = await Promise.all([
|
|
2750
|
+
approvals.queryKeys({
|
|
2751
|
+
where: {
|
|
2752
|
+
deadline: { $lte: now }
|
|
2753
|
+
},
|
|
2754
|
+
limit: 64
|
|
2755
|
+
}),
|
|
2756
|
+
grants.queryKeys({
|
|
2757
|
+
where: {
|
|
2758
|
+
expires: { $lte: now }
|
|
2759
|
+
},
|
|
2760
|
+
limit: 64
|
|
2761
|
+
})
|
|
2762
|
+
]);
|
|
2763
|
+
const removeApproval = approvals.removeIfUnchanged.bind(approvals);
|
|
2764
|
+
const removeGrant = grants.removeIfUnchanged.bind(grants);
|
|
2765
|
+
for (const entry of expiredApprovals)
|
|
2766
|
+
await removeApproval(entry.id, entry.version);
|
|
2767
|
+
for (const entry of expiredGrants)
|
|
2768
|
+
await removeGrant(entry.id, entry.version);
|
|
2769
|
+
}
|
|
2674
2770
|
function getRunner() {
|
|
2675
2771
|
if (closed)
|
|
2676
2772
|
throw new ACPFailure("closed");
|
|
@@ -2955,7 +3051,8 @@ function createACPPlatform(deps) {
|
|
|
2955
3051
|
connection,
|
|
2956
3052
|
sessions: /* @__PURE__ */ new Map(),
|
|
2957
3053
|
busy: /* @__PURE__ */ new Set(),
|
|
2958
|
-
|
|
3054
|
+
toolBindings: /* @__PURE__ */ new Map(),
|
|
3055
|
+
signal: context.signal,
|
|
2959
3056
|
nativeIds: /* @__PURE__ */ new Map(),
|
|
2960
3057
|
approvals: pendingApprovals,
|
|
2961
3058
|
lastUse: performance.now(),
|
|
@@ -2989,48 +3086,73 @@ function createACPPlatform(deps) {
|
|
|
2989
3086
|
await connection.close();
|
|
2990
3087
|
} finally {
|
|
2991
3088
|
await Promise.allSettled([
|
|
2992
|
-
...worker.
|
|
2993
|
-
].map(async (
|
|
3089
|
+
...worker.toolBindings.values()
|
|
3090
|
+
].map(async (binding) => binding.revoke()));
|
|
2994
3091
|
}
|
|
2995
3092
|
}
|
|
2996
3093
|
}
|
|
2997
|
-
async function decidePermission(binding, sessionId, context, request2,
|
|
3094
|
+
async function decidePermission(binding, sessionId, context, request2, planned) {
|
|
2998
3095
|
const denied = {
|
|
2999
3096
|
outcome: { outcome: "cancelled" }
|
|
3000
3097
|
};
|
|
3001
3098
|
const option = request2.options.find((option2) => option2.kind === "allow_once");
|
|
3002
3099
|
if (!option || context.signal.aborted || binding.mode === "shared" || !policy?.resolvePermission)
|
|
3003
3100
|
return denied;
|
|
3101
|
+
const rawInput = canonicalToolInput(request2.toolCall.rawInput);
|
|
3102
|
+
if (!rawInput || !request2.toolCall.kind)
|
|
3103
|
+
return denied;
|
|
3004
3104
|
const authorized = await policy.resolvePermission(binding.scope, sessionId, request2.toolCall);
|
|
3005
3105
|
if (!authorized || !authorized.key || Buffer.byteLength(authorized.summary) > 2048)
|
|
3006
3106
|
return denied;
|
|
3007
3107
|
const once = {
|
|
3008
3108
|
outcome: { outcome: "selected", optionId: option.optionId }
|
|
3009
3109
|
};
|
|
3110
|
+
const { agent, effective, models, nativeOptions } = planned;
|
|
3111
|
+
const { approval, ruleIds } = effective.permissions;
|
|
3010
3112
|
const target = hash(JSON.stringify([
|
|
3011
3113
|
binding.scope,
|
|
3012
|
-
|
|
3013
|
-
|
|
3114
|
+
agent.id,
|
|
3115
|
+
agent.adapter,
|
|
3116
|
+
effective.resolvedMode,
|
|
3117
|
+
effective.environmentId,
|
|
3118
|
+
effective.image,
|
|
3119
|
+
effective.workspaceId,
|
|
3120
|
+
effective.permissions.profile,
|
|
3121
|
+
agent.command,
|
|
3122
|
+
agent.args,
|
|
3123
|
+
models,
|
|
3124
|
+
nativeOptions,
|
|
3125
|
+
resolveEnvironment(agent.environmentRefs),
|
|
3014
3126
|
authorized.key,
|
|
3015
3127
|
request2.toolCall.kind,
|
|
3016
|
-
request2.toolCall.
|
|
3128
|
+
request2.toolCall.name ?? request2.toolCall.title,
|
|
3129
|
+
rawInput
|
|
3017
3130
|
]));
|
|
3018
3131
|
const sessionGrant = hash(JSON.stringify([sessionId, target]));
|
|
3019
3132
|
const now = await approvals.currentTime();
|
|
3020
|
-
const
|
|
3133
|
+
const scopeKey = hash(JSON.stringify(binding.scope));
|
|
3021
3134
|
const matching = await Promise.all([
|
|
3022
3135
|
grants.get(sessionGrant),
|
|
3023
|
-
|
|
3136
|
+
ruleIds === void 0 || ruleIds.includes(target) ? grants.get(target) : void 0
|
|
3024
3137
|
]);
|
|
3025
|
-
|
|
3138
|
+
const reusable = matching.filter((grant) => !!grant && grant.scopeKey === scopeKey && !grant.revoked && grant.expires > now);
|
|
3139
|
+
if (reusable.length) {
|
|
3026
3140
|
const fresh = await policy.resolvePermission(binding.scope, sessionId, request2.toolCall);
|
|
3027
|
-
|
|
3141
|
+
if (fresh?.key !== authorized.key || context.signal.aborted)
|
|
3142
|
+
return denied;
|
|
3143
|
+
const confirmed = await Promise.all(reusable.map((grant) => grants.get(grant.id)));
|
|
3144
|
+
const checkedAt = await approvals.currentTime();
|
|
3145
|
+
return !context.signal.aborted && confirmed.some((grant) => grant && grant.scopeKey === scopeKey && !grant.revoked && grant.expires > checkedAt) ? once : denied;
|
|
3028
3146
|
}
|
|
3029
3147
|
if (approval === "never")
|
|
3030
3148
|
return denied;
|
|
3031
3149
|
const approvalId = randomUUID();
|
|
3032
|
-
const deadline = now +
|
|
3033
|
-
await approvals.save(approvalId, {
|
|
3150
|
+
const deadline = now + effective.limits.approvalTimeoutMs;
|
|
3151
|
+
await approvals.save(approvalId, {
|
|
3152
|
+
scope: binding.scope,
|
|
3153
|
+
sessionId,
|
|
3154
|
+
deadline
|
|
3155
|
+
});
|
|
3034
3156
|
try {
|
|
3035
3157
|
unwrap(await context.emit({
|
|
3036
3158
|
type: "approval",
|
|
@@ -3048,7 +3170,6 @@ function createACPPlatform(deps) {
|
|
|
3048
3170
|
if (fresh?.key !== authorized.key || context.signal.aborted || await approvals.currentTime() >= deadline)
|
|
3049
3171
|
return denied;
|
|
3050
3172
|
const summary = authorized.summary;
|
|
3051
|
-
const scopeKey = hash(JSON.stringify(binding.scope));
|
|
3052
3173
|
if (current.decision === "allow-session") {
|
|
3053
3174
|
await grants.save(sessionGrant, {
|
|
3054
3175
|
id: sessionGrant,
|
|
@@ -3093,14 +3214,9 @@ function createACPPlatform(deps) {
|
|
|
3093
3214
|
if (command.op === "prompt" && command.singleTurn === true) {
|
|
3094
3215
|
const current = await bindings.readVersioned(id3);
|
|
3095
3216
|
if (current?.data.singleTurn && current.data.workerId === context.parentId && !current.data.closed) {
|
|
3096
|
-
const channel = worker.sessions.get(id3);
|
|
3097
3217
|
try {
|
|
3098
|
-
await
|
|
3099
|
-
await worker.revoke.get(id3)?.();
|
|
3218
|
+
await closeNativeSession(worker, id3);
|
|
3100
3219
|
} finally {
|
|
3101
|
-
worker.sessions.delete(id3);
|
|
3102
|
-
worker.revoke.delete(id3);
|
|
3103
|
-
worker.nativeIds.delete(id3);
|
|
3104
3220
|
if (current.data.mode !== "task") {
|
|
3105
3221
|
await bindings.compareAndSwap(id3, {
|
|
3106
3222
|
expectedVersion: current.version,
|
|
@@ -3114,6 +3230,21 @@ function createACPPlatform(deps) {
|
|
|
3114
3230
|
worker.busy.delete(id3);
|
|
3115
3231
|
}
|
|
3116
3232
|
}
|
|
3233
|
+
async function revokeTools(worker, id3, forget = true) {
|
|
3234
|
+
const tools = worker.toolBindings.get(id3);
|
|
3235
|
+
if (tools && forget)
|
|
3236
|
+
worker.toolBindings.delete(id3);
|
|
3237
|
+
await tools?.revoke();
|
|
3238
|
+
}
|
|
3239
|
+
async function closeNativeSession(worker, id3) {
|
|
3240
|
+
try {
|
|
3241
|
+
await worker.sessions.get(id3)?.closeSession();
|
|
3242
|
+
} finally {
|
|
3243
|
+
worker.sessions.delete(id3);
|
|
3244
|
+
worker.nativeIds.delete(id3);
|
|
3245
|
+
await revokeTools(worker, id3);
|
|
3246
|
+
}
|
|
3247
|
+
}
|
|
3117
3248
|
async function executeControl(worker, id3, command, context) {
|
|
3118
3249
|
const versioned = await bindings.readVersioned(id3);
|
|
3119
3250
|
const binding = versioned?.data;
|
|
@@ -3123,25 +3254,18 @@ function createACPPlatform(deps) {
|
|
|
3123
3254
|
return command.op === "close" ? null : { error: "closed" };
|
|
3124
3255
|
}
|
|
3125
3256
|
let channel = worker.sessions.get(id3);
|
|
3126
|
-
if (command.op === "close") {
|
|
3127
|
-
|
|
3128
|
-
await channel.closeSession();
|
|
3129
|
-
worker.sessions.delete(id3);
|
|
3130
|
-
}
|
|
3131
|
-
await worker.revoke.get(id3)?.();
|
|
3132
|
-
worker.revoke.delete(id3);
|
|
3133
|
-
worker.nativeIds.delete(id3);
|
|
3257
|
+
if (command.op === "close" || worker.toolBindings.get(id3)?.signal.aborted) {
|
|
3258
|
+
await closeNativeSession(worker, id3);
|
|
3134
3259
|
if (!await bindings.compareAndSwap(id3, {
|
|
3135
3260
|
expectedVersion: versioned?.version,
|
|
3136
3261
|
data: { ...binding, historySummary: void 0, closed: true }
|
|
3137
3262
|
})) {
|
|
3138
3263
|
throw new ACPFailure("conflict");
|
|
3139
3264
|
}
|
|
3140
|
-
return null;
|
|
3265
|
+
return command.op === "close" ? null : { error: "closed" };
|
|
3141
3266
|
}
|
|
3142
3267
|
const resolved = await plan(binding.scope, binding.request).catch(async (error) => {
|
|
3143
|
-
await worker
|
|
3144
|
-
worker.revoke.delete(id3);
|
|
3268
|
+
await revokeTools(worker, id3, false);
|
|
3145
3269
|
throw error;
|
|
3146
3270
|
});
|
|
3147
3271
|
const { effective: base, toolIds, context: authorizedContext } = resolved;
|
|
@@ -3151,16 +3275,20 @@ function createACPPlatform(deps) {
|
|
|
3151
3275
|
execution: { ...binding.request.execution, mode: base.resolvedMode, environmentId: base.environmentId }
|
|
3152
3276
|
});
|
|
3153
3277
|
if (worker.snapshot !== launchSnapshot(normalized)) {
|
|
3154
|
-
await worker
|
|
3155
|
-
worker.revoke.delete(id3);
|
|
3278
|
+
await revokeTools(worker, id3, false);
|
|
3156
3279
|
throw new ACPFailure("conflict");
|
|
3157
3280
|
}
|
|
3158
3281
|
if (!channel) {
|
|
3159
3282
|
if (worker.sessions.size >= 64)
|
|
3160
3283
|
throw new ACPFailure("busy");
|
|
3161
3284
|
channel = worker.connection.channel();
|
|
3162
|
-
const tools = toolIds.length && policy?.bindTools ? await policy.bindTools(binding.scope, id3, toolIds,
|
|
3285
|
+
const tools = toolIds.length && policy?.bindTools ? await policy.bindTools(binding.scope, id3, toolIds, worker.signal) : void 0;
|
|
3163
3286
|
try {
|
|
3287
|
+
context.signal.throwIfAborted();
|
|
3288
|
+
if (tools?.signal?.aborted) {
|
|
3289
|
+
await tools.revoke();
|
|
3290
|
+
return { error: "closed" };
|
|
3291
|
+
}
|
|
3164
3292
|
if (tools && (!tools.servers.length || tools.servers.some((server) => !("type" in server) || server.type !== "http")))
|
|
3165
3293
|
throw new ACPFailure("unsupported", { parameter: "tools.allow" });
|
|
3166
3294
|
const native = await channel.createSession("/workspace", tools?.servers);
|
|
@@ -3169,8 +3297,18 @@ function createACPPlatform(deps) {
|
|
|
3169
3297
|
await tools?.revoke();
|
|
3170
3298
|
throw error;
|
|
3171
3299
|
}
|
|
3172
|
-
if (tools)
|
|
3173
|
-
|
|
3300
|
+
if (tools) {
|
|
3301
|
+
const local = new AbortController();
|
|
3302
|
+
worker.toolBindings.set(id3, {
|
|
3303
|
+
signal: tools.signal ? AbortSignal.any([local.signal, tools.signal]) : local.signal,
|
|
3304
|
+
revoke: async () => {
|
|
3305
|
+
if (!local.signal.aborted) {
|
|
3306
|
+
local.abort();
|
|
3307
|
+
await tools.revoke();
|
|
3308
|
+
}
|
|
3309
|
+
}
|
|
3310
|
+
});
|
|
3311
|
+
}
|
|
3174
3312
|
worker.sessions.set(id3, channel);
|
|
3175
3313
|
}
|
|
3176
3314
|
if (command.op === "open")
|
|
@@ -3200,7 +3338,28 @@ function createACPPlatform(deps) {
|
|
|
3200
3338
|
const chunks = [];
|
|
3201
3339
|
let bytes = 0;
|
|
3202
3340
|
let exceeded = false;
|
|
3341
|
+
const pendingTools = /* @__PURE__ */ new Map();
|
|
3203
3342
|
const started = channel.subscribe((event) => {
|
|
3343
|
+
const update = event.update;
|
|
3344
|
+
if (update.sessionUpdate === "tool_call" || update.sessionUpdate === "tool_call_update") {
|
|
3345
|
+
const previous = pendingTools.get(update.toolCallId);
|
|
3346
|
+
if (update.status === "completed" || update.status === "failed") {
|
|
3347
|
+
pendingTools.delete(update.toolCallId);
|
|
3348
|
+
} else if ((previous || update.sessionUpdate === "tool_call") && (previous || pendingTools.size < maxPermissionCalls)) {
|
|
3349
|
+
const raw = update.rawInput ?? previous?.rawInput;
|
|
3350
|
+
if (canonicalToolInput(raw)) {
|
|
3351
|
+
pendingTools.set(update.toolCallId, {
|
|
3352
|
+
toolCallId: update.toolCallId,
|
|
3353
|
+
title: update.title ?? previous?.title,
|
|
3354
|
+
kind: update.kind ?? previous?.kind,
|
|
3355
|
+
name: update.name ?? previous?.name,
|
|
3356
|
+
rawInput: raw
|
|
3357
|
+
});
|
|
3358
|
+
} else {
|
|
3359
|
+
pendingTools.delete(update.toolCallId);
|
|
3360
|
+
}
|
|
3361
|
+
}
|
|
3362
|
+
}
|
|
3204
3363
|
if (event.update.sessionUpdate === "agent_message_chunk" && event.update.content.type === "text") {
|
|
3205
3364
|
bytes += Buffer.byteLength(event.update.content.text);
|
|
3206
3365
|
exceeded ||= bytes > effective.limits.maxOutputBytes;
|
|
@@ -3221,7 +3380,26 @@ function createACPPlatform(deps) {
|
|
|
3221
3380
|
}
|
|
3222
3381
|
const timer = setInterval(flush, 50);
|
|
3223
3382
|
const nativeId = worker.nativeIds.get(id3);
|
|
3224
|
-
worker.
|
|
3383
|
+
const toolSignal = worker.toolBindings.get(id3)?.signal;
|
|
3384
|
+
const turnSignal = toolSignal ? AbortSignal.any([context.signal, toolSignal]) : context.signal;
|
|
3385
|
+
const permissionContext = { ...context, signal: turnSignal };
|
|
3386
|
+
worker.approvals.set(nativeId, (request2) => {
|
|
3387
|
+
const fromEvent = pendingTools.get(request2.toolCall.toolCallId);
|
|
3388
|
+
const explicit = request2.toolCall;
|
|
3389
|
+
if (fromEvent && (explicit.kind && fromEvent.kind && explicit.kind !== fromEvent.kind || explicit.name && fromEvent.name && explicit.name !== fromEvent.name || explicit.rawInput !== void 0 && canonicalToolInput(explicit.rawInput) !== canonicalToolInput(fromEvent.rawInput))) {
|
|
3390
|
+
return Promise.resolve({
|
|
3391
|
+
outcome: { outcome: "cancelled" }
|
|
3392
|
+
});
|
|
3393
|
+
}
|
|
3394
|
+
const toolCall = {
|
|
3395
|
+
...explicit,
|
|
3396
|
+
kind: explicit.kind ?? fromEvent?.kind,
|
|
3397
|
+
name: explicit.name ?? fromEvent?.name,
|
|
3398
|
+
title: explicit.title ?? fromEvent?.title,
|
|
3399
|
+
rawInput: explicit.rawInput ?? fromEvent?.rawInput
|
|
3400
|
+
};
|
|
3401
|
+
return decidePermission(binding, id3, permissionContext, { ...request2, toolCall }, { ...resolved, effective });
|
|
3402
|
+
});
|
|
3225
3403
|
try {
|
|
3226
3404
|
const response = await channel.prompt([
|
|
3227
3405
|
...supplement,
|
|
@@ -3229,7 +3407,9 @@ function createACPPlatform(deps) {
|
|
|
3229
3407
|
...workspace,
|
|
3230
3408
|
...history,
|
|
3231
3409
|
...prompt
|
|
3232
|
-
],
|
|
3410
|
+
], turnSignal);
|
|
3411
|
+
if (toolSignal?.aborted)
|
|
3412
|
+
return { error: "closed" };
|
|
3233
3413
|
flush();
|
|
3234
3414
|
await writes;
|
|
3235
3415
|
if (exceeded)
|
|
@@ -3257,6 +3437,10 @@ function createACPPlatform(deps) {
|
|
|
3257
3437
|
stopReason: response.stopReason,
|
|
3258
3438
|
...parsed !== void 0 && { json: parsed }
|
|
3259
3439
|
});
|
|
3440
|
+
} catch (error) {
|
|
3441
|
+
if (toolSignal?.aborted)
|
|
3442
|
+
return { error: "closed" };
|
|
3443
|
+
throw error;
|
|
3260
3444
|
} finally {
|
|
3261
3445
|
clearInterval(timer);
|
|
3262
3446
|
worker.approvals.delete(nativeId);
|
|
@@ -3549,10 +3733,12 @@ function createACPPlatform(deps) {
|
|
|
3549
3733
|
const entries = await grants.queryPage({
|
|
3550
3734
|
where: {
|
|
3551
3735
|
scopeKey: hash(JSON.stringify(scope())),
|
|
3552
|
-
expires: { $gt: await grants.currentTime() }
|
|
3553
|
-
|
|
3736
|
+
expires: { $gt: await grants.currentTime() },
|
|
3737
|
+
revoked: { $ne: true }
|
|
3738
|
+
},
|
|
3739
|
+
orderBy: { field: "id", direction: "asc" }
|
|
3554
3740
|
}, { offset, limit });
|
|
3555
|
-
return entries.items.
|
|
3741
|
+
return entries.items.map((entry) => ({
|
|
3556
3742
|
id: entry.id,
|
|
3557
3743
|
summary: entry.summary,
|
|
3558
3744
|
sessionId: entry.sessionId,
|
|
@@ -3640,9 +3826,14 @@ function createACPPlatform(deps) {
|
|
|
3640
3826
|
expectedVersion: void 0,
|
|
3641
3827
|
data: { fingerprint }
|
|
3642
3828
|
});
|
|
3643
|
-
if (!claimed && (await intents.get(id3))?.fingerprint !== fingerprint)
|
|
3644
|
-
throw new ACPFailure("conflict");
|
|
3645
3829
|
const saved = await bindings.get(id3);
|
|
3830
|
+
if (!claimed) {
|
|
3831
|
+
const intent = await intents.readVersioned(id3);
|
|
3832
|
+
if (intent?.data.fingerprint !== fingerprint)
|
|
3833
|
+
throw new ACPFailure("conflict");
|
|
3834
|
+
if (!saved && !await intents.compareAndSwap(id3, { expectedVersion: intent.version, data: intent.data }))
|
|
3835
|
+
throw new ACPFailure("conflict");
|
|
3836
|
+
}
|
|
3646
3837
|
if (saved) {
|
|
3647
3838
|
const existing = unwrap(await getRunner().find(saved.workerScope, controlKind, `run:${id3}`));
|
|
3648
3839
|
if (existing) {
|
|
@@ -3652,6 +3843,8 @@ function createACPPlatform(deps) {
|
|
|
3652
3843
|
await stop(saved, id3);
|
|
3653
3844
|
return { taskId: existing.id, output, effectiveOptions: (await plan(subject, saved.request)).effective };
|
|
3654
3845
|
}
|
|
3846
|
+
if (saved.closed)
|
|
3847
|
+
throw new ACPFailure("missing");
|
|
3655
3848
|
}
|
|
3656
3849
|
}
|
|
3657
3850
|
const opened = await open(request2, id3, void 0, true);
|
|
@@ -3679,6 +3872,21 @@ function createACPPlatform(deps) {
|
|
|
3679
3872
|
});
|
|
3680
3873
|
})));
|
|
3681
3874
|
unregister.push(unwrap(runner.register(controlKind, control)));
|
|
3875
|
+
if (runner.isExecutor) {
|
|
3876
|
+
const maintainPersistence = createACPMaintenance(runner, { bindings, intents, receipts });
|
|
3877
|
+
maintenanceTimer = setInterval(() => {
|
|
3878
|
+
maintenancePending ??= Promise.allSettled([
|
|
3879
|
+
maintainApprovals(),
|
|
3880
|
+
maintainPersistence()
|
|
3881
|
+
]).then((results) => {
|
|
3882
|
+
if (results.some((result) => result.status === "rejected"))
|
|
3883
|
+
logger3.warn("ACP persistence maintenance failed");
|
|
3884
|
+
}).finally(() => {
|
|
3885
|
+
maintenancePending = void 0;
|
|
3886
|
+
});
|
|
3887
|
+
}, maintenanceIntervalMs);
|
|
3888
|
+
maintenanceTimer.unref();
|
|
3889
|
+
}
|
|
3682
3890
|
} catch (error) {
|
|
3683
3891
|
for (const remove of unregister.splice(0)) remove();
|
|
3684
3892
|
throw error;
|
|
@@ -3686,6 +3894,8 @@ function createACPPlatform(deps) {
|
|
|
3686
3894
|
}
|
|
3687
3895
|
async function close() {
|
|
3688
3896
|
closed = true;
|
|
3897
|
+
clearInterval(maintenanceTimer);
|
|
3898
|
+
await maintenancePending;
|
|
3689
3899
|
for (const remove of unregister.splice(0)) remove();
|
|
3690
3900
|
const results = await Promise.allSettled([...owned].map(async ([id3, scope]) => {
|
|
3691
3901
|
if (runner)
|
|
@@ -5411,7 +5621,7 @@ async function describeHttpError(response) {
|
|
|
5411
5621
|
const text = await response.text().catch(() => "");
|
|
5412
5622
|
return `HTTP ${response.status} ${text.slice(0, 200)}`.trim();
|
|
5413
5623
|
}
|
|
5414
|
-
var
|
|
5624
|
+
var logger4 = core.logger.child({ module: "ai", scope: "audio-ws" });
|
|
5415
5625
|
function openAudioWebSocket(url, headers, options) {
|
|
5416
5626
|
return new Promise((resolve3, reject) => {
|
|
5417
5627
|
const ws = new WebSocket2(url, { headers, handshakeTimeout: options?.timeout ?? 15e3 });
|
|
@@ -5471,7 +5681,7 @@ function openAudioWebSocket(url, headers, options) {
|
|
|
5471
5681
|
return;
|
|
5472
5682
|
}
|
|
5473
5683
|
failure = error;
|
|
5474
|
-
|
|
5684
|
+
logger4.debug("Audio WebSocket error", { error: error.message });
|
|
5475
5685
|
settleClosed();
|
|
5476
5686
|
});
|
|
5477
5687
|
ws.on("close", () => {
|
|
@@ -5534,7 +5744,7 @@ function openAudioWebSocket(url, headers, options) {
|
|
|
5534
5744
|
}
|
|
5535
5745
|
|
|
5536
5746
|
// src/audio/providers/ai-audio-provider-doubao.ts
|
|
5537
|
-
var
|
|
5747
|
+
var logger5 = core.logger.child({ module: "ai", scope: "audio-doubao" });
|
|
5538
5748
|
var DOUBAO_CAPABILITIES = {
|
|
5539
5749
|
transcribe: {
|
|
5540
5750
|
supported: true,
|
|
@@ -5718,7 +5928,7 @@ function createDoubaoAudioProvider() {
|
|
|
5718
5928
|
}
|
|
5719
5929
|
return ok({ text: finalText });
|
|
5720
5930
|
} catch (error) {
|
|
5721
|
-
|
|
5931
|
+
logger5.debug("Doubao transcribe failed", {
|
|
5722
5932
|
error: errorMessage(error)
|
|
5723
5933
|
});
|
|
5724
5934
|
return toAudioErrorResult(error);
|
|
@@ -5817,7 +6027,7 @@ function createDoubaoAudioProvider() {
|
|
|
5817
6027
|
channels: out.channels
|
|
5818
6028
|
});
|
|
5819
6029
|
} catch (error) {
|
|
5820
|
-
|
|
6030
|
+
logger5.debug("Doubao synthesize failed", {
|
|
5821
6031
|
error: errorMessage(error)
|
|
5822
6032
|
});
|
|
5823
6033
|
return toAudioErrorResult(error);
|
|
@@ -5907,7 +6117,7 @@ function decodeBinaryMessage(message) {
|
|
|
5907
6117
|
return void 0;
|
|
5908
6118
|
return decodeFrame(message.binary);
|
|
5909
6119
|
}
|
|
5910
|
-
var
|
|
6120
|
+
var logger6 = core.logger.child({ module: "ai", scope: "audio-indextts" });
|
|
5911
6121
|
var INDEX_TTS_CAPABILITIES = {
|
|
5912
6122
|
synthesize: {
|
|
5913
6123
|
supported: true,
|
|
@@ -5987,7 +6197,7 @@ function createIndexTtsAudioProvider() {
|
|
|
5987
6197
|
await dispatcher.close();
|
|
5988
6198
|
}
|
|
5989
6199
|
} catch (error) {
|
|
5990
|
-
|
|
6200
|
+
logger6.debug("IndexTTS synthesize failed", {
|
|
5991
6201
|
error: errorMessage(error)
|
|
5992
6202
|
});
|
|
5993
6203
|
return toAudioErrorResult(error, requestSignal);
|
|
@@ -6266,7 +6476,7 @@ function encodeSSE(event) {
|
|
|
6266
6476
|
}
|
|
6267
6477
|
|
|
6268
6478
|
// src/audio/providers/ai-audio-provider-mimo.ts
|
|
6269
|
-
var
|
|
6479
|
+
var logger7 = core.logger.child({ module: "ai", scope: "audio-mimo" });
|
|
6270
6480
|
var MIMO_CAPABILITIES = {
|
|
6271
6481
|
transcribe: {
|
|
6272
6482
|
supported: true,
|
|
@@ -6315,7 +6525,7 @@ function createMimoAudioProvider() {
|
|
|
6315
6525
|
const text = body.choices?.[0]?.message?.content ?? "";
|
|
6316
6526
|
return ok({ text });
|
|
6317
6527
|
} catch (error) {
|
|
6318
|
-
|
|
6528
|
+
logger7.debug("MiMo transcribe failed", {
|
|
6319
6529
|
error: errorMessage(error)
|
|
6320
6530
|
});
|
|
6321
6531
|
return toAudioErrorResult(error, requestSignal);
|
|
@@ -6399,7 +6609,7 @@ function createMimoAudioProvider() {
|
|
|
6399
6609
|
channels: out.channels
|
|
6400
6610
|
});
|
|
6401
6611
|
} catch (error) {
|
|
6402
|
-
|
|
6612
|
+
logger7.debug("MiMo synthesize failed", {
|
|
6403
6613
|
error: errorMessage(error)
|
|
6404
6614
|
});
|
|
6405
6615
|
return toAudioErrorResult(error, requestSignal);
|
|
@@ -6482,7 +6692,7 @@ async function* readChunks(response, signal) {
|
|
|
6482
6692
|
yield chunk;
|
|
6483
6693
|
}
|
|
6484
6694
|
}
|
|
6485
|
-
var
|
|
6695
|
+
var logger8 = core.logger.child({ module: "ai", scope: "audio-openai" });
|
|
6486
6696
|
var OPENAI_CAPABILITIES = {
|
|
6487
6697
|
transcribe: {
|
|
6488
6698
|
supported: true,
|
|
@@ -6522,7 +6732,7 @@ function createOpenAIAudioProvider() {
|
|
|
6522
6732
|
}, { signal });
|
|
6523
6733
|
return ok({ text: result.text });
|
|
6524
6734
|
} catch (error) {
|
|
6525
|
-
|
|
6735
|
+
logger8.debug("OpenAI transcribe failed", {
|
|
6526
6736
|
error: errorMessage(error)
|
|
6527
6737
|
});
|
|
6528
6738
|
return toAudioErrorResult(error, signal);
|
|
@@ -6589,7 +6799,7 @@ function createOpenAIAudioProvider() {
|
|
|
6589
6799
|
channels: out.channels
|
|
6590
6800
|
});
|
|
6591
6801
|
} catch (error) {
|
|
6592
|
-
|
|
6802
|
+
logger8.debug("OpenAI synthesize failed", {
|
|
6593
6803
|
error: errorMessage(error)
|
|
6594
6804
|
});
|
|
6595
6805
|
return toAudioErrorResult(error, signal);
|
|
@@ -6652,7 +6862,7 @@ async function toUploadFile(audio) {
|
|
|
6652
6862
|
const part = toAudioUploadPart(audio);
|
|
6653
6863
|
return toFile(Buffer.from(part.data), part.filename);
|
|
6654
6864
|
}
|
|
6655
|
-
var
|
|
6865
|
+
var logger9 = core.logger.child({ module: "ai", scope: "audio-qwen" });
|
|
6656
6866
|
var QWEN_CAPABILITIES = {
|
|
6657
6867
|
transcribe: {
|
|
6658
6868
|
supported: true,
|
|
@@ -6697,7 +6907,7 @@ function createQwenAudioProvider() {
|
|
|
6697
6907
|
}
|
|
6698
6908
|
return ok({ text: finalText });
|
|
6699
6909
|
} catch (error) {
|
|
6700
|
-
|
|
6910
|
+
logger9.debug("Qwen transcribe failed", {
|
|
6701
6911
|
error: errorMessage(error)
|
|
6702
6912
|
});
|
|
6703
6913
|
return toAudioErrorResult(error);
|
|
@@ -6806,7 +7016,7 @@ function createQwenAudioProvider() {
|
|
|
6806
7016
|
channels: out.channels
|
|
6807
7017
|
});
|
|
6808
7018
|
} catch (error) {
|
|
6809
|
-
|
|
7019
|
+
logger9.debug("Qwen synthesize failed", {
|
|
6810
7020
|
error: errorMessage(error)
|
|
6811
7021
|
});
|
|
6812
7022
|
return toAudioErrorResult(error);
|
|
@@ -6900,7 +7110,7 @@ function parseEvent(text) {
|
|
|
6900
7110
|
return {};
|
|
6901
7111
|
}
|
|
6902
7112
|
}
|
|
6903
|
-
var
|
|
7113
|
+
var logger10 = core.logger.child({ module: "ai", scope: "audio-whisper" });
|
|
6904
7114
|
var WHISPER_CAPABILITIES = {
|
|
6905
7115
|
transcribe: {
|
|
6906
7116
|
supported: true,
|
|
@@ -6949,7 +7159,7 @@ function createWhisperAudioProvider() {
|
|
|
6949
7159
|
const body = await response.json();
|
|
6950
7160
|
return ok(mapWhisperResponse(body));
|
|
6951
7161
|
} catch (error) {
|
|
6952
|
-
|
|
7162
|
+
logger10.debug("Whisper transcribe failed", {
|
|
6953
7163
|
error: errorMessage(error)
|
|
6954
7164
|
});
|
|
6955
7165
|
return toAudioErrorResult(error, signal);
|
|
@@ -6995,7 +7205,7 @@ function mapWhisperWord(word) {
|
|
|
6995
7205
|
}
|
|
6996
7206
|
|
|
6997
7207
|
// src/audio/ai-audio-functions.ts
|
|
6998
|
-
var
|
|
7208
|
+
var logger11 = core.logger.child({ module: "ai", scope: "audio" });
|
|
6999
7209
|
function createAudioOperations(config) {
|
|
7000
7210
|
const audioConfig = AudioConfigSchema.parse(config.audio ?? {});
|
|
7001
7211
|
const providerCache = /* @__PURE__ */ new Map();
|
|
@@ -7061,7 +7271,7 @@ function createAudioOperations(config) {
|
|
|
7061
7271
|
}
|
|
7062
7272
|
const startedAt = Date.now();
|
|
7063
7273
|
const context = { provider: resolved.data.provider, model: resolved.data.model, audioBytes: request2.audio.data.length };
|
|
7064
|
-
|
|
7274
|
+
logger11.debug("Audio transcription started", context);
|
|
7065
7275
|
const result = await transcription.transcribe({
|
|
7066
7276
|
model: resolved.data,
|
|
7067
7277
|
audio: request2.audio,
|
|
@@ -7072,9 +7282,9 @@ function createAudioOperations(config) {
|
|
|
7072
7282
|
signal: request2.signal
|
|
7073
7283
|
});
|
|
7074
7284
|
if (result.success) {
|
|
7075
|
-
|
|
7285
|
+
logger11.info("Audio transcription completed", { ...context, durationMs: Date.now() - startedAt, textLength: result.data.text.length });
|
|
7076
7286
|
} else {
|
|
7077
|
-
|
|
7287
|
+
logger11.warn("Audio transcription failed", {
|
|
7078
7288
|
...context,
|
|
7079
7289
|
durationMs: Date.now() - startedAt,
|
|
7080
7290
|
code: result.error.code,
|
|
@@ -7114,7 +7324,7 @@ function createAudioOperations(config) {
|
|
|
7114
7324
|
}
|
|
7115
7325
|
const startedAt = Date.now();
|
|
7116
7326
|
const context = { provider: resolved.data.provider, model: resolved.data.model };
|
|
7117
|
-
|
|
7327
|
+
logger11.debug("Audio transcription stream started", context);
|
|
7118
7328
|
const signal = withStreamTimeout(request2.signal);
|
|
7119
7329
|
try {
|
|
7120
7330
|
yield* transcribeStreamOrFallback(transcription, {
|
|
@@ -7126,9 +7336,9 @@ function createAudioOperations(config) {
|
|
|
7126
7336
|
vad: request2.vad,
|
|
7127
7337
|
signal
|
|
7128
7338
|
});
|
|
7129
|
-
|
|
7339
|
+
logger11.info("Audio transcription stream completed", { ...context, durationMs: Date.now() - startedAt });
|
|
7130
7340
|
} catch (error) {
|
|
7131
|
-
|
|
7341
|
+
logger11.warn("Audio transcription stream failed", { ...context, durationMs: Date.now() - startedAt, error });
|
|
7132
7342
|
throw mapStreamError(error, signal);
|
|
7133
7343
|
}
|
|
7134
7344
|
}
|
|
@@ -7169,7 +7379,7 @@ function createAudioOperations(config) {
|
|
|
7169
7379
|
textLength: request2.text.length,
|
|
7170
7380
|
voice: request2.voice
|
|
7171
7381
|
};
|
|
7172
|
-
|
|
7382
|
+
logger11.debug("Audio synthesis started", context);
|
|
7173
7383
|
const result = await synthesis.synthesize({
|
|
7174
7384
|
model: resolved.data,
|
|
7175
7385
|
text: request2.text,
|
|
@@ -7187,14 +7397,14 @@ function createAudioOperations(config) {
|
|
|
7187
7397
|
signal: request2.signal
|
|
7188
7398
|
});
|
|
7189
7399
|
if (result.success) {
|
|
7190
|
-
|
|
7400
|
+
logger11.info("Audio synthesis completed", {
|
|
7191
7401
|
...context,
|
|
7192
7402
|
durationMs: Date.now() - startedAt,
|
|
7193
7403
|
audioBytes: result.data.data.length,
|
|
7194
7404
|
format: result.data.format
|
|
7195
7405
|
});
|
|
7196
7406
|
} else {
|
|
7197
|
-
|
|
7407
|
+
logger11.warn("Audio synthesis failed", {
|
|
7198
7408
|
...context,
|
|
7199
7409
|
durationMs: Date.now() - startedAt,
|
|
7200
7410
|
code: result.error.code,
|
|
@@ -7230,7 +7440,7 @@ function createAudioOperations(config) {
|
|
|
7230
7440
|
}
|
|
7231
7441
|
const startedAt = Date.now();
|
|
7232
7442
|
const context = { provider: resolved.data.provider, model: resolved.data.model, voice: request2.voice };
|
|
7233
|
-
|
|
7443
|
+
logger11.debug("Audio synthesis stream started", context);
|
|
7234
7444
|
const signal = withStreamTimeout(request2.signal);
|
|
7235
7445
|
const output = synthesis.resolveSynthesisOutput({ format: request2.format, sampleRate: request2.sampleRate });
|
|
7236
7446
|
try {
|
|
@@ -7266,9 +7476,9 @@ function createAudioOperations(config) {
|
|
|
7266
7476
|
yield { type: "audio", segmentId: segment.id, data };
|
|
7267
7477
|
yield { type: "segment_done", segmentId: segment.id };
|
|
7268
7478
|
}
|
|
7269
|
-
|
|
7479
|
+
logger11.info("Audio synthesis stream completed", { ...context, durationMs: Date.now() - startedAt });
|
|
7270
7480
|
} catch (error) {
|
|
7271
|
-
|
|
7481
|
+
logger11.warn("Audio synthesis stream failed", { ...context, durationMs: Date.now() - startedAt, error });
|
|
7272
7482
|
throw mapStreamError(error, signal);
|
|
7273
7483
|
}
|
|
7274
7484
|
}
|
|
@@ -7427,7 +7637,7 @@ function createProvider(name) {
|
|
|
7427
7637
|
return createIndexTtsAudioProvider();
|
|
7428
7638
|
}
|
|
7429
7639
|
}
|
|
7430
|
-
var
|
|
7640
|
+
var logger12 = core.logger.child({ module: "ai", scope: "compress" });
|
|
7431
7641
|
var CONVERSATION_SUMMARY_PREFIX = "[Conversation Summary]";
|
|
7432
7642
|
var CONVERSATION_SUMMARY_NAME = "hai_internal_conversation_summary_v1";
|
|
7433
7643
|
function completeCompression(result, maxTokens) {
|
|
@@ -7574,7 +7784,7 @@ function createCompressOperations(config, token, summary, modelMaxTokens) {
|
|
|
7574
7784
|
const maxTokens = resolveMaxTokens(options?.maxTokens);
|
|
7575
7785
|
const preserveSystem = options?.preserveSystem ?? true;
|
|
7576
7786
|
const preserveLastN = options?.preserveLastN ?? config.preserveLastN;
|
|
7577
|
-
|
|
7787
|
+
logger12.trace("Compressing context", { strategy, maxTokens, messageCount: messages.length });
|
|
7578
7788
|
try {
|
|
7579
7789
|
const originalTokens = token.estimateMessages(messages);
|
|
7580
7790
|
if (originalTokens <= maxTokens) {
|
|
@@ -7593,7 +7803,7 @@ function createCompressOperations(config, token, summary, modelMaxTokens) {
|
|
|
7593
7803
|
preserveLastN
|
|
7594
7804
|
);
|
|
7595
7805
|
const compressedTokens = token.estimateMessages(compressed);
|
|
7596
|
-
|
|
7806
|
+
logger12.trace("Sliding window compression completed", { originalTokens, compressedTokens, removedCount });
|
|
7597
7807
|
return completeCompression({
|
|
7598
7808
|
messages: compressed,
|
|
7599
7809
|
originalTokens,
|
|
@@ -7630,7 +7840,7 @@ ${summaryText}`
|
|
|
7630
7840
|
...preserved
|
|
7631
7841
|
];
|
|
7632
7842
|
const compressedTokens = token.estimateMessages(compressed);
|
|
7633
|
-
|
|
7843
|
+
logger12.trace("Summary compression completed", { originalTokens, compressedTokens, removedCount: toSummarize2.length });
|
|
7634
7844
|
return completeCompression({
|
|
7635
7845
|
messages: compressed,
|
|
7636
7846
|
originalTokens,
|
|
@@ -7675,7 +7885,7 @@ ${summaryText}`
|
|
|
7675
7885
|
...preservedMessages
|
|
7676
7886
|
];
|
|
7677
7887
|
const compressedTokens = token.estimateMessages(compressed);
|
|
7678
|
-
|
|
7888
|
+
logger12.trace("Hybrid compression completed", { originalTokens, compressedTokens, removedCount: toSummarize.length });
|
|
7679
7889
|
return completeCompression({
|
|
7680
7890
|
messages: compressed,
|
|
7681
7891
|
originalTokens,
|
|
@@ -7691,7 +7901,7 @@ ${summaryText}`
|
|
|
7691
7901
|
removedCount: windowRemoved
|
|
7692
7902
|
}, maxTokens);
|
|
7693
7903
|
} catch (error) {
|
|
7694
|
-
|
|
7904
|
+
logger12.error("Context compression failed", { error });
|
|
7695
7905
|
return err(HaiAIError.CONTEXT_COMPRESS_FAILED, aiM("ai_contextCompressFailed", {
|
|
7696
7906
|
params: {
|
|
7697
7907
|
error: String(error)
|
|
@@ -7773,7 +7983,7 @@ function createContextStateAccess(store, scope, initial, receive) {
|
|
|
7773
7983
|
}
|
|
7774
7984
|
|
|
7775
7985
|
// src/context/ai-context-functions.ts
|
|
7776
|
-
var
|
|
7986
|
+
var logger13 = core.logger.child({ module: "ai", scope: "context" });
|
|
7777
7987
|
var GENERATION_LEASE_MS = 3e4;
|
|
7778
7988
|
function contextFailure(error) {
|
|
7779
7989
|
const code = error instanceof ContextStateError ? error.definition : HaiAIError.STORE_FAILED;
|
|
@@ -7868,11 +8078,11 @@ function createContextOperations(compressConfig, tokenOps, compressOps, contextS
|
|
|
7868
8078
|
})).then((result) => {
|
|
7869
8079
|
if (!result.success) {
|
|
7870
8080
|
failedMemoryTasks++;
|
|
7871
|
-
|
|
8081
|
+
logger13.warn("Background memory extraction failed", { source: "result" });
|
|
7872
8082
|
}
|
|
7873
8083
|
}).catch(() => {
|
|
7874
8084
|
failedMemoryTasks++;
|
|
7875
|
-
|
|
8085
|
+
logger13.warn("Background memory extraction failed", { source: "exception" });
|
|
7876
8086
|
}).finally(() => {
|
|
7877
8087
|
pendingMemoryTasks.delete(task);
|
|
7878
8088
|
});
|
|
@@ -8019,7 +8229,7 @@ function createContextOperations(compressConfig, tokenOps, compressOps, contextS
|
|
|
8019
8229
|
} catch (error) {
|
|
8020
8230
|
if (requirePersistence)
|
|
8021
8231
|
throw error;
|
|
8022
|
-
|
|
8232
|
+
logger13.warn("Context producer settlement failed", { error });
|
|
8023
8233
|
}
|
|
8024
8234
|
}
|
|
8025
8235
|
const manager = {
|
|
@@ -8170,7 +8380,7 @@ function createContextOperations(compressConfig, tokenOps, compressOps, contextS
|
|
|
8170
8380
|
return extracted;
|
|
8171
8381
|
return ok({ summary: summaryText, memories: extracted.data });
|
|
8172
8382
|
} catch (error) {
|
|
8173
|
-
|
|
8383
|
+
logger13.error("Context consolidate failed", { error });
|
|
8174
8384
|
return err(HaiAIError.MEMORY_PROMOTE_FAILED, aiM("ai_memoryPromoteFailed", {
|
|
8175
8385
|
params: {
|
|
8176
8386
|
error: String(error)
|
|
@@ -8328,7 +8538,7 @@ function createContextOperations(compressConfig, tokenOps, compressOps, contextS
|
|
|
8328
8538
|
usage: lastUsage
|
|
8329
8539
|
});
|
|
8330
8540
|
} catch (error) {
|
|
8331
|
-
|
|
8541
|
+
logger13.error("Context chat failed", { error });
|
|
8332
8542
|
return contextFailure(error);
|
|
8333
8543
|
} finally {
|
|
8334
8544
|
release();
|
|
@@ -8687,8 +8897,8 @@ function createContextOperations(compressConfig, tokenOps, compressOps, contextS
|
|
|
8687
8897
|
}
|
|
8688
8898
|
};
|
|
8689
8899
|
}
|
|
8690
|
-
var
|
|
8691
|
-
function createEmbeddingOperations(config) {
|
|
8900
|
+
var logger14 = core.logger.child({ module: "ai", scope: "embedding" });
|
|
8901
|
+
function createEmbeddingOperations(config, loadModels = () => config.llm) {
|
|
8692
8902
|
const embeddingConfig = config.embedding ?? { batchSize: 100 };
|
|
8693
8903
|
let cachedClient = null;
|
|
8694
8904
|
let cachedResolvedKey;
|
|
@@ -8703,15 +8913,7 @@ function createEmbeddingOperations(config) {
|
|
|
8703
8913
|
cachedResolvedKey = cacheKey;
|
|
8704
8914
|
return cachedClient;
|
|
8705
8915
|
}
|
|
8706
|
-
async function callEmbeddingAPI(request2) {
|
|
8707
|
-
const resolvedResult = resolveModelEntry(config.llm, "embedding", request2.model, {
|
|
8708
|
-
missingApiKeyMessage: aiM("ai_configError", {
|
|
8709
|
-
params: { error: "API Key is required for embedding" }
|
|
8710
|
-
})
|
|
8711
|
-
});
|
|
8712
|
-
if (!resolvedResult.success)
|
|
8713
|
-
return resolvedResult;
|
|
8714
|
-
const resolved = resolvedResult.data;
|
|
8916
|
+
async function callEmbeddingAPI(request2, resolved) {
|
|
8715
8917
|
const input = Array.isArray(request2.input) ? request2.input : [request2.input];
|
|
8716
8918
|
try {
|
|
8717
8919
|
const client2 = getOrCreateClient(resolved);
|
|
@@ -8735,7 +8937,7 @@ function createEmbeddingOperations(config) {
|
|
|
8735
8937
|
}
|
|
8736
8938
|
});
|
|
8737
8939
|
} catch (error) {
|
|
8738
|
-
|
|
8940
|
+
logger14.error("Embedding API call failed", { error });
|
|
8739
8941
|
return err(HaiAIError.EMBEDDING_API_ERROR, aiM("ai_internalError", {
|
|
8740
8942
|
params: {
|
|
8741
8943
|
error: String(error)
|
|
@@ -8744,18 +8946,25 @@ function createEmbeddingOperations(config) {
|
|
|
8744
8946
|
}
|
|
8745
8947
|
}
|
|
8746
8948
|
async function embedRequest(request2) {
|
|
8949
|
+
const resolved = resolveModelEntry(await loadModels(request2.model), "embedding", request2.model, {
|
|
8950
|
+
missingApiKeyMessage: aiM("ai_configError", {
|
|
8951
|
+
params: { error: "API Key is required for embedding" }
|
|
8952
|
+
})
|
|
8953
|
+
});
|
|
8954
|
+
if (!resolved.success)
|
|
8955
|
+
return resolved;
|
|
8747
8956
|
const input = Array.isArray(request2.input) ? request2.input : [request2.input];
|
|
8748
|
-
const
|
|
8749
|
-
if (input.length <=
|
|
8750
|
-
return callEmbeddingAPI(request2);
|
|
8957
|
+
const batchSize3 = embeddingConfig.batchSize;
|
|
8958
|
+
if (input.length <= batchSize3) {
|
|
8959
|
+
return callEmbeddingAPI(request2, resolved.data);
|
|
8751
8960
|
}
|
|
8752
8961
|
const allData = [];
|
|
8753
8962
|
let totalPromptTokens = 0;
|
|
8754
8963
|
let totalTokens = 0;
|
|
8755
8964
|
let resultModel = "";
|
|
8756
|
-
for (let i = 0; i < input.length; i +=
|
|
8757
|
-
const batch = input.slice(i, i +
|
|
8758
|
-
const result = await callEmbeddingAPI({ ...request2, input: batch });
|
|
8965
|
+
for (let i = 0; i < input.length; i += batchSize3) {
|
|
8966
|
+
const batch = input.slice(i, i + batchSize3);
|
|
8967
|
+
const result = await callEmbeddingAPI({ ...request2, input: batch }, resolved.data);
|
|
8759
8968
|
if (!result.success)
|
|
8760
8969
|
return result;
|
|
8761
8970
|
resultModel = result.data.model;
|
|
@@ -8934,7 +9143,7 @@ function parseHtmlFile(content, outputFormat) {
|
|
|
8934
9143
|
}
|
|
8935
9144
|
|
|
8936
9145
|
// src/file/ai-file-functions.ts
|
|
8937
|
-
var
|
|
9146
|
+
var logger15 = core.logger.child({ module: "ai", scope: "file" });
|
|
8938
9147
|
var TEXT_MIME_TYPES = /* @__PURE__ */ new Set([
|
|
8939
9148
|
"text/plain",
|
|
8940
9149
|
"text/markdown",
|
|
@@ -9079,7 +9288,7 @@ async function parseImageWithOcr(content, mimeType, llmOps, model, outputFormat
|
|
|
9079
9288
|
const dataUrl = `data:${mimeType};base64,${base64}`;
|
|
9080
9289
|
const defaultPrompt = outputFormat === "markdown" ? "Please extract all text content from this image as Markdown, preserving document structure (headings, bullet lists, bold/italic). Return only the Markdown without additional commentary." : "Please extract all text content from this image accurately. Return only the extracted text without any additional commentary.";
|
|
9081
9290
|
const prompt = customPrompt ?? defaultPrompt;
|
|
9082
|
-
|
|
9291
|
+
logger15.trace("Running OCR via vision LLM", { mimeType, model });
|
|
9083
9292
|
const result = await llmOps.chat({
|
|
9084
9293
|
model,
|
|
9085
9294
|
messages: [
|
|
@@ -9134,7 +9343,7 @@ function createFileOperations(config, llmOps) {
|
|
|
9134
9343
|
const { content, filename, options = {} } = request2;
|
|
9135
9344
|
const mimeType = detectMimeType(content, filename, options.mimeType);
|
|
9136
9345
|
const outputFormat = options.outputFormat ?? "text";
|
|
9137
|
-
|
|
9346
|
+
logger15.trace("Parsing file", {
|
|
9138
9347
|
filename,
|
|
9139
9348
|
mimeType,
|
|
9140
9349
|
outputFormat,
|
|
@@ -9179,7 +9388,7 @@ function createFileOperations(config, llmOps) {
|
|
|
9179
9388
|
metadata: { filename, mimeType, charCount: pdfResult.data.text.length }
|
|
9180
9389
|
});
|
|
9181
9390
|
}
|
|
9182
|
-
|
|
9391
|
+
logger15.warn("PDF native parser failed, falling back to OCR", { filename });
|
|
9183
9392
|
return runOcr(content, mimeType, filename, options.model, outputFormat, options.systemPrompt);
|
|
9184
9393
|
}
|
|
9185
9394
|
if (mimeType === "application/vnd.openxmlformats-officedocument.wordprocessingml.document" || mimeType === "application/msword" || mimeType === "application/zip") {
|
|
@@ -9196,7 +9405,7 @@ function createFileOperations(config, llmOps) {
|
|
|
9196
9405
|
metadata: { filename, mimeType, charCount: docxResult.data.length }
|
|
9197
9406
|
});
|
|
9198
9407
|
}
|
|
9199
|
-
|
|
9408
|
+
logger15.warn("DOCX native parser failed, falling back to OCR", { filename });
|
|
9200
9409
|
return runOcr(content, mimeType, filename, options.model, outputFormat, options.systemPrompt);
|
|
9201
9410
|
}
|
|
9202
9411
|
if (IMAGE_MIME_TYPES.has(mimeType)) {
|
|
@@ -9216,7 +9425,7 @@ function createFileOperations(config, llmOps) {
|
|
|
9216
9425
|
try {
|
|
9217
9426
|
return await doParse(request2);
|
|
9218
9427
|
} catch (error) {
|
|
9219
|
-
|
|
9428
|
+
logger15.error("File parse failed unexpectedly", { filename: request2.filename, error });
|
|
9220
9429
|
return err(HaiAIError.FILE_PARSE_FAILED, aiM("ai_fileParseFailed", {
|
|
9221
9430
|
params: {
|
|
9222
9431
|
error: String(error)
|
|
@@ -9770,7 +9979,7 @@ function createSeedreamImageProvider() {
|
|
|
9770
9979
|
}
|
|
9771
9980
|
|
|
9772
9981
|
// src/image/ai-image-functions.ts
|
|
9773
|
-
var
|
|
9982
|
+
var logger16 = core.logger.child({ module: "ai", scope: "image" });
|
|
9774
9983
|
function createImageOperations(config) {
|
|
9775
9984
|
const imageConfig = ImageConfigSchema.parse(config.image ?? {});
|
|
9776
9985
|
const providers = /* @__PURE__ */ new Map();
|
|
@@ -9796,7 +10005,7 @@ function createImageOperations(config) {
|
|
|
9796
10005
|
return err(HaiAIError.IMAGE_CANCELLED, aiM("ai_imageCancelled"));
|
|
9797
10006
|
const resolved = resolveImageModel(imageConfig, request2.model);
|
|
9798
10007
|
if (!resolved.success) {
|
|
9799
|
-
|
|
10008
|
+
logger16.warn("Image model resolution failed", {
|
|
9800
10009
|
code: resolved.error.code,
|
|
9801
10010
|
error: resolved.error.message,
|
|
9802
10011
|
requestedModel: request2.model
|
|
@@ -9811,7 +10020,7 @@ function createImageOperations(config) {
|
|
|
9811
10020
|
width: request2.size?.width,
|
|
9812
10021
|
height: request2.size?.height
|
|
9813
10022
|
};
|
|
9814
|
-
|
|
10023
|
+
logger16.debug("Image generation started", logContext);
|
|
9815
10024
|
const deadline = new AbortController();
|
|
9816
10025
|
const timer = setTimeout(() => deadline.abort(new DOMException("Image deadline exceeded", "TimeoutError")), resolved.data.timeout);
|
|
9817
10026
|
timer.unref();
|
|
@@ -9836,7 +10045,7 @@ function createImageOperations(config) {
|
|
|
9836
10045
|
if (deadline.signal.aborted)
|
|
9837
10046
|
return err(HaiAIError.IMAGE_TIMEOUT, aiM("ai_imageTimeout"));
|
|
9838
10047
|
if (!generated.success) {
|
|
9839
|
-
|
|
10048
|
+
logger16.warn("Image generation failed", {
|
|
9840
10049
|
...logContext,
|
|
9841
10050
|
durationMs: Date.now() - startedAt,
|
|
9842
10051
|
code: generated.error.code,
|
|
@@ -9854,7 +10063,7 @@ function createImageOperations(config) {
|
|
|
9854
10063
|
return validated;
|
|
9855
10064
|
images.push(validated.data);
|
|
9856
10065
|
}
|
|
9857
|
-
|
|
10066
|
+
logger16.info("Image generation completed", {
|
|
9858
10067
|
...logContext,
|
|
9859
10068
|
durationMs: Date.now() - startedAt,
|
|
9860
10069
|
imageCount: generated.data.length,
|
|
@@ -9883,7 +10092,7 @@ function createProvider2(name) {
|
|
|
9883
10092
|
return createPollinationsImageProvider();
|
|
9884
10093
|
}
|
|
9885
10094
|
}
|
|
9886
|
-
var
|
|
10095
|
+
var logger17 = core.logger.child({ module: "ai", scope: "knowledge-entity" });
|
|
9887
10096
|
var LEADING_MARKDOWN_FENCE_REGEX = /^```(?:json)?\n?/;
|
|
9888
10097
|
var TRAILING_MARKDOWN_FENCE_REGEX = /\n?```$/;
|
|
9889
10098
|
var DEFAULT_ENTITY_TYPES = [
|
|
@@ -9929,7 +10138,7 @@ async function extractEntities(llm, text, model, entityTypes, systemPrompt) {
|
|
|
9929
10138
|
enablePersist: false
|
|
9930
10139
|
});
|
|
9931
10140
|
if (!chatResult.success) {
|
|
9932
|
-
|
|
10141
|
+
logger17.warn("Entity extraction LLM call failed", { error: chatResult.error });
|
|
9933
10142
|
return err(HaiAIError.KNOWLEDGE_ENTITY_EXTRACT_FAILED, aiM("ai_knowledgeEntityExtractFailed", {
|
|
9934
10143
|
params: {
|
|
9935
10144
|
error: String(chatResult.error.message)
|
|
@@ -9939,10 +10148,10 @@ async function extractEntities(llm, text, model, entityTypes, systemPrompt) {
|
|
|
9939
10148
|
const content = chatResult.data.choices[0]?.message?.content ?? "";
|
|
9940
10149
|
const validTypes = new Set(resolvedTypes);
|
|
9941
10150
|
const entities = parseEntityResponse(content, validTypes);
|
|
9942
|
-
|
|
10151
|
+
logger17.trace("Entity extraction completed", { textLength: text.length, entityCount: entities.length });
|
|
9943
10152
|
return ok(entities);
|
|
9944
10153
|
} catch (error) {
|
|
9945
|
-
|
|
10154
|
+
logger17.error("Entity extraction failed", { error });
|
|
9946
10155
|
return err(HaiAIError.KNOWLEDGE_ENTITY_EXTRACT_FAILED, aiM("ai_knowledgeEntityExtractFailed", {
|
|
9947
10156
|
params: {
|
|
9948
10157
|
error: String(error)
|
|
@@ -9966,12 +10175,12 @@ function parseEntityResponse(content, validTypes) {
|
|
|
9966
10175
|
return entities.filter(isValidEntity).map((e) => normalizeEntity(e, validTypes));
|
|
9967
10176
|
}
|
|
9968
10177
|
}
|
|
9969
|
-
|
|
10178
|
+
logger17.warn("Entity extraction returned unexpected format", {
|
|
9970
10179
|
content: content.slice(0, 200)
|
|
9971
10180
|
});
|
|
9972
10181
|
return [];
|
|
9973
10182
|
} catch {
|
|
9974
|
-
|
|
10183
|
+
logger17.warn("Entity extraction returned invalid JSON", {
|
|
9975
10184
|
content: content.slice(0, 200)
|
|
9976
10185
|
});
|
|
9977
10186
|
return [];
|
|
@@ -10034,7 +10243,7 @@ async function extractEntitiesBatch(llm, chunks, model, entityTypes, systemPromp
|
|
|
10034
10243
|
}
|
|
10035
10244
|
|
|
10036
10245
|
// src/knowledge/ai-knowledge-functions.ts
|
|
10037
|
-
var
|
|
10246
|
+
var logger18 = core.logger.child({ module: "ai", scope: "knowledge" });
|
|
10038
10247
|
var DEFAULT_KNOWLEDGE_ASK_SYSTEM_PROMPT = `You are an expert assistant. Answer the user's question based ONLY on the provided context.
|
|
10039
10248
|
|
|
10040
10249
|
Rules:
|
|
@@ -10068,15 +10277,15 @@ function createKnowledgeOperations(config, llm, embedding, datapipe2, store) {
|
|
|
10068
10277
|
}
|
|
10069
10278
|
const collection = options?.collection ?? config.collection;
|
|
10070
10279
|
const dimension = options?.dimension ?? config.dimension;
|
|
10071
|
-
|
|
10280
|
+
logger18.debug("Setting up knowledge base", { collection, dimension });
|
|
10072
10281
|
try {
|
|
10073
10282
|
await store.initialize(collection, dimension);
|
|
10074
10283
|
await store.registerCollection(collection, dimension);
|
|
10075
10284
|
await store.repair(collection);
|
|
10076
|
-
|
|
10285
|
+
logger18.debug("Knowledge base setup completed", { collection });
|
|
10077
10286
|
return ok(void 0);
|
|
10078
10287
|
} catch (error) {
|
|
10079
|
-
|
|
10288
|
+
logger18.error("Knowledge base setup failed", { error });
|
|
10080
10289
|
return err(HaiAIError.KNOWLEDGE_SETUP_FAILED, aiM("ai_knowledgeSetupFailed", {
|
|
10081
10290
|
params: {
|
|
10082
10291
|
error: String(error)
|
|
@@ -10115,7 +10324,7 @@ function createKnowledgeOperations(config, llm, embedding, datapipe2, store) {
|
|
|
10115
10324
|
...config.chunkOptions,
|
|
10116
10325
|
...input.chunkOptions
|
|
10117
10326
|
};
|
|
10118
|
-
|
|
10327
|
+
logger18.trace("Ingesting document", { documentId: input.documentId, collection, contentLength: input.content.length });
|
|
10119
10328
|
try {
|
|
10120
10329
|
if (!await isCollectionReady(collection))
|
|
10121
10330
|
return err(HaiAIError.KNOWLEDGE_NOT_SETUP, aiM("ai_knowledgeNotSetup"));
|
|
@@ -10199,7 +10408,7 @@ function createKnowledgeOperations(config, llm, embedding, datapipe2, store) {
|
|
|
10199
10408
|
entities
|
|
10200
10409
|
});
|
|
10201
10410
|
const duration = Date.now() - startTime;
|
|
10202
|
-
|
|
10411
|
+
logger18.debug("Document ingested", {
|
|
10203
10412
|
documentId: input.documentId,
|
|
10204
10413
|
revision,
|
|
10205
10414
|
cleanupPending: published.cleanupPending,
|
|
@@ -10216,7 +10425,7 @@ function createKnowledgeOperations(config, llm, embedding, datapipe2, store) {
|
|
|
10216
10425
|
duration
|
|
10217
10426
|
});
|
|
10218
10427
|
} catch (error) {
|
|
10219
|
-
|
|
10428
|
+
logger18.error("Document ingestion failed", { documentId: input.documentId, error });
|
|
10220
10429
|
return err(HaiAIError.KNOWLEDGE_INGEST_FAILED, aiM("ai_knowledgeIngestFailed", {
|
|
10221
10430
|
params: {
|
|
10222
10431
|
error: String(error)
|
|
@@ -10240,7 +10449,7 @@ function createKnowledgeOperations(config, llm, embedding, datapipe2, store) {
|
|
|
10240
10449
|
const startTime = Date.now();
|
|
10241
10450
|
const topK = options?.topK ?? 10;
|
|
10242
10451
|
const enableEntityBoost = options?.enableEntityBoost ?? true;
|
|
10243
|
-
|
|
10452
|
+
logger18.trace("Knowledge retrieval", {
|
|
10244
10453
|
query: query.slice(0, 100),
|
|
10245
10454
|
collection,
|
|
10246
10455
|
topK
|
|
@@ -10325,7 +10534,7 @@ function createKnowledgeOperations(config, llm, embedding, datapipe2, store) {
|
|
|
10325
10534
|
}
|
|
10326
10535
|
}
|
|
10327
10536
|
const duration = Date.now() - startTime;
|
|
10328
|
-
|
|
10537
|
+
logger18.trace("Knowledge retrieval completed", { resultCount: items.length, duration });
|
|
10329
10538
|
return ok({
|
|
10330
10539
|
items,
|
|
10331
10540
|
citations: Array.from(citationMap.values()),
|
|
@@ -10333,7 +10542,7 @@ function createKnowledgeOperations(config, llm, embedding, datapipe2, store) {
|
|
|
10333
10542
|
duration
|
|
10334
10543
|
});
|
|
10335
10544
|
} catch (error) {
|
|
10336
|
-
|
|
10545
|
+
logger18.error("Knowledge retrieval failed", { error });
|
|
10337
10546
|
return err(HaiAIError.KNOWLEDGE_RETRIEVE_FAILED, aiM("ai_knowledgeRetrieveFailed", {
|
|
10338
10547
|
params: {
|
|
10339
10548
|
error: String(error)
|
|
@@ -10389,7 +10598,7 @@ ${contextText}
|
|
|
10389
10598
|
}
|
|
10390
10599
|
const choice = chatResult.data.choices[0];
|
|
10391
10600
|
const answer = choice?.message?.content ?? "";
|
|
10392
|
-
|
|
10601
|
+
logger18.trace("Knowledge ask completed", {
|
|
10393
10602
|
contextCount: items.length,
|
|
10394
10603
|
model: chatResult.data.model
|
|
10395
10604
|
});
|
|
@@ -10513,7 +10722,7 @@ ${contextText}
|
|
|
10513
10722
|
if (!await isCollectionReady(collection))
|
|
10514
10723
|
return err(HaiAIError.KNOWLEDGE_NOT_SETUP, aiM("ai_knowledgeNotSetup"));
|
|
10515
10724
|
await store.removeDocument(documentId, collection);
|
|
10516
|
-
|
|
10725
|
+
logger18.debug("Document removed", { documentId, collection });
|
|
10517
10726
|
return ok(void 0);
|
|
10518
10727
|
} catch (error) {
|
|
10519
10728
|
return err(HaiAIError.KNOWLEDGE_INGEST_FAILED, aiM("ai_knowledgeIngestFailed", {
|
|
@@ -10620,13 +10829,13 @@ ${contextText}
|
|
|
10620
10829
|
}));
|
|
10621
10830
|
}
|
|
10622
10831
|
const col = collection ?? config.collection;
|
|
10623
|
-
|
|
10832
|
+
logger18.debug("Deleting knowledge collection", { collection: col });
|
|
10624
10833
|
try {
|
|
10625
10834
|
await store.deleteCollection(col);
|
|
10626
|
-
|
|
10835
|
+
logger18.debug("Knowledge collection deleted", { collection: col });
|
|
10627
10836
|
return ok(void 0);
|
|
10628
10837
|
} catch (error) {
|
|
10629
|
-
|
|
10838
|
+
logger18.error("Knowledge collection deletion failed", { collection: col, error });
|
|
10630
10839
|
return err(HaiAIError.KNOWLEDGE_SETUP_FAILED, aiM("ai_knowledgeSetupFailed", {
|
|
10631
10840
|
params: {
|
|
10632
10841
|
error: String(error)
|
|
@@ -11570,7 +11779,7 @@ function createLLMProvider(deps) {
|
|
|
11570
11779
|
}
|
|
11571
11780
|
|
|
11572
11781
|
// src/llm/ai-llm-functions.ts
|
|
11573
|
-
var
|
|
11782
|
+
var logger19 = core.logger.child({ module: "ai", scope: "llm" });
|
|
11574
11783
|
function createAILLMFunctions(config, deps) {
|
|
11575
11784
|
let provider = createLLMProvider({ config });
|
|
11576
11785
|
let signature = JSON.stringify(config.llm);
|
|
@@ -11603,7 +11812,7 @@ function createAILLMFunctions(config, deps) {
|
|
|
11603
11812
|
objectId: record.objectId,
|
|
11604
11813
|
sessionId: record.sessionId
|
|
11605
11814
|
});
|
|
11606
|
-
|
|
11815
|
+
logger19.trace("Chat record saved", {
|
|
11607
11816
|
id: record.id,
|
|
11608
11817
|
objectId: record.objectId,
|
|
11609
11818
|
sessionId: record.sessionId
|
|
@@ -11628,7 +11837,7 @@ function createAILLMFunctions(config, deps) {
|
|
|
11628
11837
|
model: request2.model ?? request2.tempModel?.model,
|
|
11629
11838
|
messageCount: request2.messages.length
|
|
11630
11839
|
};
|
|
11631
|
-
|
|
11840
|
+
logger19.debug("LLM chat started", context);
|
|
11632
11841
|
let result;
|
|
11633
11842
|
try {
|
|
11634
11843
|
result = await (await currentProvider()).chat(request2);
|
|
@@ -11639,7 +11848,7 @@ function createAILLMFunctions(config, deps) {
|
|
|
11639
11848
|
);
|
|
11640
11849
|
}
|
|
11641
11850
|
if (result.success) {
|
|
11642
|
-
|
|
11851
|
+
logger19.info("LLM chat completed", {
|
|
11643
11852
|
...context,
|
|
11644
11853
|
model: result.data.model,
|
|
11645
11854
|
durationMs: Date.now() - start,
|
|
@@ -11647,7 +11856,7 @@ function createAILLMFunctions(config, deps) {
|
|
|
11647
11856
|
totalTokens: result.data.usage?.total_tokens
|
|
11648
11857
|
});
|
|
11649
11858
|
} else {
|
|
11650
|
-
|
|
11859
|
+
logger19.warn("LLM chat failed", {
|
|
11651
11860
|
...context,
|
|
11652
11861
|
durationMs: Date.now() - start,
|
|
11653
11862
|
code: result.error.code,
|
|
@@ -11681,7 +11890,7 @@ function createAILLMFunctions(config, deps) {
|
|
|
11681
11890
|
};
|
|
11682
11891
|
await saveRecordAndSession(record, request2.messages);
|
|
11683
11892
|
} catch (error) {
|
|
11684
|
-
|
|
11893
|
+
logger19.debug("Failed to save chat record", { error });
|
|
11685
11894
|
}
|
|
11686
11895
|
}
|
|
11687
11896
|
return result;
|
|
@@ -11692,7 +11901,7 @@ function createAILLMFunctions(config, deps) {
|
|
|
11692
11901
|
model: request2.model ?? request2.tempModel?.model,
|
|
11693
11902
|
messageCount: request2.messages.length
|
|
11694
11903
|
};
|
|
11695
|
-
|
|
11904
|
+
logger19.debug("LLM chat stream started", logContext);
|
|
11696
11905
|
const shouldRecord = !!(request2.objectId && recordStore && request2.enablePersist !== false);
|
|
11697
11906
|
let content = "";
|
|
11698
11907
|
let finishReason = null;
|
|
@@ -11732,7 +11941,7 @@ function createAILLMFunctions(config, deps) {
|
|
|
11732
11941
|
}
|
|
11733
11942
|
}
|
|
11734
11943
|
}
|
|
11735
|
-
|
|
11944
|
+
logger19.info("LLM chat stream completed", {
|
|
11736
11945
|
...logContext,
|
|
11737
11946
|
model: resolvedModel || logContext.model,
|
|
11738
11947
|
durationMs: Date.now() - start,
|
|
@@ -11740,7 +11949,7 @@ function createAILLMFunctions(config, deps) {
|
|
|
11740
11949
|
finishReason
|
|
11741
11950
|
});
|
|
11742
11951
|
} catch (error) {
|
|
11743
|
-
|
|
11952
|
+
logger19.warn("LLM chat stream failed", {
|
|
11744
11953
|
...logContext,
|
|
11745
11954
|
durationMs: Date.now() - start,
|
|
11746
11955
|
error
|
|
@@ -11773,7 +11982,7 @@ function createAILLMFunctions(config, deps) {
|
|
|
11773
11982
|
};
|
|
11774
11983
|
await saveRecordAndSession(record, request2.messages);
|
|
11775
11984
|
} catch (error) {
|
|
11776
|
-
|
|
11985
|
+
logger19.debug("Failed to save stream chat record", { error });
|
|
11777
11986
|
}
|
|
11778
11987
|
}
|
|
11779
11988
|
}
|
|
@@ -11885,6 +12094,17 @@ function createAILLMFunctions(config, deps) {
|
|
|
11885
12094
|
baseMessages.push({ role: "system", content: request2.systemPrompt });
|
|
11886
12095
|
baseMessages.push(...request2.messages);
|
|
11887
12096
|
const jsonSchema = z.toJSONSchema(request2.schema);
|
|
12097
|
+
const jsonObject = request2.responseFormat === "json_object";
|
|
12098
|
+
if (jsonObject) {
|
|
12099
|
+
baseMessages.unshift({
|
|
12100
|
+
role: "system",
|
|
12101
|
+
content: aiM("ai_generateObjectJson", {
|
|
12102
|
+
params: {
|
|
12103
|
+
schema: JSON.stringify(jsonSchema)
|
|
12104
|
+
}
|
|
12105
|
+
})
|
|
12106
|
+
});
|
|
12107
|
+
}
|
|
11888
12108
|
const schemaName = request2.schemaName ?? "result";
|
|
11889
12109
|
const maxRepairs = request2.maxRepairs ?? 1;
|
|
11890
12110
|
let lastError = "";
|
|
@@ -11905,7 +12125,7 @@ function createAILLMFunctions(config, deps) {
|
|
|
11905
12125
|
tempModel: request2.tempModel,
|
|
11906
12126
|
enablePersist: false,
|
|
11907
12127
|
signal: request2.signal,
|
|
11908
|
-
response_format: {
|
|
12128
|
+
response_format: jsonObject ? { type: "json_object" } : {
|
|
11909
12129
|
type: "json_schema",
|
|
11910
12130
|
json_schema: { name: schemaName, schema: jsonSchema, strict: true }
|
|
11911
12131
|
}
|
|
@@ -12127,9 +12347,8 @@ function createMCPServiceBroker(read, invoke, options, lifecycle) {
|
|
|
12127
12347
|
if (!endpoint || !["http:", "https:"].includes(endpoint.protocol) || endpoint.username || endpoint.password || endpoint.hash || endpoint.search || typeof options.authorize !== "function")
|
|
12128
12348
|
return err(HaiAIError.RESOURCE_INVALID, aiM("ai_resourceInvalid"));
|
|
12129
12349
|
const grants = /* @__PURE__ */ new Map();
|
|
12130
|
-
const validator = new AjvJsonSchemaValidator();
|
|
12131
12350
|
let closed = false;
|
|
12132
|
-
function createGrant(input, key) {
|
|
12351
|
+
function createGrant(input, validators, key) {
|
|
12133
12352
|
const controller = new AbortController();
|
|
12134
12353
|
const signal = AbortSignal.any([
|
|
12135
12354
|
controller.signal,
|
|
@@ -12145,6 +12364,7 @@ function createMCPServiceBroker(read, invoke, options, lifecycle) {
|
|
|
12145
12364
|
});
|
|
12146
12365
|
return {
|
|
12147
12366
|
input,
|
|
12367
|
+
validators,
|
|
12148
12368
|
signal,
|
|
12149
12369
|
revoke: () => controller.abort()
|
|
12150
12370
|
};
|
|
@@ -12170,15 +12390,19 @@ function createMCPServiceBroker(read, invoke, options, lifecycle) {
|
|
|
12170
12390
|
return err(HaiAIError.RESOURCE_INVALID, aiM("ai_resourceInvalid"));
|
|
12171
12391
|
if (Buffer.byteLength(JSON.stringify(parsed.data.tools)) > maxRequestBytes)
|
|
12172
12392
|
return err(HaiAIError.RESOURCE_INVALID, aiM("ai_resourceInvalid"));
|
|
12173
|
-
const input =
|
|
12393
|
+
const input = {
|
|
12394
|
+
...parsed.data,
|
|
12395
|
+
tools: structuredClone(parsed.data.tools)
|
|
12396
|
+
};
|
|
12174
12397
|
const services = /* @__PURE__ */ new Map();
|
|
12398
|
+
const validators = /* @__PURE__ */ new Map();
|
|
12175
12399
|
for (const tool of input.tools) {
|
|
12176
12400
|
if (!services.has(tool.serviceId))
|
|
12177
12401
|
services.set(tool.serviceId, await read(tool.serviceId));
|
|
12178
12402
|
const service = services.get(tool.serviceId);
|
|
12179
12403
|
if (!service || !["http", "job"].includes(service.transport) || !service.allowedTools?.includes(tool.tool))
|
|
12180
12404
|
return err(HaiAIError.MCP_TOOL_FORBIDDEN, aiM("ai_mcpServiceForbidden"));
|
|
12181
|
-
|
|
12405
|
+
validators.set(tool.id, new AjvJsonSchemaValidator().getValidator(tool.inputSchema));
|
|
12182
12406
|
}
|
|
12183
12407
|
if (closed || lifecycle.aborted)
|
|
12184
12408
|
return err(HaiAIError.NOT_INITIALIZED, aiM("ai_notInitialized"));
|
|
@@ -12186,10 +12410,7 @@ function createMCPServiceBroker(read, invoke, options, lifecycle) {
|
|
|
12186
12410
|
return err(HaiAIError.RESOURCE_OPERATION_FAILED, aiM("ai_resourceOperationFailed"));
|
|
12187
12411
|
const token = randomBytes(32).toString("base64url");
|
|
12188
12412
|
const key = digest(token);
|
|
12189
|
-
const grant = createGrant(
|
|
12190
|
-
...input,
|
|
12191
|
-
tools: structuredClone(input.tools)
|
|
12192
|
-
}, key);
|
|
12413
|
+
const grant = createGrant(input, validators, key);
|
|
12193
12414
|
if (!grant)
|
|
12194
12415
|
return err(HaiAIError.MCP_TOOL_CANCELLED, aiM("ai_mcpServiceCancelled"));
|
|
12195
12416
|
grants.set(key, grant);
|
|
@@ -12204,7 +12425,8 @@ function createMCPServiceBroker(read, invoke, options, lifecycle) {
|
|
|
12204
12425
|
]
|
|
12205
12426
|
}
|
|
12206
12427
|
],
|
|
12207
|
-
revoke: grant.revoke
|
|
12428
|
+
revoke: grant.revoke,
|
|
12429
|
+
signal: grant.signal
|
|
12208
12430
|
});
|
|
12209
12431
|
} catch {
|
|
12210
12432
|
return err(HaiAIError.RESOURCE_INVALID, aiM("ai_resourceInvalid"));
|
|
@@ -12260,7 +12482,7 @@ function createMCPServiceBroker(read, invoke, options, lifecycle) {
|
|
|
12260
12482
|
}));
|
|
12261
12483
|
server.setRequestHandler(CallToolRequestSchema, async ({ params }) => {
|
|
12262
12484
|
const tool = grant.input.tools.find((tool2) => tool2.id === params.name);
|
|
12263
|
-
if (!tool || signal.aborted || !
|
|
12485
|
+
if (!tool || signal.aborted || !grant.validators.get(params.name)?.(params.arguments ?? {}).valid)
|
|
12264
12486
|
return failure();
|
|
12265
12487
|
const result = await invoke({ serviceId: tool.serviceId, tool: tool.tool, arguments: params.arguments }, {
|
|
12266
12488
|
principal: grant.input.principal,
|
|
@@ -12693,27 +12915,27 @@ function createMCPServiceOperations(read, runner, files, configuredServices = []
|
|
|
12693
12915
|
}
|
|
12694
12916
|
};
|
|
12695
12917
|
}
|
|
12696
|
-
function createScopedMemory(
|
|
12918
|
+
function createScopedMemory(core34, binding) {
|
|
12697
12919
|
if (typeof binding.objectId !== "string" || !binding.objectId.trim())
|
|
12698
12920
|
throw new TypeError(aiM("ai_memoryScopeInvalid"));
|
|
12699
12921
|
const { objectId, scope } = binding;
|
|
12700
12922
|
const accessScope = { objectId, scope };
|
|
12701
12923
|
return {
|
|
12702
|
-
extract: (messages, options) =>
|
|
12703
|
-
recall: (query, options) =>
|
|
12704
|
-
injectMemories: (messages, options) =>
|
|
12705
|
-
add: (entry) =>
|
|
12706
|
-
update: (memoryId, updates) =>
|
|
12707
|
-
get: (memoryId) =>
|
|
12708
|
-
remove: (memoryId) =>
|
|
12709
|
-
list: (options) =>
|
|
12710
|
-
listPage: (options) =>
|
|
12711
|
-
clear: (options) =>
|
|
12924
|
+
extract: (messages, options) => core34.extract(messages, { ...options, objectId, scope }),
|
|
12925
|
+
recall: (query, options) => core34.recall(query, { ...options, objectId, scope }),
|
|
12926
|
+
injectMemories: (messages, options) => core34.injectMemories(messages, { ...options, objectId, scope }),
|
|
12927
|
+
add: (entry) => core34.add({ ...entry, objectId, scope }),
|
|
12928
|
+
update: (memoryId, updates) => core34.update(memoryId, updates, accessScope),
|
|
12929
|
+
get: (memoryId) => core34.get(memoryId, accessScope),
|
|
12930
|
+
remove: (memoryId) => core34.remove(memoryId, accessScope),
|
|
12931
|
+
list: (options) => core34.list({ ...options, objectId, scope }),
|
|
12932
|
+
listPage: (options) => core34.listPage({ ...options, objectId, scope }),
|
|
12933
|
+
clear: (options) => core34.clear({ ...options, objectId, scope })
|
|
12712
12934
|
};
|
|
12713
12935
|
}
|
|
12714
|
-
function createMemoryOperations(
|
|
12936
|
+
function createMemoryOperations(core34) {
|
|
12715
12937
|
return {
|
|
12716
|
-
...
|
|
12938
|
+
...core34,
|
|
12717
12939
|
/**
|
|
12718
12940
|
* 清空记忆(空过滤保护)。
|
|
12719
12941
|
*
|
|
@@ -12727,20 +12949,20 @@ function createMemoryOperations(core32) {
|
|
|
12727
12949
|
if (!hasFilter) {
|
|
12728
12950
|
return err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryClearRequiresFilter"));
|
|
12729
12951
|
}
|
|
12730
|
-
return
|
|
12952
|
+
return core34.clear(options);
|
|
12731
12953
|
},
|
|
12732
|
-
scoped: (binding) => createScopedMemory(
|
|
12954
|
+
scoped: (binding) => createScopedMemory(core34, binding),
|
|
12733
12955
|
admin: {
|
|
12734
12956
|
async clearAll(options) {
|
|
12735
12957
|
if (options?.confirm !== true) {
|
|
12736
12958
|
return err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryClearAllUnconfirmed"));
|
|
12737
12959
|
}
|
|
12738
|
-
return
|
|
12960
|
+
return core34.clear();
|
|
12739
12961
|
}
|
|
12740
12962
|
}
|
|
12741
12963
|
};
|
|
12742
12964
|
}
|
|
12743
|
-
var
|
|
12965
|
+
var logger20 = core.logger.child({ module: "ai", scope: "memory-extractor" });
|
|
12744
12966
|
var LEADING_MARKDOWN_FENCE_REGEX2 = /^```(?:json)?\n?/;
|
|
12745
12967
|
var TRAILING_MARKDOWN_FENCE_REGEX2 = /\n?```$/;
|
|
12746
12968
|
var MEMORY_EXTRACTION_SYSTEM_PROMPT = `You are a memory extraction assistant. Analyze the conversation and extract important information worth remembering for future interactions.
|
|
@@ -12793,7 +13015,7 @@ Only extract memories of these types: ${options.types.join(", ")}`;
|
|
|
12793
13015
|
signal: options?.signal
|
|
12794
13016
|
});
|
|
12795
13017
|
if (!chatResult.success) {
|
|
12796
|
-
|
|
13018
|
+
logger20.warn("Memory extraction LLM call failed", { error: chatResult.error });
|
|
12797
13019
|
return err(HaiAIError.MEMORY_EXTRACT_FAILED, aiM("ai_memoryExtractFailed", {
|
|
12798
13020
|
params: {
|
|
12799
13021
|
error: String(chatResult.error.message)
|
|
@@ -12812,10 +13034,10 @@ Only extract memories of these types: ${options.types.join(", ")}`;
|
|
|
12812
13034
|
if (options?.objectId) {
|
|
12813
13035
|
entries = entries.map((e) => ({ ...e, objectId: options.objectId }));
|
|
12814
13036
|
}
|
|
12815
|
-
|
|
13037
|
+
logger20.trace("Memory extraction completed", { messageCount: messages.length, extractedCount: entries.length });
|
|
12816
13038
|
return ok(entries);
|
|
12817
13039
|
} catch (error) {
|
|
12818
|
-
|
|
13040
|
+
logger20.error("Memory extraction failed", { error });
|
|
12819
13041
|
return err(HaiAIError.MEMORY_EXTRACT_FAILED, aiM("ai_memoryExtractFailed", {
|
|
12820
13042
|
params: {
|
|
12821
13043
|
error: String(error)
|
|
@@ -12846,12 +13068,12 @@ function parseMemoryResponse(content) {
|
|
|
12846
13068
|
return memories.filter(isValidMemoryItem).map(normalizeMemoryItem);
|
|
12847
13069
|
}
|
|
12848
13070
|
}
|
|
12849
|
-
|
|
13071
|
+
logger20.warn("Memory extraction returned unexpected format", {
|
|
12850
13072
|
content: content.slice(0, 200)
|
|
12851
13073
|
});
|
|
12852
13074
|
return [];
|
|
12853
13075
|
} catch {
|
|
12854
|
-
|
|
13076
|
+
logger20.warn("Memory extraction returned invalid JSON", {
|
|
12855
13077
|
content: content.slice(0, 200)
|
|
12856
13078
|
});
|
|
12857
13079
|
return [];
|
|
@@ -12872,7 +13094,7 @@ function normalizeMemoryItem(item2) {
|
|
|
12872
13094
|
importance
|
|
12873
13095
|
};
|
|
12874
13096
|
}
|
|
12875
|
-
var
|
|
13097
|
+
var logger21 = core.logger.child({ module: "ai", scope: "memory" });
|
|
12876
13098
|
function isMemoryAccessDenied(entry, accessScope) {
|
|
12877
13099
|
if (!accessScope)
|
|
12878
13100
|
return false;
|
|
@@ -12960,10 +13182,10 @@ ${memoryText}
|
|
|
12960
13182
|
});
|
|
12961
13183
|
}
|
|
12962
13184
|
}
|
|
12963
|
-
|
|
13185
|
+
logger21.trace("Memories enriched", { count: recallResult.data.length, position });
|
|
12964
13186
|
return ok(result);
|
|
12965
13187
|
} catch (error) {
|
|
12966
|
-
|
|
13188
|
+
logger21.error("Memory enrichment failed", { error });
|
|
12967
13189
|
return err(HaiAIError.MEMORY_ENRICH_FAILED, aiM("ai_memoryEnrichFailed", {
|
|
12968
13190
|
params: {
|
|
12969
13191
|
error: String(error)
|
|
@@ -13280,7 +13502,7 @@ async function createMem0Store(options) {
|
|
|
13280
13502
|
}
|
|
13281
13503
|
|
|
13282
13504
|
// src/memory/providers/ai-memory-provider-mem0.ts
|
|
13283
|
-
var
|
|
13505
|
+
var logger22 = core.logger.child({ module: "ai", scope: "memory-mem0" });
|
|
13284
13506
|
var DEFAULT_IMPORTANCE = 0.5;
|
|
13285
13507
|
var DEFAULT_OBJECT_ID = "hai-global";
|
|
13286
13508
|
var MEM0_LIST_CANDIDATE_LIMIT = 1e3;
|
|
@@ -13396,7 +13618,7 @@ function buildVectorStoreConfig(deps) {
|
|
|
13396
13618
|
);
|
|
13397
13619
|
}
|
|
13398
13620
|
if (backend)
|
|
13399
|
-
|
|
13621
|
+
logger22.warn("Mem0 format falls back to in-memory vector store (allowEphemeralFallback=true); data will not survive restart", { backend: backend.type });
|
|
13400
13622
|
return ok({
|
|
13401
13623
|
provider: "memory",
|
|
13402
13624
|
persistent: false
|
|
@@ -13437,7 +13659,7 @@ async function extractMemories2(context, messages, options) {
|
|
|
13437
13659
|
throw failed.reason;
|
|
13438
13660
|
return ok(stored.flatMap((result) => result.status === "fulfilled" ? [result.value] : []));
|
|
13439
13661
|
} catch (error) {
|
|
13440
|
-
|
|
13662
|
+
logger22.error("Mem0 format extract failed", {
|
|
13441
13663
|
error: core.sanitize.sanitizeSensitiveFields(error)
|
|
13442
13664
|
});
|
|
13443
13665
|
return memoryWriteFailure(HaiAIError.MEMORY_EXTRACT_FAILED, aiM("ai_memoryOperationFailed"), memoryIds);
|
|
@@ -13464,7 +13686,7 @@ async function recallMemories(context, query, options) {
|
|
|
13464
13686
|
}
|
|
13465
13687
|
return ok(entries.slice(0, topK));
|
|
13466
13688
|
} catch (error) {
|
|
13467
|
-
|
|
13689
|
+
logger22.error("Mem0 format recall failed", {
|
|
13468
13690
|
error: core.sanitize.sanitizeSensitiveFields(error)
|
|
13469
13691
|
});
|
|
13470
13692
|
return err(HaiAIError.MEMORY_RECALL_FAILED, aiM("ai_memoryOperationFailed"));
|
|
@@ -13481,7 +13703,7 @@ async function addMemory(context, entry) {
|
|
|
13481
13703
|
throw new Error("Mem0 format stored memory could not be read back");
|
|
13482
13704
|
return ok(toMemoryEntry(persisted, objectId));
|
|
13483
13705
|
} catch (error) {
|
|
13484
|
-
|
|
13706
|
+
logger22.error("Mem0 format add failed", {
|
|
13485
13707
|
error: core.sanitize.sanitizeSensitiveFields(error)
|
|
13486
13708
|
});
|
|
13487
13709
|
return memoryWriteFailure(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryOperationFailed"), memoryIds);
|
|
@@ -13519,7 +13741,7 @@ async function updateMemory(context, memoryId, updates, accessScope) {
|
|
|
13519
13741
|
}
|
|
13520
13742
|
return ok(toMemoryEntry(refreshed, objectId));
|
|
13521
13743
|
} catch (error) {
|
|
13522
|
-
|
|
13744
|
+
logger22.error("Mem0 format update failed", {
|
|
13523
13745
|
id: memoryId,
|
|
13524
13746
|
error: core.sanitize.sanitizeSensitiveFields(error)
|
|
13525
13747
|
});
|
|
@@ -13542,7 +13764,7 @@ async function getMemory(context, memoryId, accessScope) {
|
|
|
13542
13764
|
}
|
|
13543
13765
|
return ok(entry);
|
|
13544
13766
|
} catch (error) {
|
|
13545
|
-
|
|
13767
|
+
logger22.error("Mem0 format read failed", {
|
|
13546
13768
|
error: core.sanitize.sanitizeSensitiveFields(error)
|
|
13547
13769
|
});
|
|
13548
13770
|
return err(HaiAIError.MEMORY_RECALL_FAILED, aiM("ai_memoryOperationFailed"));
|
|
@@ -13561,7 +13783,7 @@ async function removeMemory(context, memoryId, accessScope) {
|
|
|
13561
13783
|
await context.memory.remove(memoryId);
|
|
13562
13784
|
return ok(void 0);
|
|
13563
13785
|
} catch (error) {
|
|
13564
|
-
|
|
13786
|
+
logger22.error("Mem0 format delete failed", {
|
|
13565
13787
|
error: core.sanitize.sanitizeSensitiveFields(error)
|
|
13566
13788
|
});
|
|
13567
13789
|
return err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryOperationFailed"));
|
|
@@ -13610,7 +13832,7 @@ async function createMem0MemoryOperations(deps) {
|
|
|
13610
13832
|
backend: configResult.data.backend
|
|
13611
13833
|
});
|
|
13612
13834
|
} catch (error) {
|
|
13613
|
-
|
|
13835
|
+
logger22.error("Mem0 data storage initialization failed", {
|
|
13614
13836
|
error: core.sanitize.sanitizeSensitiveFields(error)
|
|
13615
13837
|
});
|
|
13616
13838
|
const failure = err(HaiAIError.CONFIGURATION_ERROR, aiM("ai_memoryOperationFailed"));
|
|
@@ -13618,7 +13840,7 @@ async function createMem0MemoryOperations(deps) {
|
|
|
13618
13840
|
throw failure.error;
|
|
13619
13841
|
throw new Error("Unreachable memory initialization state");
|
|
13620
13842
|
}
|
|
13621
|
-
|
|
13843
|
+
logger22.info("Mem0 format memory initialized", {
|
|
13622
13844
|
vectorProvider: configResult.data.provider,
|
|
13623
13845
|
persistent: configResult.data.persistent
|
|
13624
13846
|
});
|
|
@@ -13651,7 +13873,7 @@ async function createMem0MemoryOperations(deps) {
|
|
|
13651
13873
|
try {
|
|
13652
13874
|
return ok(await listMemories(context, options));
|
|
13653
13875
|
} catch (error) {
|
|
13654
|
-
|
|
13876
|
+
logger22.error("Mem0 data list failed", {
|
|
13655
13877
|
operation: "list",
|
|
13656
13878
|
...core.context.get(),
|
|
13657
13879
|
error: core.sanitize.sanitizeSensitiveFields(error)
|
|
@@ -13671,7 +13893,7 @@ async function createMem0MemoryOperations(deps) {
|
|
|
13671
13893
|
total: all.length
|
|
13672
13894
|
});
|
|
13673
13895
|
} catch (error) {
|
|
13674
|
-
|
|
13896
|
+
logger22.error("Mem0 data page failed", {
|
|
13675
13897
|
operation: "page",
|
|
13676
13898
|
...core.context.get(),
|
|
13677
13899
|
error: core.sanitize.sanitizeSensitiveFields(error)
|
|
@@ -13702,7 +13924,7 @@ async function createMem0MemoryOperations(deps) {
|
|
|
13702
13924
|
const matched = await listMemories(context, { objectId: options?.objectId, types: options?.types, scope: options?.scope });
|
|
13703
13925
|
for (const entry of matched)
|
|
13704
13926
|
await context.memory.remove(entry.id);
|
|
13705
|
-
|
|
13927
|
+
logger22.debug("Mem0 format memories cleared", {
|
|
13706
13928
|
removed: matched.length,
|
|
13707
13929
|
objectId: options?.objectId,
|
|
13708
13930
|
types: options?.types,
|
|
@@ -13710,7 +13932,7 @@ async function createMem0MemoryOperations(deps) {
|
|
|
13710
13932
|
});
|
|
13711
13933
|
return ok(void 0);
|
|
13712
13934
|
} catch (error) {
|
|
13713
|
-
|
|
13935
|
+
logger22.error("Mem0 data clear failed", {
|
|
13714
13936
|
operation: "clear",
|
|
13715
13937
|
...core.context.get(),
|
|
13716
13938
|
error: core.sanitize.sanitizeSensitiveFields(error)
|
|
@@ -13722,7 +13944,7 @@ async function createMem0MemoryOperations(deps) {
|
|
|
13722
13944
|
}
|
|
13723
13945
|
};
|
|
13724
13946
|
}
|
|
13725
|
-
var
|
|
13947
|
+
var logger23 = core.logger.child({ module: "ai", scope: "memory-consolidation" });
|
|
13726
13948
|
var DEFAULT_IMPORTANCE2 = 0.5;
|
|
13727
13949
|
var MEMORY_TYPES2 = /* @__PURE__ */ new Set([
|
|
13728
13950
|
"fact",
|
|
@@ -13853,7 +14075,7 @@ async function applyConsolidationOps(deps, ops, options) {
|
|
|
13853
14075
|
if (op.event === "DELETE" && op.id) {
|
|
13854
14076
|
const removeResult = await deps.remove(op.id);
|
|
13855
14077
|
if (!removeResult.success)
|
|
13856
|
-
|
|
14078
|
+
logger23.warn("Consolidation delete skipped", { id: op.id, error: removeResult.error.message });
|
|
13857
14079
|
continue;
|
|
13858
14080
|
}
|
|
13859
14081
|
if (op.event === "UPDATE" && op.id) {
|
|
@@ -13883,7 +14105,7 @@ async function applyConsolidationOps(deps, ops, options) {
|
|
|
13883
14105
|
return ok(entries);
|
|
13884
14106
|
}
|
|
13885
14107
|
async function extractAndConsolidate(deps, messages, options) {
|
|
13886
|
-
|
|
14108
|
+
logger23.trace("Consolidation extract", { messageCount: messages.length });
|
|
13887
14109
|
const extractResult = await extractMemories(deps.llm, messages, {
|
|
13888
14110
|
types: options?.types,
|
|
13889
14111
|
model: options?.model,
|
|
@@ -13941,7 +14163,7 @@ async function extractAndConsolidate(deps, messages, options) {
|
|
|
13941
14163
|
try {
|
|
13942
14164
|
ops = parseConsolidationOps(rawContent, candidates, relatedIds);
|
|
13943
14165
|
} catch {
|
|
13944
|
-
|
|
14166
|
+
logger23.warn("Consolidation returned invalid JSON, falling back to ADD-all", {
|
|
13945
14167
|
content: rawContent.slice(0, 200)
|
|
13946
14168
|
});
|
|
13947
14169
|
ops = candidates.map((candidate) => ({
|
|
@@ -13954,7 +14176,7 @@ async function extractAndConsolidate(deps, messages, options) {
|
|
|
13954
14176
|
const applyResult = await applyConsolidationOps(deps, ops, options);
|
|
13955
14177
|
if (!applyResult.success)
|
|
13956
14178
|
return applyResult;
|
|
13957
|
-
|
|
14179
|
+
logger23.trace("Consolidation completed", {
|
|
13958
14180
|
candidates: candidates.length,
|
|
13959
14181
|
related: related.length,
|
|
13960
14182
|
ops: ops.length,
|
|
@@ -13962,12 +14184,158 @@ async function extractAndConsolidate(deps, messages, options) {
|
|
|
13962
14184
|
});
|
|
13963
14185
|
return ok(applyResult.data);
|
|
13964
14186
|
}
|
|
14187
|
+
var logger24 = core.logger.child({ module: "ai", scope: "memory-vector-sync" });
|
|
14188
|
+
var pollMs = 1e3;
|
|
14189
|
+
var inFlightRetryMs = 45e3;
|
|
14190
|
+
var lateWriteWindowMs = 6e4;
|
|
14191
|
+
var batchSize2 = 16;
|
|
14192
|
+
function backoff(attempts) {
|
|
14193
|
+
return Math.min(3e4, 1e3 * 2 ** Math.min(Math.max(attempts - 1, 0), 5));
|
|
14194
|
+
}
|
|
14195
|
+
function vectorId(memory) {
|
|
14196
|
+
return memory.vectorId ?? memory.id;
|
|
14197
|
+
}
|
|
14198
|
+
function createMemoryVectorSync(store, queue, vectors) {
|
|
14199
|
+
const lock = store.withRelatedWriteLock?.bind(store);
|
|
14200
|
+
if (!lock || !queue.queryKeys)
|
|
14201
|
+
return void 0;
|
|
14202
|
+
function write(run) {
|
|
14203
|
+
return lock(queue, run);
|
|
14204
|
+
}
|
|
14205
|
+
let active;
|
|
14206
|
+
let timer;
|
|
14207
|
+
async function reconcile(id3) {
|
|
14208
|
+
const claimed = await write(async (memory, pending) => {
|
|
14209
|
+
const job = await pending.get(id3);
|
|
14210
|
+
if (!job)
|
|
14211
|
+
return void 0;
|
|
14212
|
+
const now = await pending.currentTime();
|
|
14213
|
+
if (job.updatedAt > now)
|
|
14214
|
+
return void 0;
|
|
14215
|
+
const entry = await memory.get(job.memoryId);
|
|
14216
|
+
const current = entry?.vector && vectorId(entry) === id3 ? entry : void 0;
|
|
14217
|
+
if (current && job.cooldown) {
|
|
14218
|
+
await pending.remove(id3);
|
|
14219
|
+
return void 0;
|
|
14220
|
+
}
|
|
14221
|
+
const token = randomUUID();
|
|
14222
|
+
const next = {
|
|
14223
|
+
...job,
|
|
14224
|
+
token,
|
|
14225
|
+
attempts: job.attempts + 1,
|
|
14226
|
+
updatedAt: now + inFlightRetryMs
|
|
14227
|
+
};
|
|
14228
|
+
await pending.save(id3, next);
|
|
14229
|
+
return { ...next, entry: current };
|
|
14230
|
+
});
|
|
14231
|
+
if (!claimed)
|
|
14232
|
+
return;
|
|
14233
|
+
let succeeded = false;
|
|
14234
|
+
try {
|
|
14235
|
+
if (claimed.entry?.vector) {
|
|
14236
|
+
await vectors.upsert(id3, claimed.entry.vector, {
|
|
14237
|
+
objectId: claimed.entry.objectId,
|
|
14238
|
+
type: claimed.entry.type
|
|
14239
|
+
});
|
|
14240
|
+
} else {
|
|
14241
|
+
await vectors.remove(id3);
|
|
14242
|
+
}
|
|
14243
|
+
succeeded = true;
|
|
14244
|
+
} catch {
|
|
14245
|
+
logger24.debug("Memory vector sync will retry", {
|
|
14246
|
+
operation: claimed.entry ? "upsert" : "delete"
|
|
14247
|
+
});
|
|
14248
|
+
}
|
|
14249
|
+
await write(async (_memory, pending) => {
|
|
14250
|
+
const job = await pending.get(id3);
|
|
14251
|
+
if (!job || job.token !== claimed.token)
|
|
14252
|
+
return;
|
|
14253
|
+
const now = await pending.currentTime();
|
|
14254
|
+
if (succeeded && claimed.entry && job.attempts > 1) {
|
|
14255
|
+
await pending.save(id3, {
|
|
14256
|
+
...job,
|
|
14257
|
+
token: void 0,
|
|
14258
|
+
cooldown: true,
|
|
14259
|
+
updatedAt: now + lateWriteWindowMs
|
|
14260
|
+
});
|
|
14261
|
+
return;
|
|
14262
|
+
}
|
|
14263
|
+
if (succeeded && (!job.retireUntil || job.retireUntil <= now)) {
|
|
14264
|
+
await pending.remove(id3);
|
|
14265
|
+
return;
|
|
14266
|
+
}
|
|
14267
|
+
const delay3 = backoff(job.attempts);
|
|
14268
|
+
await pending.save(id3, {
|
|
14269
|
+
...job,
|
|
14270
|
+
token: void 0,
|
|
14271
|
+
updatedAt: job.retireUntil && succeeded ? Math.min(now + delay3, job.retireUntil) : now + delay3
|
|
14272
|
+
});
|
|
14273
|
+
});
|
|
14274
|
+
}
|
|
14275
|
+
async function drain() {
|
|
14276
|
+
const now = await queue.currentTime();
|
|
14277
|
+
const due = await queue.queryKeys({ updatedBefore: now + 1, limit: batchSize2 });
|
|
14278
|
+
for (const { id: id3 } of due) {
|
|
14279
|
+
if (!timer)
|
|
14280
|
+
return;
|
|
14281
|
+
await reconcile(id3);
|
|
14282
|
+
}
|
|
14283
|
+
}
|
|
14284
|
+
function kick() {
|
|
14285
|
+
if (timer && !active) {
|
|
14286
|
+
active = drain().catch(() => {
|
|
14287
|
+
logger24.warn("Memory vector compensation storage unavailable");
|
|
14288
|
+
}).finally(() => {
|
|
14289
|
+
active = void 0;
|
|
14290
|
+
});
|
|
14291
|
+
}
|
|
14292
|
+
}
|
|
14293
|
+
return {
|
|
14294
|
+
write,
|
|
14295
|
+
kick,
|
|
14296
|
+
start() {
|
|
14297
|
+
if (!timer) {
|
|
14298
|
+
timer = setInterval(kick, pollMs);
|
|
14299
|
+
timer.unref();
|
|
14300
|
+
kick();
|
|
14301
|
+
}
|
|
14302
|
+
},
|
|
14303
|
+
async close() {
|
|
14304
|
+
clearInterval(timer);
|
|
14305
|
+
timer = void 0;
|
|
14306
|
+
await active;
|
|
14307
|
+
},
|
|
14308
|
+
async enqueue(pending, entry) {
|
|
14309
|
+
const now = await pending.currentTime();
|
|
14310
|
+
await pending.save(vectorId(entry), { memoryId: entry.id, updatedAt: now, attempts: 0 });
|
|
14311
|
+
},
|
|
14312
|
+
async retire(pending, entry) {
|
|
14313
|
+
const id3 = vectorId(entry);
|
|
14314
|
+
const prior = await pending.get(id3);
|
|
14315
|
+
if (prior?.attempts === 0) {
|
|
14316
|
+
await pending.remove(id3);
|
|
14317
|
+
return;
|
|
14318
|
+
}
|
|
14319
|
+
const now = await pending.currentTime();
|
|
14320
|
+
await pending.save(id3, {
|
|
14321
|
+
memoryId: entry.id,
|
|
14322
|
+
updatedAt: now,
|
|
14323
|
+
attempts: 0,
|
|
14324
|
+
...prior && { retireUntil: now + lateWriteWindowMs }
|
|
14325
|
+
});
|
|
14326
|
+
}
|
|
14327
|
+
};
|
|
14328
|
+
}
|
|
13965
14329
|
|
|
13966
14330
|
// src/memory/providers/ai-memory-provider-native.ts
|
|
13967
|
-
var
|
|
14331
|
+
var logger25 = core.logger.child({ module: "ai", scope: "memory-native" });
|
|
13968
14332
|
var EVICTION_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1e3;
|
|
14333
|
+
var EVICTION_CANDIDATES = 64;
|
|
13969
14334
|
function generateId() {
|
|
13970
|
-
return `mem_${
|
|
14335
|
+
return `mem_${randomUUID()}`;
|
|
14336
|
+
}
|
|
14337
|
+
function publicEntry({ vectorId: _vectorId, ...entry }) {
|
|
14338
|
+
return entry;
|
|
13971
14339
|
}
|
|
13972
14340
|
function cosineSimilarity(a, b) {
|
|
13973
14341
|
if (a.length !== b.length)
|
|
@@ -13988,12 +14356,27 @@ function matchScope2(entry, scope) {
|
|
|
13988
14356
|
return false;
|
|
13989
14357
|
return Object.entries(scope).every(([k, v]) => entry.scope[k] === v);
|
|
13990
14358
|
}
|
|
13991
|
-
function
|
|
14359
|
+
function assembleNativeMemory(config, llm, embedding, store, vectorStore, vectorQueue) {
|
|
14360
|
+
const sync = vectorQueue && createMemoryVectorSync(store, vectorQueue, vectorStore);
|
|
14361
|
+
const maxPending = Math.max(1024, config.maxEntriesGlobal * 2);
|
|
14362
|
+
async function ensureVectorCapacity(pending) {
|
|
14363
|
+
if (pending && await pending.count() >= maxPending)
|
|
14364
|
+
throw new Error("Memory vector synchronization backlog is full");
|
|
14365
|
+
}
|
|
14366
|
+
async function deleteEntry(activeStore, entry, pending) {
|
|
14367
|
+
if (sync && pending) {
|
|
14368
|
+
if (entry.vector)
|
|
14369
|
+
await sync.retire(pending, entry);
|
|
14370
|
+
} else {
|
|
14371
|
+
await vectorStore.remove(entry.id);
|
|
14372
|
+
}
|
|
14373
|
+
return activeStore.remove(entry.id);
|
|
14374
|
+
}
|
|
13992
14375
|
async function protect(operation) {
|
|
13993
14376
|
try {
|
|
13994
14377
|
return await operation();
|
|
13995
14378
|
} catch (error) {
|
|
13996
|
-
|
|
14379
|
+
logger25.error("Memory storage operation failed", {
|
|
13997
14380
|
error: core.sanitize.sanitizeSensitiveFields(error)
|
|
13998
14381
|
});
|
|
13999
14382
|
return err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryOperationFailed"));
|
|
@@ -14025,52 +14408,61 @@ function createNativeMemoryOperations(config, llm, embedding, store, vectorStore
|
|
|
14025
14408
|
const result = await embedding.embedText(text);
|
|
14026
14409
|
if (result.success)
|
|
14027
14410
|
return result.data;
|
|
14028
|
-
|
|
14411
|
+
logger25.warn("Failed to compute embedding for memory", { error: result.error });
|
|
14029
14412
|
return void 0;
|
|
14030
14413
|
}
|
|
14031
|
-
async function evictLowest(candidates) {
|
|
14032
|
-
if (candidates.length === 0)
|
|
14033
|
-
return;
|
|
14414
|
+
async function evictLowest(activeStore, candidates, count, pending) {
|
|
14034
14415
|
const now = Date.now();
|
|
14035
|
-
|
|
14036
|
-
let lowestId = null;
|
|
14037
|
-
for (const entry of candidates) {
|
|
14416
|
+
const ranked = candidates.map((entry) => {
|
|
14038
14417
|
const age = now - entry.createdAt;
|
|
14039
14418
|
const recency = Math.max(0, 1 - age / EVICTION_MAX_AGE_MS);
|
|
14040
|
-
|
|
14041
|
-
|
|
14042
|
-
|
|
14043
|
-
|
|
14044
|
-
|
|
14045
|
-
}
|
|
14046
|
-
if (lowestId) {
|
|
14047
|
-
await vectorStore.remove(lowestId);
|
|
14048
|
-
await store.remove(lowestId);
|
|
14049
|
-
}
|
|
14419
|
+
return { entry, score: entry.importance * 0.7 + recency * 0.3 };
|
|
14420
|
+
}).sort((left, right) => left.score - right.score).slice(0, count);
|
|
14421
|
+
for (const { entry } of ranked)
|
|
14422
|
+
await deleteEntry(activeStore, entry, pending);
|
|
14423
|
+
return ranked.length;
|
|
14050
14424
|
}
|
|
14051
|
-
async function evictIfNeeded(objectId) {
|
|
14052
|
-
const globalTotal = await store.count();
|
|
14053
|
-
if (globalTotal >= config.maxEntriesGlobal) {
|
|
14054
|
-
const all = await store.query({
|
|
14055
|
-
orderBy: { field: "createdAt", direction: "asc" },
|
|
14056
|
-
limit: globalTotal
|
|
14057
|
-
});
|
|
14058
|
-
await evictLowest(all);
|
|
14059
|
-
}
|
|
14425
|
+
async function evictIfNeeded(activeStore, objectId, pending) {
|
|
14060
14426
|
if (objectId) {
|
|
14061
|
-
const objectTotal = await
|
|
14427
|
+
const objectTotal = await activeStore.count({ objectId });
|
|
14062
14428
|
if (objectTotal >= config.maxEntriesPerObject) {
|
|
14063
|
-
const objectEntries = await
|
|
14429
|
+
const objectEntries = await activeStore.query({
|
|
14064
14430
|
objectId,
|
|
14065
14431
|
orderBy: { field: "createdAt", direction: "asc" },
|
|
14066
|
-
limit:
|
|
14432
|
+
limit: EVICTION_CANDIDATES
|
|
14067
14433
|
});
|
|
14068
|
-
|
|
14434
|
+
const needed = objectTotal - config.maxEntriesPerObject + 1;
|
|
14435
|
+
if (await evictLowest(activeStore, objectEntries, needed, pending) < needed)
|
|
14436
|
+
return false;
|
|
14069
14437
|
}
|
|
14070
14438
|
}
|
|
14439
|
+
const globalTotal = await activeStore.count();
|
|
14440
|
+
if (globalTotal >= config.maxEntriesGlobal) {
|
|
14441
|
+
const candidates = await activeStore.query({
|
|
14442
|
+
orderBy: { field: "createdAt", direction: "asc" },
|
|
14443
|
+
limit: EVICTION_CANDIDATES
|
|
14444
|
+
});
|
|
14445
|
+
const needed = globalTotal - config.maxEntriesGlobal + 1;
|
|
14446
|
+
return await evictLowest(activeStore, candidates, needed, pending) >= needed;
|
|
14447
|
+
}
|
|
14448
|
+
return true;
|
|
14449
|
+
}
|
|
14450
|
+
let localWrites = Promise.resolve();
|
|
14451
|
+
async function writeMemory(write) {
|
|
14452
|
+
if (sync) {
|
|
14453
|
+
const written = await sync.write(write);
|
|
14454
|
+
sync.kick();
|
|
14455
|
+
return written;
|
|
14456
|
+
}
|
|
14457
|
+
if (store.withWriteLock)
|
|
14458
|
+
return store.withWriteLock(write);
|
|
14459
|
+
const pending = localWrites.then(() => write(store));
|
|
14460
|
+
localWrites = pending.then(() => {
|
|
14461
|
+
}, () => {
|
|
14462
|
+
});
|
|
14463
|
+
return pending;
|
|
14071
14464
|
}
|
|
14072
14465
|
async function saveEntry(input, vector) {
|
|
14073
|
-
await evictIfNeeded(input.objectId);
|
|
14074
14466
|
const now = Date.now();
|
|
14075
14467
|
const entry = {
|
|
14076
14468
|
id: generateId(),
|
|
@@ -14085,50 +14477,81 @@ function createNativeMemoryOperations(config, llm, embedding, store, vectorStore
|
|
|
14085
14477
|
lastAccessedAt: now,
|
|
14086
14478
|
accessCount: 0
|
|
14087
14479
|
};
|
|
14088
|
-
|
|
14089
|
-
|
|
14090
|
-
await
|
|
14091
|
-
|
|
14092
|
-
|
|
14093
|
-
|
|
14094
|
-
|
|
14095
|
-
|
|
14480
|
+
return writeMemory(async (activeStore, pending) => {
|
|
14481
|
+
await ensureVectorCapacity(pending);
|
|
14482
|
+
if (!await evictIfNeeded(activeStore, input.objectId, pending))
|
|
14483
|
+
return void 0;
|
|
14484
|
+
if (sync && pending && vector) {
|
|
14485
|
+
entry.vectorId = randomUUID();
|
|
14486
|
+
await sync.enqueue(pending, entry);
|
|
14487
|
+
}
|
|
14488
|
+
await activeStore.save(entry.id, entry, { objectId: entry.objectId });
|
|
14489
|
+
if (vector) {
|
|
14490
|
+
if (!pending)
|
|
14491
|
+
await vectorStore.upsert(entry.id, vector, { objectId: entry.objectId, type: entry.type });
|
|
14492
|
+
}
|
|
14493
|
+
return publicEntry(entry);
|
|
14494
|
+
});
|
|
14096
14495
|
}
|
|
14097
14496
|
async function updateEntry(memoryId, updates, accessScope) {
|
|
14098
14497
|
try {
|
|
14099
|
-
const
|
|
14100
|
-
if (!
|
|
14498
|
+
const before = await store.get(memoryId);
|
|
14499
|
+
if (!before || isMemoryAccessDenied(before, accessScope)) {
|
|
14101
14500
|
return err(HaiAIError.MEMORY_NOT_FOUND, aiM("ai_memoryNotFound", {
|
|
14102
14501
|
params: { id: memoryId }
|
|
14103
14502
|
}));
|
|
14104
14503
|
}
|
|
14105
|
-
const
|
|
14106
|
-
|
|
14107
|
-
|
|
14108
|
-
|
|
14109
|
-
|
|
14110
|
-
|
|
14111
|
-
|
|
14112
|
-
|
|
14113
|
-
|
|
14114
|
-
|
|
14115
|
-
|
|
14116
|
-
|
|
14117
|
-
|
|
14118
|
-
|
|
14119
|
-
|
|
14120
|
-
|
|
14121
|
-
|
|
14122
|
-
|
|
14123
|
-
|
|
14124
|
-
|
|
14125
|
-
|
|
14126
|
-
|
|
14504
|
+
const vector = updates.content !== void 0 ? await computeVector(updates.content) : void 0;
|
|
14505
|
+
const existing = await writeMemory(async (active, pending) => {
|
|
14506
|
+
const record = await active.readVersioned(memoryId);
|
|
14507
|
+
if (!record || isMemoryAccessDenied(record.data, accessScope))
|
|
14508
|
+
return void 0;
|
|
14509
|
+
const previous = record.data;
|
|
14510
|
+
const changed = {
|
|
14511
|
+
...previous,
|
|
14512
|
+
...updates.type !== void 0 && { type: updates.type },
|
|
14513
|
+
...updates.importance !== void 0 && { importance: updates.importance },
|
|
14514
|
+
...updates.metadata !== void 0 && { metadata: updates.metadata },
|
|
14515
|
+
...updates.content !== void 0 && { content: updates.content },
|
|
14516
|
+
...updates.content !== void 0 && { vector }
|
|
14517
|
+
};
|
|
14518
|
+
const changesVector = updates.content !== void 0 || updates.type !== void 0 && updates.type !== previous.type;
|
|
14519
|
+
if (changesVector && sync && pending) {
|
|
14520
|
+
if (previous.vector)
|
|
14521
|
+
await sync.retire(pending, previous);
|
|
14522
|
+
changed.vectorId = changed.vector ? randomUUID() : void 0;
|
|
14523
|
+
if (changed.vector) {
|
|
14524
|
+
await ensureVectorCapacity(pending);
|
|
14525
|
+
await sync.enqueue(pending, changed);
|
|
14526
|
+
}
|
|
14527
|
+
}
|
|
14528
|
+
if (!await active.compareAndSwap(memoryId, {
|
|
14529
|
+
expectedVersion: record.version,
|
|
14530
|
+
data: changed,
|
|
14531
|
+
scope: { objectId: changed.objectId }
|
|
14532
|
+
})) {
|
|
14533
|
+
throw new Error("Memory was concurrently changed or deleted");
|
|
14534
|
+
}
|
|
14535
|
+
if (changesVector && !pending) {
|
|
14536
|
+
if (changed.vector)
|
|
14537
|
+
await vectorStore.upsert(memoryId, changed.vector, { objectId: changed.objectId, type: changed.type });
|
|
14538
|
+
else if (previous.vector)
|
|
14539
|
+
await vectorStore.remove(memoryId);
|
|
14540
|
+
}
|
|
14541
|
+
return publicEntry(changed);
|
|
14542
|
+
});
|
|
14543
|
+
if (!existing) {
|
|
14544
|
+
return err(HaiAIError.MEMORY_NOT_FOUND, aiM("ai_memoryNotFound", {
|
|
14545
|
+
params: { id: memoryId }
|
|
14546
|
+
}));
|
|
14127
14547
|
}
|
|
14128
|
-
|
|
14548
|
+
logger25.trace("Memory updated", { id: memoryId });
|
|
14129
14549
|
return ok(existing);
|
|
14130
14550
|
} catch (error) {
|
|
14131
|
-
|
|
14551
|
+
logger25.error("Memory update failed", {
|
|
14552
|
+
id: memoryId,
|
|
14553
|
+
error: core.sanitize.sanitizeSensitiveFields(error)
|
|
14554
|
+
});
|
|
14132
14555
|
return err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryOperationFailed"));
|
|
14133
14556
|
}
|
|
14134
14557
|
}
|
|
@@ -14136,7 +14559,7 @@ function createNativeMemoryOperations(config, llm, embedding, store, vectorStore
|
|
|
14136
14559
|
const topK = options?.topK ?? config.defaultTopK;
|
|
14137
14560
|
const recencyWeight = options?.recencyWeight ?? 1 - config.recencyDecay;
|
|
14138
14561
|
const candidateMultiplier = Math.max(1, options?.candidateMultiplier ?? config.candidateMultiplier);
|
|
14139
|
-
|
|
14562
|
+
logger25.trace("Recalling memories", {
|
|
14140
14563
|
query: query.slice(0, 100),
|
|
14141
14564
|
topK,
|
|
14142
14565
|
updateAccessStats
|
|
@@ -14170,17 +14593,22 @@ function createNativeMemoryOperations(config, llm, embedding, store, vectorStore
|
|
|
14170
14593
|
}
|
|
14171
14594
|
const vectorScores = /* @__PURE__ */ new Map();
|
|
14172
14595
|
if (queryVector) {
|
|
14173
|
-
|
|
14174
|
-
|
|
14175
|
-
|
|
14176
|
-
|
|
14177
|
-
|
|
14178
|
-
|
|
14596
|
+
try {
|
|
14597
|
+
const vectorResults = await vectorStore.search(queryVector, {
|
|
14598
|
+
topK: topK * candidateMultiplier,
|
|
14599
|
+
filter: options?.objectId ? { objectId: options.objectId } : void 0
|
|
14600
|
+
});
|
|
14601
|
+
for (const r of vectorResults)
|
|
14602
|
+
vectorScores.set(r.id, r.score);
|
|
14603
|
+
} catch (error) {
|
|
14604
|
+
if (!sync)
|
|
14605
|
+
throw error;
|
|
14606
|
+
logger25.debug("Memory vector search unavailable; using persisted embeddings");
|
|
14179
14607
|
}
|
|
14180
14608
|
}
|
|
14181
14609
|
const now = Date.now();
|
|
14182
14610
|
const scored = candidates.map((entry) => {
|
|
14183
|
-
let similarity = vectorScores.get(entry.id) ?? 0;
|
|
14611
|
+
let similarity = entry.vector ? vectorScores.get(entry.vectorId ?? entry.id) ?? 0 : 0;
|
|
14184
14612
|
if (!similarity && queryVector && entry.vector) {
|
|
14185
14613
|
similarity = cosineSimilarity(queryVector, entry.vector);
|
|
14186
14614
|
} else if (!similarity) {
|
|
@@ -14200,19 +14628,19 @@ function createNativeMemoryOperations(config, llm, embedding, store, vectorStore
|
|
|
14200
14628
|
if (updateAccessStats) {
|
|
14201
14629
|
const updated = await touchEntry(entry.id, options?.objectId ? { objectId: options.objectId, scope: options.scope } : void 0);
|
|
14202
14630
|
if (updated && (!options?.scope || matchScope2(updated, options.scope)) && (!options?.types?.length || options.types.includes(updated.type)))
|
|
14203
|
-
results.push(updated);
|
|
14631
|
+
results.push(publicEntry(updated));
|
|
14204
14632
|
continue;
|
|
14205
14633
|
}
|
|
14206
|
-
results.push(
|
|
14634
|
+
results.push(publicEntry(entry));
|
|
14207
14635
|
}
|
|
14208
|
-
|
|
14636
|
+
logger25.trace("Memory recall completed", {
|
|
14209
14637
|
query: query.slice(0, 50),
|
|
14210
14638
|
resultCount: results.length,
|
|
14211
14639
|
updateAccessStats
|
|
14212
14640
|
});
|
|
14213
14641
|
return ok(results);
|
|
14214
14642
|
} catch (error) {
|
|
14215
|
-
|
|
14643
|
+
logger25.error("Memory recall failed", {
|
|
14216
14644
|
error: core.sanitize.sanitizeSensitiveFields(error)
|
|
14217
14645
|
});
|
|
14218
14646
|
return err(HaiAIError.MEMORY_RECALL_FAILED, aiM("ai_memoryOperationFailed"));
|
|
@@ -14262,10 +14690,12 @@ function createNativeMemoryOperations(config, llm, embedding, store, vectorStore
|
|
|
14262
14690
|
try {
|
|
14263
14691
|
const vector = await computeVector(entry.content);
|
|
14264
14692
|
const stored = await saveEntry(entry, vector);
|
|
14265
|
-
|
|
14693
|
+
if (!stored)
|
|
14694
|
+
return err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryOperationFailed"));
|
|
14695
|
+
logger25.trace("Memory added", { id: stored.id, type: stored.type });
|
|
14266
14696
|
return ok(stored);
|
|
14267
14697
|
} catch (error) {
|
|
14268
|
-
|
|
14698
|
+
logger25.error("Memory add failed", {
|
|
14269
14699
|
error: core.sanitize.sanitizeSensitiveFields(error)
|
|
14270
14700
|
});
|
|
14271
14701
|
return err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryOperationFailed"));
|
|
@@ -14291,7 +14721,7 @@ function createNativeMemoryOperations(config, llm, embedding, store, vectorStore
|
|
|
14291
14721
|
params: { id: memoryId }
|
|
14292
14722
|
}));
|
|
14293
14723
|
}
|
|
14294
|
-
return ok(entry);
|
|
14724
|
+
return ok(publicEntry(entry));
|
|
14295
14725
|
},
|
|
14296
14726
|
/**
|
|
14297
14727
|
* 根据 ID 删除一条记忆(同时清理关系存储与向量库)
|
|
@@ -14301,20 +14731,18 @@ function createNativeMemoryOperations(config, llm, embedding, store, vectorStore
|
|
|
14301
14731
|
* @returns `ok(undefined)` 删除成功;ID 不存在或归属不符时返回 `MEMORY_NOT_FOUND`
|
|
14302
14732
|
*/
|
|
14303
14733
|
async remove(memoryId, accessScope) {
|
|
14304
|
-
const
|
|
14305
|
-
|
|
14306
|
-
|
|
14307
|
-
|
|
14308
|
-
|
|
14309
|
-
}
|
|
14310
|
-
|
|
14311
|
-
const removed = await store.remove(memoryId);
|
|
14312
|
-
if (!removed) {
|
|
14734
|
+
const removed2 = await writeMemory(async (active, pending) => {
|
|
14735
|
+
const existing = await active.get(memoryId);
|
|
14736
|
+
if (!existing || isMemoryAccessDenied(existing, accessScope))
|
|
14737
|
+
return false;
|
|
14738
|
+
return deleteEntry(active, existing, pending);
|
|
14739
|
+
});
|
|
14740
|
+
if (!removed2) {
|
|
14313
14741
|
return err(HaiAIError.MEMORY_NOT_FOUND, aiM("ai_memoryNotFound", {
|
|
14314
14742
|
params: { id: memoryId }
|
|
14315
14743
|
}));
|
|
14316
14744
|
}
|
|
14317
|
-
|
|
14745
|
+
logger25.trace("Memory removed", { id: memoryId });
|
|
14318
14746
|
return ok(void 0);
|
|
14319
14747
|
},
|
|
14320
14748
|
/**
|
|
@@ -14340,9 +14768,9 @@ function createNativeMemoryOperations(config, llm, embedding, store, vectorStore
|
|
|
14340
14768
|
limit: options?.scope ? void 0 : options?.limit
|
|
14341
14769
|
});
|
|
14342
14770
|
if (!options?.scope)
|
|
14343
|
-
return ok(results);
|
|
14771
|
+
return ok(results.map(publicEntry));
|
|
14344
14772
|
const filtered = results.filter((e) => matchScope2(e, options.scope));
|
|
14345
|
-
return ok(options.limit ? filtered.slice(0, options.limit) : filtered);
|
|
14773
|
+
return ok((options.limit ? filtered.slice(0, options.limit) : filtered).map(publicEntry));
|
|
14346
14774
|
},
|
|
14347
14775
|
/**
|
|
14348
14776
|
* 分页列出记忆条目
|
|
@@ -14370,7 +14798,10 @@ function createNativeMemoryOperations(config, llm, embedding, store, vectorStore
|
|
|
14370
14798
|
},
|
|
14371
14799
|
{ offset, limit }
|
|
14372
14800
|
);
|
|
14373
|
-
return ok(
|
|
14801
|
+
return ok({
|
|
14802
|
+
...page,
|
|
14803
|
+
items: page.items.map(publicEntry)
|
|
14804
|
+
});
|
|
14374
14805
|
}
|
|
14375
14806
|
const all = await store.query({
|
|
14376
14807
|
objectId: options?.objectId,
|
|
@@ -14380,7 +14811,7 @@ function createNativeMemoryOperations(config, llm, embedding, store, vectorStore
|
|
|
14380
14811
|
});
|
|
14381
14812
|
const filtered = all.filter((e) => matchScope2(e, options.scope));
|
|
14382
14813
|
return ok({
|
|
14383
|
-
items: filtered.slice(offset, offset + limit),
|
|
14814
|
+
items: filtered.slice(offset, offset + limit).map(publicEntry),
|
|
14384
14815
|
total: filtered.length
|
|
14385
14816
|
});
|
|
14386
14817
|
},
|
|
@@ -14394,46 +14825,62 @@ function createNativeMemoryOperations(config, llm, embedding, store, vectorStore
|
|
|
14394
14825
|
* @returns `ok(undefined)` 操作成功
|
|
14395
14826
|
*/
|
|
14396
14827
|
async clear(options) {
|
|
14397
|
-
if (!options?.types && !options?.objectId && !options?.scope) {
|
|
14828
|
+
if (!sync && !options?.types && !options?.objectId && !options?.scope) {
|
|
14398
14829
|
await vectorStore.clear();
|
|
14399
14830
|
await store.clear();
|
|
14400
|
-
|
|
14831
|
+
logger25.debug("All memories cleared");
|
|
14401
14832
|
return ok(void 0);
|
|
14402
14833
|
}
|
|
14403
14834
|
const where = {};
|
|
14404
|
-
if (options
|
|
14835
|
+
if (options?.types && options.types.length === 1)
|
|
14405
14836
|
where.type = options.types[0];
|
|
14406
|
-
else if (options
|
|
14837
|
+
else if (options?.types && options.types.length > 1)
|
|
14407
14838
|
where.type = { $in: options.types };
|
|
14408
|
-
const
|
|
14409
|
-
objectId: options
|
|
14410
|
-
scope: options
|
|
14839
|
+
const filter = {
|
|
14840
|
+
objectId: options?.objectId,
|
|
14841
|
+
scope: options?.scope,
|
|
14411
14842
|
where: Object.keys(where).length > 0 ? where : void 0
|
|
14412
|
-
}
|
|
14413
|
-
const
|
|
14414
|
-
|
|
14415
|
-
|
|
14416
|
-
|
|
14843
|
+
};
|
|
14844
|
+
const scope = options?.scope;
|
|
14845
|
+
let removed2 = 0;
|
|
14846
|
+
let afterId = "";
|
|
14847
|
+
while (true) {
|
|
14848
|
+
const batch = await writeMemory(async (active, pending) => {
|
|
14849
|
+
const rows = await active.query(sync ? { ...filter, afterId, limit: EVICTION_CANDIDATES } : filter);
|
|
14850
|
+
const selected = scope ? rows.filter((e) => matchScope2(e, scope)) : rows;
|
|
14851
|
+
for (const entry of selected)
|
|
14852
|
+
await deleteEntry(active, entry, pending);
|
|
14853
|
+
return { nextId: rows.at(-1)?.id, total: rows.length, selected: selected.length };
|
|
14854
|
+
});
|
|
14855
|
+
removed2 += batch.selected;
|
|
14856
|
+
if (!sync || batch.total < EVICTION_CANDIDATES || !batch.nextId)
|
|
14857
|
+
break;
|
|
14858
|
+
if (batch.nextId === afterId)
|
|
14859
|
+
throw new Error("Memory store did not advance the primary-key cursor");
|
|
14860
|
+
afterId = batch.nextId;
|
|
14417
14861
|
}
|
|
14418
|
-
|
|
14419
|
-
removed:
|
|
14420
|
-
objectId: options
|
|
14421
|
-
types: options
|
|
14422
|
-
scoped: Boolean(
|
|
14862
|
+
logger25.debug("Memories cleared", {
|
|
14863
|
+
removed: removed2,
|
|
14864
|
+
objectId: options?.objectId,
|
|
14865
|
+
types: options?.types,
|
|
14866
|
+
scoped: Boolean(scope)
|
|
14423
14867
|
});
|
|
14424
14868
|
return ok(void 0);
|
|
14425
14869
|
}
|
|
14426
14870
|
};
|
|
14427
14871
|
return {
|
|
14428
|
-
|
|
14429
|
-
|
|
14430
|
-
|
|
14431
|
-
|
|
14432
|
-
|
|
14433
|
-
|
|
14872
|
+
sync,
|
|
14873
|
+
operations: {
|
|
14874
|
+
...operations2,
|
|
14875
|
+
get: (id3, scope) => protect(() => operations2.get(id3, scope)),
|
|
14876
|
+
remove: (id3, scope) => protect(() => operations2.remove(id3, scope)),
|
|
14877
|
+
list: (options) => protect(() => operations2.list(options)),
|
|
14878
|
+
listPage: (options) => protect(() => operations2.listPage(options)),
|
|
14879
|
+
clear: (options) => protect(() => operations2.clear(options))
|
|
14880
|
+
}
|
|
14434
14881
|
};
|
|
14435
14882
|
}
|
|
14436
|
-
var
|
|
14883
|
+
var logger26 = core.logger.child({ module: "ai", scope: "persona" });
|
|
14437
14884
|
var DEFAULT_OBJECT_ID2 = "system";
|
|
14438
14885
|
function personaKey(objectId, id3) {
|
|
14439
14886
|
return JSON.stringify([objectId, id3]);
|
|
@@ -14452,7 +14899,7 @@ function createPersonaOperations(store) {
|
|
|
14452
14899
|
try {
|
|
14453
14900
|
return await operation();
|
|
14454
14901
|
} catch (error) {
|
|
14455
|
-
|
|
14902
|
+
logger26.error("Persona storage operation failed", {
|
|
14456
14903
|
error: core.sanitize.sanitizeSensitiveFields(error)
|
|
14457
14904
|
});
|
|
14458
14905
|
return err(HaiAIError.PERSONA_SAVE_FAILED, aiM("ai_personaOperationFailed"));
|
|
@@ -14476,10 +14923,10 @@ function createPersonaOperations(store) {
|
|
|
14476
14923
|
updatedAt: now
|
|
14477
14924
|
};
|
|
14478
14925
|
await store.save(key, profile, { objectId });
|
|
14479
|
-
|
|
14926
|
+
logger26.trace("Persona saved", { id: profile.id, objectId });
|
|
14480
14927
|
return ok(profile);
|
|
14481
14928
|
} catch (error) {
|
|
14482
|
-
|
|
14929
|
+
logger26.error("Persona save failed", {
|
|
14483
14930
|
error: core.sanitize.sanitizeSensitiveFields(error)
|
|
14484
14931
|
});
|
|
14485
14932
|
return err(HaiAIError.PERSONA_SAVE_FAILED, aiM("ai_personaOperationFailed"));
|
|
@@ -14516,7 +14963,7 @@ function createPersonaOperations(store) {
|
|
|
14516
14963
|
await store.save(key, profile, { objectId });
|
|
14517
14964
|
return ok(profile);
|
|
14518
14965
|
} catch (error) {
|
|
14519
|
-
|
|
14966
|
+
logger26.error("Persona update failed", {
|
|
14520
14967
|
error: core.sanitize.sanitizeSensitiveFields(error)
|
|
14521
14968
|
});
|
|
14522
14969
|
return err(HaiAIError.PERSONA_SAVE_FAILED, aiM("ai_personaOperationFailed"));
|
|
@@ -14555,7 +15002,7 @@ function createPersonaOperations(store) {
|
|
|
14555
15002
|
compose: (id3, options) => protect(() => operations2.compose(id3, options))
|
|
14556
15003
|
};
|
|
14557
15004
|
}
|
|
14558
|
-
var
|
|
15005
|
+
var logger27 = core.logger.child({ module: "ai", scope: "rag" });
|
|
14559
15006
|
var DEFAULT_RAG_SYSTEM_PROMPT = `You are a helpful assistant. Answer the user's question based on the provided context.
|
|
14560
15007
|
If the context doesn't contain relevant information, say so honestly.
|
|
14561
15008
|
When using information from the context, cite the source by its number, e.g. [1] or [2].`;
|
|
@@ -14584,7 +15031,7 @@ function createRagOperations(llm, retrieval) {
|
|
|
14584
15031
|
* @returns `ok(RagResult)` 含 answer、context 列表与引用信源;检索或生成失败时返回错误
|
|
14585
15032
|
*/
|
|
14586
15033
|
async query(query, options) {
|
|
14587
|
-
|
|
15034
|
+
logger27.trace("Starting RAG query", {
|
|
14588
15035
|
query: query.slice(0, 100)
|
|
14589
15036
|
});
|
|
14590
15037
|
try {
|
|
@@ -14639,7 +15086,7 @@ ${contextText}
|
|
|
14639
15086
|
}
|
|
14640
15087
|
const choice = chatResult.data.choices[0];
|
|
14641
15088
|
const answer = choice?.message?.content ?? "";
|
|
14642
|
-
|
|
15089
|
+
logger27.trace("RAG query completed", {
|
|
14643
15090
|
contextCount: contextItems.length,
|
|
14644
15091
|
model: chatResult.data.model
|
|
14645
15092
|
});
|
|
@@ -14666,7 +15113,7 @@ ${contextText}
|
|
|
14666
15113
|
} : void 0
|
|
14667
15114
|
});
|
|
14668
15115
|
} catch (error) {
|
|
14669
|
-
|
|
15116
|
+
logger27.error("RAG query failed", { error });
|
|
14670
15117
|
return err(HaiAIError.RAG_FAILED, aiM("ai_internalError", {
|
|
14671
15118
|
params: {
|
|
14672
15119
|
error: String(error)
|
|
@@ -14678,7 +15125,7 @@ ${contextText}
|
|
|
14678
15125
|
* 流式 RAG 查询:先产出 context,再逐 chunk 产出 delta,最后 done
|
|
14679
15126
|
*/
|
|
14680
15127
|
async *queryStream(query, options) {
|
|
14681
|
-
|
|
15128
|
+
logger27.trace("Starting RAG stream", {
|
|
14682
15129
|
query: query.slice(0, 100)
|
|
14683
15130
|
});
|
|
14684
15131
|
const retrieveResult = await retrieval.retrieve({
|
|
@@ -14762,7 +15209,7 @@ ${contextText}
|
|
|
14762
15209
|
}
|
|
14763
15210
|
};
|
|
14764
15211
|
}
|
|
14765
|
-
var
|
|
15212
|
+
var logger28 = core.logger.child({ module: "ai", scope: "reasoning" });
|
|
14766
15213
|
var REACT_SYSTEM_PROMPT = `You are a reasoning agent that follows the ReAct (Reasoning and Acting) framework.
|
|
14767
15214
|
For each step:
|
|
14768
15215
|
1. Think: Analyze what you know and what you need to find out.
|
|
@@ -15012,7 +15459,7 @@ ${query}` }
|
|
|
15012
15459
|
return {
|
|
15013
15460
|
async run(query, options) {
|
|
15014
15461
|
const strategy = options?.strategy ?? "react";
|
|
15015
|
-
|
|
15462
|
+
logger28.trace("Starting reasoning", { strategy, maxRounds: options?.maxRounds });
|
|
15016
15463
|
try {
|
|
15017
15464
|
switch (strategy) {
|
|
15018
15465
|
case "react":
|
|
@@ -15027,7 +15474,7 @@ ${query}` }
|
|
|
15027
15474
|
}));
|
|
15028
15475
|
}
|
|
15029
15476
|
} catch (error) {
|
|
15030
|
-
|
|
15477
|
+
logger28.error("Reasoning failed", { error });
|
|
15031
15478
|
return err(HaiAIError.REASONING_FAILED, aiM("ai_internalError", {
|
|
15032
15479
|
params: {
|
|
15033
15480
|
error: String(error)
|
|
@@ -15059,8 +15506,8 @@ ${query}` }
|
|
|
15059
15506
|
}
|
|
15060
15507
|
};
|
|
15061
15508
|
}
|
|
15062
|
-
var
|
|
15063
|
-
function createRerankOperations(config) {
|
|
15509
|
+
var logger29 = core.logger.child({ module: "ai", scope: "rerank" });
|
|
15510
|
+
function createRerankOperations(config, loadModels = () => config.llm) {
|
|
15064
15511
|
function normalizeDocuments(documents) {
|
|
15065
15512
|
if (documents.length === 0) {
|
|
15066
15513
|
return { texts: [], ids: [] };
|
|
@@ -15079,7 +15526,7 @@ function createRerankOperations(config) {
|
|
|
15079
15526
|
};
|
|
15080
15527
|
}
|
|
15081
15528
|
async function callRerankAPI(request2) {
|
|
15082
|
-
const resolvedResult = resolveModelEntry(
|
|
15529
|
+
const resolvedResult = resolveModelEntry(await loadModels(request2.model), "rerank", request2.model, {
|
|
15083
15530
|
missingApiKeyMessage: aiM("ai_configError", {
|
|
15084
15531
|
params: { error: "API Key is required for rerank" }
|
|
15085
15532
|
})
|
|
@@ -15104,7 +15551,7 @@ function createRerankOperations(config) {
|
|
|
15104
15551
|
if (request2.returnDocuments) {
|
|
15105
15552
|
body.return_documents = true;
|
|
15106
15553
|
}
|
|
15107
|
-
|
|
15554
|
+
logger29.trace("Calling rerank API", { model: resolved.model, documentCount: texts.length, topN: request2.topN });
|
|
15108
15555
|
try {
|
|
15109
15556
|
const response = await fetch(`${resolved.baseUrl}/v1/rerank`, {
|
|
15110
15557
|
method: "POST",
|
|
@@ -15119,7 +15566,7 @@ function createRerankOperations(config) {
|
|
|
15119
15566
|
const requestId = response.headers.get("x-request-id");
|
|
15120
15567
|
await response.body?.cancel().catch(() => {
|
|
15121
15568
|
});
|
|
15122
|
-
|
|
15569
|
+
logger29.error("Rerank API request failed", {
|
|
15123
15570
|
status: response.status,
|
|
15124
15571
|
providerRequestId: requestId && /^[\w.:-]{1,128}$/.test(requestId) ? requestId : void 0
|
|
15125
15572
|
});
|
|
@@ -15134,11 +15581,11 @@ function createRerankOperations(config) {
|
|
|
15134
15581
|
relevanceScore: item2.relevance_score,
|
|
15135
15582
|
document: item2.document?.text
|
|
15136
15583
|
}));
|
|
15137
|
-
|
|
15584
|
+
logger29.trace("Rerank completed", { resultCount: results.length });
|
|
15138
15585
|
return ok({ model: resolved.model, results });
|
|
15139
15586
|
} catch (error) {
|
|
15140
15587
|
const causeName = error instanceof Error ? error.name : void 0;
|
|
15141
|
-
|
|
15588
|
+
logger29.error("Rerank API call failed", { causeName });
|
|
15142
15589
|
return err(HaiAIError.RERANK_API_ERROR, aiM("ai_rerankApiFailed", {
|
|
15143
15590
|
params: {
|
|
15144
15591
|
error: causeName ?? core.i18n.coreM("core_errorInternal")
|
|
@@ -15174,7 +15621,7 @@ function createRerankOperations(config) {
|
|
|
15174
15621
|
}
|
|
15175
15622
|
};
|
|
15176
15623
|
}
|
|
15177
|
-
var
|
|
15624
|
+
var logger30 = core.logger.child({ module: "ai", scope: "retrieval" });
|
|
15178
15625
|
function createRetrievalOperations(embeddingOps, storeProvider, sourceStore, rerankOps, registry) {
|
|
15179
15626
|
const vectorStoreCache = /* @__PURE__ */ new Map();
|
|
15180
15627
|
function getVectorStore(collection) {
|
|
@@ -15207,7 +15654,7 @@ function createRetrievalOperations(embeddingOps, storeProvider, sourceStore, rer
|
|
|
15207
15654
|
}));
|
|
15208
15655
|
}
|
|
15209
15656
|
await sourceStore.save(source.id, source);
|
|
15210
|
-
|
|
15657
|
+
logger30.debug("Retrieval source added", { sourceId: source.id, collection: source.collection });
|
|
15211
15658
|
return ok(void 0);
|
|
15212
15659
|
},
|
|
15213
15660
|
/**
|
|
@@ -15228,7 +15675,7 @@ function createRetrievalOperations(embeddingOps, storeProvider, sourceStore, rer
|
|
|
15228
15675
|
}));
|
|
15229
15676
|
}
|
|
15230
15677
|
await sourceStore.remove(sourceId);
|
|
15231
|
-
|
|
15678
|
+
logger30.debug("Retrieval source removed", { sourceId });
|
|
15232
15679
|
return ok(void 0);
|
|
15233
15680
|
},
|
|
15234
15681
|
/**
|
|
@@ -15315,21 +15762,21 @@ function createRetrievalOperations(embeddingOps, storeProvider, sourceStore, rer
|
|
|
15315
15762
|
allItems.length = 0;
|
|
15316
15763
|
allItems.push(...reranked);
|
|
15317
15764
|
} else {
|
|
15318
|
-
|
|
15765
|
+
logger30.warn("Rerank failed, falling back to vector scores", { error: rerankResult.error });
|
|
15319
15766
|
}
|
|
15320
15767
|
}
|
|
15321
15768
|
allItems.sort((a, b) => b.score - a.score);
|
|
15322
15769
|
const topK = request2.topK ?? 10;
|
|
15323
15770
|
const limitedItems = allItems.slice(0, topK);
|
|
15324
15771
|
const duration = Date.now() - startTime;
|
|
15325
|
-
|
|
15772
|
+
logger30.trace("Retrieval completed", { queryLength: request2.query.length, resultCount: limitedItems.length, duration });
|
|
15326
15773
|
return ok({
|
|
15327
15774
|
items: limitedItems,
|
|
15328
15775
|
query: request2.query,
|
|
15329
15776
|
duration
|
|
15330
15777
|
});
|
|
15331
15778
|
} catch (error) {
|
|
15332
|
-
|
|
15779
|
+
logger30.error("Retrieval failed", { error });
|
|
15333
15780
|
return err(HaiAIError.RETRIEVAL_FAILED, aiM("ai_internalError", {
|
|
15334
15781
|
params: {
|
|
15335
15782
|
error: String(error)
|
|
@@ -15339,7 +15786,7 @@ function createRetrievalOperations(embeddingOps, storeProvider, sourceStore, rer
|
|
|
15339
15786
|
}
|
|
15340
15787
|
};
|
|
15341
15788
|
}
|
|
15342
|
-
var
|
|
15789
|
+
var logger31 = core.logger.child({ module: "ai", scope: "summary" });
|
|
15343
15790
|
var SUMMARIZE_SYSTEM_PROMPT = `You are a conversation summarizer. Create a concise summary of the conversation that preserves:
|
|
15344
15791
|
1. Key facts and decisions made
|
|
15345
15792
|
2. Important context and background information
|
|
@@ -15397,7 +15844,7 @@ ${INCREMENTAL_SUMMARIZE_SUFFIX.replace("{previousSummary}", options.previousSumm
|
|
|
15397
15844
|
return ok(chatResult.data.choices[0]?.message?.content ?? "");
|
|
15398
15845
|
}
|
|
15399
15846
|
async function summarize(messages, options) {
|
|
15400
|
-
|
|
15847
|
+
logger31.trace("Summarizing messages", { messageCount: messages.length });
|
|
15401
15848
|
try {
|
|
15402
15849
|
const result = await generate(messages, options);
|
|
15403
15850
|
if (!result.success)
|
|
@@ -15409,7 +15856,7 @@ ${INCREMENTAL_SUMMARIZE_SUFFIX.replace("{previousSummary}", options.previousSumm
|
|
|
15409
15856
|
coveredMessages: messages.filter((m) => m.role !== "system").length
|
|
15410
15857
|
});
|
|
15411
15858
|
} catch (error) {
|
|
15412
|
-
|
|
15859
|
+
logger31.error("Context summarization failed", { error });
|
|
15413
15860
|
return err(HaiAIError.CONTEXT_SUMMARIZE_FAILED, aiM("ai_contextSummarizeFailed", {
|
|
15414
15861
|
params: {
|
|
15415
15862
|
error: String(error)
|
|
@@ -15474,8 +15921,10 @@ async function createAISubsystems(config, deps) {
|
|
|
15474
15921
|
);
|
|
15475
15922
|
const memoryStore = useMem0Oss ? null : storeProvider.createRelStore("hai_ai_memory", {
|
|
15476
15923
|
hasObjectId: true,
|
|
15477
|
-
hasScopeIndex: true
|
|
15924
|
+
hasScopeIndex: true,
|
|
15925
|
+
serializeWrites: true
|
|
15478
15926
|
});
|
|
15927
|
+
const memoryVectorQueue = memoryStore?.withRelatedWriteLock ? storeProvider.createRelStore("hai_ai_memory_vector_outbox", { hasUpdatedAtIndex: true }) : void 0;
|
|
15479
15928
|
const contextStore = storeProvider.createRelStore(
|
|
15480
15929
|
"hai_ai_context",
|
|
15481
15930
|
{ hasObjectId: true, hasSessionId: true }
|
|
@@ -15524,6 +15973,18 @@ async function createAISubsystems(config, deps) {
|
|
|
15524
15973
|
llm: { ...config.llm, models: await llmModels.values() }
|
|
15525
15974
|
};
|
|
15526
15975
|
}
|
|
15976
|
+
async function scenarioModels(scenario, explicit) {
|
|
15977
|
+
if (explicit)
|
|
15978
|
+
return (await llmConfig()).llm;
|
|
15979
|
+
const modelId = config.llm.scenarios?.[scenario] ?? config.llm.scenarios?.default;
|
|
15980
|
+
if (!modelId)
|
|
15981
|
+
return config.llm;
|
|
15982
|
+
const entry = await llmModels.read(modelId);
|
|
15983
|
+
return {
|
|
15984
|
+
...config.llm,
|
|
15985
|
+
models: entry ? [entry.value] : []
|
|
15986
|
+
};
|
|
15987
|
+
}
|
|
15527
15988
|
async function audioConfig() {
|
|
15528
15989
|
return {
|
|
15529
15990
|
...config,
|
|
@@ -15601,16 +16062,11 @@ async function createAISubsystems(config, deps) {
|
|
|
15601
16062
|
);
|
|
15602
16063
|
}
|
|
15603
16064
|
}
|
|
16065
|
+
const embeddingRuntime = createEmbeddingOperations(config, (model) => scenarioModels("embedding", model));
|
|
15604
16066
|
const embedding = {
|
|
15605
|
-
embed: (request2) => resourceCall(
|
|
15606
|
-
|
|
15607
|
-
)
|
|
15608
|
-
embedText: (text) => resourceCall(
|
|
15609
|
-
async () => createEmbeddingOperations(await llmConfig()).embedText(text)
|
|
15610
|
-
),
|
|
15611
|
-
embedBatch: (texts) => resourceCall(
|
|
15612
|
-
async () => createEmbeddingOperations(await llmConfig()).embedBatch(texts)
|
|
15613
|
-
)
|
|
16067
|
+
embed: (request2) => resourceCall(() => embeddingRuntime.embed(request2)),
|
|
16068
|
+
embedText: (text) => resourceCall(() => embeddingRuntime.embedText(text)),
|
|
16069
|
+
embedBatch: (texts) => resourceCall(() => embeddingRuntime.embedBatch(texts))
|
|
15614
16070
|
};
|
|
15615
16071
|
const reasoning = {
|
|
15616
16072
|
run: (query, options) => resourceCall(async () => createReasoningOperations(await llmConfig(), llm).run(query, options)),
|
|
@@ -15618,17 +16074,10 @@ async function createAISubsystems(config, deps) {
|
|
|
15618
16074
|
yield* createReasoningOperations(await llmConfig(), llm).runStream(query, options);
|
|
15619
16075
|
}
|
|
15620
16076
|
};
|
|
16077
|
+
const rerankRuntime = createRerankOperations(config, (model) => scenarioModels("rerank", model));
|
|
15621
16078
|
const rerank = {
|
|
15622
|
-
rerank: (request2) => resourceCall(
|
|
15623
|
-
|
|
15624
|
-
),
|
|
15625
|
-
rerankTexts: (query, texts, topN) => resourceCall(
|
|
15626
|
-
async () => createRerankOperations(await llmConfig()).rerankTexts(
|
|
15627
|
-
query,
|
|
15628
|
-
texts,
|
|
15629
|
-
topN
|
|
15630
|
-
)
|
|
15631
|
-
)
|
|
16079
|
+
rerank: (request2) => resourceCall(() => rerankRuntime.rerank(request2)),
|
|
16080
|
+
rerankTexts: (query, texts, topN) => resourceCall(() => rerankRuntime.rerankTexts(query, texts, topN))
|
|
15632
16081
|
};
|
|
15633
16082
|
const retrieval = Object.assign(
|
|
15634
16083
|
createRetrievalOperations(
|
|
@@ -15650,13 +16099,8 @@ async function createAISubsystems(config, deps) {
|
|
|
15650
16099
|
datapipeDep,
|
|
15651
16100
|
knowledgeStore
|
|
15652
16101
|
);
|
|
15653
|
-
const
|
|
15654
|
-
|
|
15655
|
-
llm,
|
|
15656
|
-
embedding,
|
|
15657
|
-
memoryStore,
|
|
15658
|
-
memoryVectorStore
|
|
15659
|
-
) : await createMem0MemoryOperations({
|
|
16102
|
+
const nativeMemory = memoryStore && memoryVectorStore ? assembleNativeMemory(memoryParsed, llm, embedding, memoryStore, memoryVectorStore, memoryVectorQueue) : void 0;
|
|
16103
|
+
const memoryCore = nativeMemory?.operations ?? await createMem0MemoryOperations({
|
|
15660
16104
|
config: memoryParsed,
|
|
15661
16105
|
embedding,
|
|
15662
16106
|
llm,
|
|
@@ -15763,10 +16207,12 @@ async function createAISubsystems(config, deps) {
|
|
|
15763
16207
|
servers: managedMCPServers,
|
|
15764
16208
|
services: mcpServices.operations
|
|
15765
16209
|
});
|
|
16210
|
+
nativeMemory?.sync?.start();
|
|
15766
16211
|
return {
|
|
15767
|
-
closeRegistries: () => {
|
|
16212
|
+
closeRegistries: async () => {
|
|
15768
16213
|
mcpServices.close();
|
|
15769
16214
|
registriesOpen = false;
|
|
16215
|
+
await nativeMemory?.sync?.close();
|
|
15770
16216
|
},
|
|
15771
16217
|
a2aStores,
|
|
15772
16218
|
llm,
|
|
@@ -16163,7 +16609,7 @@ function documentInfo(document) {
|
|
|
16163
16609
|
}
|
|
16164
16610
|
|
|
16165
16611
|
// src/store/providers/ai-store-provider-db.ts
|
|
16166
|
-
var
|
|
16612
|
+
var logger32 = core.logger.child({ module: "ai", scope: "store-provider-db" });
|
|
16167
16613
|
function requireSqlSuccess(result) {
|
|
16168
16614
|
if (!result.success)
|
|
16169
16615
|
throw new Error(result.error.message, { cause: result.error });
|
|
@@ -16188,8 +16634,9 @@ function isMysqlDuplicateIndex(error) {
|
|
|
16188
16634
|
}
|
|
16189
16635
|
return false;
|
|
16190
16636
|
}
|
|
16191
|
-
var ReldbAIRelStore = class {
|
|
16637
|
+
var ReldbAIRelStore = class _ReldbAIRelStore {
|
|
16192
16638
|
sql;
|
|
16639
|
+
connection;
|
|
16193
16640
|
table;
|
|
16194
16641
|
jsonOps;
|
|
16195
16642
|
dbType;
|
|
@@ -16198,7 +16645,12 @@ var ReldbAIRelStore = class {
|
|
|
16198
16645
|
hasStatus;
|
|
16199
16646
|
hasRefId;
|
|
16200
16647
|
hasScopeIndex;
|
|
16201
|
-
|
|
16648
|
+
hasUpdatedAtIndex;
|
|
16649
|
+
gate;
|
|
16650
|
+
withWriteLock;
|
|
16651
|
+
withRelatedWriteLock;
|
|
16652
|
+
constructor(sql, table, jsonOps, dbType, options, tx) {
|
|
16653
|
+
this.connection = sql;
|
|
16202
16654
|
this.sql = {
|
|
16203
16655
|
...sql,
|
|
16204
16656
|
execute: (query, params) => sql.execute(query, params).then(requireSqlSuccess),
|
|
@@ -16213,6 +16665,33 @@ var ReldbAIRelStore = class {
|
|
|
16213
16665
|
this.hasStatus = options?.hasStatus ?? false;
|
|
16214
16666
|
this.hasRefId = options?.hasRefId ?? false;
|
|
16215
16667
|
this.hasScopeIndex = options?.hasScopeIndex ?? false;
|
|
16668
|
+
this.hasUpdatedAtIndex = options?.hasUpdatedAtIndex ?? false;
|
|
16669
|
+
if (options?.serializeWrites && tx) {
|
|
16670
|
+
const gate = `${table}_write_gate`;
|
|
16671
|
+
this.gate = gate;
|
|
16672
|
+
const lockedWrite = async (write) => requireSqlSuccess(await tx.wrap(async (connection) => {
|
|
16673
|
+
const locked = requireSqlSuccess(await connection.execute(`UPDATE ${gate} SET marker = 1 - marker WHERE id = 1`));
|
|
16674
|
+
if (locked.data.changes !== 1)
|
|
16675
|
+
throw new Error("Missing AI store write gate");
|
|
16676
|
+
return write(connection);
|
|
16677
|
+
})).data;
|
|
16678
|
+
this.withWriteLock = (write) => lockedWrite((connection) => write(new _ReldbAIRelStore(connection, table, jsonOps, dbType, options)));
|
|
16679
|
+
this.withRelatedWriteLock = (related, write) => {
|
|
16680
|
+
if (!(related instanceof _ReldbAIRelStore) || related.connection !== sql || related.dbType !== dbType || related.jsonOps !== jsonOps)
|
|
16681
|
+
throw new TypeError("Related AI stores must share a database");
|
|
16682
|
+
return lockedWrite((connection) => write(
|
|
16683
|
+
new _ReldbAIRelStore(connection, table, jsonOps, dbType, options),
|
|
16684
|
+
new _ReldbAIRelStore(connection, related.table, jsonOps, dbType, {
|
|
16685
|
+
hasObjectId: related.hasObjectId,
|
|
16686
|
+
hasSessionId: related.hasSessionId,
|
|
16687
|
+
hasStatus: related.hasStatus,
|
|
16688
|
+
hasRefId: related.hasRefId,
|
|
16689
|
+
hasScopeIndex: related.hasScopeIndex,
|
|
16690
|
+
hasUpdatedAtIndex: related.hasUpdatedAtIndex
|
|
16691
|
+
})
|
|
16692
|
+
));
|
|
16693
|
+
};
|
|
16694
|
+
}
|
|
16216
16695
|
}
|
|
16217
16696
|
/** 创建表及索引(幂等) */
|
|
16218
16697
|
async createTable() {
|
|
@@ -16232,6 +16711,11 @@ var ReldbAIRelStore = class {
|
|
|
16232
16711
|
cols.push(`ref_id ${scopeType}`);
|
|
16233
16712
|
cols.push("version VARCHAR(36) NOT NULL", `data ${dataType} NOT NULL`, `created_at BIGINT NOT NULL`, `updated_at BIGINT NOT NULL`);
|
|
16234
16713
|
await this.sql.execute(`CREATE TABLE IF NOT EXISTS ${t} (${cols.join(", ")})`);
|
|
16714
|
+
if (this.gate) {
|
|
16715
|
+
await this.sql.execute(`CREATE TABLE IF NOT EXISTS ${this.gate} (id INTEGER PRIMARY KEY, marker INTEGER NOT NULL)`);
|
|
16716
|
+
const conflict = db === "mysql" ? "ON DUPLICATE KEY UPDATE id = id" : "ON CONFLICT(id) DO NOTHING";
|
|
16717
|
+
await this.sql.execute(`INSERT INTO ${this.gate} (id, marker) VALUES (1, 0) ${conflict}`);
|
|
16718
|
+
}
|
|
16235
16719
|
if (this.hasObjectId)
|
|
16236
16720
|
await this.createIndex(`idx_${t}_object_id`, "object_id");
|
|
16237
16721
|
if (this.hasSessionId)
|
|
@@ -16242,6 +16726,8 @@ var ReldbAIRelStore = class {
|
|
|
16242
16726
|
await this.createIndex(`idx_${t}_status`, "status");
|
|
16243
16727
|
if (this.hasRefId)
|
|
16244
16728
|
await this.createIndex(`idx_${t}_ref_id`, "ref_id");
|
|
16729
|
+
if (this.hasUpdatedAtIndex)
|
|
16730
|
+
await this.createIndex(`idx_${t}_updated_at`, "updated_at, id");
|
|
16245
16731
|
if (this.hasScopeIndex && db === "postgresql")
|
|
16246
16732
|
await this.sql.execute(`CREATE INDEX IF NOT EXISTS idx_${t}_data_gin ON ${t} USING GIN (data jsonb_path_ops)`);
|
|
16247
16733
|
}
|
|
@@ -16387,18 +16873,41 @@ var ReldbAIRelStore = class {
|
|
|
16387
16873
|
let countSql = `SELECT COUNT(*) as cnt FROM ${this.table}`;
|
|
16388
16874
|
if (countConditions.length > 0)
|
|
16389
16875
|
countSql += ` WHERE ${countConditions.join(" AND ")}`;
|
|
16390
|
-
const
|
|
16391
|
-
const total = countResult.success && countResult.data != null ? countResult.data.cnt : 0;
|
|
16876
|
+
const count = requireSqlSuccess(await this.sql.get(countSql, countParams)).data;
|
|
16392
16877
|
const { sql, params } = this.buildQuery({ ...filter, limit: void 0 });
|
|
16393
16878
|
const pagedSql = `${sql} LIMIT ? OFFSET ?`;
|
|
16394
|
-
const
|
|
16395
|
-
|
|
16396
|
-
|
|
16879
|
+
const rows = requireSqlSuccess(await this.sql.query(pagedSql, [...params, page.limit, page.offset])).data;
|
|
16880
|
+
return {
|
|
16881
|
+
items: rows.map((row) => this.decodeData(row.data)),
|
|
16882
|
+
total: Number(count?.cnt ?? 0)
|
|
16883
|
+
};
|
|
16397
16884
|
}
|
|
16398
16885
|
async remove(id3) {
|
|
16399
16886
|
await this.sql.execute(`DELETE FROM ${this.table} WHERE id = ?`, [id3]);
|
|
16400
16887
|
return true;
|
|
16401
16888
|
}
|
|
16889
|
+
async queryKeys(filter, cursor) {
|
|
16890
|
+
const params = [];
|
|
16891
|
+
const conditions = this.buildAllConditions(filter, params);
|
|
16892
|
+
if (cursor) {
|
|
16893
|
+
conditions.push("(updated_at > ? OR (updated_at = ? AND id > ?))");
|
|
16894
|
+
params.push(cursor.updatedAt, cursor.updatedAt, cursor.id);
|
|
16895
|
+
}
|
|
16896
|
+
const where = conditions.length ? ` WHERE ${conditions.join(" AND ")}` : "";
|
|
16897
|
+
const result = await this.sql.query(
|
|
16898
|
+
`SELECT id, updated_at, version FROM ${this.table}${where} ORDER BY updated_at, id LIMIT ?`,
|
|
16899
|
+
[...params, filter.limit ?? 64]
|
|
16900
|
+
);
|
|
16901
|
+
return requireSqlSuccess(result).data.map((row) => ({
|
|
16902
|
+
id: row.id,
|
|
16903
|
+
updatedAt: Number(row.updated_at),
|
|
16904
|
+
version: row.version
|
|
16905
|
+
}));
|
|
16906
|
+
}
|
|
16907
|
+
async removeIfUnchanged(id3, version) {
|
|
16908
|
+
const deleted = await this.sql.execute(`DELETE FROM ${this.table} WHERE id = ? AND version = ?`, [id3, version]);
|
|
16909
|
+
return requireSqlSuccess(deleted).data.changes === 1;
|
|
16910
|
+
}
|
|
16402
16911
|
async removeBy(filter) {
|
|
16403
16912
|
const params = [];
|
|
16404
16913
|
const conditions = this.buildAllConditions(filter, params);
|
|
@@ -16407,19 +16916,19 @@ var ReldbAIRelStore = class {
|
|
|
16407
16916
|
const whereClause = ` WHERE ${conditions.join(" AND ")}`;
|
|
16408
16917
|
countSql += whereClause;
|
|
16409
16918
|
const countResult2 = await this.sql.get(countSql, [...params]);
|
|
16410
|
-
const count2 = countResult2.success && countResult2.data != null ? countResult2.data.cnt : 0;
|
|
16919
|
+
const count2 = countResult2.success && countResult2.data != null ? Number(countResult2.data.cnt) : 0;
|
|
16411
16920
|
await this.sql.execute(`DELETE FROM ${this.table}${whereClause}`, params);
|
|
16412
16921
|
return count2;
|
|
16413
16922
|
}
|
|
16414
16923
|
const countResult = await this.sql.get(countSql);
|
|
16415
|
-
const count = countResult.success && countResult.data != null ? countResult.data.cnt : 0;
|
|
16924
|
+
const count = countResult.success && countResult.data != null ? Number(countResult.data.cnt) : 0;
|
|
16416
16925
|
await this.sql.execute(`DELETE FROM ${this.table}`);
|
|
16417
16926
|
return count;
|
|
16418
16927
|
}
|
|
16419
16928
|
async count(filter) {
|
|
16420
|
-
if (!filter?.where && !filter?.objectId && !filter?.sessionId && !filter?.status && !filter?.refId) {
|
|
16929
|
+
if (!filter?.where && !filter?.objectId && !filter?.sessionId && !filter?.status && !filter?.refId && !filter?.scope && filter?.updatedBefore === void 0 && filter?.afterId === void 0) {
|
|
16421
16930
|
const result2 = await this.sql.get(`SELECT COUNT(*) as cnt FROM ${this.table}`);
|
|
16422
|
-
return result2.success && result2.data != null ? result2.data.cnt : 0;
|
|
16931
|
+
return result2.success && result2.data != null ? Number(result2.data.cnt) : 0;
|
|
16423
16932
|
}
|
|
16424
16933
|
const params = [];
|
|
16425
16934
|
const conditions = this.buildAllConditions(filter, params);
|
|
@@ -16427,10 +16936,10 @@ var ReldbAIRelStore = class {
|
|
|
16427
16936
|
if (conditions.length > 0)
|
|
16428
16937
|
sql += ` WHERE ${conditions.join(" AND ")}`;
|
|
16429
16938
|
const result = await this.sql.get(sql, params);
|
|
16430
|
-
return result.success && result.data != null ? result.data.cnt : 0;
|
|
16939
|
+
return result.success && result.data != null ? Number(result.data.cnt) : 0;
|
|
16431
16940
|
}
|
|
16432
16941
|
async clear(filter) {
|
|
16433
|
-
if (!filter?.where && !filter?.objectId && !filter?.sessionId && !filter?.status && !filter?.refId) {
|
|
16942
|
+
if (!filter?.where && !filter?.objectId && !filter?.sessionId && !filter?.status && !filter?.refId && !filter?.scope && filter?.updatedBefore === void 0 && filter?.afterId === void 0) {
|
|
16434
16943
|
await this.sql.execute(`DELETE FROM ${this.table}`);
|
|
16435
16944
|
return;
|
|
16436
16945
|
}
|
|
@@ -16505,7 +17014,9 @@ var ReldbAIRelStore = class {
|
|
|
16505
17014
|
const conditions = this.buildAllConditions(filter, params);
|
|
16506
17015
|
if (conditions.length > 0)
|
|
16507
17016
|
sql += ` WHERE ${conditions.join(" AND ")}`;
|
|
16508
|
-
if (filter.
|
|
17017
|
+
if (filter.afterId !== void 0) {
|
|
17018
|
+
sql += " ORDER BY id ASC";
|
|
17019
|
+
} else if (filter.orderBy) {
|
|
16509
17020
|
const dir = filter.orderBy.direction === "asc" ? "ASC" : "DESC";
|
|
16510
17021
|
const field = String(filter.orderBy.field);
|
|
16511
17022
|
if (field === "createdAt") {
|
|
@@ -16528,6 +17039,14 @@ var ReldbAIRelStore = class {
|
|
|
16528
17039
|
}
|
|
16529
17040
|
buildAllConditions(filter, params) {
|
|
16530
17041
|
const conditions = [];
|
|
17042
|
+
if (filter.afterId !== void 0) {
|
|
17043
|
+
conditions.push("id > ?");
|
|
17044
|
+
params.push(filter.afterId);
|
|
17045
|
+
}
|
|
17046
|
+
if (filter.updatedBefore !== void 0) {
|
|
17047
|
+
conditions.push("updated_at < ?");
|
|
17048
|
+
params.push(filter.updatedBefore);
|
|
17049
|
+
}
|
|
16531
17050
|
if (filter.objectId && this.hasObjectId) {
|
|
16532
17051
|
conditions.push("object_id = ?");
|
|
16533
17052
|
params.push(filter.objectId);
|
|
@@ -16567,47 +17086,69 @@ var ReldbAIRelStore = class {
|
|
|
16567
17086
|
if (op.$in !== void 0 && Array.isArray(op.$in)) {
|
|
16568
17087
|
const { sql: jsonSql, params: jsonParams } = this.jsonOps.extract("data", path);
|
|
16569
17088
|
params.push(...jsonParams);
|
|
16570
|
-
conditions.push(`${jsonSql} IN (${op.$in.map(() =>
|
|
16571
|
-
params.push(...op.$in);
|
|
17089
|
+
conditions.push(`${jsonSql} IN (${op.$in.map(() => this.jsonComparisonParameter()).join(", ")})`);
|
|
17090
|
+
params.push(...op.$in.map((value2) => this.jsonComparisonValue(value2)));
|
|
17091
|
+
}
|
|
17092
|
+
if (op.$ne !== void 0) {
|
|
17093
|
+
const { sql: expression, params: pathParams } = this.jsonOps.extract("data", path);
|
|
17094
|
+
conditions.push(`COALESCE(${expression} <> ${this.jsonComparisonParameter()}, TRUE)`);
|
|
17095
|
+
params.push(...pathParams, this.jsonComparisonValue(op.$ne));
|
|
16572
17096
|
}
|
|
16573
17097
|
if (op.$gte !== void 0) {
|
|
16574
17098
|
const { sql: j, params: p } = this.jsonOps.extract("data", path);
|
|
16575
17099
|
params.push(...p);
|
|
16576
|
-
conditions.push(`${j} >=
|
|
16577
|
-
params.push(op.$gte);
|
|
17100
|
+
conditions.push(`${j} >= ${this.jsonComparisonParameter()}`);
|
|
17101
|
+
params.push(this.jsonComparisonValue(op.$gte));
|
|
16578
17102
|
}
|
|
16579
17103
|
if (op.$gt !== void 0) {
|
|
16580
17104
|
const { sql: j, params: p } = this.jsonOps.extract("data", path);
|
|
16581
17105
|
params.push(...p);
|
|
16582
|
-
conditions.push(`${j} >
|
|
16583
|
-
params.push(op.$gt);
|
|
17106
|
+
conditions.push(`${j} > ${this.jsonComparisonParameter()}`);
|
|
17107
|
+
params.push(this.jsonComparisonValue(op.$gt));
|
|
16584
17108
|
}
|
|
16585
17109
|
if (op.$lte !== void 0) {
|
|
16586
17110
|
const { sql: j, params: p } = this.jsonOps.extract("data", path);
|
|
16587
17111
|
params.push(...p);
|
|
16588
|
-
conditions.push(`${j} <=
|
|
16589
|
-
params.push(op.$lte);
|
|
17112
|
+
conditions.push(`${j} <= ${this.jsonComparisonParameter()}`);
|
|
17113
|
+
params.push(this.jsonComparisonValue(op.$lte));
|
|
16590
17114
|
}
|
|
16591
17115
|
if (op.$lt !== void 0) {
|
|
16592
17116
|
const { sql: j, params: p } = this.jsonOps.extract("data", path);
|
|
16593
17117
|
params.push(...p);
|
|
16594
|
-
conditions.push(`${j} <
|
|
16595
|
-
params.push(op.$lt);
|
|
17118
|
+
conditions.push(`${j} < ${this.jsonComparisonParameter()}`);
|
|
17119
|
+
params.push(this.jsonComparisonValue(op.$lt));
|
|
16596
17120
|
}
|
|
16597
17121
|
} else {
|
|
16598
17122
|
const { sql: jsonSql, params: jsonParams } = this.jsonOps.extract("data", path);
|
|
16599
17123
|
params.push(...jsonParams);
|
|
16600
|
-
conditions.push(`${jsonSql} =
|
|
16601
|
-
params.push(value);
|
|
17124
|
+
conditions.push(`${jsonSql} = ${this.jsonComparisonParameter()}`);
|
|
17125
|
+
params.push(this.jsonComparisonValue(value));
|
|
16602
17126
|
}
|
|
16603
17127
|
}
|
|
16604
17128
|
return conditions;
|
|
16605
17129
|
}
|
|
17130
|
+
jsonComparisonParameter() {
|
|
17131
|
+
if (this.dbType === "postgresql")
|
|
17132
|
+
return "?::jsonb";
|
|
17133
|
+
return this.dbType === "mysql" ? "CAST(? AS JSON)" : "?";
|
|
17134
|
+
}
|
|
17135
|
+
jsonComparisonValue(value) {
|
|
17136
|
+
if (this.dbType !== "sqlite")
|
|
17137
|
+
return JSON.stringify(value);
|
|
17138
|
+
return typeof value === "boolean" ? Number(value) : value;
|
|
17139
|
+
}
|
|
16606
17140
|
isWhereOperator(value) {
|
|
16607
17141
|
if (typeof value !== "object" || value === null || Array.isArray(value))
|
|
16608
17142
|
return false;
|
|
16609
17143
|
const keys = Object.keys(value);
|
|
16610
|
-
return keys.length > 0 && keys.every((k) => [
|
|
17144
|
+
return keys.length > 0 && keys.every((k) => [
|
|
17145
|
+
"$in",
|
|
17146
|
+
"$ne",
|
|
17147
|
+
"$gte",
|
|
17148
|
+
"$gt",
|
|
17149
|
+
"$lte",
|
|
17150
|
+
"$lt"
|
|
17151
|
+
].includes(k));
|
|
16611
17152
|
}
|
|
16612
17153
|
};
|
|
16613
17154
|
function requireVecdbSuccess(result) {
|
|
@@ -16662,7 +17203,7 @@ function createDbStoreProvider(deps) {
|
|
|
16662
17203
|
return dbType !== "sqlite" && sharedVector ? "shared" : "local";
|
|
16663
17204
|
},
|
|
16664
17205
|
createRelStore(name, options) {
|
|
16665
|
-
const store = new ReldbAIRelStore(sql, name, jsonOps, dbType, options);
|
|
17206
|
+
const store = new ReldbAIRelStore(sql, name, jsonOps, dbType, options, deps.tx);
|
|
16666
17207
|
const stores = relStores.get(name) ?? [];
|
|
16667
17208
|
stores.push(store);
|
|
16668
17209
|
relStores.set(name, stores);
|
|
@@ -16700,7 +17241,7 @@ function createDbStoreProvider(deps) {
|
|
|
16700
17241
|
if (result.status === "rejected")
|
|
16701
17242
|
throw result.reason;
|
|
16702
17243
|
}
|
|
16703
|
-
|
|
17244
|
+
logger32.debug("DB store provider initialized", { tableCount: relStores.size });
|
|
16704
17245
|
}
|
|
16705
17246
|
},
|
|
16706
17247
|
async close() {
|
|
@@ -16714,6 +17255,7 @@ function isDbStoreAvailable() {
|
|
|
16714
17255
|
function createDbStoreProviderFromModules() {
|
|
16715
17256
|
return createDbStoreProvider({
|
|
16716
17257
|
sql: reldb.sql,
|
|
17258
|
+
tx: reldb.tx,
|
|
16717
17259
|
jsonOps: reldb.json,
|
|
16718
17260
|
dbType: reldb.config?.type,
|
|
16719
17261
|
vecdb
|
|
@@ -16722,7 +17264,14 @@ function createDbStoreProviderFromModules() {
|
|
|
16722
17264
|
|
|
16723
17265
|
// src/store/providers/ai-store-provider-memory.ts
|
|
16724
17266
|
function isWhereOperator(value) {
|
|
16725
|
-
return typeof value === "object" && value !== null && [
|
|
17267
|
+
return typeof value === "object" && value !== null && [
|
|
17268
|
+
"$in",
|
|
17269
|
+
"$ne",
|
|
17270
|
+
"$gte",
|
|
17271
|
+
"$gt",
|
|
17272
|
+
"$lte",
|
|
17273
|
+
"$lt"
|
|
17274
|
+
].some((key) => key in value);
|
|
16726
17275
|
}
|
|
16727
17276
|
function compare(left, right) {
|
|
16728
17277
|
if (typeof left === "number" && typeof right === "number")
|
|
@@ -16732,6 +17281,8 @@ function compare(left, right) {
|
|
|
16732
17281
|
function matchesOperator(value, operator) {
|
|
16733
17282
|
if (operator.$in && !operator.$in.some((candidate) => Object.is(candidate, value)))
|
|
16734
17283
|
return false;
|
|
17284
|
+
if (operator.$ne !== void 0 && Object.is(operator.$ne, value))
|
|
17285
|
+
return false;
|
|
16735
17286
|
if (operator.$gte !== void 0 && compare(value, operator.$gte) < 0)
|
|
16736
17287
|
return false;
|
|
16737
17288
|
if (operator.$gt !== void 0 && compare(value, operator.$gt) <= 0)
|
|
@@ -16743,6 +17294,8 @@ function matchesOperator(value, operator) {
|
|
|
16743
17294
|
return true;
|
|
16744
17295
|
}
|
|
16745
17296
|
function matchesRecord(record, filter) {
|
|
17297
|
+
if (filter.updatedBefore !== void 0 && record.updatedAt >= filter.updatedBefore)
|
|
17298
|
+
return false;
|
|
16746
17299
|
if (filter.objectId !== void 0 && record.scope?.objectId !== filter.objectId)
|
|
16747
17300
|
return false;
|
|
16748
17301
|
if (filter.sessionId !== void 0 && record.scope?.sessionId !== filter.sessionId)
|
|
@@ -16779,8 +17332,15 @@ function matchesRecord(record, filter) {
|
|
|
16779
17332
|
}
|
|
16780
17333
|
function createRelStore(records) {
|
|
16781
17334
|
function select(filter) {
|
|
16782
|
-
|
|
16783
|
-
|
|
17335
|
+
const afterId = filter.afterId;
|
|
17336
|
+
let entries = [
|
|
17337
|
+
...records.entries()
|
|
17338
|
+
].filter(([id3, record]) => (afterId === void 0 || id3 > afterId) && matchesRecord(record, filter));
|
|
17339
|
+
if (afterId !== void 0) {
|
|
17340
|
+
entries = entries.sort(([left], [right]) => left < right ? -1 : Number(left > right));
|
|
17341
|
+
}
|
|
17342
|
+
let values = entries.map(([, record]) => structuredClone(record.data));
|
|
17343
|
+
if (filter.orderBy && afterId === void 0) {
|
|
16784
17344
|
const { field, direction } = filter.orderBy;
|
|
16785
17345
|
const multiplier = direction === "asc" ? 1 : -1;
|
|
16786
17346
|
values = values.sort((left, right) => compare(left[field], right[field]) * multiplier);
|
|
@@ -16810,7 +17370,8 @@ function createRelStore(records) {
|
|
|
16810
17370
|
records.set(id3, {
|
|
16811
17371
|
version,
|
|
16812
17372
|
data: structuredClone(input.data),
|
|
16813
|
-
scope: structuredClone(input.scope ?? record?.scope)
|
|
17373
|
+
scope: structuredClone(input.scope ?? record?.scope),
|
|
17374
|
+
updatedAt: Date.now()
|
|
16814
17375
|
});
|
|
16815
17376
|
return version;
|
|
16816
17377
|
},
|
|
@@ -16818,7 +17379,8 @@ function createRelStore(records) {
|
|
|
16818
17379
|
records.set(id3, {
|
|
16819
17380
|
version: crypto.randomUUID(),
|
|
16820
17381
|
data: structuredClone(data),
|
|
16821
|
-
scope: structuredClone(scope)
|
|
17382
|
+
scope: structuredClone(scope),
|
|
17383
|
+
updatedAt: Date.now()
|
|
16822
17384
|
});
|
|
16823
17385
|
},
|
|
16824
17386
|
async saveMany(items) {
|
|
@@ -16826,7 +17388,8 @@ function createRelStore(records) {
|
|
|
16826
17388
|
records.set(item2.id, {
|
|
16827
17389
|
version: crypto.randomUUID(),
|
|
16828
17390
|
data: structuredClone(item2.data),
|
|
16829
|
-
scope: structuredClone(item2.scope)
|
|
17391
|
+
scope: structuredClone(item2.scope),
|
|
17392
|
+
updatedAt: Date.now()
|
|
16830
17393
|
});
|
|
16831
17394
|
}
|
|
16832
17395
|
},
|
|
@@ -16846,8 +17409,16 @@ function createRelStore(records) {
|
|
|
16846
17409
|
async remove(id3) {
|
|
16847
17410
|
return records.delete(id3);
|
|
16848
17411
|
},
|
|
17412
|
+
async queryKeys(filter, cursor) {
|
|
17413
|
+
return [
|
|
17414
|
+
...records.entries()
|
|
17415
|
+
].filter(([id3, record]) => (filter.afterId === void 0 || id3 > filter.afterId) && matchesRecord(record, filter) && (!cursor || record.updatedAt > cursor.updatedAt || record.updatedAt === cursor.updatedAt && id3 > cursor.id)).map(([id3, { updatedAt, version }]) => ({ id: id3, updatedAt, version })).sort((left, right) => left.updatedAt - right.updatedAt || (left.id < right.id ? -1 : Number(left.id > right.id))).slice(0, filter.limit ?? 64);
|
|
17416
|
+
},
|
|
17417
|
+
async removeIfUnchanged(id3, version) {
|
|
17418
|
+
return records.get(id3)?.version === version && records.delete(id3);
|
|
17419
|
+
},
|
|
16849
17420
|
async removeBy(filter) {
|
|
16850
|
-
const ids = Array.from(records.entries()).filter(([, record]) => matchesRecord(record, filter)).map(([id3]) => id3);
|
|
17421
|
+
const ids = Array.from(records.entries()).filter(([id3, record]) => (filter.afterId === void 0 || id3 > filter.afterId) && matchesRecord(record, filter)).map(([id3]) => id3);
|
|
16851
17422
|
for (const id3 of ids)
|
|
16852
17423
|
records.delete(id3);
|
|
16853
17424
|
return ids.length;
|
|
@@ -16860,7 +17431,7 @@ function createRelStore(records) {
|
|
|
16860
17431
|
records.clear();
|
|
16861
17432
|
return;
|
|
16862
17433
|
}
|
|
16863
|
-
const ids = Array.from(records.entries()).filter(([, record]) => matchesRecord(record, filter)).map(([id3]) => id3);
|
|
17434
|
+
const ids = Array.from(records.entries()).filter(([id3, record]) => (filter.afterId === void 0 || id3 > filter.afterId) && matchesRecord(record, filter)).map(([id3]) => id3);
|
|
16864
17435
|
for (const id3 of ids)
|
|
16865
17436
|
records.delete(id3);
|
|
16866
17437
|
}
|
|
@@ -16950,7 +17521,7 @@ function createMemoryStoreProvider() {
|
|
|
16950
17521
|
}
|
|
16951
17522
|
|
|
16952
17523
|
// src/ai-main.ts
|
|
16953
|
-
var
|
|
17524
|
+
var logger33 = core.logger.child({ module: "ai", scope: "main" });
|
|
16954
17525
|
var initInProgress = false;
|
|
16955
17526
|
var initCompletion = null;
|
|
16956
17527
|
var closingPromise = null;
|
|
@@ -17101,7 +17672,7 @@ async function resetAllState() {
|
|
|
17101
17672
|
await currentA2AImpl?.close();
|
|
17102
17673
|
await currentACP?.close();
|
|
17103
17674
|
currentLLM = null;
|
|
17104
|
-
currentRegistriesClose?.();
|
|
17675
|
+
await currentRegistriesClose?.();
|
|
17105
17676
|
currentRegistriesClose = null;
|
|
17106
17677
|
currentACP = null;
|
|
17107
17678
|
currentMCP = null;
|
|
@@ -17129,7 +17700,7 @@ async function resetAllState() {
|
|
|
17129
17700
|
try {
|
|
17130
17701
|
await storeProvider.close();
|
|
17131
17702
|
} catch (error) {
|
|
17132
|
-
|
|
17703
|
+
logger33.error("AI store provider close failed", { error });
|
|
17133
17704
|
}
|
|
17134
17705
|
}
|
|
17135
17706
|
}
|
|
@@ -17146,7 +17717,7 @@ var streamOperations = {
|
|
|
17146
17717
|
var ai = {
|
|
17147
17718
|
async init(config, options) {
|
|
17148
17719
|
if (initInProgress || closingPromise) {
|
|
17149
|
-
|
|
17720
|
+
logger33.warn("AI init already in progress, skipping concurrent call");
|
|
17150
17721
|
return err(HaiAIError.INIT_IN_PROGRESS, aiM("ai_initInProgress"));
|
|
17151
17722
|
}
|
|
17152
17723
|
initInProgress = true;
|
|
@@ -17157,15 +17728,15 @@ var ai = {
|
|
|
17157
17728
|
let closingPrevious = false;
|
|
17158
17729
|
try {
|
|
17159
17730
|
if (currentConfig) {
|
|
17160
|
-
|
|
17731
|
+
logger33.warn("AI module is already initialized, reinitializing");
|
|
17161
17732
|
closingPrevious = true;
|
|
17162
17733
|
await resetAllState();
|
|
17163
17734
|
closingPrevious = false;
|
|
17164
17735
|
}
|
|
17165
|
-
|
|
17736
|
+
logger33.info("Initializing AI module");
|
|
17166
17737
|
const parseResult = AIConfigSchema.safeParse(config ?? {});
|
|
17167
17738
|
if (!parseResult.success) {
|
|
17168
|
-
|
|
17739
|
+
logger33.error("AI config validation failed", { error: parseResult.error.message });
|
|
17169
17740
|
return err(
|
|
17170
17741
|
HaiAIError.CONFIGURATION_ERROR,
|
|
17171
17742
|
aiM("ai_configError", {
|
|
@@ -17182,7 +17753,7 @@ var ai = {
|
|
|
17182
17753
|
storeProvider = createDbStoreProviderFromModules();
|
|
17183
17754
|
} else {
|
|
17184
17755
|
storeProvider = createMemoryStoreProvider();
|
|
17185
|
-
|
|
17756
|
+
logger33.warn("AI is using the ephemeral in-memory store; initialize reldb and vecdb before ai.init() for persistent data");
|
|
17186
17757
|
}
|
|
17187
17758
|
if (core.module.requiresSharedState(process2.env) && storeProvider.stateScope !== "shared")
|
|
17188
17759
|
return err(HaiAIError.CONFIGURATION_ERROR, aiM("ai_sharedBackendRequired"));
|
|
@@ -17218,17 +17789,17 @@ var ai = {
|
|
|
17218
17789
|
currentA2AConfig = parsed.a2a;
|
|
17219
17790
|
currentA2AStores = subs.a2aStores;
|
|
17220
17791
|
currentConfig = parsed;
|
|
17221
|
-
|
|
17792
|
+
logger33.info("AI module initialized", { model: parsed.llm?.model });
|
|
17222
17793
|
return ok(void 0);
|
|
17223
17794
|
} catch (error) {
|
|
17224
17795
|
if (!closingPrevious) {
|
|
17225
17796
|
try {
|
|
17226
17797
|
await resetAllState();
|
|
17227
17798
|
} catch (cleanupError) {
|
|
17228
|
-
|
|
17799
|
+
logger33.error("AI initialization cleanup failed", { error: cleanupError });
|
|
17229
17800
|
}
|
|
17230
17801
|
}
|
|
17231
|
-
|
|
17802
|
+
logger33.error("AI module initialization failed", { error });
|
|
17232
17803
|
return err(
|
|
17233
17804
|
HaiAIError.CONFIGURATION_ERROR,
|
|
17234
17805
|
aiM("ai_initFailed", {
|
|
@@ -17318,9 +17889,9 @@ var ai = {
|
|
|
17318
17889
|
closingPromise = (async () => {
|
|
17319
17890
|
if (initCompletion)
|
|
17320
17891
|
await initCompletion;
|
|
17321
|
-
|
|
17892
|
+
logger33.info("Closing AI module");
|
|
17322
17893
|
await resetAllState();
|
|
17323
|
-
|
|
17894
|
+
logger33.info("AI module closed");
|
|
17324
17895
|
})().finally(() => {
|
|
17325
17896
|
closingPromise = null;
|
|
17326
17897
|
});
|