@h-ai/ai 1.0.0-beta.24 → 1.0.0-beta.25
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 +164 -1
- package/README.ja.md +164 -1
- package/README.md +164 -1
- package/dist/{ai-acp-types-B99Oa7WD.d.ts → ai-acp-types-Bwp6PcL8.d.ts} +29 -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 +663 -353
- 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';
|
|
@@ -2583,6 +2584,42 @@ function createGitOperations(workspace, runtime) {
|
|
|
2583
2584
|
})
|
|
2584
2585
|
};
|
|
2585
2586
|
}
|
|
2587
|
+
var batchSize = 64;
|
|
2588
|
+
var retentionMs = 7 * 24 * 60 * 60 * 1e3;
|
|
2589
|
+
function removed(result) {
|
|
2590
|
+
return !result.success && result.error.code === HaiRunnerError.NOT_FOUND.code;
|
|
2591
|
+
}
|
|
2592
|
+
function createACPMaintenance(runner, stores) {
|
|
2593
|
+
const { bindings, intents, receipts } = stores;
|
|
2594
|
+
function scan(store, consider) {
|
|
2595
|
+
let cursor;
|
|
2596
|
+
return async (updatedBefore) => {
|
|
2597
|
+
if (!store.queryKeys || !store.removeIfUnchanged)
|
|
2598
|
+
return;
|
|
2599
|
+
const page = await store.queryKeys({ updatedBefore, limit: batchSize }, cursor);
|
|
2600
|
+
for (const key of page) {
|
|
2601
|
+
if (await consider(key))
|
|
2602
|
+
await store.removeIfUnchanged(key.id, key.version);
|
|
2603
|
+
}
|
|
2604
|
+
cursor = page.length === batchSize ? page.at(-1) : void 0;
|
|
2605
|
+
};
|
|
2606
|
+
}
|
|
2607
|
+
const pruneBindings = scan(bindings, async ({ id: id3, version }) => {
|
|
2608
|
+
const record = await bindings.readVersioned(id3);
|
|
2609
|
+
return record?.version === version && removed(await runner.get(record.data.workerScope, record.data.workerId));
|
|
2610
|
+
});
|
|
2611
|
+
const pruneIntents = scan(intents, async ({ id: id3 }) => !await bindings.get(id3));
|
|
2612
|
+
const pruneReceipts = scan(receipts, async ({ id: id3, version }) => {
|
|
2613
|
+
const record = await receipts.readVersioned(id3);
|
|
2614
|
+
return record?.version === version && removed(await runner.get(record.data.workerScope, id3));
|
|
2615
|
+
});
|
|
2616
|
+
return async () => {
|
|
2617
|
+
const cutoff = await bindings.currentTime() - retentionMs;
|
|
2618
|
+
await pruneBindings(cutoff);
|
|
2619
|
+
await pruneIntents(cutoff);
|
|
2620
|
+
await pruneReceipts(cutoff);
|
|
2621
|
+
};
|
|
2622
|
+
}
|
|
2586
2623
|
function encodeWorkspaceSnapshot(snapshot2, scratchMiB) {
|
|
2587
2624
|
const files = Object.entries(snapshot2);
|
|
2588
2625
|
const maxBytes = Math.min(16, scratchMiB) * 1024 * 1024;
|
|
@@ -2600,9 +2637,24 @@ var workerKind = "hai.acp.worker.v1";
|
|
|
2600
2637
|
var controlKind = "hai.acp.control.v1";
|
|
2601
2638
|
var turnSchema = platformOptionsSchema.pick({ limits: true, output: true });
|
|
2602
2639
|
var historySummaryMaxBytes = 8192;
|
|
2640
|
+
var maxPermissionCalls = 64;
|
|
2641
|
+
var maxPermissionInputBytes = 8192;
|
|
2642
|
+
var maintenanceIntervalMs = 3e4;
|
|
2643
|
+
var logger3 = core.logger.child({ module: "ai", scope: "acp-maintenance" });
|
|
2603
2644
|
function hash(value) {
|
|
2604
2645
|
return createHash("sha256").update(value).digest("hex");
|
|
2605
2646
|
}
|
|
2647
|
+
function canonicalToolInput(value) {
|
|
2648
|
+
if (value === void 0 || value === null)
|
|
2649
|
+
return void 0;
|
|
2650
|
+
const sorted = JSON.stringify(value, (_key, item2) => {
|
|
2651
|
+
if (item2 && typeof item2 === "object" && !Array.isArray(item2)) {
|
|
2652
|
+
return Object.fromEntries(Object.entries(item2).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0));
|
|
2653
|
+
}
|
|
2654
|
+
return item2;
|
|
2655
|
+
});
|
|
2656
|
+
return Buffer.byteLength(sorted) <= maxPermissionInputBytes ? sorted : void 0;
|
|
2657
|
+
}
|
|
2606
2658
|
function json(value) {
|
|
2607
2659
|
return JSON.parse(JSON.stringify(value));
|
|
2608
2660
|
}
|
|
@@ -2661,16 +2713,44 @@ function turnRequest(base, options) {
|
|
|
2661
2713
|
}
|
|
2662
2714
|
function createACPPlatform(deps) {
|
|
2663
2715
|
const { limits, runner, policy } = deps;
|
|
2664
|
-
const
|
|
2665
|
-
const
|
|
2666
|
-
const
|
|
2667
|
-
const
|
|
2668
|
-
const
|
|
2716
|
+
const maintenanceIndex = { hasUpdatedAtIndex: true };
|
|
2717
|
+
const bindings = deps.store.createRelStore("hai_ai_acp_managed_sessions", maintenanceIndex);
|
|
2718
|
+
const intents = deps.store.createRelStore("hai_ai_acp_managed_requests", maintenanceIndex);
|
|
2719
|
+
const approvals = deps.store.createRelStore("hai_ai_acp_managed_approvals", maintenanceIndex);
|
|
2720
|
+
const grants = deps.store.createRelStore("hai_ai_acp_managed_grants", maintenanceIndex);
|
|
2721
|
+
const receipts = deps.store.createRelStore("hai_ai_acp_managed_receipts", maintenanceIndex);
|
|
2669
2722
|
const workers = /* @__PURE__ */ new Map();
|
|
2670
2723
|
const localWorkers = /* @__PURE__ */ new Map();
|
|
2671
2724
|
const owned = /* @__PURE__ */ new Map();
|
|
2672
2725
|
const unregister = [];
|
|
2673
2726
|
let closed = false;
|
|
2727
|
+
let maintenanceTimer;
|
|
2728
|
+
let maintenancePending;
|
|
2729
|
+
async function maintainApprovals() {
|
|
2730
|
+
if (!approvals.queryKeys || !approvals.removeIfUnchanged || !grants.queryKeys || !grants.removeIfUnchanged)
|
|
2731
|
+
return;
|
|
2732
|
+
const now = await approvals.currentTime();
|
|
2733
|
+
const [expiredApprovals, expiredGrants] = await Promise.all([
|
|
2734
|
+
approvals.queryKeys({
|
|
2735
|
+
where: {
|
|
2736
|
+
deadline: { $lte: now }
|
|
2737
|
+
},
|
|
2738
|
+
limit: 64
|
|
2739
|
+
}),
|
|
2740
|
+
grants.queryKeys({
|
|
2741
|
+
where: {
|
|
2742
|
+
expires: { $lte: now }
|
|
2743
|
+
},
|
|
2744
|
+
limit: 64
|
|
2745
|
+
})
|
|
2746
|
+
]);
|
|
2747
|
+
const removeApproval = approvals.removeIfUnchanged.bind(approvals);
|
|
2748
|
+
const removeGrant = grants.removeIfUnchanged.bind(grants);
|
|
2749
|
+
for (const entry of expiredApprovals)
|
|
2750
|
+
await removeApproval(entry.id, entry.version);
|
|
2751
|
+
for (const entry of expiredGrants)
|
|
2752
|
+
await removeGrant(entry.id, entry.version);
|
|
2753
|
+
}
|
|
2674
2754
|
function getRunner() {
|
|
2675
2755
|
if (closed)
|
|
2676
2756
|
throw new ACPFailure("closed");
|
|
@@ -2955,7 +3035,8 @@ function createACPPlatform(deps) {
|
|
|
2955
3035
|
connection,
|
|
2956
3036
|
sessions: /* @__PURE__ */ new Map(),
|
|
2957
3037
|
busy: /* @__PURE__ */ new Set(),
|
|
2958
|
-
|
|
3038
|
+
toolBindings: /* @__PURE__ */ new Map(),
|
|
3039
|
+
signal: context.signal,
|
|
2959
3040
|
nativeIds: /* @__PURE__ */ new Map(),
|
|
2960
3041
|
approvals: pendingApprovals,
|
|
2961
3042
|
lastUse: performance.now(),
|
|
@@ -2989,48 +3070,73 @@ function createACPPlatform(deps) {
|
|
|
2989
3070
|
await connection.close();
|
|
2990
3071
|
} finally {
|
|
2991
3072
|
await Promise.allSettled([
|
|
2992
|
-
...worker.
|
|
2993
|
-
].map(async (
|
|
3073
|
+
...worker.toolBindings.values()
|
|
3074
|
+
].map(async (binding) => binding.revoke()));
|
|
2994
3075
|
}
|
|
2995
3076
|
}
|
|
2996
3077
|
}
|
|
2997
|
-
async function decidePermission(binding, sessionId, context, request2,
|
|
3078
|
+
async function decidePermission(binding, sessionId, context, request2, planned) {
|
|
2998
3079
|
const denied = {
|
|
2999
3080
|
outcome: { outcome: "cancelled" }
|
|
3000
3081
|
};
|
|
3001
3082
|
const option = request2.options.find((option2) => option2.kind === "allow_once");
|
|
3002
3083
|
if (!option || context.signal.aborted || binding.mode === "shared" || !policy?.resolvePermission)
|
|
3003
3084
|
return denied;
|
|
3085
|
+
const rawInput = canonicalToolInput(request2.toolCall.rawInput);
|
|
3086
|
+
if (!rawInput || !request2.toolCall.kind)
|
|
3087
|
+
return denied;
|
|
3004
3088
|
const authorized = await policy.resolvePermission(binding.scope, sessionId, request2.toolCall);
|
|
3005
3089
|
if (!authorized || !authorized.key || Buffer.byteLength(authorized.summary) > 2048)
|
|
3006
3090
|
return denied;
|
|
3007
3091
|
const once = {
|
|
3008
3092
|
outcome: { outcome: "selected", optionId: option.optionId }
|
|
3009
3093
|
};
|
|
3094
|
+
const { agent, effective, models, nativeOptions } = planned;
|
|
3095
|
+
const { approval, ruleIds } = effective.permissions;
|
|
3010
3096
|
const target = hash(JSON.stringify([
|
|
3011
3097
|
binding.scope,
|
|
3012
|
-
|
|
3013
|
-
|
|
3098
|
+
agent.id,
|
|
3099
|
+
agent.adapter,
|
|
3100
|
+
effective.resolvedMode,
|
|
3101
|
+
effective.environmentId,
|
|
3102
|
+
effective.image,
|
|
3103
|
+
effective.workspaceId,
|
|
3104
|
+
effective.permissions.profile,
|
|
3105
|
+
agent.command,
|
|
3106
|
+
agent.args,
|
|
3107
|
+
models,
|
|
3108
|
+
nativeOptions,
|
|
3109
|
+
resolveEnvironment(agent.environmentRefs),
|
|
3014
3110
|
authorized.key,
|
|
3015
3111
|
request2.toolCall.kind,
|
|
3016
|
-
request2.toolCall.
|
|
3112
|
+
request2.toolCall.name ?? request2.toolCall.title,
|
|
3113
|
+
rawInput
|
|
3017
3114
|
]));
|
|
3018
3115
|
const sessionGrant = hash(JSON.stringify([sessionId, target]));
|
|
3019
3116
|
const now = await approvals.currentTime();
|
|
3020
|
-
const
|
|
3117
|
+
const scopeKey = hash(JSON.stringify(binding.scope));
|
|
3021
3118
|
const matching = await Promise.all([
|
|
3022
3119
|
grants.get(sessionGrant),
|
|
3023
|
-
|
|
3120
|
+
ruleIds === void 0 || ruleIds.includes(target) ? grants.get(target) : void 0
|
|
3024
3121
|
]);
|
|
3025
|
-
|
|
3122
|
+
const reusable = matching.filter((grant) => !!grant && grant.scopeKey === scopeKey && !grant.revoked && grant.expires > now);
|
|
3123
|
+
if (reusable.length) {
|
|
3026
3124
|
const fresh = await policy.resolvePermission(binding.scope, sessionId, request2.toolCall);
|
|
3027
|
-
|
|
3125
|
+
if (fresh?.key !== authorized.key || context.signal.aborted)
|
|
3126
|
+
return denied;
|
|
3127
|
+
const confirmed = await Promise.all(reusable.map((grant) => grants.get(grant.id)));
|
|
3128
|
+
const checkedAt = await approvals.currentTime();
|
|
3129
|
+
return !context.signal.aborted && confirmed.some((grant) => grant && grant.scopeKey === scopeKey && !grant.revoked && grant.expires > checkedAt) ? once : denied;
|
|
3028
3130
|
}
|
|
3029
3131
|
if (approval === "never")
|
|
3030
3132
|
return denied;
|
|
3031
3133
|
const approvalId = randomUUID();
|
|
3032
|
-
const deadline = now +
|
|
3033
|
-
await approvals.save(approvalId, {
|
|
3134
|
+
const deadline = now + effective.limits.approvalTimeoutMs;
|
|
3135
|
+
await approvals.save(approvalId, {
|
|
3136
|
+
scope: binding.scope,
|
|
3137
|
+
sessionId,
|
|
3138
|
+
deadline
|
|
3139
|
+
});
|
|
3034
3140
|
try {
|
|
3035
3141
|
unwrap(await context.emit({
|
|
3036
3142
|
type: "approval",
|
|
@@ -3048,7 +3154,6 @@ function createACPPlatform(deps) {
|
|
|
3048
3154
|
if (fresh?.key !== authorized.key || context.signal.aborted || await approvals.currentTime() >= deadline)
|
|
3049
3155
|
return denied;
|
|
3050
3156
|
const summary = authorized.summary;
|
|
3051
|
-
const scopeKey = hash(JSON.stringify(binding.scope));
|
|
3052
3157
|
if (current.decision === "allow-session") {
|
|
3053
3158
|
await grants.save(sessionGrant, {
|
|
3054
3159
|
id: sessionGrant,
|
|
@@ -3093,14 +3198,9 @@ function createACPPlatform(deps) {
|
|
|
3093
3198
|
if (command.op === "prompt" && command.singleTurn === true) {
|
|
3094
3199
|
const current = await bindings.readVersioned(id3);
|
|
3095
3200
|
if (current?.data.singleTurn && current.data.workerId === context.parentId && !current.data.closed) {
|
|
3096
|
-
const channel = worker.sessions.get(id3);
|
|
3097
3201
|
try {
|
|
3098
|
-
await
|
|
3099
|
-
await worker.revoke.get(id3)?.();
|
|
3202
|
+
await closeNativeSession(worker, id3);
|
|
3100
3203
|
} finally {
|
|
3101
|
-
worker.sessions.delete(id3);
|
|
3102
|
-
worker.revoke.delete(id3);
|
|
3103
|
-
worker.nativeIds.delete(id3);
|
|
3104
3204
|
if (current.data.mode !== "task") {
|
|
3105
3205
|
await bindings.compareAndSwap(id3, {
|
|
3106
3206
|
expectedVersion: current.version,
|
|
@@ -3114,6 +3214,21 @@ function createACPPlatform(deps) {
|
|
|
3114
3214
|
worker.busy.delete(id3);
|
|
3115
3215
|
}
|
|
3116
3216
|
}
|
|
3217
|
+
async function revokeTools(worker, id3, forget = true) {
|
|
3218
|
+
const tools = worker.toolBindings.get(id3);
|
|
3219
|
+
if (tools && forget)
|
|
3220
|
+
worker.toolBindings.delete(id3);
|
|
3221
|
+
await tools?.revoke();
|
|
3222
|
+
}
|
|
3223
|
+
async function closeNativeSession(worker, id3) {
|
|
3224
|
+
try {
|
|
3225
|
+
await worker.sessions.get(id3)?.closeSession();
|
|
3226
|
+
} finally {
|
|
3227
|
+
worker.sessions.delete(id3);
|
|
3228
|
+
worker.nativeIds.delete(id3);
|
|
3229
|
+
await revokeTools(worker, id3);
|
|
3230
|
+
}
|
|
3231
|
+
}
|
|
3117
3232
|
async function executeControl(worker, id3, command, context) {
|
|
3118
3233
|
const versioned = await bindings.readVersioned(id3);
|
|
3119
3234
|
const binding = versioned?.data;
|
|
@@ -3123,25 +3238,18 @@ function createACPPlatform(deps) {
|
|
|
3123
3238
|
return command.op === "close" ? null : { error: "closed" };
|
|
3124
3239
|
}
|
|
3125
3240
|
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);
|
|
3241
|
+
if (command.op === "close" || worker.toolBindings.get(id3)?.signal.aborted) {
|
|
3242
|
+
await closeNativeSession(worker, id3);
|
|
3134
3243
|
if (!await bindings.compareAndSwap(id3, {
|
|
3135
3244
|
expectedVersion: versioned?.version,
|
|
3136
3245
|
data: { ...binding, historySummary: void 0, closed: true }
|
|
3137
3246
|
})) {
|
|
3138
3247
|
throw new ACPFailure("conflict");
|
|
3139
3248
|
}
|
|
3140
|
-
return null;
|
|
3249
|
+
return command.op === "close" ? null : { error: "closed" };
|
|
3141
3250
|
}
|
|
3142
3251
|
const resolved = await plan(binding.scope, binding.request).catch(async (error) => {
|
|
3143
|
-
await worker
|
|
3144
|
-
worker.revoke.delete(id3);
|
|
3252
|
+
await revokeTools(worker, id3, false);
|
|
3145
3253
|
throw error;
|
|
3146
3254
|
});
|
|
3147
3255
|
const { effective: base, toolIds, context: authorizedContext } = resolved;
|
|
@@ -3151,16 +3259,20 @@ function createACPPlatform(deps) {
|
|
|
3151
3259
|
execution: { ...binding.request.execution, mode: base.resolvedMode, environmentId: base.environmentId }
|
|
3152
3260
|
});
|
|
3153
3261
|
if (worker.snapshot !== launchSnapshot(normalized)) {
|
|
3154
|
-
await worker
|
|
3155
|
-
worker.revoke.delete(id3);
|
|
3262
|
+
await revokeTools(worker, id3, false);
|
|
3156
3263
|
throw new ACPFailure("conflict");
|
|
3157
3264
|
}
|
|
3158
3265
|
if (!channel) {
|
|
3159
3266
|
if (worker.sessions.size >= 64)
|
|
3160
3267
|
throw new ACPFailure("busy");
|
|
3161
3268
|
channel = worker.connection.channel();
|
|
3162
|
-
const tools = toolIds.length && policy?.bindTools ? await policy.bindTools(binding.scope, id3, toolIds,
|
|
3269
|
+
const tools = toolIds.length && policy?.bindTools ? await policy.bindTools(binding.scope, id3, toolIds, worker.signal) : void 0;
|
|
3163
3270
|
try {
|
|
3271
|
+
context.signal.throwIfAborted();
|
|
3272
|
+
if (tools?.signal?.aborted) {
|
|
3273
|
+
await tools.revoke();
|
|
3274
|
+
return { error: "closed" };
|
|
3275
|
+
}
|
|
3164
3276
|
if (tools && (!tools.servers.length || tools.servers.some((server) => !("type" in server) || server.type !== "http")))
|
|
3165
3277
|
throw new ACPFailure("unsupported", { parameter: "tools.allow" });
|
|
3166
3278
|
const native = await channel.createSession("/workspace", tools?.servers);
|
|
@@ -3169,8 +3281,18 @@ function createACPPlatform(deps) {
|
|
|
3169
3281
|
await tools?.revoke();
|
|
3170
3282
|
throw error;
|
|
3171
3283
|
}
|
|
3172
|
-
if (tools)
|
|
3173
|
-
|
|
3284
|
+
if (tools) {
|
|
3285
|
+
const local = new AbortController();
|
|
3286
|
+
worker.toolBindings.set(id3, {
|
|
3287
|
+
signal: tools.signal ? AbortSignal.any([local.signal, tools.signal]) : local.signal,
|
|
3288
|
+
revoke: async () => {
|
|
3289
|
+
if (!local.signal.aborted) {
|
|
3290
|
+
local.abort();
|
|
3291
|
+
await tools.revoke();
|
|
3292
|
+
}
|
|
3293
|
+
}
|
|
3294
|
+
});
|
|
3295
|
+
}
|
|
3174
3296
|
worker.sessions.set(id3, channel);
|
|
3175
3297
|
}
|
|
3176
3298
|
if (command.op === "open")
|
|
@@ -3200,7 +3322,28 @@ function createACPPlatform(deps) {
|
|
|
3200
3322
|
const chunks = [];
|
|
3201
3323
|
let bytes = 0;
|
|
3202
3324
|
let exceeded = false;
|
|
3325
|
+
const pendingTools = /* @__PURE__ */ new Map();
|
|
3203
3326
|
const started = channel.subscribe((event) => {
|
|
3327
|
+
const update = event.update;
|
|
3328
|
+
if (update.sessionUpdate === "tool_call" || update.sessionUpdate === "tool_call_update") {
|
|
3329
|
+
const previous = pendingTools.get(update.toolCallId);
|
|
3330
|
+
if (update.status === "completed" || update.status === "failed") {
|
|
3331
|
+
pendingTools.delete(update.toolCallId);
|
|
3332
|
+
} else if ((previous || update.sessionUpdate === "tool_call") && (previous || pendingTools.size < maxPermissionCalls)) {
|
|
3333
|
+
const raw = update.rawInput ?? previous?.rawInput;
|
|
3334
|
+
if (canonicalToolInput(raw)) {
|
|
3335
|
+
pendingTools.set(update.toolCallId, {
|
|
3336
|
+
toolCallId: update.toolCallId,
|
|
3337
|
+
title: update.title ?? previous?.title,
|
|
3338
|
+
kind: update.kind ?? previous?.kind,
|
|
3339
|
+
name: update.name ?? previous?.name,
|
|
3340
|
+
rawInput: raw
|
|
3341
|
+
});
|
|
3342
|
+
} else {
|
|
3343
|
+
pendingTools.delete(update.toolCallId);
|
|
3344
|
+
}
|
|
3345
|
+
}
|
|
3346
|
+
}
|
|
3204
3347
|
if (event.update.sessionUpdate === "agent_message_chunk" && event.update.content.type === "text") {
|
|
3205
3348
|
bytes += Buffer.byteLength(event.update.content.text);
|
|
3206
3349
|
exceeded ||= bytes > effective.limits.maxOutputBytes;
|
|
@@ -3221,7 +3364,26 @@ function createACPPlatform(deps) {
|
|
|
3221
3364
|
}
|
|
3222
3365
|
const timer = setInterval(flush, 50);
|
|
3223
3366
|
const nativeId = worker.nativeIds.get(id3);
|
|
3224
|
-
worker.
|
|
3367
|
+
const toolSignal = worker.toolBindings.get(id3)?.signal;
|
|
3368
|
+
const turnSignal = toolSignal ? AbortSignal.any([context.signal, toolSignal]) : context.signal;
|
|
3369
|
+
const permissionContext = { ...context, signal: turnSignal };
|
|
3370
|
+
worker.approvals.set(nativeId, (request2) => {
|
|
3371
|
+
const fromEvent = pendingTools.get(request2.toolCall.toolCallId);
|
|
3372
|
+
const explicit = request2.toolCall;
|
|
3373
|
+
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))) {
|
|
3374
|
+
return Promise.resolve({
|
|
3375
|
+
outcome: { outcome: "cancelled" }
|
|
3376
|
+
});
|
|
3377
|
+
}
|
|
3378
|
+
const toolCall = {
|
|
3379
|
+
...explicit,
|
|
3380
|
+
kind: explicit.kind ?? fromEvent?.kind,
|
|
3381
|
+
name: explicit.name ?? fromEvent?.name,
|
|
3382
|
+
title: explicit.title ?? fromEvent?.title,
|
|
3383
|
+
rawInput: explicit.rawInput ?? fromEvent?.rawInput
|
|
3384
|
+
};
|
|
3385
|
+
return decidePermission(binding, id3, permissionContext, { ...request2, toolCall }, { ...resolved, effective });
|
|
3386
|
+
});
|
|
3225
3387
|
try {
|
|
3226
3388
|
const response = await channel.prompt([
|
|
3227
3389
|
...supplement,
|
|
@@ -3229,7 +3391,9 @@ function createACPPlatform(deps) {
|
|
|
3229
3391
|
...workspace,
|
|
3230
3392
|
...history,
|
|
3231
3393
|
...prompt
|
|
3232
|
-
],
|
|
3394
|
+
], turnSignal);
|
|
3395
|
+
if (toolSignal?.aborted)
|
|
3396
|
+
return { error: "closed" };
|
|
3233
3397
|
flush();
|
|
3234
3398
|
await writes;
|
|
3235
3399
|
if (exceeded)
|
|
@@ -3257,6 +3421,10 @@ function createACPPlatform(deps) {
|
|
|
3257
3421
|
stopReason: response.stopReason,
|
|
3258
3422
|
...parsed !== void 0 && { json: parsed }
|
|
3259
3423
|
});
|
|
3424
|
+
} catch (error) {
|
|
3425
|
+
if (toolSignal?.aborted)
|
|
3426
|
+
return { error: "closed" };
|
|
3427
|
+
throw error;
|
|
3260
3428
|
} finally {
|
|
3261
3429
|
clearInterval(timer);
|
|
3262
3430
|
worker.approvals.delete(nativeId);
|
|
@@ -3549,10 +3717,12 @@ function createACPPlatform(deps) {
|
|
|
3549
3717
|
const entries = await grants.queryPage({
|
|
3550
3718
|
where: {
|
|
3551
3719
|
scopeKey: hash(JSON.stringify(scope())),
|
|
3552
|
-
expires: { $gt: await grants.currentTime() }
|
|
3553
|
-
|
|
3720
|
+
expires: { $gt: await grants.currentTime() },
|
|
3721
|
+
revoked: { $ne: true }
|
|
3722
|
+
},
|
|
3723
|
+
orderBy: { field: "id", direction: "asc" }
|
|
3554
3724
|
}, { offset, limit });
|
|
3555
|
-
return entries.items.
|
|
3725
|
+
return entries.items.map((entry) => ({
|
|
3556
3726
|
id: entry.id,
|
|
3557
3727
|
summary: entry.summary,
|
|
3558
3728
|
sessionId: entry.sessionId,
|
|
@@ -3640,9 +3810,14 @@ function createACPPlatform(deps) {
|
|
|
3640
3810
|
expectedVersion: void 0,
|
|
3641
3811
|
data: { fingerprint }
|
|
3642
3812
|
});
|
|
3643
|
-
if (!claimed && (await intents.get(id3))?.fingerprint !== fingerprint)
|
|
3644
|
-
throw new ACPFailure("conflict");
|
|
3645
3813
|
const saved = await bindings.get(id3);
|
|
3814
|
+
if (!claimed) {
|
|
3815
|
+
const intent = await intents.readVersioned(id3);
|
|
3816
|
+
if (intent?.data.fingerprint !== fingerprint)
|
|
3817
|
+
throw new ACPFailure("conflict");
|
|
3818
|
+
if (!saved && !await intents.compareAndSwap(id3, { expectedVersion: intent.version, data: intent.data }))
|
|
3819
|
+
throw new ACPFailure("conflict");
|
|
3820
|
+
}
|
|
3646
3821
|
if (saved) {
|
|
3647
3822
|
const existing = unwrap(await getRunner().find(saved.workerScope, controlKind, `run:${id3}`));
|
|
3648
3823
|
if (existing) {
|
|
@@ -3652,6 +3827,8 @@ function createACPPlatform(deps) {
|
|
|
3652
3827
|
await stop(saved, id3);
|
|
3653
3828
|
return { taskId: existing.id, output, effectiveOptions: (await plan(subject, saved.request)).effective };
|
|
3654
3829
|
}
|
|
3830
|
+
if (saved.closed)
|
|
3831
|
+
throw new ACPFailure("missing");
|
|
3655
3832
|
}
|
|
3656
3833
|
}
|
|
3657
3834
|
const opened = await open(request2, id3, void 0, true);
|
|
@@ -3679,6 +3856,21 @@ function createACPPlatform(deps) {
|
|
|
3679
3856
|
});
|
|
3680
3857
|
})));
|
|
3681
3858
|
unregister.push(unwrap(runner.register(controlKind, control)));
|
|
3859
|
+
if (runner.isExecutor) {
|
|
3860
|
+
const maintainPersistence = createACPMaintenance(runner, { bindings, intents, receipts });
|
|
3861
|
+
maintenanceTimer = setInterval(() => {
|
|
3862
|
+
maintenancePending ??= Promise.allSettled([
|
|
3863
|
+
maintainApprovals(),
|
|
3864
|
+
maintainPersistence()
|
|
3865
|
+
]).then((results) => {
|
|
3866
|
+
if (results.some((result) => result.status === "rejected"))
|
|
3867
|
+
logger3.warn("ACP persistence maintenance failed");
|
|
3868
|
+
}).finally(() => {
|
|
3869
|
+
maintenancePending = void 0;
|
|
3870
|
+
});
|
|
3871
|
+
}, maintenanceIntervalMs);
|
|
3872
|
+
maintenanceTimer.unref();
|
|
3873
|
+
}
|
|
3682
3874
|
} catch (error) {
|
|
3683
3875
|
for (const remove of unregister.splice(0)) remove();
|
|
3684
3876
|
throw error;
|
|
@@ -3686,6 +3878,8 @@ function createACPPlatform(deps) {
|
|
|
3686
3878
|
}
|
|
3687
3879
|
async function close() {
|
|
3688
3880
|
closed = true;
|
|
3881
|
+
clearInterval(maintenanceTimer);
|
|
3882
|
+
await maintenancePending;
|
|
3689
3883
|
for (const remove of unregister.splice(0)) remove();
|
|
3690
3884
|
const results = await Promise.allSettled([...owned].map(async ([id3, scope]) => {
|
|
3691
3885
|
if (runner)
|
|
@@ -5411,7 +5605,7 @@ async function describeHttpError(response) {
|
|
|
5411
5605
|
const text = await response.text().catch(() => "");
|
|
5412
5606
|
return `HTTP ${response.status} ${text.slice(0, 200)}`.trim();
|
|
5413
5607
|
}
|
|
5414
|
-
var
|
|
5608
|
+
var logger4 = core.logger.child({ module: "ai", scope: "audio-ws" });
|
|
5415
5609
|
function openAudioWebSocket(url, headers, options) {
|
|
5416
5610
|
return new Promise((resolve3, reject) => {
|
|
5417
5611
|
const ws = new WebSocket2(url, { headers, handshakeTimeout: options?.timeout ?? 15e3 });
|
|
@@ -5471,7 +5665,7 @@ function openAudioWebSocket(url, headers, options) {
|
|
|
5471
5665
|
return;
|
|
5472
5666
|
}
|
|
5473
5667
|
failure = error;
|
|
5474
|
-
|
|
5668
|
+
logger4.debug("Audio WebSocket error", { error: error.message });
|
|
5475
5669
|
settleClosed();
|
|
5476
5670
|
});
|
|
5477
5671
|
ws.on("close", () => {
|
|
@@ -5534,7 +5728,7 @@ function openAudioWebSocket(url, headers, options) {
|
|
|
5534
5728
|
}
|
|
5535
5729
|
|
|
5536
5730
|
// src/audio/providers/ai-audio-provider-doubao.ts
|
|
5537
|
-
var
|
|
5731
|
+
var logger5 = core.logger.child({ module: "ai", scope: "audio-doubao" });
|
|
5538
5732
|
var DOUBAO_CAPABILITIES = {
|
|
5539
5733
|
transcribe: {
|
|
5540
5734
|
supported: true,
|
|
@@ -5718,7 +5912,7 @@ function createDoubaoAudioProvider() {
|
|
|
5718
5912
|
}
|
|
5719
5913
|
return ok({ text: finalText });
|
|
5720
5914
|
} catch (error) {
|
|
5721
|
-
|
|
5915
|
+
logger5.debug("Doubao transcribe failed", {
|
|
5722
5916
|
error: errorMessage(error)
|
|
5723
5917
|
});
|
|
5724
5918
|
return toAudioErrorResult(error);
|
|
@@ -5817,7 +6011,7 @@ function createDoubaoAudioProvider() {
|
|
|
5817
6011
|
channels: out.channels
|
|
5818
6012
|
});
|
|
5819
6013
|
} catch (error) {
|
|
5820
|
-
|
|
6014
|
+
logger5.debug("Doubao synthesize failed", {
|
|
5821
6015
|
error: errorMessage(error)
|
|
5822
6016
|
});
|
|
5823
6017
|
return toAudioErrorResult(error);
|
|
@@ -5907,7 +6101,7 @@ function decodeBinaryMessage(message) {
|
|
|
5907
6101
|
return void 0;
|
|
5908
6102
|
return decodeFrame(message.binary);
|
|
5909
6103
|
}
|
|
5910
|
-
var
|
|
6104
|
+
var logger6 = core.logger.child({ module: "ai", scope: "audio-indextts" });
|
|
5911
6105
|
var INDEX_TTS_CAPABILITIES = {
|
|
5912
6106
|
synthesize: {
|
|
5913
6107
|
supported: true,
|
|
@@ -5987,7 +6181,7 @@ function createIndexTtsAudioProvider() {
|
|
|
5987
6181
|
await dispatcher.close();
|
|
5988
6182
|
}
|
|
5989
6183
|
} catch (error) {
|
|
5990
|
-
|
|
6184
|
+
logger6.debug("IndexTTS synthesize failed", {
|
|
5991
6185
|
error: errorMessage(error)
|
|
5992
6186
|
});
|
|
5993
6187
|
return toAudioErrorResult(error, requestSignal);
|
|
@@ -6266,7 +6460,7 @@ function encodeSSE(event) {
|
|
|
6266
6460
|
}
|
|
6267
6461
|
|
|
6268
6462
|
// src/audio/providers/ai-audio-provider-mimo.ts
|
|
6269
|
-
var
|
|
6463
|
+
var logger7 = core.logger.child({ module: "ai", scope: "audio-mimo" });
|
|
6270
6464
|
var MIMO_CAPABILITIES = {
|
|
6271
6465
|
transcribe: {
|
|
6272
6466
|
supported: true,
|
|
@@ -6315,7 +6509,7 @@ function createMimoAudioProvider() {
|
|
|
6315
6509
|
const text = body.choices?.[0]?.message?.content ?? "";
|
|
6316
6510
|
return ok({ text });
|
|
6317
6511
|
} catch (error) {
|
|
6318
|
-
|
|
6512
|
+
logger7.debug("MiMo transcribe failed", {
|
|
6319
6513
|
error: errorMessage(error)
|
|
6320
6514
|
});
|
|
6321
6515
|
return toAudioErrorResult(error, requestSignal);
|
|
@@ -6399,7 +6593,7 @@ function createMimoAudioProvider() {
|
|
|
6399
6593
|
channels: out.channels
|
|
6400
6594
|
});
|
|
6401
6595
|
} catch (error) {
|
|
6402
|
-
|
|
6596
|
+
logger7.debug("MiMo synthesize failed", {
|
|
6403
6597
|
error: errorMessage(error)
|
|
6404
6598
|
});
|
|
6405
6599
|
return toAudioErrorResult(error, requestSignal);
|
|
@@ -6482,7 +6676,7 @@ async function* readChunks(response, signal) {
|
|
|
6482
6676
|
yield chunk;
|
|
6483
6677
|
}
|
|
6484
6678
|
}
|
|
6485
|
-
var
|
|
6679
|
+
var logger8 = core.logger.child({ module: "ai", scope: "audio-openai" });
|
|
6486
6680
|
var OPENAI_CAPABILITIES = {
|
|
6487
6681
|
transcribe: {
|
|
6488
6682
|
supported: true,
|
|
@@ -6522,7 +6716,7 @@ function createOpenAIAudioProvider() {
|
|
|
6522
6716
|
}, { signal });
|
|
6523
6717
|
return ok({ text: result.text });
|
|
6524
6718
|
} catch (error) {
|
|
6525
|
-
|
|
6719
|
+
logger8.debug("OpenAI transcribe failed", {
|
|
6526
6720
|
error: errorMessage(error)
|
|
6527
6721
|
});
|
|
6528
6722
|
return toAudioErrorResult(error, signal);
|
|
@@ -6589,7 +6783,7 @@ function createOpenAIAudioProvider() {
|
|
|
6589
6783
|
channels: out.channels
|
|
6590
6784
|
});
|
|
6591
6785
|
} catch (error) {
|
|
6592
|
-
|
|
6786
|
+
logger8.debug("OpenAI synthesize failed", {
|
|
6593
6787
|
error: errorMessage(error)
|
|
6594
6788
|
});
|
|
6595
6789
|
return toAudioErrorResult(error, signal);
|
|
@@ -6652,7 +6846,7 @@ async function toUploadFile(audio) {
|
|
|
6652
6846
|
const part = toAudioUploadPart(audio);
|
|
6653
6847
|
return toFile(Buffer.from(part.data), part.filename);
|
|
6654
6848
|
}
|
|
6655
|
-
var
|
|
6849
|
+
var logger9 = core.logger.child({ module: "ai", scope: "audio-qwen" });
|
|
6656
6850
|
var QWEN_CAPABILITIES = {
|
|
6657
6851
|
transcribe: {
|
|
6658
6852
|
supported: true,
|
|
@@ -6697,7 +6891,7 @@ function createQwenAudioProvider() {
|
|
|
6697
6891
|
}
|
|
6698
6892
|
return ok({ text: finalText });
|
|
6699
6893
|
} catch (error) {
|
|
6700
|
-
|
|
6894
|
+
logger9.debug("Qwen transcribe failed", {
|
|
6701
6895
|
error: errorMessage(error)
|
|
6702
6896
|
});
|
|
6703
6897
|
return toAudioErrorResult(error);
|
|
@@ -6806,7 +7000,7 @@ function createQwenAudioProvider() {
|
|
|
6806
7000
|
channels: out.channels
|
|
6807
7001
|
});
|
|
6808
7002
|
} catch (error) {
|
|
6809
|
-
|
|
7003
|
+
logger9.debug("Qwen synthesize failed", {
|
|
6810
7004
|
error: errorMessage(error)
|
|
6811
7005
|
});
|
|
6812
7006
|
return toAudioErrorResult(error);
|
|
@@ -6900,7 +7094,7 @@ function parseEvent(text) {
|
|
|
6900
7094
|
return {};
|
|
6901
7095
|
}
|
|
6902
7096
|
}
|
|
6903
|
-
var
|
|
7097
|
+
var logger10 = core.logger.child({ module: "ai", scope: "audio-whisper" });
|
|
6904
7098
|
var WHISPER_CAPABILITIES = {
|
|
6905
7099
|
transcribe: {
|
|
6906
7100
|
supported: true,
|
|
@@ -6949,7 +7143,7 @@ function createWhisperAudioProvider() {
|
|
|
6949
7143
|
const body = await response.json();
|
|
6950
7144
|
return ok(mapWhisperResponse(body));
|
|
6951
7145
|
} catch (error) {
|
|
6952
|
-
|
|
7146
|
+
logger10.debug("Whisper transcribe failed", {
|
|
6953
7147
|
error: errorMessage(error)
|
|
6954
7148
|
});
|
|
6955
7149
|
return toAudioErrorResult(error, signal);
|
|
@@ -6995,7 +7189,7 @@ function mapWhisperWord(word) {
|
|
|
6995
7189
|
}
|
|
6996
7190
|
|
|
6997
7191
|
// src/audio/ai-audio-functions.ts
|
|
6998
|
-
var
|
|
7192
|
+
var logger11 = core.logger.child({ module: "ai", scope: "audio" });
|
|
6999
7193
|
function createAudioOperations(config) {
|
|
7000
7194
|
const audioConfig = AudioConfigSchema.parse(config.audio ?? {});
|
|
7001
7195
|
const providerCache = /* @__PURE__ */ new Map();
|
|
@@ -7061,7 +7255,7 @@ function createAudioOperations(config) {
|
|
|
7061
7255
|
}
|
|
7062
7256
|
const startedAt = Date.now();
|
|
7063
7257
|
const context = { provider: resolved.data.provider, model: resolved.data.model, audioBytes: request2.audio.data.length };
|
|
7064
|
-
|
|
7258
|
+
logger11.debug("Audio transcription started", context);
|
|
7065
7259
|
const result = await transcription.transcribe({
|
|
7066
7260
|
model: resolved.data,
|
|
7067
7261
|
audio: request2.audio,
|
|
@@ -7072,9 +7266,9 @@ function createAudioOperations(config) {
|
|
|
7072
7266
|
signal: request2.signal
|
|
7073
7267
|
});
|
|
7074
7268
|
if (result.success) {
|
|
7075
|
-
|
|
7269
|
+
logger11.info("Audio transcription completed", { ...context, durationMs: Date.now() - startedAt, textLength: result.data.text.length });
|
|
7076
7270
|
} else {
|
|
7077
|
-
|
|
7271
|
+
logger11.warn("Audio transcription failed", {
|
|
7078
7272
|
...context,
|
|
7079
7273
|
durationMs: Date.now() - startedAt,
|
|
7080
7274
|
code: result.error.code,
|
|
@@ -7114,7 +7308,7 @@ function createAudioOperations(config) {
|
|
|
7114
7308
|
}
|
|
7115
7309
|
const startedAt = Date.now();
|
|
7116
7310
|
const context = { provider: resolved.data.provider, model: resolved.data.model };
|
|
7117
|
-
|
|
7311
|
+
logger11.debug("Audio transcription stream started", context);
|
|
7118
7312
|
const signal = withStreamTimeout(request2.signal);
|
|
7119
7313
|
try {
|
|
7120
7314
|
yield* transcribeStreamOrFallback(transcription, {
|
|
@@ -7126,9 +7320,9 @@ function createAudioOperations(config) {
|
|
|
7126
7320
|
vad: request2.vad,
|
|
7127
7321
|
signal
|
|
7128
7322
|
});
|
|
7129
|
-
|
|
7323
|
+
logger11.info("Audio transcription stream completed", { ...context, durationMs: Date.now() - startedAt });
|
|
7130
7324
|
} catch (error) {
|
|
7131
|
-
|
|
7325
|
+
logger11.warn("Audio transcription stream failed", { ...context, durationMs: Date.now() - startedAt, error });
|
|
7132
7326
|
throw mapStreamError(error, signal);
|
|
7133
7327
|
}
|
|
7134
7328
|
}
|
|
@@ -7169,7 +7363,7 @@ function createAudioOperations(config) {
|
|
|
7169
7363
|
textLength: request2.text.length,
|
|
7170
7364
|
voice: request2.voice
|
|
7171
7365
|
};
|
|
7172
|
-
|
|
7366
|
+
logger11.debug("Audio synthesis started", context);
|
|
7173
7367
|
const result = await synthesis.synthesize({
|
|
7174
7368
|
model: resolved.data,
|
|
7175
7369
|
text: request2.text,
|
|
@@ -7187,14 +7381,14 @@ function createAudioOperations(config) {
|
|
|
7187
7381
|
signal: request2.signal
|
|
7188
7382
|
});
|
|
7189
7383
|
if (result.success) {
|
|
7190
|
-
|
|
7384
|
+
logger11.info("Audio synthesis completed", {
|
|
7191
7385
|
...context,
|
|
7192
7386
|
durationMs: Date.now() - startedAt,
|
|
7193
7387
|
audioBytes: result.data.data.length,
|
|
7194
7388
|
format: result.data.format
|
|
7195
7389
|
});
|
|
7196
7390
|
} else {
|
|
7197
|
-
|
|
7391
|
+
logger11.warn("Audio synthesis failed", {
|
|
7198
7392
|
...context,
|
|
7199
7393
|
durationMs: Date.now() - startedAt,
|
|
7200
7394
|
code: result.error.code,
|
|
@@ -7230,7 +7424,7 @@ function createAudioOperations(config) {
|
|
|
7230
7424
|
}
|
|
7231
7425
|
const startedAt = Date.now();
|
|
7232
7426
|
const context = { provider: resolved.data.provider, model: resolved.data.model, voice: request2.voice };
|
|
7233
|
-
|
|
7427
|
+
logger11.debug("Audio synthesis stream started", context);
|
|
7234
7428
|
const signal = withStreamTimeout(request2.signal);
|
|
7235
7429
|
const output = synthesis.resolveSynthesisOutput({ format: request2.format, sampleRate: request2.sampleRate });
|
|
7236
7430
|
try {
|
|
@@ -7266,9 +7460,9 @@ function createAudioOperations(config) {
|
|
|
7266
7460
|
yield { type: "audio", segmentId: segment.id, data };
|
|
7267
7461
|
yield { type: "segment_done", segmentId: segment.id };
|
|
7268
7462
|
}
|
|
7269
|
-
|
|
7463
|
+
logger11.info("Audio synthesis stream completed", { ...context, durationMs: Date.now() - startedAt });
|
|
7270
7464
|
} catch (error) {
|
|
7271
|
-
|
|
7465
|
+
logger11.warn("Audio synthesis stream failed", { ...context, durationMs: Date.now() - startedAt, error });
|
|
7272
7466
|
throw mapStreamError(error, signal);
|
|
7273
7467
|
}
|
|
7274
7468
|
}
|
|
@@ -7427,7 +7621,7 @@ function createProvider(name) {
|
|
|
7427
7621
|
return createIndexTtsAudioProvider();
|
|
7428
7622
|
}
|
|
7429
7623
|
}
|
|
7430
|
-
var
|
|
7624
|
+
var logger12 = core.logger.child({ module: "ai", scope: "compress" });
|
|
7431
7625
|
var CONVERSATION_SUMMARY_PREFIX = "[Conversation Summary]";
|
|
7432
7626
|
var CONVERSATION_SUMMARY_NAME = "hai_internal_conversation_summary_v1";
|
|
7433
7627
|
function completeCompression(result, maxTokens) {
|
|
@@ -7574,7 +7768,7 @@ function createCompressOperations(config, token, summary, modelMaxTokens) {
|
|
|
7574
7768
|
const maxTokens = resolveMaxTokens(options?.maxTokens);
|
|
7575
7769
|
const preserveSystem = options?.preserveSystem ?? true;
|
|
7576
7770
|
const preserveLastN = options?.preserveLastN ?? config.preserveLastN;
|
|
7577
|
-
|
|
7771
|
+
logger12.trace("Compressing context", { strategy, maxTokens, messageCount: messages.length });
|
|
7578
7772
|
try {
|
|
7579
7773
|
const originalTokens = token.estimateMessages(messages);
|
|
7580
7774
|
if (originalTokens <= maxTokens) {
|
|
@@ -7593,7 +7787,7 @@ function createCompressOperations(config, token, summary, modelMaxTokens) {
|
|
|
7593
7787
|
preserveLastN
|
|
7594
7788
|
);
|
|
7595
7789
|
const compressedTokens = token.estimateMessages(compressed);
|
|
7596
|
-
|
|
7790
|
+
logger12.trace("Sliding window compression completed", { originalTokens, compressedTokens, removedCount });
|
|
7597
7791
|
return completeCompression({
|
|
7598
7792
|
messages: compressed,
|
|
7599
7793
|
originalTokens,
|
|
@@ -7630,7 +7824,7 @@ ${summaryText}`
|
|
|
7630
7824
|
...preserved
|
|
7631
7825
|
];
|
|
7632
7826
|
const compressedTokens = token.estimateMessages(compressed);
|
|
7633
|
-
|
|
7827
|
+
logger12.trace("Summary compression completed", { originalTokens, compressedTokens, removedCount: toSummarize2.length });
|
|
7634
7828
|
return completeCompression({
|
|
7635
7829
|
messages: compressed,
|
|
7636
7830
|
originalTokens,
|
|
@@ -7675,7 +7869,7 @@ ${summaryText}`
|
|
|
7675
7869
|
...preservedMessages
|
|
7676
7870
|
];
|
|
7677
7871
|
const compressedTokens = token.estimateMessages(compressed);
|
|
7678
|
-
|
|
7872
|
+
logger12.trace("Hybrid compression completed", { originalTokens, compressedTokens, removedCount: toSummarize.length });
|
|
7679
7873
|
return completeCompression({
|
|
7680
7874
|
messages: compressed,
|
|
7681
7875
|
originalTokens,
|
|
@@ -7691,7 +7885,7 @@ ${summaryText}`
|
|
|
7691
7885
|
removedCount: windowRemoved
|
|
7692
7886
|
}, maxTokens);
|
|
7693
7887
|
} catch (error) {
|
|
7694
|
-
|
|
7888
|
+
logger12.error("Context compression failed", { error });
|
|
7695
7889
|
return err(HaiAIError.CONTEXT_COMPRESS_FAILED, aiM("ai_contextCompressFailed", {
|
|
7696
7890
|
params: {
|
|
7697
7891
|
error: String(error)
|
|
@@ -7773,7 +7967,7 @@ function createContextStateAccess(store, scope, initial, receive) {
|
|
|
7773
7967
|
}
|
|
7774
7968
|
|
|
7775
7969
|
// src/context/ai-context-functions.ts
|
|
7776
|
-
var
|
|
7970
|
+
var logger13 = core.logger.child({ module: "ai", scope: "context" });
|
|
7777
7971
|
var GENERATION_LEASE_MS = 3e4;
|
|
7778
7972
|
function contextFailure(error) {
|
|
7779
7973
|
const code = error instanceof ContextStateError ? error.definition : HaiAIError.STORE_FAILED;
|
|
@@ -7868,11 +8062,11 @@ function createContextOperations(compressConfig, tokenOps, compressOps, contextS
|
|
|
7868
8062
|
})).then((result) => {
|
|
7869
8063
|
if (!result.success) {
|
|
7870
8064
|
failedMemoryTasks++;
|
|
7871
|
-
|
|
8065
|
+
logger13.warn("Background memory extraction failed", { source: "result" });
|
|
7872
8066
|
}
|
|
7873
8067
|
}).catch(() => {
|
|
7874
8068
|
failedMemoryTasks++;
|
|
7875
|
-
|
|
8069
|
+
logger13.warn("Background memory extraction failed", { source: "exception" });
|
|
7876
8070
|
}).finally(() => {
|
|
7877
8071
|
pendingMemoryTasks.delete(task);
|
|
7878
8072
|
});
|
|
@@ -8019,7 +8213,7 @@ function createContextOperations(compressConfig, tokenOps, compressOps, contextS
|
|
|
8019
8213
|
} catch (error) {
|
|
8020
8214
|
if (requirePersistence)
|
|
8021
8215
|
throw error;
|
|
8022
|
-
|
|
8216
|
+
logger13.warn("Context producer settlement failed", { error });
|
|
8023
8217
|
}
|
|
8024
8218
|
}
|
|
8025
8219
|
const manager = {
|
|
@@ -8170,7 +8364,7 @@ function createContextOperations(compressConfig, tokenOps, compressOps, contextS
|
|
|
8170
8364
|
return extracted;
|
|
8171
8365
|
return ok({ summary: summaryText, memories: extracted.data });
|
|
8172
8366
|
} catch (error) {
|
|
8173
|
-
|
|
8367
|
+
logger13.error("Context consolidate failed", { error });
|
|
8174
8368
|
return err(HaiAIError.MEMORY_PROMOTE_FAILED, aiM("ai_memoryPromoteFailed", {
|
|
8175
8369
|
params: {
|
|
8176
8370
|
error: String(error)
|
|
@@ -8328,7 +8522,7 @@ function createContextOperations(compressConfig, tokenOps, compressOps, contextS
|
|
|
8328
8522
|
usage: lastUsage
|
|
8329
8523
|
});
|
|
8330
8524
|
} catch (error) {
|
|
8331
|
-
|
|
8525
|
+
logger13.error("Context chat failed", { error });
|
|
8332
8526
|
return contextFailure(error);
|
|
8333
8527
|
} finally {
|
|
8334
8528
|
release();
|
|
@@ -8687,8 +8881,8 @@ function createContextOperations(compressConfig, tokenOps, compressOps, contextS
|
|
|
8687
8881
|
}
|
|
8688
8882
|
};
|
|
8689
8883
|
}
|
|
8690
|
-
var
|
|
8691
|
-
function createEmbeddingOperations(config) {
|
|
8884
|
+
var logger14 = core.logger.child({ module: "ai", scope: "embedding" });
|
|
8885
|
+
function createEmbeddingOperations(config, loadModels = () => config.llm) {
|
|
8692
8886
|
const embeddingConfig = config.embedding ?? { batchSize: 100 };
|
|
8693
8887
|
let cachedClient = null;
|
|
8694
8888
|
let cachedResolvedKey;
|
|
@@ -8703,15 +8897,7 @@ function createEmbeddingOperations(config) {
|
|
|
8703
8897
|
cachedResolvedKey = cacheKey;
|
|
8704
8898
|
return cachedClient;
|
|
8705
8899
|
}
|
|
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;
|
|
8900
|
+
async function callEmbeddingAPI(request2, resolved) {
|
|
8715
8901
|
const input = Array.isArray(request2.input) ? request2.input : [request2.input];
|
|
8716
8902
|
try {
|
|
8717
8903
|
const client2 = getOrCreateClient(resolved);
|
|
@@ -8735,7 +8921,7 @@ function createEmbeddingOperations(config) {
|
|
|
8735
8921
|
}
|
|
8736
8922
|
});
|
|
8737
8923
|
} catch (error) {
|
|
8738
|
-
|
|
8924
|
+
logger14.error("Embedding API call failed", { error });
|
|
8739
8925
|
return err(HaiAIError.EMBEDDING_API_ERROR, aiM("ai_internalError", {
|
|
8740
8926
|
params: {
|
|
8741
8927
|
error: String(error)
|
|
@@ -8744,18 +8930,25 @@ function createEmbeddingOperations(config) {
|
|
|
8744
8930
|
}
|
|
8745
8931
|
}
|
|
8746
8932
|
async function embedRequest(request2) {
|
|
8933
|
+
const resolved = resolveModelEntry(await loadModels(request2.model), "embedding", request2.model, {
|
|
8934
|
+
missingApiKeyMessage: aiM("ai_configError", {
|
|
8935
|
+
params: { error: "API Key is required for embedding" }
|
|
8936
|
+
})
|
|
8937
|
+
});
|
|
8938
|
+
if (!resolved.success)
|
|
8939
|
+
return resolved;
|
|
8747
8940
|
const input = Array.isArray(request2.input) ? request2.input : [request2.input];
|
|
8748
|
-
const
|
|
8749
|
-
if (input.length <=
|
|
8750
|
-
return callEmbeddingAPI(request2);
|
|
8941
|
+
const batchSize2 = embeddingConfig.batchSize;
|
|
8942
|
+
if (input.length <= batchSize2) {
|
|
8943
|
+
return callEmbeddingAPI(request2, resolved.data);
|
|
8751
8944
|
}
|
|
8752
8945
|
const allData = [];
|
|
8753
8946
|
let totalPromptTokens = 0;
|
|
8754
8947
|
let totalTokens = 0;
|
|
8755
8948
|
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 });
|
|
8949
|
+
for (let i = 0; i < input.length; i += batchSize2) {
|
|
8950
|
+
const batch = input.slice(i, i + batchSize2);
|
|
8951
|
+
const result = await callEmbeddingAPI({ ...request2, input: batch }, resolved.data);
|
|
8759
8952
|
if (!result.success)
|
|
8760
8953
|
return result;
|
|
8761
8954
|
resultModel = result.data.model;
|
|
@@ -8934,7 +9127,7 @@ function parseHtmlFile(content, outputFormat) {
|
|
|
8934
9127
|
}
|
|
8935
9128
|
|
|
8936
9129
|
// src/file/ai-file-functions.ts
|
|
8937
|
-
var
|
|
9130
|
+
var logger15 = core.logger.child({ module: "ai", scope: "file" });
|
|
8938
9131
|
var TEXT_MIME_TYPES = /* @__PURE__ */ new Set([
|
|
8939
9132
|
"text/plain",
|
|
8940
9133
|
"text/markdown",
|
|
@@ -9079,7 +9272,7 @@ async function parseImageWithOcr(content, mimeType, llmOps, model, outputFormat
|
|
|
9079
9272
|
const dataUrl = `data:${mimeType};base64,${base64}`;
|
|
9080
9273
|
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
9274
|
const prompt = customPrompt ?? defaultPrompt;
|
|
9082
|
-
|
|
9275
|
+
logger15.trace("Running OCR via vision LLM", { mimeType, model });
|
|
9083
9276
|
const result = await llmOps.chat({
|
|
9084
9277
|
model,
|
|
9085
9278
|
messages: [
|
|
@@ -9134,7 +9327,7 @@ function createFileOperations(config, llmOps) {
|
|
|
9134
9327
|
const { content, filename, options = {} } = request2;
|
|
9135
9328
|
const mimeType = detectMimeType(content, filename, options.mimeType);
|
|
9136
9329
|
const outputFormat = options.outputFormat ?? "text";
|
|
9137
|
-
|
|
9330
|
+
logger15.trace("Parsing file", {
|
|
9138
9331
|
filename,
|
|
9139
9332
|
mimeType,
|
|
9140
9333
|
outputFormat,
|
|
@@ -9179,7 +9372,7 @@ function createFileOperations(config, llmOps) {
|
|
|
9179
9372
|
metadata: { filename, mimeType, charCount: pdfResult.data.text.length }
|
|
9180
9373
|
});
|
|
9181
9374
|
}
|
|
9182
|
-
|
|
9375
|
+
logger15.warn("PDF native parser failed, falling back to OCR", { filename });
|
|
9183
9376
|
return runOcr(content, mimeType, filename, options.model, outputFormat, options.systemPrompt);
|
|
9184
9377
|
}
|
|
9185
9378
|
if (mimeType === "application/vnd.openxmlformats-officedocument.wordprocessingml.document" || mimeType === "application/msword" || mimeType === "application/zip") {
|
|
@@ -9196,7 +9389,7 @@ function createFileOperations(config, llmOps) {
|
|
|
9196
9389
|
metadata: { filename, mimeType, charCount: docxResult.data.length }
|
|
9197
9390
|
});
|
|
9198
9391
|
}
|
|
9199
|
-
|
|
9392
|
+
logger15.warn("DOCX native parser failed, falling back to OCR", { filename });
|
|
9200
9393
|
return runOcr(content, mimeType, filename, options.model, outputFormat, options.systemPrompt);
|
|
9201
9394
|
}
|
|
9202
9395
|
if (IMAGE_MIME_TYPES.has(mimeType)) {
|
|
@@ -9216,7 +9409,7 @@ function createFileOperations(config, llmOps) {
|
|
|
9216
9409
|
try {
|
|
9217
9410
|
return await doParse(request2);
|
|
9218
9411
|
} catch (error) {
|
|
9219
|
-
|
|
9412
|
+
logger15.error("File parse failed unexpectedly", { filename: request2.filename, error });
|
|
9220
9413
|
return err(HaiAIError.FILE_PARSE_FAILED, aiM("ai_fileParseFailed", {
|
|
9221
9414
|
params: {
|
|
9222
9415
|
error: String(error)
|
|
@@ -9770,7 +9963,7 @@ function createSeedreamImageProvider() {
|
|
|
9770
9963
|
}
|
|
9771
9964
|
|
|
9772
9965
|
// src/image/ai-image-functions.ts
|
|
9773
|
-
var
|
|
9966
|
+
var logger16 = core.logger.child({ module: "ai", scope: "image" });
|
|
9774
9967
|
function createImageOperations(config) {
|
|
9775
9968
|
const imageConfig = ImageConfigSchema.parse(config.image ?? {});
|
|
9776
9969
|
const providers = /* @__PURE__ */ new Map();
|
|
@@ -9796,7 +9989,7 @@ function createImageOperations(config) {
|
|
|
9796
9989
|
return err(HaiAIError.IMAGE_CANCELLED, aiM("ai_imageCancelled"));
|
|
9797
9990
|
const resolved = resolveImageModel(imageConfig, request2.model);
|
|
9798
9991
|
if (!resolved.success) {
|
|
9799
|
-
|
|
9992
|
+
logger16.warn("Image model resolution failed", {
|
|
9800
9993
|
code: resolved.error.code,
|
|
9801
9994
|
error: resolved.error.message,
|
|
9802
9995
|
requestedModel: request2.model
|
|
@@ -9811,7 +10004,7 @@ function createImageOperations(config) {
|
|
|
9811
10004
|
width: request2.size?.width,
|
|
9812
10005
|
height: request2.size?.height
|
|
9813
10006
|
};
|
|
9814
|
-
|
|
10007
|
+
logger16.debug("Image generation started", logContext);
|
|
9815
10008
|
const deadline = new AbortController();
|
|
9816
10009
|
const timer = setTimeout(() => deadline.abort(new DOMException("Image deadline exceeded", "TimeoutError")), resolved.data.timeout);
|
|
9817
10010
|
timer.unref();
|
|
@@ -9836,7 +10029,7 @@ function createImageOperations(config) {
|
|
|
9836
10029
|
if (deadline.signal.aborted)
|
|
9837
10030
|
return err(HaiAIError.IMAGE_TIMEOUT, aiM("ai_imageTimeout"));
|
|
9838
10031
|
if (!generated.success) {
|
|
9839
|
-
|
|
10032
|
+
logger16.warn("Image generation failed", {
|
|
9840
10033
|
...logContext,
|
|
9841
10034
|
durationMs: Date.now() - startedAt,
|
|
9842
10035
|
code: generated.error.code,
|
|
@@ -9854,7 +10047,7 @@ function createImageOperations(config) {
|
|
|
9854
10047
|
return validated;
|
|
9855
10048
|
images.push(validated.data);
|
|
9856
10049
|
}
|
|
9857
|
-
|
|
10050
|
+
logger16.info("Image generation completed", {
|
|
9858
10051
|
...logContext,
|
|
9859
10052
|
durationMs: Date.now() - startedAt,
|
|
9860
10053
|
imageCount: generated.data.length,
|
|
@@ -9883,7 +10076,7 @@ function createProvider2(name) {
|
|
|
9883
10076
|
return createPollinationsImageProvider();
|
|
9884
10077
|
}
|
|
9885
10078
|
}
|
|
9886
|
-
var
|
|
10079
|
+
var logger17 = core.logger.child({ module: "ai", scope: "knowledge-entity" });
|
|
9887
10080
|
var LEADING_MARKDOWN_FENCE_REGEX = /^```(?:json)?\n?/;
|
|
9888
10081
|
var TRAILING_MARKDOWN_FENCE_REGEX = /\n?```$/;
|
|
9889
10082
|
var DEFAULT_ENTITY_TYPES = [
|
|
@@ -9929,7 +10122,7 @@ async function extractEntities(llm, text, model, entityTypes, systemPrompt) {
|
|
|
9929
10122
|
enablePersist: false
|
|
9930
10123
|
});
|
|
9931
10124
|
if (!chatResult.success) {
|
|
9932
|
-
|
|
10125
|
+
logger17.warn("Entity extraction LLM call failed", { error: chatResult.error });
|
|
9933
10126
|
return err(HaiAIError.KNOWLEDGE_ENTITY_EXTRACT_FAILED, aiM("ai_knowledgeEntityExtractFailed", {
|
|
9934
10127
|
params: {
|
|
9935
10128
|
error: String(chatResult.error.message)
|
|
@@ -9939,10 +10132,10 @@ async function extractEntities(llm, text, model, entityTypes, systemPrompt) {
|
|
|
9939
10132
|
const content = chatResult.data.choices[0]?.message?.content ?? "";
|
|
9940
10133
|
const validTypes = new Set(resolvedTypes);
|
|
9941
10134
|
const entities = parseEntityResponse(content, validTypes);
|
|
9942
|
-
|
|
10135
|
+
logger17.trace("Entity extraction completed", { textLength: text.length, entityCount: entities.length });
|
|
9943
10136
|
return ok(entities);
|
|
9944
10137
|
} catch (error) {
|
|
9945
|
-
|
|
10138
|
+
logger17.error("Entity extraction failed", { error });
|
|
9946
10139
|
return err(HaiAIError.KNOWLEDGE_ENTITY_EXTRACT_FAILED, aiM("ai_knowledgeEntityExtractFailed", {
|
|
9947
10140
|
params: {
|
|
9948
10141
|
error: String(error)
|
|
@@ -9966,12 +10159,12 @@ function parseEntityResponse(content, validTypes) {
|
|
|
9966
10159
|
return entities.filter(isValidEntity).map((e) => normalizeEntity(e, validTypes));
|
|
9967
10160
|
}
|
|
9968
10161
|
}
|
|
9969
|
-
|
|
10162
|
+
logger17.warn("Entity extraction returned unexpected format", {
|
|
9970
10163
|
content: content.slice(0, 200)
|
|
9971
10164
|
});
|
|
9972
10165
|
return [];
|
|
9973
10166
|
} catch {
|
|
9974
|
-
|
|
10167
|
+
logger17.warn("Entity extraction returned invalid JSON", {
|
|
9975
10168
|
content: content.slice(0, 200)
|
|
9976
10169
|
});
|
|
9977
10170
|
return [];
|
|
@@ -10034,7 +10227,7 @@ async function extractEntitiesBatch(llm, chunks, model, entityTypes, systemPromp
|
|
|
10034
10227
|
}
|
|
10035
10228
|
|
|
10036
10229
|
// src/knowledge/ai-knowledge-functions.ts
|
|
10037
|
-
var
|
|
10230
|
+
var logger18 = core.logger.child({ module: "ai", scope: "knowledge" });
|
|
10038
10231
|
var DEFAULT_KNOWLEDGE_ASK_SYSTEM_PROMPT = `You are an expert assistant. Answer the user's question based ONLY on the provided context.
|
|
10039
10232
|
|
|
10040
10233
|
Rules:
|
|
@@ -10068,15 +10261,15 @@ function createKnowledgeOperations(config, llm, embedding, datapipe2, store) {
|
|
|
10068
10261
|
}
|
|
10069
10262
|
const collection = options?.collection ?? config.collection;
|
|
10070
10263
|
const dimension = options?.dimension ?? config.dimension;
|
|
10071
|
-
|
|
10264
|
+
logger18.debug("Setting up knowledge base", { collection, dimension });
|
|
10072
10265
|
try {
|
|
10073
10266
|
await store.initialize(collection, dimension);
|
|
10074
10267
|
await store.registerCollection(collection, dimension);
|
|
10075
10268
|
await store.repair(collection);
|
|
10076
|
-
|
|
10269
|
+
logger18.debug("Knowledge base setup completed", { collection });
|
|
10077
10270
|
return ok(void 0);
|
|
10078
10271
|
} catch (error) {
|
|
10079
|
-
|
|
10272
|
+
logger18.error("Knowledge base setup failed", { error });
|
|
10080
10273
|
return err(HaiAIError.KNOWLEDGE_SETUP_FAILED, aiM("ai_knowledgeSetupFailed", {
|
|
10081
10274
|
params: {
|
|
10082
10275
|
error: String(error)
|
|
@@ -10115,7 +10308,7 @@ function createKnowledgeOperations(config, llm, embedding, datapipe2, store) {
|
|
|
10115
10308
|
...config.chunkOptions,
|
|
10116
10309
|
...input.chunkOptions
|
|
10117
10310
|
};
|
|
10118
|
-
|
|
10311
|
+
logger18.trace("Ingesting document", { documentId: input.documentId, collection, contentLength: input.content.length });
|
|
10119
10312
|
try {
|
|
10120
10313
|
if (!await isCollectionReady(collection))
|
|
10121
10314
|
return err(HaiAIError.KNOWLEDGE_NOT_SETUP, aiM("ai_knowledgeNotSetup"));
|
|
@@ -10199,7 +10392,7 @@ function createKnowledgeOperations(config, llm, embedding, datapipe2, store) {
|
|
|
10199
10392
|
entities
|
|
10200
10393
|
});
|
|
10201
10394
|
const duration = Date.now() - startTime;
|
|
10202
|
-
|
|
10395
|
+
logger18.debug("Document ingested", {
|
|
10203
10396
|
documentId: input.documentId,
|
|
10204
10397
|
revision,
|
|
10205
10398
|
cleanupPending: published.cleanupPending,
|
|
@@ -10216,7 +10409,7 @@ function createKnowledgeOperations(config, llm, embedding, datapipe2, store) {
|
|
|
10216
10409
|
duration
|
|
10217
10410
|
});
|
|
10218
10411
|
} catch (error) {
|
|
10219
|
-
|
|
10412
|
+
logger18.error("Document ingestion failed", { documentId: input.documentId, error });
|
|
10220
10413
|
return err(HaiAIError.KNOWLEDGE_INGEST_FAILED, aiM("ai_knowledgeIngestFailed", {
|
|
10221
10414
|
params: {
|
|
10222
10415
|
error: String(error)
|
|
@@ -10240,7 +10433,7 @@ function createKnowledgeOperations(config, llm, embedding, datapipe2, store) {
|
|
|
10240
10433
|
const startTime = Date.now();
|
|
10241
10434
|
const topK = options?.topK ?? 10;
|
|
10242
10435
|
const enableEntityBoost = options?.enableEntityBoost ?? true;
|
|
10243
|
-
|
|
10436
|
+
logger18.trace("Knowledge retrieval", {
|
|
10244
10437
|
query: query.slice(0, 100),
|
|
10245
10438
|
collection,
|
|
10246
10439
|
topK
|
|
@@ -10325,7 +10518,7 @@ function createKnowledgeOperations(config, llm, embedding, datapipe2, store) {
|
|
|
10325
10518
|
}
|
|
10326
10519
|
}
|
|
10327
10520
|
const duration = Date.now() - startTime;
|
|
10328
|
-
|
|
10521
|
+
logger18.trace("Knowledge retrieval completed", { resultCount: items.length, duration });
|
|
10329
10522
|
return ok({
|
|
10330
10523
|
items,
|
|
10331
10524
|
citations: Array.from(citationMap.values()),
|
|
@@ -10333,7 +10526,7 @@ function createKnowledgeOperations(config, llm, embedding, datapipe2, store) {
|
|
|
10333
10526
|
duration
|
|
10334
10527
|
});
|
|
10335
10528
|
} catch (error) {
|
|
10336
|
-
|
|
10529
|
+
logger18.error("Knowledge retrieval failed", { error });
|
|
10337
10530
|
return err(HaiAIError.KNOWLEDGE_RETRIEVE_FAILED, aiM("ai_knowledgeRetrieveFailed", {
|
|
10338
10531
|
params: {
|
|
10339
10532
|
error: String(error)
|
|
@@ -10389,7 +10582,7 @@ ${contextText}
|
|
|
10389
10582
|
}
|
|
10390
10583
|
const choice = chatResult.data.choices[0];
|
|
10391
10584
|
const answer = choice?.message?.content ?? "";
|
|
10392
|
-
|
|
10585
|
+
logger18.trace("Knowledge ask completed", {
|
|
10393
10586
|
contextCount: items.length,
|
|
10394
10587
|
model: chatResult.data.model
|
|
10395
10588
|
});
|
|
@@ -10513,7 +10706,7 @@ ${contextText}
|
|
|
10513
10706
|
if (!await isCollectionReady(collection))
|
|
10514
10707
|
return err(HaiAIError.KNOWLEDGE_NOT_SETUP, aiM("ai_knowledgeNotSetup"));
|
|
10515
10708
|
await store.removeDocument(documentId, collection);
|
|
10516
|
-
|
|
10709
|
+
logger18.debug("Document removed", { documentId, collection });
|
|
10517
10710
|
return ok(void 0);
|
|
10518
10711
|
} catch (error) {
|
|
10519
10712
|
return err(HaiAIError.KNOWLEDGE_INGEST_FAILED, aiM("ai_knowledgeIngestFailed", {
|
|
@@ -10620,13 +10813,13 @@ ${contextText}
|
|
|
10620
10813
|
}));
|
|
10621
10814
|
}
|
|
10622
10815
|
const col = collection ?? config.collection;
|
|
10623
|
-
|
|
10816
|
+
logger18.debug("Deleting knowledge collection", { collection: col });
|
|
10624
10817
|
try {
|
|
10625
10818
|
await store.deleteCollection(col);
|
|
10626
|
-
|
|
10819
|
+
logger18.debug("Knowledge collection deleted", { collection: col });
|
|
10627
10820
|
return ok(void 0);
|
|
10628
10821
|
} catch (error) {
|
|
10629
|
-
|
|
10822
|
+
logger18.error("Knowledge collection deletion failed", { collection: col, error });
|
|
10630
10823
|
return err(HaiAIError.KNOWLEDGE_SETUP_FAILED, aiM("ai_knowledgeSetupFailed", {
|
|
10631
10824
|
params: {
|
|
10632
10825
|
error: String(error)
|
|
@@ -11570,7 +11763,7 @@ function createLLMProvider(deps) {
|
|
|
11570
11763
|
}
|
|
11571
11764
|
|
|
11572
11765
|
// src/llm/ai-llm-functions.ts
|
|
11573
|
-
var
|
|
11766
|
+
var logger19 = core.logger.child({ module: "ai", scope: "llm" });
|
|
11574
11767
|
function createAILLMFunctions(config, deps) {
|
|
11575
11768
|
let provider = createLLMProvider({ config });
|
|
11576
11769
|
let signature = JSON.stringify(config.llm);
|
|
@@ -11603,7 +11796,7 @@ function createAILLMFunctions(config, deps) {
|
|
|
11603
11796
|
objectId: record.objectId,
|
|
11604
11797
|
sessionId: record.sessionId
|
|
11605
11798
|
});
|
|
11606
|
-
|
|
11799
|
+
logger19.trace("Chat record saved", {
|
|
11607
11800
|
id: record.id,
|
|
11608
11801
|
objectId: record.objectId,
|
|
11609
11802
|
sessionId: record.sessionId
|
|
@@ -11628,7 +11821,7 @@ function createAILLMFunctions(config, deps) {
|
|
|
11628
11821
|
model: request2.model ?? request2.tempModel?.model,
|
|
11629
11822
|
messageCount: request2.messages.length
|
|
11630
11823
|
};
|
|
11631
|
-
|
|
11824
|
+
logger19.debug("LLM chat started", context);
|
|
11632
11825
|
let result;
|
|
11633
11826
|
try {
|
|
11634
11827
|
result = await (await currentProvider()).chat(request2);
|
|
@@ -11639,7 +11832,7 @@ function createAILLMFunctions(config, deps) {
|
|
|
11639
11832
|
);
|
|
11640
11833
|
}
|
|
11641
11834
|
if (result.success) {
|
|
11642
|
-
|
|
11835
|
+
logger19.info("LLM chat completed", {
|
|
11643
11836
|
...context,
|
|
11644
11837
|
model: result.data.model,
|
|
11645
11838
|
durationMs: Date.now() - start,
|
|
@@ -11647,7 +11840,7 @@ function createAILLMFunctions(config, deps) {
|
|
|
11647
11840
|
totalTokens: result.data.usage?.total_tokens
|
|
11648
11841
|
});
|
|
11649
11842
|
} else {
|
|
11650
|
-
|
|
11843
|
+
logger19.warn("LLM chat failed", {
|
|
11651
11844
|
...context,
|
|
11652
11845
|
durationMs: Date.now() - start,
|
|
11653
11846
|
code: result.error.code,
|
|
@@ -11681,7 +11874,7 @@ function createAILLMFunctions(config, deps) {
|
|
|
11681
11874
|
};
|
|
11682
11875
|
await saveRecordAndSession(record, request2.messages);
|
|
11683
11876
|
} catch (error) {
|
|
11684
|
-
|
|
11877
|
+
logger19.debug("Failed to save chat record", { error });
|
|
11685
11878
|
}
|
|
11686
11879
|
}
|
|
11687
11880
|
return result;
|
|
@@ -11692,7 +11885,7 @@ function createAILLMFunctions(config, deps) {
|
|
|
11692
11885
|
model: request2.model ?? request2.tempModel?.model,
|
|
11693
11886
|
messageCount: request2.messages.length
|
|
11694
11887
|
};
|
|
11695
|
-
|
|
11888
|
+
logger19.debug("LLM chat stream started", logContext);
|
|
11696
11889
|
const shouldRecord = !!(request2.objectId && recordStore && request2.enablePersist !== false);
|
|
11697
11890
|
let content = "";
|
|
11698
11891
|
let finishReason = null;
|
|
@@ -11732,7 +11925,7 @@ function createAILLMFunctions(config, deps) {
|
|
|
11732
11925
|
}
|
|
11733
11926
|
}
|
|
11734
11927
|
}
|
|
11735
|
-
|
|
11928
|
+
logger19.info("LLM chat stream completed", {
|
|
11736
11929
|
...logContext,
|
|
11737
11930
|
model: resolvedModel || logContext.model,
|
|
11738
11931
|
durationMs: Date.now() - start,
|
|
@@ -11740,7 +11933,7 @@ function createAILLMFunctions(config, deps) {
|
|
|
11740
11933
|
finishReason
|
|
11741
11934
|
});
|
|
11742
11935
|
} catch (error) {
|
|
11743
|
-
|
|
11936
|
+
logger19.warn("LLM chat stream failed", {
|
|
11744
11937
|
...logContext,
|
|
11745
11938
|
durationMs: Date.now() - start,
|
|
11746
11939
|
error
|
|
@@ -11773,7 +11966,7 @@ function createAILLMFunctions(config, deps) {
|
|
|
11773
11966
|
};
|
|
11774
11967
|
await saveRecordAndSession(record, request2.messages);
|
|
11775
11968
|
} catch (error) {
|
|
11776
|
-
|
|
11969
|
+
logger19.debug("Failed to save stream chat record", { error });
|
|
11777
11970
|
}
|
|
11778
11971
|
}
|
|
11779
11972
|
}
|
|
@@ -11885,6 +12078,17 @@ function createAILLMFunctions(config, deps) {
|
|
|
11885
12078
|
baseMessages.push({ role: "system", content: request2.systemPrompt });
|
|
11886
12079
|
baseMessages.push(...request2.messages);
|
|
11887
12080
|
const jsonSchema = z.toJSONSchema(request2.schema);
|
|
12081
|
+
const jsonObject = request2.responseFormat === "json_object";
|
|
12082
|
+
if (jsonObject) {
|
|
12083
|
+
baseMessages.unshift({
|
|
12084
|
+
role: "system",
|
|
12085
|
+
content: aiM("ai_generateObjectJson", {
|
|
12086
|
+
params: {
|
|
12087
|
+
schema: JSON.stringify(jsonSchema)
|
|
12088
|
+
}
|
|
12089
|
+
})
|
|
12090
|
+
});
|
|
12091
|
+
}
|
|
11888
12092
|
const schemaName = request2.schemaName ?? "result";
|
|
11889
12093
|
const maxRepairs = request2.maxRepairs ?? 1;
|
|
11890
12094
|
let lastError = "";
|
|
@@ -11905,7 +12109,7 @@ function createAILLMFunctions(config, deps) {
|
|
|
11905
12109
|
tempModel: request2.tempModel,
|
|
11906
12110
|
enablePersist: false,
|
|
11907
12111
|
signal: request2.signal,
|
|
11908
|
-
response_format: {
|
|
12112
|
+
response_format: jsonObject ? { type: "json_object" } : {
|
|
11909
12113
|
type: "json_schema",
|
|
11910
12114
|
json_schema: { name: schemaName, schema: jsonSchema, strict: true }
|
|
11911
12115
|
}
|
|
@@ -12127,9 +12331,8 @@ function createMCPServiceBroker(read, invoke, options, lifecycle) {
|
|
|
12127
12331
|
if (!endpoint || !["http:", "https:"].includes(endpoint.protocol) || endpoint.username || endpoint.password || endpoint.hash || endpoint.search || typeof options.authorize !== "function")
|
|
12128
12332
|
return err(HaiAIError.RESOURCE_INVALID, aiM("ai_resourceInvalid"));
|
|
12129
12333
|
const grants = /* @__PURE__ */ new Map();
|
|
12130
|
-
const validator = new AjvJsonSchemaValidator();
|
|
12131
12334
|
let closed = false;
|
|
12132
|
-
function createGrant(input, key) {
|
|
12335
|
+
function createGrant(input, validators, key) {
|
|
12133
12336
|
const controller = new AbortController();
|
|
12134
12337
|
const signal = AbortSignal.any([
|
|
12135
12338
|
controller.signal,
|
|
@@ -12145,6 +12348,7 @@ function createMCPServiceBroker(read, invoke, options, lifecycle) {
|
|
|
12145
12348
|
});
|
|
12146
12349
|
return {
|
|
12147
12350
|
input,
|
|
12351
|
+
validators,
|
|
12148
12352
|
signal,
|
|
12149
12353
|
revoke: () => controller.abort()
|
|
12150
12354
|
};
|
|
@@ -12170,15 +12374,19 @@ function createMCPServiceBroker(read, invoke, options, lifecycle) {
|
|
|
12170
12374
|
return err(HaiAIError.RESOURCE_INVALID, aiM("ai_resourceInvalid"));
|
|
12171
12375
|
if (Buffer.byteLength(JSON.stringify(parsed.data.tools)) > maxRequestBytes)
|
|
12172
12376
|
return err(HaiAIError.RESOURCE_INVALID, aiM("ai_resourceInvalid"));
|
|
12173
|
-
const input =
|
|
12377
|
+
const input = {
|
|
12378
|
+
...parsed.data,
|
|
12379
|
+
tools: structuredClone(parsed.data.tools)
|
|
12380
|
+
};
|
|
12174
12381
|
const services = /* @__PURE__ */ new Map();
|
|
12382
|
+
const validators = /* @__PURE__ */ new Map();
|
|
12175
12383
|
for (const tool of input.tools) {
|
|
12176
12384
|
if (!services.has(tool.serviceId))
|
|
12177
12385
|
services.set(tool.serviceId, await read(tool.serviceId));
|
|
12178
12386
|
const service = services.get(tool.serviceId);
|
|
12179
12387
|
if (!service || !["http", "job"].includes(service.transport) || !service.allowedTools?.includes(tool.tool))
|
|
12180
12388
|
return err(HaiAIError.MCP_TOOL_FORBIDDEN, aiM("ai_mcpServiceForbidden"));
|
|
12181
|
-
|
|
12389
|
+
validators.set(tool.id, new AjvJsonSchemaValidator().getValidator(tool.inputSchema));
|
|
12182
12390
|
}
|
|
12183
12391
|
if (closed || lifecycle.aborted)
|
|
12184
12392
|
return err(HaiAIError.NOT_INITIALIZED, aiM("ai_notInitialized"));
|
|
@@ -12186,10 +12394,7 @@ function createMCPServiceBroker(read, invoke, options, lifecycle) {
|
|
|
12186
12394
|
return err(HaiAIError.RESOURCE_OPERATION_FAILED, aiM("ai_resourceOperationFailed"));
|
|
12187
12395
|
const token = randomBytes(32).toString("base64url");
|
|
12188
12396
|
const key = digest(token);
|
|
12189
|
-
const grant = createGrant(
|
|
12190
|
-
...input,
|
|
12191
|
-
tools: structuredClone(input.tools)
|
|
12192
|
-
}, key);
|
|
12397
|
+
const grant = createGrant(input, validators, key);
|
|
12193
12398
|
if (!grant)
|
|
12194
12399
|
return err(HaiAIError.MCP_TOOL_CANCELLED, aiM("ai_mcpServiceCancelled"));
|
|
12195
12400
|
grants.set(key, grant);
|
|
@@ -12204,7 +12409,8 @@ function createMCPServiceBroker(read, invoke, options, lifecycle) {
|
|
|
12204
12409
|
]
|
|
12205
12410
|
}
|
|
12206
12411
|
],
|
|
12207
|
-
revoke: grant.revoke
|
|
12412
|
+
revoke: grant.revoke,
|
|
12413
|
+
signal: grant.signal
|
|
12208
12414
|
});
|
|
12209
12415
|
} catch {
|
|
12210
12416
|
return err(HaiAIError.RESOURCE_INVALID, aiM("ai_resourceInvalid"));
|
|
@@ -12260,7 +12466,7 @@ function createMCPServiceBroker(read, invoke, options, lifecycle) {
|
|
|
12260
12466
|
}));
|
|
12261
12467
|
server.setRequestHandler(CallToolRequestSchema, async ({ params }) => {
|
|
12262
12468
|
const tool = grant.input.tools.find((tool2) => tool2.id === params.name);
|
|
12263
|
-
if (!tool || signal.aborted || !
|
|
12469
|
+
if (!tool || signal.aborted || !grant.validators.get(params.name)?.(params.arguments ?? {}).valid)
|
|
12264
12470
|
return failure();
|
|
12265
12471
|
const result = await invoke({ serviceId: tool.serviceId, tool: tool.tool, arguments: params.arguments }, {
|
|
12266
12472
|
principal: grant.input.principal,
|
|
@@ -12693,27 +12899,27 @@ function createMCPServiceOperations(read, runner, files, configuredServices = []
|
|
|
12693
12899
|
}
|
|
12694
12900
|
};
|
|
12695
12901
|
}
|
|
12696
|
-
function createScopedMemory(
|
|
12902
|
+
function createScopedMemory(core33, binding) {
|
|
12697
12903
|
if (typeof binding.objectId !== "string" || !binding.objectId.trim())
|
|
12698
12904
|
throw new TypeError(aiM("ai_memoryScopeInvalid"));
|
|
12699
12905
|
const { objectId, scope } = binding;
|
|
12700
12906
|
const accessScope = { objectId, scope };
|
|
12701
12907
|
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) =>
|
|
12908
|
+
extract: (messages, options) => core33.extract(messages, { ...options, objectId, scope }),
|
|
12909
|
+
recall: (query, options) => core33.recall(query, { ...options, objectId, scope }),
|
|
12910
|
+
injectMemories: (messages, options) => core33.injectMemories(messages, { ...options, objectId, scope }),
|
|
12911
|
+
add: (entry) => core33.add({ ...entry, objectId, scope }),
|
|
12912
|
+
update: (memoryId, updates) => core33.update(memoryId, updates, accessScope),
|
|
12913
|
+
get: (memoryId) => core33.get(memoryId, accessScope),
|
|
12914
|
+
remove: (memoryId) => core33.remove(memoryId, accessScope),
|
|
12915
|
+
list: (options) => core33.list({ ...options, objectId, scope }),
|
|
12916
|
+
listPage: (options) => core33.listPage({ ...options, objectId, scope }),
|
|
12917
|
+
clear: (options) => core33.clear({ ...options, objectId, scope })
|
|
12712
12918
|
};
|
|
12713
12919
|
}
|
|
12714
|
-
function createMemoryOperations(
|
|
12920
|
+
function createMemoryOperations(core33) {
|
|
12715
12921
|
return {
|
|
12716
|
-
...
|
|
12922
|
+
...core33,
|
|
12717
12923
|
/**
|
|
12718
12924
|
* 清空记忆(空过滤保护)。
|
|
12719
12925
|
*
|
|
@@ -12727,20 +12933,20 @@ function createMemoryOperations(core32) {
|
|
|
12727
12933
|
if (!hasFilter) {
|
|
12728
12934
|
return err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryClearRequiresFilter"));
|
|
12729
12935
|
}
|
|
12730
|
-
return
|
|
12936
|
+
return core33.clear(options);
|
|
12731
12937
|
},
|
|
12732
|
-
scoped: (binding) => createScopedMemory(
|
|
12938
|
+
scoped: (binding) => createScopedMemory(core33, binding),
|
|
12733
12939
|
admin: {
|
|
12734
12940
|
async clearAll(options) {
|
|
12735
12941
|
if (options?.confirm !== true) {
|
|
12736
12942
|
return err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryClearAllUnconfirmed"));
|
|
12737
12943
|
}
|
|
12738
|
-
return
|
|
12944
|
+
return core33.clear();
|
|
12739
12945
|
}
|
|
12740
12946
|
}
|
|
12741
12947
|
};
|
|
12742
12948
|
}
|
|
12743
|
-
var
|
|
12949
|
+
var logger20 = core.logger.child({ module: "ai", scope: "memory-extractor" });
|
|
12744
12950
|
var LEADING_MARKDOWN_FENCE_REGEX2 = /^```(?:json)?\n?/;
|
|
12745
12951
|
var TRAILING_MARKDOWN_FENCE_REGEX2 = /\n?```$/;
|
|
12746
12952
|
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 +12999,7 @@ Only extract memories of these types: ${options.types.join(", ")}`;
|
|
|
12793
12999
|
signal: options?.signal
|
|
12794
13000
|
});
|
|
12795
13001
|
if (!chatResult.success) {
|
|
12796
|
-
|
|
13002
|
+
logger20.warn("Memory extraction LLM call failed", { error: chatResult.error });
|
|
12797
13003
|
return err(HaiAIError.MEMORY_EXTRACT_FAILED, aiM("ai_memoryExtractFailed", {
|
|
12798
13004
|
params: {
|
|
12799
13005
|
error: String(chatResult.error.message)
|
|
@@ -12812,10 +13018,10 @@ Only extract memories of these types: ${options.types.join(", ")}`;
|
|
|
12812
13018
|
if (options?.objectId) {
|
|
12813
13019
|
entries = entries.map((e) => ({ ...e, objectId: options.objectId }));
|
|
12814
13020
|
}
|
|
12815
|
-
|
|
13021
|
+
logger20.trace("Memory extraction completed", { messageCount: messages.length, extractedCount: entries.length });
|
|
12816
13022
|
return ok(entries);
|
|
12817
13023
|
} catch (error) {
|
|
12818
|
-
|
|
13024
|
+
logger20.error("Memory extraction failed", { error });
|
|
12819
13025
|
return err(HaiAIError.MEMORY_EXTRACT_FAILED, aiM("ai_memoryExtractFailed", {
|
|
12820
13026
|
params: {
|
|
12821
13027
|
error: String(error)
|
|
@@ -12846,12 +13052,12 @@ function parseMemoryResponse(content) {
|
|
|
12846
13052
|
return memories.filter(isValidMemoryItem).map(normalizeMemoryItem);
|
|
12847
13053
|
}
|
|
12848
13054
|
}
|
|
12849
|
-
|
|
13055
|
+
logger20.warn("Memory extraction returned unexpected format", {
|
|
12850
13056
|
content: content.slice(0, 200)
|
|
12851
13057
|
});
|
|
12852
13058
|
return [];
|
|
12853
13059
|
} catch {
|
|
12854
|
-
|
|
13060
|
+
logger20.warn("Memory extraction returned invalid JSON", {
|
|
12855
13061
|
content: content.slice(0, 200)
|
|
12856
13062
|
});
|
|
12857
13063
|
return [];
|
|
@@ -12872,7 +13078,7 @@ function normalizeMemoryItem(item2) {
|
|
|
12872
13078
|
importance
|
|
12873
13079
|
};
|
|
12874
13080
|
}
|
|
12875
|
-
var
|
|
13081
|
+
var logger21 = core.logger.child({ module: "ai", scope: "memory" });
|
|
12876
13082
|
function isMemoryAccessDenied(entry, accessScope) {
|
|
12877
13083
|
if (!accessScope)
|
|
12878
13084
|
return false;
|
|
@@ -12960,10 +13166,10 @@ ${memoryText}
|
|
|
12960
13166
|
});
|
|
12961
13167
|
}
|
|
12962
13168
|
}
|
|
12963
|
-
|
|
13169
|
+
logger21.trace("Memories enriched", { count: recallResult.data.length, position });
|
|
12964
13170
|
return ok(result);
|
|
12965
13171
|
} catch (error) {
|
|
12966
|
-
|
|
13172
|
+
logger21.error("Memory enrichment failed", { error });
|
|
12967
13173
|
return err(HaiAIError.MEMORY_ENRICH_FAILED, aiM("ai_memoryEnrichFailed", {
|
|
12968
13174
|
params: {
|
|
12969
13175
|
error: String(error)
|
|
@@ -13280,7 +13486,7 @@ async function createMem0Store(options) {
|
|
|
13280
13486
|
}
|
|
13281
13487
|
|
|
13282
13488
|
// src/memory/providers/ai-memory-provider-mem0.ts
|
|
13283
|
-
var
|
|
13489
|
+
var logger22 = core.logger.child({ module: "ai", scope: "memory-mem0" });
|
|
13284
13490
|
var DEFAULT_IMPORTANCE = 0.5;
|
|
13285
13491
|
var DEFAULT_OBJECT_ID = "hai-global";
|
|
13286
13492
|
var MEM0_LIST_CANDIDATE_LIMIT = 1e3;
|
|
@@ -13396,7 +13602,7 @@ function buildVectorStoreConfig(deps) {
|
|
|
13396
13602
|
);
|
|
13397
13603
|
}
|
|
13398
13604
|
if (backend)
|
|
13399
|
-
|
|
13605
|
+
logger22.warn("Mem0 format falls back to in-memory vector store (allowEphemeralFallback=true); data will not survive restart", { backend: backend.type });
|
|
13400
13606
|
return ok({
|
|
13401
13607
|
provider: "memory",
|
|
13402
13608
|
persistent: false
|
|
@@ -13437,7 +13643,7 @@ async function extractMemories2(context, messages, options) {
|
|
|
13437
13643
|
throw failed.reason;
|
|
13438
13644
|
return ok(stored.flatMap((result) => result.status === "fulfilled" ? [result.value] : []));
|
|
13439
13645
|
} catch (error) {
|
|
13440
|
-
|
|
13646
|
+
logger22.error("Mem0 format extract failed", {
|
|
13441
13647
|
error: core.sanitize.sanitizeSensitiveFields(error)
|
|
13442
13648
|
});
|
|
13443
13649
|
return memoryWriteFailure(HaiAIError.MEMORY_EXTRACT_FAILED, aiM("ai_memoryOperationFailed"), memoryIds);
|
|
@@ -13464,7 +13670,7 @@ async function recallMemories(context, query, options) {
|
|
|
13464
13670
|
}
|
|
13465
13671
|
return ok(entries.slice(0, topK));
|
|
13466
13672
|
} catch (error) {
|
|
13467
|
-
|
|
13673
|
+
logger22.error("Mem0 format recall failed", {
|
|
13468
13674
|
error: core.sanitize.sanitizeSensitiveFields(error)
|
|
13469
13675
|
});
|
|
13470
13676
|
return err(HaiAIError.MEMORY_RECALL_FAILED, aiM("ai_memoryOperationFailed"));
|
|
@@ -13481,7 +13687,7 @@ async function addMemory(context, entry) {
|
|
|
13481
13687
|
throw new Error("Mem0 format stored memory could not be read back");
|
|
13482
13688
|
return ok(toMemoryEntry(persisted, objectId));
|
|
13483
13689
|
} catch (error) {
|
|
13484
|
-
|
|
13690
|
+
logger22.error("Mem0 format add failed", {
|
|
13485
13691
|
error: core.sanitize.sanitizeSensitiveFields(error)
|
|
13486
13692
|
});
|
|
13487
13693
|
return memoryWriteFailure(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryOperationFailed"), memoryIds);
|
|
@@ -13519,7 +13725,7 @@ async function updateMemory(context, memoryId, updates, accessScope) {
|
|
|
13519
13725
|
}
|
|
13520
13726
|
return ok(toMemoryEntry(refreshed, objectId));
|
|
13521
13727
|
} catch (error) {
|
|
13522
|
-
|
|
13728
|
+
logger22.error("Mem0 format update failed", {
|
|
13523
13729
|
id: memoryId,
|
|
13524
13730
|
error: core.sanitize.sanitizeSensitiveFields(error)
|
|
13525
13731
|
});
|
|
@@ -13542,7 +13748,7 @@ async function getMemory(context, memoryId, accessScope) {
|
|
|
13542
13748
|
}
|
|
13543
13749
|
return ok(entry);
|
|
13544
13750
|
} catch (error) {
|
|
13545
|
-
|
|
13751
|
+
logger22.error("Mem0 format read failed", {
|
|
13546
13752
|
error: core.sanitize.sanitizeSensitiveFields(error)
|
|
13547
13753
|
});
|
|
13548
13754
|
return err(HaiAIError.MEMORY_RECALL_FAILED, aiM("ai_memoryOperationFailed"));
|
|
@@ -13561,7 +13767,7 @@ async function removeMemory(context, memoryId, accessScope) {
|
|
|
13561
13767
|
await context.memory.remove(memoryId);
|
|
13562
13768
|
return ok(void 0);
|
|
13563
13769
|
} catch (error) {
|
|
13564
|
-
|
|
13770
|
+
logger22.error("Mem0 format delete failed", {
|
|
13565
13771
|
error: core.sanitize.sanitizeSensitiveFields(error)
|
|
13566
13772
|
});
|
|
13567
13773
|
return err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryOperationFailed"));
|
|
@@ -13610,7 +13816,7 @@ async function createMem0MemoryOperations(deps) {
|
|
|
13610
13816
|
backend: configResult.data.backend
|
|
13611
13817
|
});
|
|
13612
13818
|
} catch (error) {
|
|
13613
|
-
|
|
13819
|
+
logger22.error("Mem0 data storage initialization failed", {
|
|
13614
13820
|
error: core.sanitize.sanitizeSensitiveFields(error)
|
|
13615
13821
|
});
|
|
13616
13822
|
const failure = err(HaiAIError.CONFIGURATION_ERROR, aiM("ai_memoryOperationFailed"));
|
|
@@ -13618,7 +13824,7 @@ async function createMem0MemoryOperations(deps) {
|
|
|
13618
13824
|
throw failure.error;
|
|
13619
13825
|
throw new Error("Unreachable memory initialization state");
|
|
13620
13826
|
}
|
|
13621
|
-
|
|
13827
|
+
logger22.info("Mem0 format memory initialized", {
|
|
13622
13828
|
vectorProvider: configResult.data.provider,
|
|
13623
13829
|
persistent: configResult.data.persistent
|
|
13624
13830
|
});
|
|
@@ -13651,7 +13857,7 @@ async function createMem0MemoryOperations(deps) {
|
|
|
13651
13857
|
try {
|
|
13652
13858
|
return ok(await listMemories(context, options));
|
|
13653
13859
|
} catch (error) {
|
|
13654
|
-
|
|
13860
|
+
logger22.error("Mem0 data list failed", {
|
|
13655
13861
|
operation: "list",
|
|
13656
13862
|
...core.context.get(),
|
|
13657
13863
|
error: core.sanitize.sanitizeSensitiveFields(error)
|
|
@@ -13671,7 +13877,7 @@ async function createMem0MemoryOperations(deps) {
|
|
|
13671
13877
|
total: all.length
|
|
13672
13878
|
});
|
|
13673
13879
|
} catch (error) {
|
|
13674
|
-
|
|
13880
|
+
logger22.error("Mem0 data page failed", {
|
|
13675
13881
|
operation: "page",
|
|
13676
13882
|
...core.context.get(),
|
|
13677
13883
|
error: core.sanitize.sanitizeSensitiveFields(error)
|
|
@@ -13702,7 +13908,7 @@ async function createMem0MemoryOperations(deps) {
|
|
|
13702
13908
|
const matched = await listMemories(context, { objectId: options?.objectId, types: options?.types, scope: options?.scope });
|
|
13703
13909
|
for (const entry of matched)
|
|
13704
13910
|
await context.memory.remove(entry.id);
|
|
13705
|
-
|
|
13911
|
+
logger22.debug("Mem0 format memories cleared", {
|
|
13706
13912
|
removed: matched.length,
|
|
13707
13913
|
objectId: options?.objectId,
|
|
13708
13914
|
types: options?.types,
|
|
@@ -13710,7 +13916,7 @@ async function createMem0MemoryOperations(deps) {
|
|
|
13710
13916
|
});
|
|
13711
13917
|
return ok(void 0);
|
|
13712
13918
|
} catch (error) {
|
|
13713
|
-
|
|
13919
|
+
logger22.error("Mem0 data clear failed", {
|
|
13714
13920
|
operation: "clear",
|
|
13715
13921
|
...core.context.get(),
|
|
13716
13922
|
error: core.sanitize.sanitizeSensitiveFields(error)
|
|
@@ -13722,7 +13928,7 @@ async function createMem0MemoryOperations(deps) {
|
|
|
13722
13928
|
}
|
|
13723
13929
|
};
|
|
13724
13930
|
}
|
|
13725
|
-
var
|
|
13931
|
+
var logger23 = core.logger.child({ module: "ai", scope: "memory-consolidation" });
|
|
13726
13932
|
var DEFAULT_IMPORTANCE2 = 0.5;
|
|
13727
13933
|
var MEMORY_TYPES2 = /* @__PURE__ */ new Set([
|
|
13728
13934
|
"fact",
|
|
@@ -13853,7 +14059,7 @@ async function applyConsolidationOps(deps, ops, options) {
|
|
|
13853
14059
|
if (op.event === "DELETE" && op.id) {
|
|
13854
14060
|
const removeResult = await deps.remove(op.id);
|
|
13855
14061
|
if (!removeResult.success)
|
|
13856
|
-
|
|
14062
|
+
logger23.warn("Consolidation delete skipped", { id: op.id, error: removeResult.error.message });
|
|
13857
14063
|
continue;
|
|
13858
14064
|
}
|
|
13859
14065
|
if (op.event === "UPDATE" && op.id) {
|
|
@@ -13883,7 +14089,7 @@ async function applyConsolidationOps(deps, ops, options) {
|
|
|
13883
14089
|
return ok(entries);
|
|
13884
14090
|
}
|
|
13885
14091
|
async function extractAndConsolidate(deps, messages, options) {
|
|
13886
|
-
|
|
14092
|
+
logger23.trace("Consolidation extract", { messageCount: messages.length });
|
|
13887
14093
|
const extractResult = await extractMemories(deps.llm, messages, {
|
|
13888
14094
|
types: options?.types,
|
|
13889
14095
|
model: options?.model,
|
|
@@ -13941,7 +14147,7 @@ async function extractAndConsolidate(deps, messages, options) {
|
|
|
13941
14147
|
try {
|
|
13942
14148
|
ops = parseConsolidationOps(rawContent, candidates, relatedIds);
|
|
13943
14149
|
} catch {
|
|
13944
|
-
|
|
14150
|
+
logger23.warn("Consolidation returned invalid JSON, falling back to ADD-all", {
|
|
13945
14151
|
content: rawContent.slice(0, 200)
|
|
13946
14152
|
});
|
|
13947
14153
|
ops = candidates.map((candidate) => ({
|
|
@@ -13954,7 +14160,7 @@ async function extractAndConsolidate(deps, messages, options) {
|
|
|
13954
14160
|
const applyResult = await applyConsolidationOps(deps, ops, options);
|
|
13955
14161
|
if (!applyResult.success)
|
|
13956
14162
|
return applyResult;
|
|
13957
|
-
|
|
14163
|
+
logger23.trace("Consolidation completed", {
|
|
13958
14164
|
candidates: candidates.length,
|
|
13959
14165
|
related: related.length,
|
|
13960
14166
|
ops: ops.length,
|
|
@@ -13964,8 +14170,9 @@ async function extractAndConsolidate(deps, messages, options) {
|
|
|
13964
14170
|
}
|
|
13965
14171
|
|
|
13966
14172
|
// src/memory/providers/ai-memory-provider-native.ts
|
|
13967
|
-
var
|
|
14173
|
+
var logger24 = core.logger.child({ module: "ai", scope: "memory-native" });
|
|
13968
14174
|
var EVICTION_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1e3;
|
|
14175
|
+
var EVICTION_CANDIDATES = 64;
|
|
13969
14176
|
function generateId() {
|
|
13970
14177
|
return `mem_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;
|
|
13971
14178
|
}
|
|
@@ -13993,7 +14200,7 @@ function createNativeMemoryOperations(config, llm, embedding, store, vectorStore
|
|
|
13993
14200
|
try {
|
|
13994
14201
|
return await operation();
|
|
13995
14202
|
} catch (error) {
|
|
13996
|
-
|
|
14203
|
+
logger24.error("Memory storage operation failed", {
|
|
13997
14204
|
error: core.sanitize.sanitizeSensitiveFields(error)
|
|
13998
14205
|
});
|
|
13999
14206
|
return err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryOperationFailed"));
|
|
@@ -14025,52 +14232,58 @@ function createNativeMemoryOperations(config, llm, embedding, store, vectorStore
|
|
|
14025
14232
|
const result = await embedding.embedText(text);
|
|
14026
14233
|
if (result.success)
|
|
14027
14234
|
return result.data;
|
|
14028
|
-
|
|
14235
|
+
logger24.warn("Failed to compute embedding for memory", { error: result.error });
|
|
14029
14236
|
return void 0;
|
|
14030
14237
|
}
|
|
14031
|
-
async function evictLowest(candidates) {
|
|
14032
|
-
if (candidates.length === 0)
|
|
14033
|
-
return;
|
|
14238
|
+
async function evictLowest(activeStore, candidates, count) {
|
|
14034
14239
|
const now = Date.now();
|
|
14035
|
-
|
|
14036
|
-
let lowestId = null;
|
|
14037
|
-
for (const entry of candidates) {
|
|
14240
|
+
const ranked = candidates.map((entry) => {
|
|
14038
14241
|
const age = now - entry.createdAt;
|
|
14039
14242
|
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);
|
|
14243
|
+
return { id: entry.id, score: entry.importance * 0.7 + recency * 0.3 };
|
|
14244
|
+
}).sort((left, right) => left.score - right.score).slice(0, count);
|
|
14245
|
+
for (const { id: id3 } of ranked) {
|
|
14246
|
+
await vectorStore.remove(id3);
|
|
14247
|
+
await activeStore.remove(id3);
|
|
14049
14248
|
}
|
|
14249
|
+
return ranked.length;
|
|
14050
14250
|
}
|
|
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
|
-
}
|
|
14251
|
+
async function evictIfNeeded(activeStore, objectId) {
|
|
14060
14252
|
if (objectId) {
|
|
14061
|
-
const objectTotal = await
|
|
14253
|
+
const objectTotal = await activeStore.count({ objectId });
|
|
14062
14254
|
if (objectTotal >= config.maxEntriesPerObject) {
|
|
14063
|
-
const objectEntries = await
|
|
14255
|
+
const objectEntries = await activeStore.query({
|
|
14064
14256
|
objectId,
|
|
14065
14257
|
orderBy: { field: "createdAt", direction: "asc" },
|
|
14066
|
-
limit:
|
|
14258
|
+
limit: EVICTION_CANDIDATES
|
|
14067
14259
|
});
|
|
14068
|
-
|
|
14260
|
+
const needed = objectTotal - config.maxEntriesPerObject + 1;
|
|
14261
|
+
if (await evictLowest(activeStore, objectEntries, needed) < needed)
|
|
14262
|
+
return false;
|
|
14069
14263
|
}
|
|
14070
14264
|
}
|
|
14265
|
+
const globalTotal = await activeStore.count();
|
|
14266
|
+
if (globalTotal >= config.maxEntriesGlobal) {
|
|
14267
|
+
const candidates = await activeStore.query({
|
|
14268
|
+
orderBy: { field: "createdAt", direction: "asc" },
|
|
14269
|
+
limit: EVICTION_CANDIDATES
|
|
14270
|
+
});
|
|
14271
|
+
const needed = globalTotal - config.maxEntriesGlobal + 1;
|
|
14272
|
+
return await evictLowest(activeStore, candidates, needed) >= needed;
|
|
14273
|
+
}
|
|
14274
|
+
return true;
|
|
14275
|
+
}
|
|
14276
|
+
let localWrites = Promise.resolve();
|
|
14277
|
+
function writeMemory(write) {
|
|
14278
|
+
if (store.withWriteLock)
|
|
14279
|
+
return store.withWriteLock(write);
|
|
14280
|
+
const pending = localWrites.then(() => write(store));
|
|
14281
|
+
localWrites = pending.then(() => {
|
|
14282
|
+
}, () => {
|
|
14283
|
+
});
|
|
14284
|
+
return pending;
|
|
14071
14285
|
}
|
|
14072
14286
|
async function saveEntry(input, vector) {
|
|
14073
|
-
await evictIfNeeded(input.objectId);
|
|
14074
14287
|
const now = Date.now();
|
|
14075
14288
|
const entry = {
|
|
14076
14289
|
id: generateId(),
|
|
@@ -14085,14 +14298,15 @@ function createNativeMemoryOperations(config, llm, embedding, store, vectorStore
|
|
|
14085
14298
|
lastAccessedAt: now,
|
|
14086
14299
|
accessCount: 0
|
|
14087
14300
|
};
|
|
14088
|
-
|
|
14089
|
-
|
|
14090
|
-
|
|
14091
|
-
|
|
14092
|
-
|
|
14093
|
-
|
|
14094
|
-
|
|
14095
|
-
|
|
14301
|
+
return writeMemory(async (activeStore) => {
|
|
14302
|
+
if (!await evictIfNeeded(activeStore, input.objectId))
|
|
14303
|
+
return void 0;
|
|
14304
|
+
await activeStore.save(entry.id, entry, { objectId: entry.objectId });
|
|
14305
|
+
if (vector) {
|
|
14306
|
+
await vectorStore.upsert(entry.id, vector, { objectId: entry.objectId, type: entry.type });
|
|
14307
|
+
}
|
|
14308
|
+
return entry;
|
|
14309
|
+
});
|
|
14096
14310
|
}
|
|
14097
14311
|
async function updateEntry(memoryId, updates, accessScope) {
|
|
14098
14312
|
try {
|
|
@@ -14125,10 +14339,10 @@ function createNativeMemoryOperations(config, llm, embedding, store, vectorStore
|
|
|
14125
14339
|
if (updates.content !== void 0 && existing.vector) {
|
|
14126
14340
|
await vectorStore.upsert(memoryId, existing.vector, { objectId: existing.objectId, type: existing.type });
|
|
14127
14341
|
}
|
|
14128
|
-
|
|
14342
|
+
logger24.trace("Memory updated", { id: memoryId });
|
|
14129
14343
|
return ok(existing);
|
|
14130
14344
|
} catch (error) {
|
|
14131
|
-
|
|
14345
|
+
logger24.error("Memory update failed", { id: memoryId, error });
|
|
14132
14346
|
return err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryOperationFailed"));
|
|
14133
14347
|
}
|
|
14134
14348
|
}
|
|
@@ -14136,7 +14350,7 @@ function createNativeMemoryOperations(config, llm, embedding, store, vectorStore
|
|
|
14136
14350
|
const topK = options?.topK ?? config.defaultTopK;
|
|
14137
14351
|
const recencyWeight = options?.recencyWeight ?? 1 - config.recencyDecay;
|
|
14138
14352
|
const candidateMultiplier = Math.max(1, options?.candidateMultiplier ?? config.candidateMultiplier);
|
|
14139
|
-
|
|
14353
|
+
logger24.trace("Recalling memories", {
|
|
14140
14354
|
query: query.slice(0, 100),
|
|
14141
14355
|
topK,
|
|
14142
14356
|
updateAccessStats
|
|
@@ -14205,14 +14419,14 @@ function createNativeMemoryOperations(config, llm, embedding, store, vectorStore
|
|
|
14205
14419
|
}
|
|
14206
14420
|
results.push({ ...entry });
|
|
14207
14421
|
}
|
|
14208
|
-
|
|
14422
|
+
logger24.trace("Memory recall completed", {
|
|
14209
14423
|
query: query.slice(0, 50),
|
|
14210
14424
|
resultCount: results.length,
|
|
14211
14425
|
updateAccessStats
|
|
14212
14426
|
});
|
|
14213
14427
|
return ok(results);
|
|
14214
14428
|
} catch (error) {
|
|
14215
|
-
|
|
14429
|
+
logger24.error("Memory recall failed", {
|
|
14216
14430
|
error: core.sanitize.sanitizeSensitiveFields(error)
|
|
14217
14431
|
});
|
|
14218
14432
|
return err(HaiAIError.MEMORY_RECALL_FAILED, aiM("ai_memoryOperationFailed"));
|
|
@@ -14262,10 +14476,12 @@ function createNativeMemoryOperations(config, llm, embedding, store, vectorStore
|
|
|
14262
14476
|
try {
|
|
14263
14477
|
const vector = await computeVector(entry.content);
|
|
14264
14478
|
const stored = await saveEntry(entry, vector);
|
|
14265
|
-
|
|
14479
|
+
if (!stored)
|
|
14480
|
+
return err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryOperationFailed"));
|
|
14481
|
+
logger24.trace("Memory added", { id: stored.id, type: stored.type });
|
|
14266
14482
|
return ok(stored);
|
|
14267
14483
|
} catch (error) {
|
|
14268
|
-
|
|
14484
|
+
logger24.error("Memory add failed", {
|
|
14269
14485
|
error: core.sanitize.sanitizeSensitiveFields(error)
|
|
14270
14486
|
});
|
|
14271
14487
|
return err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryOperationFailed"));
|
|
@@ -14308,13 +14524,13 @@ function createNativeMemoryOperations(config, llm, embedding, store, vectorStore
|
|
|
14308
14524
|
}));
|
|
14309
14525
|
}
|
|
14310
14526
|
await vectorStore.remove(memoryId);
|
|
14311
|
-
const
|
|
14312
|
-
if (!
|
|
14527
|
+
const removed2 = await store.remove(memoryId);
|
|
14528
|
+
if (!removed2) {
|
|
14313
14529
|
return err(HaiAIError.MEMORY_NOT_FOUND, aiM("ai_memoryNotFound", {
|
|
14314
14530
|
params: { id: memoryId }
|
|
14315
14531
|
}));
|
|
14316
14532
|
}
|
|
14317
|
-
|
|
14533
|
+
logger24.trace("Memory removed", { id: memoryId });
|
|
14318
14534
|
return ok(void 0);
|
|
14319
14535
|
},
|
|
14320
14536
|
/**
|
|
@@ -14397,7 +14613,7 @@ function createNativeMemoryOperations(config, llm, embedding, store, vectorStore
|
|
|
14397
14613
|
if (!options?.types && !options?.objectId && !options?.scope) {
|
|
14398
14614
|
await vectorStore.clear();
|
|
14399
14615
|
await store.clear();
|
|
14400
|
-
|
|
14616
|
+
logger24.debug("All memories cleared");
|
|
14401
14617
|
return ok(void 0);
|
|
14402
14618
|
}
|
|
14403
14619
|
const where = {};
|
|
@@ -14415,7 +14631,7 @@ function createNativeMemoryOperations(config, llm, embedding, store, vectorStore
|
|
|
14415
14631
|
await vectorStore.remove(entry.id);
|
|
14416
14632
|
await store.remove(entry.id);
|
|
14417
14633
|
}
|
|
14418
|
-
|
|
14634
|
+
logger24.debug("Memories cleared", {
|
|
14419
14635
|
removed: toRemove.length,
|
|
14420
14636
|
objectId: options.objectId,
|
|
14421
14637
|
types: options.types,
|
|
@@ -14433,7 +14649,7 @@ function createNativeMemoryOperations(config, llm, embedding, store, vectorStore
|
|
|
14433
14649
|
clear: (options) => protect(() => operations2.clear(options))
|
|
14434
14650
|
};
|
|
14435
14651
|
}
|
|
14436
|
-
var
|
|
14652
|
+
var logger25 = core.logger.child({ module: "ai", scope: "persona" });
|
|
14437
14653
|
var DEFAULT_OBJECT_ID2 = "system";
|
|
14438
14654
|
function personaKey(objectId, id3) {
|
|
14439
14655
|
return JSON.stringify([objectId, id3]);
|
|
@@ -14452,7 +14668,7 @@ function createPersonaOperations(store) {
|
|
|
14452
14668
|
try {
|
|
14453
14669
|
return await operation();
|
|
14454
14670
|
} catch (error) {
|
|
14455
|
-
|
|
14671
|
+
logger25.error("Persona storage operation failed", {
|
|
14456
14672
|
error: core.sanitize.sanitizeSensitiveFields(error)
|
|
14457
14673
|
});
|
|
14458
14674
|
return err(HaiAIError.PERSONA_SAVE_FAILED, aiM("ai_personaOperationFailed"));
|
|
@@ -14476,10 +14692,10 @@ function createPersonaOperations(store) {
|
|
|
14476
14692
|
updatedAt: now
|
|
14477
14693
|
};
|
|
14478
14694
|
await store.save(key, profile, { objectId });
|
|
14479
|
-
|
|
14695
|
+
logger25.trace("Persona saved", { id: profile.id, objectId });
|
|
14480
14696
|
return ok(profile);
|
|
14481
14697
|
} catch (error) {
|
|
14482
|
-
|
|
14698
|
+
logger25.error("Persona save failed", {
|
|
14483
14699
|
error: core.sanitize.sanitizeSensitiveFields(error)
|
|
14484
14700
|
});
|
|
14485
14701
|
return err(HaiAIError.PERSONA_SAVE_FAILED, aiM("ai_personaOperationFailed"));
|
|
@@ -14516,7 +14732,7 @@ function createPersonaOperations(store) {
|
|
|
14516
14732
|
await store.save(key, profile, { objectId });
|
|
14517
14733
|
return ok(profile);
|
|
14518
14734
|
} catch (error) {
|
|
14519
|
-
|
|
14735
|
+
logger25.error("Persona update failed", {
|
|
14520
14736
|
error: core.sanitize.sanitizeSensitiveFields(error)
|
|
14521
14737
|
});
|
|
14522
14738
|
return err(HaiAIError.PERSONA_SAVE_FAILED, aiM("ai_personaOperationFailed"));
|
|
@@ -14555,7 +14771,7 @@ function createPersonaOperations(store) {
|
|
|
14555
14771
|
compose: (id3, options) => protect(() => operations2.compose(id3, options))
|
|
14556
14772
|
};
|
|
14557
14773
|
}
|
|
14558
|
-
var
|
|
14774
|
+
var logger26 = core.logger.child({ module: "ai", scope: "rag" });
|
|
14559
14775
|
var DEFAULT_RAG_SYSTEM_PROMPT = `You are a helpful assistant. Answer the user's question based on the provided context.
|
|
14560
14776
|
If the context doesn't contain relevant information, say so honestly.
|
|
14561
14777
|
When using information from the context, cite the source by its number, e.g. [1] or [2].`;
|
|
@@ -14584,7 +14800,7 @@ function createRagOperations(llm, retrieval) {
|
|
|
14584
14800
|
* @returns `ok(RagResult)` 含 answer、context 列表与引用信源;检索或生成失败时返回错误
|
|
14585
14801
|
*/
|
|
14586
14802
|
async query(query, options) {
|
|
14587
|
-
|
|
14803
|
+
logger26.trace("Starting RAG query", {
|
|
14588
14804
|
query: query.slice(0, 100)
|
|
14589
14805
|
});
|
|
14590
14806
|
try {
|
|
@@ -14639,7 +14855,7 @@ ${contextText}
|
|
|
14639
14855
|
}
|
|
14640
14856
|
const choice = chatResult.data.choices[0];
|
|
14641
14857
|
const answer = choice?.message?.content ?? "";
|
|
14642
|
-
|
|
14858
|
+
logger26.trace("RAG query completed", {
|
|
14643
14859
|
contextCount: contextItems.length,
|
|
14644
14860
|
model: chatResult.data.model
|
|
14645
14861
|
});
|
|
@@ -14666,7 +14882,7 @@ ${contextText}
|
|
|
14666
14882
|
} : void 0
|
|
14667
14883
|
});
|
|
14668
14884
|
} catch (error) {
|
|
14669
|
-
|
|
14885
|
+
logger26.error("RAG query failed", { error });
|
|
14670
14886
|
return err(HaiAIError.RAG_FAILED, aiM("ai_internalError", {
|
|
14671
14887
|
params: {
|
|
14672
14888
|
error: String(error)
|
|
@@ -14678,7 +14894,7 @@ ${contextText}
|
|
|
14678
14894
|
* 流式 RAG 查询:先产出 context,再逐 chunk 产出 delta,最后 done
|
|
14679
14895
|
*/
|
|
14680
14896
|
async *queryStream(query, options) {
|
|
14681
|
-
|
|
14897
|
+
logger26.trace("Starting RAG stream", {
|
|
14682
14898
|
query: query.slice(0, 100)
|
|
14683
14899
|
});
|
|
14684
14900
|
const retrieveResult = await retrieval.retrieve({
|
|
@@ -14762,7 +14978,7 @@ ${contextText}
|
|
|
14762
14978
|
}
|
|
14763
14979
|
};
|
|
14764
14980
|
}
|
|
14765
|
-
var
|
|
14981
|
+
var logger27 = core.logger.child({ module: "ai", scope: "reasoning" });
|
|
14766
14982
|
var REACT_SYSTEM_PROMPT = `You are a reasoning agent that follows the ReAct (Reasoning and Acting) framework.
|
|
14767
14983
|
For each step:
|
|
14768
14984
|
1. Think: Analyze what you know and what you need to find out.
|
|
@@ -15012,7 +15228,7 @@ ${query}` }
|
|
|
15012
15228
|
return {
|
|
15013
15229
|
async run(query, options) {
|
|
15014
15230
|
const strategy = options?.strategy ?? "react";
|
|
15015
|
-
|
|
15231
|
+
logger27.trace("Starting reasoning", { strategy, maxRounds: options?.maxRounds });
|
|
15016
15232
|
try {
|
|
15017
15233
|
switch (strategy) {
|
|
15018
15234
|
case "react":
|
|
@@ -15027,7 +15243,7 @@ ${query}` }
|
|
|
15027
15243
|
}));
|
|
15028
15244
|
}
|
|
15029
15245
|
} catch (error) {
|
|
15030
|
-
|
|
15246
|
+
logger27.error("Reasoning failed", { error });
|
|
15031
15247
|
return err(HaiAIError.REASONING_FAILED, aiM("ai_internalError", {
|
|
15032
15248
|
params: {
|
|
15033
15249
|
error: String(error)
|
|
@@ -15059,8 +15275,8 @@ ${query}` }
|
|
|
15059
15275
|
}
|
|
15060
15276
|
};
|
|
15061
15277
|
}
|
|
15062
|
-
var
|
|
15063
|
-
function createRerankOperations(config) {
|
|
15278
|
+
var logger28 = core.logger.child({ module: "ai", scope: "rerank" });
|
|
15279
|
+
function createRerankOperations(config, loadModels = () => config.llm) {
|
|
15064
15280
|
function normalizeDocuments(documents) {
|
|
15065
15281
|
if (documents.length === 0) {
|
|
15066
15282
|
return { texts: [], ids: [] };
|
|
@@ -15079,7 +15295,7 @@ function createRerankOperations(config) {
|
|
|
15079
15295
|
};
|
|
15080
15296
|
}
|
|
15081
15297
|
async function callRerankAPI(request2) {
|
|
15082
|
-
const resolvedResult = resolveModelEntry(
|
|
15298
|
+
const resolvedResult = resolveModelEntry(await loadModels(request2.model), "rerank", request2.model, {
|
|
15083
15299
|
missingApiKeyMessage: aiM("ai_configError", {
|
|
15084
15300
|
params: { error: "API Key is required for rerank" }
|
|
15085
15301
|
})
|
|
@@ -15104,7 +15320,7 @@ function createRerankOperations(config) {
|
|
|
15104
15320
|
if (request2.returnDocuments) {
|
|
15105
15321
|
body.return_documents = true;
|
|
15106
15322
|
}
|
|
15107
|
-
|
|
15323
|
+
logger28.trace("Calling rerank API", { model: resolved.model, documentCount: texts.length, topN: request2.topN });
|
|
15108
15324
|
try {
|
|
15109
15325
|
const response = await fetch(`${resolved.baseUrl}/v1/rerank`, {
|
|
15110
15326
|
method: "POST",
|
|
@@ -15119,7 +15335,7 @@ function createRerankOperations(config) {
|
|
|
15119
15335
|
const requestId = response.headers.get("x-request-id");
|
|
15120
15336
|
await response.body?.cancel().catch(() => {
|
|
15121
15337
|
});
|
|
15122
|
-
|
|
15338
|
+
logger28.error("Rerank API request failed", {
|
|
15123
15339
|
status: response.status,
|
|
15124
15340
|
providerRequestId: requestId && /^[\w.:-]{1,128}$/.test(requestId) ? requestId : void 0
|
|
15125
15341
|
});
|
|
@@ -15134,11 +15350,11 @@ function createRerankOperations(config) {
|
|
|
15134
15350
|
relevanceScore: item2.relevance_score,
|
|
15135
15351
|
document: item2.document?.text
|
|
15136
15352
|
}));
|
|
15137
|
-
|
|
15353
|
+
logger28.trace("Rerank completed", { resultCount: results.length });
|
|
15138
15354
|
return ok({ model: resolved.model, results });
|
|
15139
15355
|
} catch (error) {
|
|
15140
15356
|
const causeName = error instanceof Error ? error.name : void 0;
|
|
15141
|
-
|
|
15357
|
+
logger28.error("Rerank API call failed", { causeName });
|
|
15142
15358
|
return err(HaiAIError.RERANK_API_ERROR, aiM("ai_rerankApiFailed", {
|
|
15143
15359
|
params: {
|
|
15144
15360
|
error: causeName ?? core.i18n.coreM("core_errorInternal")
|
|
@@ -15174,7 +15390,7 @@ function createRerankOperations(config) {
|
|
|
15174
15390
|
}
|
|
15175
15391
|
};
|
|
15176
15392
|
}
|
|
15177
|
-
var
|
|
15393
|
+
var logger29 = core.logger.child({ module: "ai", scope: "retrieval" });
|
|
15178
15394
|
function createRetrievalOperations(embeddingOps, storeProvider, sourceStore, rerankOps, registry) {
|
|
15179
15395
|
const vectorStoreCache = /* @__PURE__ */ new Map();
|
|
15180
15396
|
function getVectorStore(collection) {
|
|
@@ -15207,7 +15423,7 @@ function createRetrievalOperations(embeddingOps, storeProvider, sourceStore, rer
|
|
|
15207
15423
|
}));
|
|
15208
15424
|
}
|
|
15209
15425
|
await sourceStore.save(source.id, source);
|
|
15210
|
-
|
|
15426
|
+
logger29.debug("Retrieval source added", { sourceId: source.id, collection: source.collection });
|
|
15211
15427
|
return ok(void 0);
|
|
15212
15428
|
},
|
|
15213
15429
|
/**
|
|
@@ -15228,7 +15444,7 @@ function createRetrievalOperations(embeddingOps, storeProvider, sourceStore, rer
|
|
|
15228
15444
|
}));
|
|
15229
15445
|
}
|
|
15230
15446
|
await sourceStore.remove(sourceId);
|
|
15231
|
-
|
|
15447
|
+
logger29.debug("Retrieval source removed", { sourceId });
|
|
15232
15448
|
return ok(void 0);
|
|
15233
15449
|
},
|
|
15234
15450
|
/**
|
|
@@ -15315,21 +15531,21 @@ function createRetrievalOperations(embeddingOps, storeProvider, sourceStore, rer
|
|
|
15315
15531
|
allItems.length = 0;
|
|
15316
15532
|
allItems.push(...reranked);
|
|
15317
15533
|
} else {
|
|
15318
|
-
|
|
15534
|
+
logger29.warn("Rerank failed, falling back to vector scores", { error: rerankResult.error });
|
|
15319
15535
|
}
|
|
15320
15536
|
}
|
|
15321
15537
|
allItems.sort((a, b) => b.score - a.score);
|
|
15322
15538
|
const topK = request2.topK ?? 10;
|
|
15323
15539
|
const limitedItems = allItems.slice(0, topK);
|
|
15324
15540
|
const duration = Date.now() - startTime;
|
|
15325
|
-
|
|
15541
|
+
logger29.trace("Retrieval completed", { queryLength: request2.query.length, resultCount: limitedItems.length, duration });
|
|
15326
15542
|
return ok({
|
|
15327
15543
|
items: limitedItems,
|
|
15328
15544
|
query: request2.query,
|
|
15329
15545
|
duration
|
|
15330
15546
|
});
|
|
15331
15547
|
} catch (error) {
|
|
15332
|
-
|
|
15548
|
+
logger29.error("Retrieval failed", { error });
|
|
15333
15549
|
return err(HaiAIError.RETRIEVAL_FAILED, aiM("ai_internalError", {
|
|
15334
15550
|
params: {
|
|
15335
15551
|
error: String(error)
|
|
@@ -15339,7 +15555,7 @@ function createRetrievalOperations(embeddingOps, storeProvider, sourceStore, rer
|
|
|
15339
15555
|
}
|
|
15340
15556
|
};
|
|
15341
15557
|
}
|
|
15342
|
-
var
|
|
15558
|
+
var logger30 = core.logger.child({ module: "ai", scope: "summary" });
|
|
15343
15559
|
var SUMMARIZE_SYSTEM_PROMPT = `You are a conversation summarizer. Create a concise summary of the conversation that preserves:
|
|
15344
15560
|
1. Key facts and decisions made
|
|
15345
15561
|
2. Important context and background information
|
|
@@ -15397,7 +15613,7 @@ ${INCREMENTAL_SUMMARIZE_SUFFIX.replace("{previousSummary}", options.previousSumm
|
|
|
15397
15613
|
return ok(chatResult.data.choices[0]?.message?.content ?? "");
|
|
15398
15614
|
}
|
|
15399
15615
|
async function summarize(messages, options) {
|
|
15400
|
-
|
|
15616
|
+
logger30.trace("Summarizing messages", { messageCount: messages.length });
|
|
15401
15617
|
try {
|
|
15402
15618
|
const result = await generate(messages, options);
|
|
15403
15619
|
if (!result.success)
|
|
@@ -15409,7 +15625,7 @@ ${INCREMENTAL_SUMMARIZE_SUFFIX.replace("{previousSummary}", options.previousSumm
|
|
|
15409
15625
|
coveredMessages: messages.filter((m) => m.role !== "system").length
|
|
15410
15626
|
});
|
|
15411
15627
|
} catch (error) {
|
|
15412
|
-
|
|
15628
|
+
logger30.error("Context summarization failed", { error });
|
|
15413
15629
|
return err(HaiAIError.CONTEXT_SUMMARIZE_FAILED, aiM("ai_contextSummarizeFailed", {
|
|
15414
15630
|
params: {
|
|
15415
15631
|
error: String(error)
|
|
@@ -15474,7 +15690,8 @@ async function createAISubsystems(config, deps) {
|
|
|
15474
15690
|
);
|
|
15475
15691
|
const memoryStore = useMem0Oss ? null : storeProvider.createRelStore("hai_ai_memory", {
|
|
15476
15692
|
hasObjectId: true,
|
|
15477
|
-
hasScopeIndex: true
|
|
15693
|
+
hasScopeIndex: true,
|
|
15694
|
+
serializeWrites: true
|
|
15478
15695
|
});
|
|
15479
15696
|
const contextStore = storeProvider.createRelStore(
|
|
15480
15697
|
"hai_ai_context",
|
|
@@ -15524,6 +15741,18 @@ async function createAISubsystems(config, deps) {
|
|
|
15524
15741
|
llm: { ...config.llm, models: await llmModels.values() }
|
|
15525
15742
|
};
|
|
15526
15743
|
}
|
|
15744
|
+
async function scenarioModels(scenario, explicit) {
|
|
15745
|
+
if (explicit)
|
|
15746
|
+
return (await llmConfig()).llm;
|
|
15747
|
+
const modelId = config.llm.scenarios?.[scenario] ?? config.llm.scenarios?.default;
|
|
15748
|
+
if (!modelId)
|
|
15749
|
+
return config.llm;
|
|
15750
|
+
const entry = await llmModels.read(modelId);
|
|
15751
|
+
return {
|
|
15752
|
+
...config.llm,
|
|
15753
|
+
models: entry ? [entry.value] : []
|
|
15754
|
+
};
|
|
15755
|
+
}
|
|
15527
15756
|
async function audioConfig() {
|
|
15528
15757
|
return {
|
|
15529
15758
|
...config,
|
|
@@ -15601,16 +15830,11 @@ async function createAISubsystems(config, deps) {
|
|
|
15601
15830
|
);
|
|
15602
15831
|
}
|
|
15603
15832
|
}
|
|
15833
|
+
const embeddingRuntime = createEmbeddingOperations(config, (model) => scenarioModels("embedding", model));
|
|
15604
15834
|
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
|
-
)
|
|
15835
|
+
embed: (request2) => resourceCall(() => embeddingRuntime.embed(request2)),
|
|
15836
|
+
embedText: (text) => resourceCall(() => embeddingRuntime.embedText(text)),
|
|
15837
|
+
embedBatch: (texts) => resourceCall(() => embeddingRuntime.embedBatch(texts))
|
|
15614
15838
|
};
|
|
15615
15839
|
const reasoning = {
|
|
15616
15840
|
run: (query, options) => resourceCall(async () => createReasoningOperations(await llmConfig(), llm).run(query, options)),
|
|
@@ -15618,17 +15842,10 @@ async function createAISubsystems(config, deps) {
|
|
|
15618
15842
|
yield* createReasoningOperations(await llmConfig(), llm).runStream(query, options);
|
|
15619
15843
|
}
|
|
15620
15844
|
};
|
|
15845
|
+
const rerankRuntime = createRerankOperations(config, (model) => scenarioModels("rerank", model));
|
|
15621
15846
|
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
|
-
)
|
|
15847
|
+
rerank: (request2) => resourceCall(() => rerankRuntime.rerank(request2)),
|
|
15848
|
+
rerankTexts: (query, texts, topN) => resourceCall(() => rerankRuntime.rerankTexts(query, texts, topN))
|
|
15632
15849
|
};
|
|
15633
15850
|
const retrieval = Object.assign(
|
|
15634
15851
|
createRetrievalOperations(
|
|
@@ -16163,7 +16380,7 @@ function documentInfo(document) {
|
|
|
16163
16380
|
}
|
|
16164
16381
|
|
|
16165
16382
|
// src/store/providers/ai-store-provider-db.ts
|
|
16166
|
-
var
|
|
16383
|
+
var logger31 = core.logger.child({ module: "ai", scope: "store-provider-db" });
|
|
16167
16384
|
function requireSqlSuccess(result) {
|
|
16168
16385
|
if (!result.success)
|
|
16169
16386
|
throw new Error(result.error.message, { cause: result.error });
|
|
@@ -16188,7 +16405,7 @@ function isMysqlDuplicateIndex(error) {
|
|
|
16188
16405
|
}
|
|
16189
16406
|
return false;
|
|
16190
16407
|
}
|
|
16191
|
-
var ReldbAIRelStore = class {
|
|
16408
|
+
var ReldbAIRelStore = class _ReldbAIRelStore {
|
|
16192
16409
|
sql;
|
|
16193
16410
|
table;
|
|
16194
16411
|
jsonOps;
|
|
@@ -16198,7 +16415,10 @@ var ReldbAIRelStore = class {
|
|
|
16198
16415
|
hasStatus;
|
|
16199
16416
|
hasRefId;
|
|
16200
16417
|
hasScopeIndex;
|
|
16201
|
-
|
|
16418
|
+
hasUpdatedAtIndex;
|
|
16419
|
+
gate;
|
|
16420
|
+
withWriteLock;
|
|
16421
|
+
constructor(sql, table, jsonOps, dbType, options, tx) {
|
|
16202
16422
|
this.sql = {
|
|
16203
16423
|
...sql,
|
|
16204
16424
|
execute: (query, params) => sql.execute(query, params).then(requireSqlSuccess),
|
|
@@ -16213,6 +16433,17 @@ var ReldbAIRelStore = class {
|
|
|
16213
16433
|
this.hasStatus = options?.hasStatus ?? false;
|
|
16214
16434
|
this.hasRefId = options?.hasRefId ?? false;
|
|
16215
16435
|
this.hasScopeIndex = options?.hasScopeIndex ?? false;
|
|
16436
|
+
this.hasUpdatedAtIndex = options?.hasUpdatedAtIndex ?? false;
|
|
16437
|
+
if (options?.serializeWrites && tx) {
|
|
16438
|
+
const gate = `${table}_write_gate`;
|
|
16439
|
+
this.gate = gate;
|
|
16440
|
+
this.withWriteLock = async (write) => requireSqlSuccess(await tx.wrap(async (connection) => {
|
|
16441
|
+
const locked = requireSqlSuccess(await connection.execute(`UPDATE ${gate} SET marker = 1 - marker WHERE id = 1`));
|
|
16442
|
+
if (locked.data.changes !== 1)
|
|
16443
|
+
throw new Error("Missing AI store write gate");
|
|
16444
|
+
return write(new _ReldbAIRelStore(connection, table, jsonOps, dbType, options));
|
|
16445
|
+
})).data;
|
|
16446
|
+
}
|
|
16216
16447
|
}
|
|
16217
16448
|
/** 创建表及索引(幂等) */
|
|
16218
16449
|
async createTable() {
|
|
@@ -16232,6 +16463,11 @@ var ReldbAIRelStore = class {
|
|
|
16232
16463
|
cols.push(`ref_id ${scopeType}`);
|
|
16233
16464
|
cols.push("version VARCHAR(36) NOT NULL", `data ${dataType} NOT NULL`, `created_at BIGINT NOT NULL`, `updated_at BIGINT NOT NULL`);
|
|
16234
16465
|
await this.sql.execute(`CREATE TABLE IF NOT EXISTS ${t} (${cols.join(", ")})`);
|
|
16466
|
+
if (this.gate) {
|
|
16467
|
+
await this.sql.execute(`CREATE TABLE IF NOT EXISTS ${this.gate} (id INTEGER PRIMARY KEY, marker INTEGER NOT NULL)`);
|
|
16468
|
+
const conflict = db === "mysql" ? "ON DUPLICATE KEY UPDATE id = id" : "ON CONFLICT(id) DO NOTHING";
|
|
16469
|
+
await this.sql.execute(`INSERT INTO ${this.gate} (id, marker) VALUES (1, 0) ${conflict}`);
|
|
16470
|
+
}
|
|
16235
16471
|
if (this.hasObjectId)
|
|
16236
16472
|
await this.createIndex(`idx_${t}_object_id`, "object_id");
|
|
16237
16473
|
if (this.hasSessionId)
|
|
@@ -16242,6 +16478,8 @@ var ReldbAIRelStore = class {
|
|
|
16242
16478
|
await this.createIndex(`idx_${t}_status`, "status");
|
|
16243
16479
|
if (this.hasRefId)
|
|
16244
16480
|
await this.createIndex(`idx_${t}_ref_id`, "ref_id");
|
|
16481
|
+
if (this.hasUpdatedAtIndex)
|
|
16482
|
+
await this.createIndex(`idx_${t}_updated_at`, "updated_at, id");
|
|
16245
16483
|
if (this.hasScopeIndex && db === "postgresql")
|
|
16246
16484
|
await this.sql.execute(`CREATE INDEX IF NOT EXISTS idx_${t}_data_gin ON ${t} USING GIN (data jsonb_path_ops)`);
|
|
16247
16485
|
}
|
|
@@ -16387,18 +16625,41 @@ var ReldbAIRelStore = class {
|
|
|
16387
16625
|
let countSql = `SELECT COUNT(*) as cnt FROM ${this.table}`;
|
|
16388
16626
|
if (countConditions.length > 0)
|
|
16389
16627
|
countSql += ` WHERE ${countConditions.join(" AND ")}`;
|
|
16390
|
-
const
|
|
16391
|
-
const total = countResult.success && countResult.data != null ? countResult.data.cnt : 0;
|
|
16628
|
+
const count = requireSqlSuccess(await this.sql.get(countSql, countParams)).data;
|
|
16392
16629
|
const { sql, params } = this.buildQuery({ ...filter, limit: void 0 });
|
|
16393
16630
|
const pagedSql = `${sql} LIMIT ? OFFSET ?`;
|
|
16394
|
-
const
|
|
16395
|
-
|
|
16396
|
-
|
|
16631
|
+
const rows = requireSqlSuccess(await this.sql.query(pagedSql, [...params, page.limit, page.offset])).data;
|
|
16632
|
+
return {
|
|
16633
|
+
items: rows.map((row) => this.decodeData(row.data)),
|
|
16634
|
+
total: Number(count?.cnt ?? 0)
|
|
16635
|
+
};
|
|
16397
16636
|
}
|
|
16398
16637
|
async remove(id3) {
|
|
16399
16638
|
await this.sql.execute(`DELETE FROM ${this.table} WHERE id = ?`, [id3]);
|
|
16400
16639
|
return true;
|
|
16401
16640
|
}
|
|
16641
|
+
async queryKeys(filter, cursor) {
|
|
16642
|
+
const params = [];
|
|
16643
|
+
const conditions = this.buildAllConditions(filter, params);
|
|
16644
|
+
if (cursor) {
|
|
16645
|
+
conditions.push("(updated_at > ? OR (updated_at = ? AND id > ?))");
|
|
16646
|
+
params.push(cursor.updatedAt, cursor.updatedAt, cursor.id);
|
|
16647
|
+
}
|
|
16648
|
+
const where = conditions.length ? ` WHERE ${conditions.join(" AND ")}` : "";
|
|
16649
|
+
const result = await this.sql.query(
|
|
16650
|
+
`SELECT id, updated_at, version FROM ${this.table}${where} ORDER BY updated_at, id LIMIT ?`,
|
|
16651
|
+
[...params, filter.limit ?? 64]
|
|
16652
|
+
);
|
|
16653
|
+
return requireSqlSuccess(result).data.map((row) => ({
|
|
16654
|
+
id: row.id,
|
|
16655
|
+
updatedAt: Number(row.updated_at),
|
|
16656
|
+
version: row.version
|
|
16657
|
+
}));
|
|
16658
|
+
}
|
|
16659
|
+
async removeIfUnchanged(id3, version) {
|
|
16660
|
+
const deleted = await this.sql.execute(`DELETE FROM ${this.table} WHERE id = ? AND version = ?`, [id3, version]);
|
|
16661
|
+
return requireSqlSuccess(deleted).data.changes === 1;
|
|
16662
|
+
}
|
|
16402
16663
|
async removeBy(filter) {
|
|
16403
16664
|
const params = [];
|
|
16404
16665
|
const conditions = this.buildAllConditions(filter, params);
|
|
@@ -16407,19 +16668,19 @@ var ReldbAIRelStore = class {
|
|
|
16407
16668
|
const whereClause = ` WHERE ${conditions.join(" AND ")}`;
|
|
16408
16669
|
countSql += whereClause;
|
|
16409
16670
|
const countResult2 = await this.sql.get(countSql, [...params]);
|
|
16410
|
-
const count2 = countResult2.success && countResult2.data != null ? countResult2.data.cnt : 0;
|
|
16671
|
+
const count2 = countResult2.success && countResult2.data != null ? Number(countResult2.data.cnt) : 0;
|
|
16411
16672
|
await this.sql.execute(`DELETE FROM ${this.table}${whereClause}`, params);
|
|
16412
16673
|
return count2;
|
|
16413
16674
|
}
|
|
16414
16675
|
const countResult = await this.sql.get(countSql);
|
|
16415
|
-
const count = countResult.success && countResult.data != null ? countResult.data.cnt : 0;
|
|
16676
|
+
const count = countResult.success && countResult.data != null ? Number(countResult.data.cnt) : 0;
|
|
16416
16677
|
await this.sql.execute(`DELETE FROM ${this.table}`);
|
|
16417
16678
|
return count;
|
|
16418
16679
|
}
|
|
16419
16680
|
async count(filter) {
|
|
16420
|
-
if (!filter?.where && !filter?.objectId && !filter?.sessionId && !filter?.status && !filter?.refId) {
|
|
16681
|
+
if (!filter?.where && !filter?.objectId && !filter?.sessionId && !filter?.status && !filter?.refId && !filter?.scope && filter?.updatedBefore === void 0) {
|
|
16421
16682
|
const result2 = await this.sql.get(`SELECT COUNT(*) as cnt FROM ${this.table}`);
|
|
16422
|
-
return result2.success && result2.data != null ? result2.data.cnt : 0;
|
|
16683
|
+
return result2.success && result2.data != null ? Number(result2.data.cnt) : 0;
|
|
16423
16684
|
}
|
|
16424
16685
|
const params = [];
|
|
16425
16686
|
const conditions = this.buildAllConditions(filter, params);
|
|
@@ -16427,7 +16688,7 @@ var ReldbAIRelStore = class {
|
|
|
16427
16688
|
if (conditions.length > 0)
|
|
16428
16689
|
sql += ` WHERE ${conditions.join(" AND ")}`;
|
|
16429
16690
|
const result = await this.sql.get(sql, params);
|
|
16430
|
-
return result.success && result.data != null ? result.data.cnt : 0;
|
|
16691
|
+
return result.success && result.data != null ? Number(result.data.cnt) : 0;
|
|
16431
16692
|
}
|
|
16432
16693
|
async clear(filter) {
|
|
16433
16694
|
if (!filter?.where && !filter?.objectId && !filter?.sessionId && !filter?.status && !filter?.refId) {
|
|
@@ -16528,6 +16789,10 @@ var ReldbAIRelStore = class {
|
|
|
16528
16789
|
}
|
|
16529
16790
|
buildAllConditions(filter, params) {
|
|
16530
16791
|
const conditions = [];
|
|
16792
|
+
if (filter.updatedBefore !== void 0) {
|
|
16793
|
+
conditions.push("updated_at < ?");
|
|
16794
|
+
params.push(filter.updatedBefore);
|
|
16795
|
+
}
|
|
16531
16796
|
if (filter.objectId && this.hasObjectId) {
|
|
16532
16797
|
conditions.push("object_id = ?");
|
|
16533
16798
|
params.push(filter.objectId);
|
|
@@ -16567,47 +16832,69 @@ var ReldbAIRelStore = class {
|
|
|
16567
16832
|
if (op.$in !== void 0 && Array.isArray(op.$in)) {
|
|
16568
16833
|
const { sql: jsonSql, params: jsonParams } = this.jsonOps.extract("data", path);
|
|
16569
16834
|
params.push(...jsonParams);
|
|
16570
|
-
conditions.push(`${jsonSql} IN (${op.$in.map(() =>
|
|
16571
|
-
params.push(...op.$in);
|
|
16835
|
+
conditions.push(`${jsonSql} IN (${op.$in.map(() => this.jsonComparisonParameter()).join(", ")})`);
|
|
16836
|
+
params.push(...op.$in.map((value2) => this.jsonComparisonValue(value2)));
|
|
16837
|
+
}
|
|
16838
|
+
if (op.$ne !== void 0) {
|
|
16839
|
+
const { sql: expression, params: pathParams } = this.jsonOps.extract("data", path);
|
|
16840
|
+
conditions.push(`COALESCE(${expression} <> ${this.jsonComparisonParameter()}, TRUE)`);
|
|
16841
|
+
params.push(...pathParams, this.jsonComparisonValue(op.$ne));
|
|
16572
16842
|
}
|
|
16573
16843
|
if (op.$gte !== void 0) {
|
|
16574
16844
|
const { sql: j, params: p } = this.jsonOps.extract("data", path);
|
|
16575
16845
|
params.push(...p);
|
|
16576
|
-
conditions.push(`${j} >=
|
|
16577
|
-
params.push(op.$gte);
|
|
16846
|
+
conditions.push(`${j} >= ${this.jsonComparisonParameter()}`);
|
|
16847
|
+
params.push(this.jsonComparisonValue(op.$gte));
|
|
16578
16848
|
}
|
|
16579
16849
|
if (op.$gt !== void 0) {
|
|
16580
16850
|
const { sql: j, params: p } = this.jsonOps.extract("data", path);
|
|
16581
16851
|
params.push(...p);
|
|
16582
|
-
conditions.push(`${j} >
|
|
16583
|
-
params.push(op.$gt);
|
|
16852
|
+
conditions.push(`${j} > ${this.jsonComparisonParameter()}`);
|
|
16853
|
+
params.push(this.jsonComparisonValue(op.$gt));
|
|
16584
16854
|
}
|
|
16585
16855
|
if (op.$lte !== void 0) {
|
|
16586
16856
|
const { sql: j, params: p } = this.jsonOps.extract("data", path);
|
|
16587
16857
|
params.push(...p);
|
|
16588
|
-
conditions.push(`${j} <=
|
|
16589
|
-
params.push(op.$lte);
|
|
16858
|
+
conditions.push(`${j} <= ${this.jsonComparisonParameter()}`);
|
|
16859
|
+
params.push(this.jsonComparisonValue(op.$lte));
|
|
16590
16860
|
}
|
|
16591
16861
|
if (op.$lt !== void 0) {
|
|
16592
16862
|
const { sql: j, params: p } = this.jsonOps.extract("data", path);
|
|
16593
16863
|
params.push(...p);
|
|
16594
|
-
conditions.push(`${j} <
|
|
16595
|
-
params.push(op.$lt);
|
|
16864
|
+
conditions.push(`${j} < ${this.jsonComparisonParameter()}`);
|
|
16865
|
+
params.push(this.jsonComparisonValue(op.$lt));
|
|
16596
16866
|
}
|
|
16597
16867
|
} else {
|
|
16598
16868
|
const { sql: jsonSql, params: jsonParams } = this.jsonOps.extract("data", path);
|
|
16599
16869
|
params.push(...jsonParams);
|
|
16600
|
-
conditions.push(`${jsonSql} =
|
|
16601
|
-
params.push(value);
|
|
16870
|
+
conditions.push(`${jsonSql} = ${this.jsonComparisonParameter()}`);
|
|
16871
|
+
params.push(this.jsonComparisonValue(value));
|
|
16602
16872
|
}
|
|
16603
16873
|
}
|
|
16604
16874
|
return conditions;
|
|
16605
16875
|
}
|
|
16876
|
+
jsonComparisonParameter() {
|
|
16877
|
+
if (this.dbType === "postgresql")
|
|
16878
|
+
return "?::jsonb";
|
|
16879
|
+
return this.dbType === "mysql" ? "CAST(? AS JSON)" : "?";
|
|
16880
|
+
}
|
|
16881
|
+
jsonComparisonValue(value) {
|
|
16882
|
+
if (this.dbType !== "sqlite")
|
|
16883
|
+
return JSON.stringify(value);
|
|
16884
|
+
return typeof value === "boolean" ? Number(value) : value;
|
|
16885
|
+
}
|
|
16606
16886
|
isWhereOperator(value) {
|
|
16607
16887
|
if (typeof value !== "object" || value === null || Array.isArray(value))
|
|
16608
16888
|
return false;
|
|
16609
16889
|
const keys = Object.keys(value);
|
|
16610
|
-
return keys.length > 0 && keys.every((k) => [
|
|
16890
|
+
return keys.length > 0 && keys.every((k) => [
|
|
16891
|
+
"$in",
|
|
16892
|
+
"$ne",
|
|
16893
|
+
"$gte",
|
|
16894
|
+
"$gt",
|
|
16895
|
+
"$lte",
|
|
16896
|
+
"$lt"
|
|
16897
|
+
].includes(k));
|
|
16611
16898
|
}
|
|
16612
16899
|
};
|
|
16613
16900
|
function requireVecdbSuccess(result) {
|
|
@@ -16662,7 +16949,7 @@ function createDbStoreProvider(deps) {
|
|
|
16662
16949
|
return dbType !== "sqlite" && sharedVector ? "shared" : "local";
|
|
16663
16950
|
},
|
|
16664
16951
|
createRelStore(name, options) {
|
|
16665
|
-
const store = new ReldbAIRelStore(sql, name, jsonOps, dbType, options);
|
|
16952
|
+
const store = new ReldbAIRelStore(sql, name, jsonOps, dbType, options, deps.tx);
|
|
16666
16953
|
const stores = relStores.get(name) ?? [];
|
|
16667
16954
|
stores.push(store);
|
|
16668
16955
|
relStores.set(name, stores);
|
|
@@ -16700,7 +16987,7 @@ function createDbStoreProvider(deps) {
|
|
|
16700
16987
|
if (result.status === "rejected")
|
|
16701
16988
|
throw result.reason;
|
|
16702
16989
|
}
|
|
16703
|
-
|
|
16990
|
+
logger31.debug("DB store provider initialized", { tableCount: relStores.size });
|
|
16704
16991
|
}
|
|
16705
16992
|
},
|
|
16706
16993
|
async close() {
|
|
@@ -16714,6 +17001,7 @@ function isDbStoreAvailable() {
|
|
|
16714
17001
|
function createDbStoreProviderFromModules() {
|
|
16715
17002
|
return createDbStoreProvider({
|
|
16716
17003
|
sql: reldb.sql,
|
|
17004
|
+
tx: reldb.tx,
|
|
16717
17005
|
jsonOps: reldb.json,
|
|
16718
17006
|
dbType: reldb.config?.type,
|
|
16719
17007
|
vecdb
|
|
@@ -16722,7 +17010,14 @@ function createDbStoreProviderFromModules() {
|
|
|
16722
17010
|
|
|
16723
17011
|
// src/store/providers/ai-store-provider-memory.ts
|
|
16724
17012
|
function isWhereOperator(value) {
|
|
16725
|
-
return typeof value === "object" && value !== null && [
|
|
17013
|
+
return typeof value === "object" && value !== null && [
|
|
17014
|
+
"$in",
|
|
17015
|
+
"$ne",
|
|
17016
|
+
"$gte",
|
|
17017
|
+
"$gt",
|
|
17018
|
+
"$lte",
|
|
17019
|
+
"$lt"
|
|
17020
|
+
].some((key) => key in value);
|
|
16726
17021
|
}
|
|
16727
17022
|
function compare(left, right) {
|
|
16728
17023
|
if (typeof left === "number" && typeof right === "number")
|
|
@@ -16732,6 +17027,8 @@ function compare(left, right) {
|
|
|
16732
17027
|
function matchesOperator(value, operator) {
|
|
16733
17028
|
if (operator.$in && !operator.$in.some((candidate) => Object.is(candidate, value)))
|
|
16734
17029
|
return false;
|
|
17030
|
+
if (operator.$ne !== void 0 && Object.is(operator.$ne, value))
|
|
17031
|
+
return false;
|
|
16735
17032
|
if (operator.$gte !== void 0 && compare(value, operator.$gte) < 0)
|
|
16736
17033
|
return false;
|
|
16737
17034
|
if (operator.$gt !== void 0 && compare(value, operator.$gt) <= 0)
|
|
@@ -16743,6 +17040,8 @@ function matchesOperator(value, operator) {
|
|
|
16743
17040
|
return true;
|
|
16744
17041
|
}
|
|
16745
17042
|
function matchesRecord(record, filter) {
|
|
17043
|
+
if (filter.updatedBefore !== void 0 && record.updatedAt >= filter.updatedBefore)
|
|
17044
|
+
return false;
|
|
16746
17045
|
if (filter.objectId !== void 0 && record.scope?.objectId !== filter.objectId)
|
|
16747
17046
|
return false;
|
|
16748
17047
|
if (filter.sessionId !== void 0 && record.scope?.sessionId !== filter.sessionId)
|
|
@@ -16810,7 +17109,8 @@ function createRelStore(records) {
|
|
|
16810
17109
|
records.set(id3, {
|
|
16811
17110
|
version,
|
|
16812
17111
|
data: structuredClone(input.data),
|
|
16813
|
-
scope: structuredClone(input.scope ?? record?.scope)
|
|
17112
|
+
scope: structuredClone(input.scope ?? record?.scope),
|
|
17113
|
+
updatedAt: Date.now()
|
|
16814
17114
|
});
|
|
16815
17115
|
return version;
|
|
16816
17116
|
},
|
|
@@ -16818,7 +17118,8 @@ function createRelStore(records) {
|
|
|
16818
17118
|
records.set(id3, {
|
|
16819
17119
|
version: crypto.randomUUID(),
|
|
16820
17120
|
data: structuredClone(data),
|
|
16821
|
-
scope: structuredClone(scope)
|
|
17121
|
+
scope: structuredClone(scope),
|
|
17122
|
+
updatedAt: Date.now()
|
|
16822
17123
|
});
|
|
16823
17124
|
},
|
|
16824
17125
|
async saveMany(items) {
|
|
@@ -16826,7 +17127,8 @@ function createRelStore(records) {
|
|
|
16826
17127
|
records.set(item2.id, {
|
|
16827
17128
|
version: crypto.randomUUID(),
|
|
16828
17129
|
data: structuredClone(item2.data),
|
|
16829
|
-
scope: structuredClone(item2.scope)
|
|
17130
|
+
scope: structuredClone(item2.scope),
|
|
17131
|
+
updatedAt: Date.now()
|
|
16830
17132
|
});
|
|
16831
17133
|
}
|
|
16832
17134
|
},
|
|
@@ -16846,6 +17148,14 @@ function createRelStore(records) {
|
|
|
16846
17148
|
async remove(id3) {
|
|
16847
17149
|
return records.delete(id3);
|
|
16848
17150
|
},
|
|
17151
|
+
async queryKeys(filter, cursor) {
|
|
17152
|
+
return [
|
|
17153
|
+
...records.entries()
|
|
17154
|
+
].filter(([id3, record]) => 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);
|
|
17155
|
+
},
|
|
17156
|
+
async removeIfUnchanged(id3, version) {
|
|
17157
|
+
return records.get(id3)?.version === version && records.delete(id3);
|
|
17158
|
+
},
|
|
16849
17159
|
async removeBy(filter) {
|
|
16850
17160
|
const ids = Array.from(records.entries()).filter(([, record]) => matchesRecord(record, filter)).map(([id3]) => id3);
|
|
16851
17161
|
for (const id3 of ids)
|
|
@@ -16950,7 +17260,7 @@ function createMemoryStoreProvider() {
|
|
|
16950
17260
|
}
|
|
16951
17261
|
|
|
16952
17262
|
// src/ai-main.ts
|
|
16953
|
-
var
|
|
17263
|
+
var logger32 = core.logger.child({ module: "ai", scope: "main" });
|
|
16954
17264
|
var initInProgress = false;
|
|
16955
17265
|
var initCompletion = null;
|
|
16956
17266
|
var closingPromise = null;
|
|
@@ -17129,7 +17439,7 @@ async function resetAllState() {
|
|
|
17129
17439
|
try {
|
|
17130
17440
|
await storeProvider.close();
|
|
17131
17441
|
} catch (error) {
|
|
17132
|
-
|
|
17442
|
+
logger32.error("AI store provider close failed", { error });
|
|
17133
17443
|
}
|
|
17134
17444
|
}
|
|
17135
17445
|
}
|
|
@@ -17146,7 +17456,7 @@ var streamOperations = {
|
|
|
17146
17456
|
var ai = {
|
|
17147
17457
|
async init(config, options) {
|
|
17148
17458
|
if (initInProgress || closingPromise) {
|
|
17149
|
-
|
|
17459
|
+
logger32.warn("AI init already in progress, skipping concurrent call");
|
|
17150
17460
|
return err(HaiAIError.INIT_IN_PROGRESS, aiM("ai_initInProgress"));
|
|
17151
17461
|
}
|
|
17152
17462
|
initInProgress = true;
|
|
@@ -17157,15 +17467,15 @@ var ai = {
|
|
|
17157
17467
|
let closingPrevious = false;
|
|
17158
17468
|
try {
|
|
17159
17469
|
if (currentConfig) {
|
|
17160
|
-
|
|
17470
|
+
logger32.warn("AI module is already initialized, reinitializing");
|
|
17161
17471
|
closingPrevious = true;
|
|
17162
17472
|
await resetAllState();
|
|
17163
17473
|
closingPrevious = false;
|
|
17164
17474
|
}
|
|
17165
|
-
|
|
17475
|
+
logger32.info("Initializing AI module");
|
|
17166
17476
|
const parseResult = AIConfigSchema.safeParse(config ?? {});
|
|
17167
17477
|
if (!parseResult.success) {
|
|
17168
|
-
|
|
17478
|
+
logger32.error("AI config validation failed", { error: parseResult.error.message });
|
|
17169
17479
|
return err(
|
|
17170
17480
|
HaiAIError.CONFIGURATION_ERROR,
|
|
17171
17481
|
aiM("ai_configError", {
|
|
@@ -17182,7 +17492,7 @@ var ai = {
|
|
|
17182
17492
|
storeProvider = createDbStoreProviderFromModules();
|
|
17183
17493
|
} else {
|
|
17184
17494
|
storeProvider = createMemoryStoreProvider();
|
|
17185
|
-
|
|
17495
|
+
logger32.warn("AI is using the ephemeral in-memory store; initialize reldb and vecdb before ai.init() for persistent data");
|
|
17186
17496
|
}
|
|
17187
17497
|
if (core.module.requiresSharedState(process2.env) && storeProvider.stateScope !== "shared")
|
|
17188
17498
|
return err(HaiAIError.CONFIGURATION_ERROR, aiM("ai_sharedBackendRequired"));
|
|
@@ -17218,17 +17528,17 @@ var ai = {
|
|
|
17218
17528
|
currentA2AConfig = parsed.a2a;
|
|
17219
17529
|
currentA2AStores = subs.a2aStores;
|
|
17220
17530
|
currentConfig = parsed;
|
|
17221
|
-
|
|
17531
|
+
logger32.info("AI module initialized", { model: parsed.llm?.model });
|
|
17222
17532
|
return ok(void 0);
|
|
17223
17533
|
} catch (error) {
|
|
17224
17534
|
if (!closingPrevious) {
|
|
17225
17535
|
try {
|
|
17226
17536
|
await resetAllState();
|
|
17227
17537
|
} catch (cleanupError) {
|
|
17228
|
-
|
|
17538
|
+
logger32.error("AI initialization cleanup failed", { error: cleanupError });
|
|
17229
17539
|
}
|
|
17230
17540
|
}
|
|
17231
|
-
|
|
17541
|
+
logger32.error("AI module initialization failed", { error });
|
|
17232
17542
|
return err(
|
|
17233
17543
|
HaiAIError.CONFIGURATION_ERROR,
|
|
17234
17544
|
aiM("ai_initFailed", {
|
|
@@ -17318,9 +17628,9 @@ var ai = {
|
|
|
17318
17628
|
closingPromise = (async () => {
|
|
17319
17629
|
if (initCompletion)
|
|
17320
17630
|
await initCompletion;
|
|
17321
|
-
|
|
17631
|
+
logger32.info("Closing AI module");
|
|
17322
17632
|
await resetAllState();
|
|
17323
|
-
|
|
17633
|
+
logger32.info("AI module closed");
|
|
17324
17634
|
})().finally(() => {
|
|
17325
17635
|
closingPromise = null;
|
|
17326
17636
|
});
|