@h-ai/ai 1.0.0-beta.34 → 1.0.0-beta.36

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/dist/index.js CHANGED
@@ -1,16 +1,15 @@
1
- import { platformOptionsSchema, platformRunSchema, AIConfigSchema, MemoryConfigSchema, ModelEntrySchema, AudioModelEntrySchema, ImageModelEntrySchema, MCPExternalServerSchema, RetrievalSourceSchema, KnowledgeConfigSchema, TokenConfigSchema, SummaryConfigSchema, CompressConfigSchema, serializePlayableAudio, ACPConfigSchema, ACPAgentSchema, ACPWorkspaceSchema, AudioConfigSchema, resolveModelEntry, resolveAudioModel, ensureAudioCredential, platformScopeSchema, resolveModelApi, platformRequestSchema, sessionIdentitySchema, branchNameSchema, ImageConfigSchema, resolveImageModel, ACPPublishSchema } from './chunk-IVEOIRBO.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-IVEOIRBO.js';
1
+ import { platformOptionsSchema, platformRunSchema, serializePlayableAudio, resolveModelEntry, resolveModelApi, resolveImageModel, resolveAudioModel, ensureAudioCredential, AIConfigSchema, MemoryConfigSchema, ModelEntrySchema, AudioModelEntrySchema, ImageModelEntrySchema, MCPExternalServerSchema, RetrievalSourceSchema, KnowledgeConfigSchema, TokenConfigSchema, SummaryConfigSchema, CompressConfigSchema, ACPConfigSchema, ACPAgentSchema, ACPWorkspaceSchema, AudioConfigSchema, platformScopeSchema, platformRequestSchema, sessionIdentitySchema, branchNameSchema, ImageConfigSchema, ACPPublishSchema } from './chunk-XURRFCRC.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 } from './chunk-XURRFCRC.js';
3
3
  import { parseHtmlFile } from './chunk-OWR55FRO.js';
4
- import { aiM } from './chunk-HZDINADT.js';
5
- import { HaiAIError } from './chunk-C6T3ONVG.js';
6
- export { HaiAIError } from './chunk-C6T3ONVG.js';
7
- import { TaskState, SendMessageRequest, Message, Role, AgentCard, TaskStatus, Task } from '@a2a-js/sdk';
8
- export { Message, Part, Role, SendMessageRequest, Task, TaskArtifactUpdateEvent, TaskState, TaskStatus, TaskStatusUpdateEvent } from '@a2a-js/sdk';
9
- import { JsonRpcTransportHandler, ServerCallContext, AgentEvent, RequestContext, ResultManager, DefaultExecutionEventBus } from '@a2a-js/sdk/server';
10
- export { AgentEvent } from '@a2a-js/sdk/server';
4
+ import { aiM } from './chunk-CLCPQTW2.js';
5
+ import { HaiAIError } from './chunk-A3DZ6LJ5.js';
6
+ export { HaiAIError } from './chunk-A3DZ6LJ5.js';
7
+ import { TaskState, TaskStatusUpdateEvent, TaskStatus, TaskArtifactUpdateEvent, Task, SendMessageRequest, Part, Message, Role, AgentCard } from '@a2a-js/sdk';
8
+ export { Role, TaskState } from '@a2a-js/sdk';
9
+ import { AgentEvent, JsonRpcTransportHandler, ServerCallContext, RequestContext, ResultManager, DefaultExecutionEventBus } from '@a2a-js/sdk/server';
11
10
  import process2 from 'process';
12
- import { core, err, ok } from '@h-ai/core';
13
- import { datapipe, HaiDatapipeError } from '@h-ai/datapipe';
11
+ import { core } from '@h-ai/core';
12
+ import { datapipe } from '@h-ai/datapipe';
14
13
  import { JsonRpcTransportFactory, ClientFactory } from '@a2a-js/sdk/client';
15
14
  import { Buffer } from 'buffer';
16
15
  import { createHash, randomBytes, randomUUID } from 'crypto';
@@ -33,6 +32,7 @@ import { gunzipSync } from 'zlib';
33
32
  import { FormData as FormData$1, Agent, fetch as fetch$1 } from 'undici';
34
33
  import OpenAI3, { toFile } from 'openai';
35
34
  import { nanoid } from 'nanoid';
35
+ import { Worker } from 'worker_threads';
36
36
  import dns from 'dns';
37
37
  import { BlockList, isIP } from 'net';
38
38
  import { ToolSchema, PromptMessageSchema, TextResourceContentsSchema, BlobResourceContentsSchema, ListToolsRequestSchema, CallToolRequestSchema, CallToolResultSchema } from '@modelcontextprotocol/sdk/types.js';
@@ -41,11 +41,9 @@ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
41
41
  import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
42
42
  import { Server } from '@modelcontextprotocol/sdk/server/index.js';
43
43
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
44
- export { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
45
- export { SSEServerTransport } from '@modelcontextprotocol/sdk/server/sse.js';
46
- export { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
44
+ import { SSEServerTransport } from '@modelcontextprotocol/sdk/server/sse.js';
45
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
47
46
  import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
48
- export { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
49
47
  import { reldb } from '@h-ai/reldb';
50
48
  import { vecdb, HaiVecdbError } from '@h-ai/vecdb';
51
49
  import { tools } from '@h-ai/tools';
@@ -704,10 +702,10 @@ async function executeRemoteAgentCall(remoteUrl, message, options) {
704
702
  } else {
705
703
  result = {};
706
704
  }
707
- return ok(result);
705
+ return core.ok(result);
708
706
  } catch (error) {
709
707
  const errorName = error instanceof Error ? error.name : "UnknownError";
710
- return err(HaiAIError.A2A_REMOTE_CALL_FAILED, aiM("ai_a2aRemoteCallFailed", {
708
+ return core.err(HaiAIError.A2A_REMOTE_CALL_FAILED, aiM("ai_a2aRemoteCallFailed", {
711
709
  params: { url: safeLabel, error: errorName }
712
710
  }));
713
711
  }
@@ -734,10 +732,10 @@ function createA2AOperations(options, deps) {
734
732
  close: () => requestHandler.close(),
735
733
  registerExecutor() {
736
734
  logger2.warn("A2A executor already registered, ignoring duplicate registerExecutor call");
737
- return ok(void 0);
735
+ return core.ok(void 0);
738
736
  },
739
737
  getAgentCard() {
740
- return ok(buildAgentCardDocument(agentCardConfig));
738
+ return core.ok(buildAgentCardDocument(agentCardConfig));
741
739
  },
742
740
  async handleRequest(requestBody, context) {
743
741
  const agentId = typeof context?.agentId === "string" ? context.agentId : void 0;
@@ -774,9 +772,9 @@ function createA2AOperations(options, deps) {
774
772
  },
775
773
  { offset: filter.offset ?? 0, limit: filter.limit ?? 50 }
776
774
  );
777
- return ok(page);
775
+ return core.ok(page);
778
776
  } catch {
779
- return err(HaiAIError.A2A_LIST_MESSAGES_FAILED, aiM("ai_a2aListMessagesFailed"));
777
+ return core.err(HaiAIError.A2A_LIST_MESSAGES_FAILED, aiM("ai_a2aListMessagesFailed"));
780
778
  }
781
779
  },
782
780
  async callRemoteAgent(remoteUrl, message, options2) {
@@ -792,14 +790,14 @@ function createA2ALazyProxy(deps) {
792
790
  }
793
791
  const a2aConfig = deps.getA2AConfig();
794
792
  if (!a2aConfig) {
795
- return err(HaiAIError.A2A_NOT_CONFIGURED, aiM("ai_a2aNotConfigured"));
793
+ return core.err(HaiAIError.A2A_NOT_CONFIGURED, aiM("ai_a2aNotConfigured"));
796
794
  }
797
795
  if (deps.getA2AImpl()) {
798
- return err(HaiAIError.CONFIGURATION_ERROR, aiM("ai_a2aExecutorAlreadyRegistered"));
796
+ return core.err(HaiAIError.CONFIGURATION_ERROR, aiM("ai_a2aExecutorAlreadyRegistered"));
799
797
  }
800
798
  const stores = deps.getStores();
801
799
  if (!stores) {
802
- return err(HaiAIError.STORE_FAILED, aiM("ai_internalError", {
800
+ return core.err(HaiAIError.STORE_FAILED, aiM("ai_internalError", {
803
801
  params: { error: "StoreProvider not available" }
804
802
  }));
805
803
  }
@@ -810,7 +808,7 @@ function createA2ALazyProxy(deps) {
810
808
  );
811
809
  deps.setA2AImpl(impl);
812
810
  logger2.info("A2A executor registered", { agentName: a2aConfig.agentCard.name });
813
- return ok(void 0);
811
+ return core.ok(void 0);
814
812
  },
815
813
  getAgentCard() {
816
814
  const impl = deps.getA2AImpl();
@@ -818,10 +816,10 @@ function createA2ALazyProxy(deps) {
818
816
  return impl.getAgentCard();
819
817
  const a2aConfig = deps.getA2AConfig();
820
818
  if (a2aConfig)
821
- return ok(buildAgentCardDocument({ ...a2aConfig.agentCard, security: a2aConfig.security }));
819
+ return core.ok(buildAgentCardDocument({ ...a2aConfig.agentCard, security: a2aConfig.security }));
822
820
  if (!deps.isInitialized())
823
821
  return deps.notInitializedResult();
824
- return err(HaiAIError.A2A_NOT_CONFIGURED, aiM("ai_a2aNotConfigured"));
822
+ return core.err(HaiAIError.A2A_NOT_CONFIGURED, aiM("ai_a2aNotConfigured"));
825
823
  },
826
824
  async handleRequest(requestBody, context) {
827
825
  const impl = deps.getA2AImpl();
@@ -846,7 +844,7 @@ function createA2ALazyProxy(deps) {
846
844
  return impl.listMessages(filter);
847
845
  if (!deps.isInitialized())
848
846
  return deps.notInitializedResult();
849
- return err(HaiAIError.A2A_NOT_CONFIGURED, aiM("ai_a2aNotConfigured"));
847
+ return core.err(HaiAIError.A2A_NOT_CONFIGURED, aiM("ai_a2aNotConfigured"));
850
848
  },
851
849
  async callRemoteAgent(remoteUrl, message, options) {
852
850
  const impl = deps.getA2AImpl();
@@ -898,7 +896,7 @@ var mappings = {
898
896
  function acpError(error) {
899
897
  const failure = error instanceof ACPFailure ? error : new ACPFailure(error instanceof ZodError ? "invalid" : "failed");
900
898
  const [code, message] = mappings[failure.kind];
901
- return err(HaiAIError[code], aiM(message), failure.details);
899
+ return core.err(HaiAIError[code], aiM(message), failure.details);
902
900
  }
903
901
 
904
902
  // src/acp/ai-acp-adapters.ts
@@ -1238,11 +1236,11 @@ function createResourceRegistry(store, schema, configured, isOpen) {
1238
1236
  }
1239
1237
  async function protect(operation) {
1240
1238
  if (!isOpen())
1241
- return err(HaiAIError.NOT_INITIALIZED, aiM("ai_notInitialized"));
1239
+ return core.err(HaiAIError.NOT_INITIALIZED, aiM("ai_notInitialized"));
1242
1240
  try {
1243
- return ok(await operation());
1241
+ return core.ok(await operation());
1244
1242
  } catch {
1245
- return err(
1243
+ return core.err(
1246
1244
  HaiAIError.RESOURCE_OPERATION_FAILED,
1247
1245
  aiM("ai_resourceOperationFailed")
1248
1246
  );
@@ -1250,34 +1248,34 @@ function createResourceRegistry(store, schema, configured, isOpen) {
1250
1248
  }
1251
1249
  async function write(input, update, expectedVersion) {
1252
1250
  if (!isOpen())
1253
- return err(HaiAIError.NOT_INITIALIZED, aiM("ai_notInitialized"));
1251
+ return core.err(HaiAIError.NOT_INITIALIZED, aiM("ai_notInitialized"));
1254
1252
  const parsed = schema.safeParse(input);
1255
1253
  if (!parsed.success || !parsed.data.id)
1256
- return err(HaiAIError.RESOURCE_INVALID, aiM("ai_resourceInvalid"));
1254
+ return core.err(HaiAIError.RESOURCE_INVALID, aiM("ai_resourceInvalid"));
1257
1255
  const value = parsed.data;
1258
1256
  if (config.has(value.id))
1259
- return err(HaiAIError.RESOURCE_READ_ONLY, aiM("ai_resourceReadOnly"));
1257
+ return core.err(HaiAIError.RESOURCE_READ_ONLY, aiM("ai_resourceReadOnly"));
1260
1258
  try {
1261
1259
  const previous = await store.readVersioned(value.id);
1262
1260
  const exists = previous && !previous.data.__deleted;
1263
1261
  if (update && !exists)
1264
- return err(HaiAIError.RESOURCE_NOT_FOUND, aiM("ai_resourceNotFound"));
1262
+ return core.err(HaiAIError.RESOURCE_NOT_FOUND, aiM("ai_resourceNotFound"));
1265
1263
  if (!update && exists || expectedVersion !== void 0 && expectedVersion !== previous?.version) {
1266
- return err(HaiAIError.RESOURCE_CONFLICT, aiM("ai_resourceConflict"));
1264
+ return core.err(HaiAIError.RESOURCE_CONFLICT, aiM("ai_resourceConflict"));
1267
1265
  }
1268
1266
  const version = await store.compareAndSwap(value.id, {
1269
1267
  expectedVersion: previous?.version,
1270
1268
  data: value
1271
1269
  });
1272
1270
  if (!version)
1273
- return err(HaiAIError.RESOURCE_CONFLICT, aiM("ai_resourceConflict"));
1274
- return ok({
1271
+ return core.err(HaiAIError.RESOURCE_CONFLICT, aiM("ai_resourceConflict"));
1272
+ return core.ok({
1275
1273
  value: structuredClone(value),
1276
1274
  source: "database",
1277
1275
  version
1278
1276
  });
1279
1277
  } catch {
1280
- return err(
1278
+ return core.err(
1281
1279
  HaiAIError.RESOURCE_OPERATION_FAILED,
1282
1280
  aiM("ai_resourceOperationFailed")
1283
1281
  );
@@ -1289,31 +1287,31 @@ function createResourceRegistry(store, schema, configured, isOpen) {
1289
1287
  const result = await protect(() => read(id3));
1290
1288
  if (!result.success)
1291
1289
  return result;
1292
- return result.data ? ok(result.data) : err(HaiAIError.RESOURCE_NOT_FOUND, aiM("ai_resourceNotFound"));
1290
+ return result.data ? core.ok(result.data) : core.err(HaiAIError.RESOURCE_NOT_FOUND, aiM("ai_resourceNotFound"));
1293
1291
  },
1294
1292
  register: (input) => write(input, false),
1295
1293
  update: (input, version) => write(input, true, version),
1296
1294
  remove: async (id3, expectedVersion) => {
1297
1295
  if (!isOpen())
1298
- return err(HaiAIError.NOT_INITIALIZED, aiM("ai_notInitialized"));
1296
+ return core.err(HaiAIError.NOT_INITIALIZED, aiM("ai_notInitialized"));
1299
1297
  if (config.has(id3))
1300
- return err(HaiAIError.RESOURCE_READ_ONLY, aiM("ai_resourceReadOnly"));
1298
+ return core.err(HaiAIError.RESOURCE_READ_ONLY, aiM("ai_resourceReadOnly"));
1301
1299
  try {
1302
1300
  const previous = await store.readVersioned(id3);
1303
1301
  if (!previous || previous.data.__deleted)
1304
- return err(HaiAIError.RESOURCE_NOT_FOUND, aiM("ai_resourceNotFound"));
1302
+ return core.err(HaiAIError.RESOURCE_NOT_FOUND, aiM("ai_resourceNotFound"));
1305
1303
  if (expectedVersion !== void 0 && expectedVersion !== previous.version) {
1306
- return err(HaiAIError.RESOURCE_CONFLICT, aiM("ai_resourceConflict"));
1304
+ return core.err(HaiAIError.RESOURCE_CONFLICT, aiM("ai_resourceConflict"));
1307
1305
  }
1308
1306
  if (!await store.compareAndSwap(id3, {
1309
1307
  expectedVersion: previous.version,
1310
1308
  data: { ...previous.data, __deleted: true }
1311
1309
  })) {
1312
- return err(HaiAIError.RESOURCE_CONFLICT, aiM("ai_resourceConflict"));
1310
+ return core.err(HaiAIError.RESOURCE_CONFLICT, aiM("ai_resourceConflict"));
1313
1311
  }
1314
- return ok(void 0);
1312
+ return core.ok(void 0);
1315
1313
  } catch {
1316
- return err(
1314
+ return core.err(
1317
1315
  HaiAIError.RESOURCE_OPERATION_FAILED,
1318
1316
  aiM("ai_resourceOperationFailed")
1319
1317
  );
@@ -3845,7 +3843,7 @@ function createACPPlatform(deps) {
3845
3843
  }
3846
3844
  async function protectedCall(operation) {
3847
3845
  try {
3848
- return ok(await operation());
3846
+ return core.ok(await operation());
3849
3847
  } catch (error) {
3850
3848
  return acpError(error);
3851
3849
  }
@@ -4712,7 +4710,7 @@ function createACPOperations(provider, config, extensions = {}, modelConfig = as
4712
4710
  const task = (async () => {
4713
4711
  try {
4714
4712
  ensure();
4715
- return ok(await operation());
4713
+ return core.ok(await operation());
4716
4714
  } catch (error) {
4717
4715
  return acpError(error);
4718
4716
  }
@@ -5480,11 +5478,11 @@ function createACPOperations(provider, config, extensions = {}, modelConfig = as
5480
5478
  },
5481
5479
  workspaces: {
5482
5480
  /** 从受信仓库的一次提交读取有界普通文件快照。 */
5483
- readGitSnapshot: (input, signal) => protectResult(async () => ok(await readGitSnapshot(input, signal))),
5481
+ readGitSnapshot: (input, signal) => protectResult(async () => core.ok(await readGitSnapshot(input, signal))),
5484
5482
  /** 比较快照并生成可下载的补丁。 */
5485
- diffSnapshot: (before, after, signal) => protectResult(async () => ok(await diffSnapshot(before, after, signal))),
5483
+ diffSnapshot: (before, after, signal) => protectResult(async () => core.ok(await diffSnapshot(before, after, signal))),
5486
5484
  /** 应用重新验权后,向独立任务分支提交并普通推送。 */
5487
- publishSnapshot: (input, signal) => protectResult(async () => ok(await publishSnapshot(input, signal))),
5485
+ publishSnapshot: (input, signal) => protectResult(async () => core.ok(await publishSnapshot(input, signal))),
5488
5486
  /**
5489
5487
  * 新增数据库工作区并归一化存储位置;拒绝目录重叠或同一 volume 重复登记。
5490
5488
  * @param input - 工作区存储位置、显式 Git 主分支和环境变量引用。
@@ -6413,7 +6411,7 @@ function createDoubaoAudioProvider() {
6413
6411
  if (event.type === "transcript" && event.final)
6414
6412
  finalText = event.text;
6415
6413
  }
6416
- return ok({ text: finalText });
6414
+ return core.ok({ text: finalText });
6417
6415
  } catch (error) {
6418
6416
  logger5.debug("Doubao transcribe failed", {
6419
6417
  error: errorMessage(error)
@@ -6507,7 +6505,7 @@ function createDoubaoAudioProvider() {
6507
6505
  signal: request2.signal
6508
6506
  }))
6509
6507
  chunks.push(audio);
6510
- return ok({
6508
+ return core.ok({
6511
6509
  data: concatChunks(chunks),
6512
6510
  format: out.format,
6513
6511
  sampleRate: out.sampleRate,
@@ -6630,7 +6628,7 @@ function createIndexTtsAudioProvider() {
6630
6628
  async function synthesize(request2) {
6631
6629
  const { model, text, language: language2, speakerReference, styleReference, styleStrength, speed, targetDurationMs, durationToleranceMs, format, sampleRate, signal } = request2;
6632
6630
  if (!speakerReference) {
6633
- return err(HaiAIError.AUDIO_INVALID_REQUEST, aiM("ai_audioInvalidRequest", {
6631
+ return core.err(HaiAIError.AUDIO_INVALID_REQUEST, aiM("ai_audioInvalidRequest", {
6634
6632
  params: { reason: "speaker_reference is required" }
6635
6633
  }));
6636
6634
  }
@@ -6674,12 +6672,12 @@ function createIndexTtsAudioProvider() {
6674
6672
  dispatcher
6675
6673
  });
6676
6674
  if (!response.ok) {
6677
- return err(HaiAIError.AUDIO_UPSTREAM_ERROR, aiM("ai_audioUpstreamError", {
6675
+ return core.err(HaiAIError.AUDIO_UPSTREAM_ERROR, aiM("ai_audioUpstreamError", {
6678
6676
  params: { error: await describeHttpError(response) }
6679
6677
  }));
6680
6678
  }
6681
6679
  const data = new Uint8Array(await response.arrayBuffer());
6682
- return ok(buildSynthesisResult(data, out, response.headers));
6680
+ return core.ok(buildSynthesisResult(data, out, response.headers));
6683
6681
  } finally {
6684
6682
  await dispatcher.close();
6685
6683
  }
@@ -6982,7 +6980,7 @@ function createMimoAudioProvider() {
6982
6980
  const { model, audio, language: language2, signal } = request2;
6983
6981
  const mime = MIMO_ASR_MIME[audio.format];
6984
6982
  if (!mime) {
6985
- return err(HaiAIError.AUDIO_UNSUPPORTED_INPUT, aiM("ai_audioUnsupportedInput", {
6983
+ return core.err(HaiAIError.AUDIO_UNSUPPORTED_INPUT, aiM("ai_audioUnsupportedInput", {
6986
6984
  params: { provider: "mimo", reason: `format ${audio.format} (only wav/mp3)` }
6987
6985
  }));
6988
6986
  }
@@ -7004,13 +7002,13 @@ function createMimoAudioProvider() {
7004
7002
  asr_options: { language: language2 ?? "auto" }
7005
7003
  }, requestSignal);
7006
7004
  if (!response.ok) {
7007
- return err(HaiAIError.AUDIO_UPSTREAM_ERROR, aiM("ai_audioUpstreamError", {
7005
+ return core.err(HaiAIError.AUDIO_UPSTREAM_ERROR, aiM("ai_audioUpstreamError", {
7008
7006
  params: { error: await describeHttpError(response) }
7009
7007
  }));
7010
7008
  }
7011
7009
  const body = await response.json();
7012
7010
  const text = body.choices?.[0]?.message?.content ?? "";
7013
- return ok({ text });
7011
+ return core.ok({ text });
7014
7012
  } catch (error) {
7015
7013
  logger7.debug("MiMo transcribe failed", {
7016
7014
  error: errorMessage(error)
@@ -7078,18 +7076,18 @@ function createMimoAudioProvider() {
7078
7076
  }
7079
7077
  }, requestSignal);
7080
7078
  if (!response.ok) {
7081
- return err(HaiAIError.AUDIO_UPSTREAM_ERROR, aiM("ai_audioUpstreamError", {
7079
+ return core.err(HaiAIError.AUDIO_UPSTREAM_ERROR, aiM("ai_audioUpstreamError", {
7082
7080
  params: { error: await describeHttpError(response) }
7083
7081
  }));
7084
7082
  }
7085
7083
  const body = await response.json();
7086
7084
  const base64 = body.choices?.[0]?.message?.audio?.data;
7087
7085
  if (!base64) {
7088
- return err(HaiAIError.AUDIO_UPSTREAM_ERROR, aiM("ai_audioUpstreamError", {
7086
+ return core.err(HaiAIError.AUDIO_UPSTREAM_ERROR, aiM("ai_audioUpstreamError", {
7089
7087
  params: { error: "missing audio data" }
7090
7088
  }));
7091
7089
  }
7092
- return ok({
7090
+ return core.ok({
7093
7091
  data: fromBase64(base64),
7094
7092
  format: out.format,
7095
7093
  sampleRate: out.sampleRate,
@@ -7202,7 +7200,7 @@ function createOpenAIAudioProvider() {
7202
7200
  async function transcribe(request2) {
7203
7201
  const { model, audio, language: language2, contextHints, signal } = request2;
7204
7202
  if (!model.apiKey) {
7205
- return err(HaiAIError.CONFIGURATION_ERROR, aiM("ai_audioMissingApiKey", {
7203
+ return core.err(HaiAIError.CONFIGURATION_ERROR, aiM("ai_audioMissingApiKey", {
7206
7204
  params: { provider: "openai" }
7207
7205
  }));
7208
7206
  }
@@ -7217,7 +7215,7 @@ function createOpenAIAudioProvider() {
7217
7215
  prompt: contextHints.join(", ")
7218
7216
  } : {}
7219
7217
  }, { signal });
7220
- return ok({ text: result.text });
7218
+ return core.ok({ text: result.text });
7221
7219
  } catch (error) {
7222
7220
  logger8.debug("OpenAI transcribe failed", {
7223
7221
  error: errorMessage(error)
@@ -7264,7 +7262,7 @@ function createOpenAIAudioProvider() {
7264
7262
  async function synthesize(request2) {
7265
7263
  const { model, text, voice, instruction, format, sampleRate, signal } = request2;
7266
7264
  if (!model.apiKey) {
7267
- return err(HaiAIError.CONFIGURATION_ERROR, aiM("ai_audioMissingApiKey", {
7265
+ return core.err(HaiAIError.CONFIGURATION_ERROR, aiM("ai_audioMissingApiKey", {
7268
7266
  params: { provider: "openai" }
7269
7267
  }));
7270
7268
  }
@@ -7279,7 +7277,7 @@ function createOpenAIAudioProvider() {
7279
7277
  ...instruction ? { instructions: instruction } : {}
7280
7278
  }, { signal });
7281
7279
  const data = new Uint8Array(await response.arrayBuffer());
7282
- return ok({
7280
+ return core.ok({
7283
7281
  data,
7284
7282
  format: out.format,
7285
7283
  sampleRate: out.sampleRate,
@@ -7392,7 +7390,7 @@ function createQwenAudioProvider() {
7392
7390
  finalText = finalText ? `${finalText}${event.text}` : event.text;
7393
7391
  }
7394
7392
  }
7395
- return ok({ text: finalText });
7393
+ return core.ok({ text: finalText });
7396
7394
  } catch (error) {
7397
7395
  logger9.debug("Qwen transcribe failed", {
7398
7396
  error: errorMessage(error)
@@ -7496,7 +7494,7 @@ function createQwenAudioProvider() {
7496
7494
  signal: request2.signal
7497
7495
  }))
7498
7496
  chunks.push(audio);
7499
- return ok({
7497
+ return core.ok({
7500
7498
  data: concatChunks(chunks),
7501
7499
  format: out.format,
7502
7500
  sampleRate: out.sampleRate,
@@ -7639,12 +7637,12 @@ function createWhisperAudioProvider() {
7639
7637
  signal: combineSignal(signal, model.timeout)
7640
7638
  });
7641
7639
  if (!response.ok) {
7642
- return err(HaiAIError.AUDIO_UPSTREAM_ERROR, aiM("ai_audioUpstreamError", {
7640
+ return core.err(HaiAIError.AUDIO_UPSTREAM_ERROR, aiM("ai_audioUpstreamError", {
7643
7641
  params: { error: await describeHttpError(response) }
7644
7642
  }));
7645
7643
  }
7646
7644
  const body = await response.json();
7647
- return ok(mapWhisperResponse(body));
7645
+ return core.ok(mapWhisperResponse(body));
7648
7646
  } catch (error) {
7649
7647
  logger10.debug("Whisper transcribe failed", {
7650
7648
  error: errorMessage(error)
@@ -7731,7 +7729,7 @@ function createAudioOperations(config) {
7731
7729
  }
7732
7730
  async function transcribe(request2) {
7733
7731
  if (!request2.audio?.data?.length) {
7734
- return err(HaiAIError.AUDIO_INVALID_REQUEST, aiM("ai_audioInvalidRequest", {
7732
+ return core.err(HaiAIError.AUDIO_INVALID_REQUEST, aiM("ai_audioInvalidRequest", {
7735
7733
  params: { reason: "empty audio" }
7736
7734
  }));
7737
7735
  }
@@ -7744,7 +7742,7 @@ function createAudioOperations(config) {
7744
7742
  const provider = getProvider(resolved.data.provider);
7745
7743
  const transcription = provider.transcription;
7746
7744
  if (!transcription) {
7747
- return err(HaiAIError.AUDIO_UNSUPPORTED_INPUT, aiM("ai_audioUnsupportedInput", {
7745
+ return core.err(HaiAIError.AUDIO_UNSUPPORTED_INPUT, aiM("ai_audioUnsupportedInput", {
7748
7746
  params: { provider: resolved.data.provider, reason: "transcription" }
7749
7747
  }));
7750
7748
  }
@@ -7831,7 +7829,7 @@ function createAudioOperations(config) {
7831
7829
  }
7832
7830
  async function synthesize(request2) {
7833
7831
  if (!request2.text) {
7834
- return err(HaiAIError.AUDIO_INVALID_REQUEST, aiM("ai_audioInvalidRequest", {
7832
+ return core.err(HaiAIError.AUDIO_INVALID_REQUEST, aiM("ai_audioInvalidRequest", {
7835
7833
  params: { reason: "empty text" }
7836
7834
  }));
7837
7835
  }
@@ -7847,7 +7845,7 @@ function createAudioOperations(config) {
7847
7845
  const provider = getProvider(resolved.data.provider);
7848
7846
  const synthesis = provider.synthesis;
7849
7847
  if (!synthesis) {
7850
- return err(HaiAIError.AUDIO_UNSUPPORTED_INPUT, aiM("ai_audioUnsupportedInput", {
7848
+ return core.err(HaiAIError.AUDIO_UNSUPPORTED_INPUT, aiM("ai_audioUnsupportedInput", {
7851
7849
  params: { provider: resolved.data.provider, reason: "synthesis" }
7852
7850
  }));
7853
7851
  }
@@ -7974,7 +7972,7 @@ function createAudioOperations(config) {
7974
7972
  if (!resolved.success)
7975
7973
  return resolved;
7976
7974
  const capabilities = getProvider(resolved.data.provider).getCapabilities(resolved.data);
7977
- return ok(request2.operation === "transcribe" ? { transcribe: capabilities.transcribe } : { synthesize: capabilities.synthesize });
7975
+ return core.ok(request2.operation === "transcribe" ? { transcribe: capabilities.transcribe } : { synthesize: capabilities.synthesize });
7978
7976
  }
7979
7977
  return {
7980
7978
  transcribe,
@@ -8129,7 +8127,7 @@ var CONVERSATION_SUMMARY_PREFIX = "[Conversation Summary]";
8129
8127
  var CONVERSATION_SUMMARY_NAME = "hai_internal_conversation_summary_v1";
8130
8128
  function completeCompression(result, maxTokens) {
8131
8129
  if (result.compressedTokens > maxTokens) {
8132
- return err(
8130
+ return core.err(
8133
8131
  HaiAIError.CONTEXT_BUDGET_EXCEEDED,
8134
8132
  aiM("ai_contextBudgetExceeded", {
8135
8133
  params: {
@@ -8139,7 +8137,7 @@ function completeCompression(result, maxTokens) {
8139
8137
  })
8140
8138
  );
8141
8139
  }
8142
- return ok(result);
8140
+ return core.ok(result);
8143
8141
  }
8144
8142
  function isGeneratedConversationSummary(message) {
8145
8143
  return message.role === "system" && message.name === CONVERSATION_SUMMARY_NAME;
@@ -8275,7 +8273,7 @@ function createCompressOperations(config, token, summary, modelMaxTokens) {
8275
8273
  try {
8276
8274
  const originalTokens = token.estimateMessages(messages);
8277
8275
  if (originalTokens <= maxTokens) {
8278
- return ok({
8276
+ return core.ok({
8279
8277
  messages: [...messages],
8280
8278
  originalTokens,
8281
8279
  compressedTokens: originalTokens,
@@ -8389,7 +8387,7 @@ ${summaryText}`
8389
8387
  }, maxTokens);
8390
8388
  } catch (error) {
8391
8389
  logger12.error("Context compression failed", { error });
8392
- return err(HaiAIError.CONTEXT_COMPRESS_FAILED, aiM("ai_contextCompressFailed", {
8390
+ return core.err(HaiAIError.CONTEXT_COMPRESS_FAILED, aiM("ai_contextCompressFailed", {
8393
8391
  params: {
8394
8392
  error: String(error)
8395
8393
  }
@@ -8474,7 +8472,7 @@ var logger13 = core.logger.child({ module: "ai", scope: "context" });
8474
8472
  var GENERATION_LEASE_MS = 3e4;
8475
8473
  function contextFailure(error) {
8476
8474
  const code = error instanceof ContextStateError ? error.definition : HaiAIError.STORE_FAILED;
8477
- return err(code, aiM("ai_sessionFailed", {
8475
+ return core.err(code, aiM("ai_sessionFailed", {
8478
8476
  params: {
8479
8477
  error: String(error)
8480
8478
  }
@@ -8651,7 +8649,7 @@ function createContextOperations(compressConfig, tokenOps, compressOps, contextS
8651
8649
  });
8652
8650
  if (!generation) {
8653
8651
  if (concurrency === "reject")
8654
- return err(HaiAIError.CONTEXT_BUSY, aiM("ai_contextBusy"));
8652
+ return core.err(HaiAIError.CONTEXT_BUSY, aiM("ai_contextBusy"));
8655
8653
  await waitForContext(caller);
8656
8654
  continue;
8657
8655
  }
@@ -8682,7 +8680,7 @@ function createContextOperations(compressConfig, tokenOps, compressOps, contextS
8682
8680
  signal.addEventListener("abort", onAbort2, { once: true });
8683
8681
  if (signal.aborted)
8684
8682
  onAbort2();
8685
- return ok({ generation, signal, release });
8683
+ return core.ok({ generation, signal, release });
8686
8684
  }
8687
8685
  } catch (error) {
8688
8686
  return contextFailure(error);
@@ -8732,7 +8730,7 @@ function createContextOperations(compressConfig, tokenOps, compressOps, contextS
8732
8730
  await append(candidate, message);
8733
8731
  return { value: void 0 };
8734
8732
  });
8735
- return ok(void 0);
8733
+ return core.ok(void 0);
8736
8734
  } catch (error) {
8737
8735
  return contextFailure(error);
8738
8736
  }
@@ -8740,22 +8738,22 @@ function createContextOperations(compressConfig, tokenOps, compressOps, contextS
8740
8738
  async reload() {
8741
8739
  try {
8742
8740
  await access.read();
8743
- return ok(void 0);
8741
+ return core.ok(void 0);
8744
8742
  } catch (error) {
8745
8743
  return contextFailure(error);
8746
8744
  }
8747
8745
  },
8748
8746
  getMessages() {
8749
- return ok(structuredClone(state.messages));
8747
+ return core.ok(structuredClone(state.messages));
8750
8748
  },
8751
8749
  getTokenUsage() {
8752
- return ok({
8750
+ return core.ok({
8753
8751
  current: tokenOps.estimateMessages(state.messages),
8754
8752
  budget: managerMaxTokens
8755
8753
  });
8756
8754
  },
8757
8755
  getSummaries() {
8758
- return ok(structuredClone(state.summaries));
8756
+ return core.ok(structuredClone(state.summaries));
8759
8757
  },
8760
8758
  async save() {
8761
8759
  const flushed = await manager.flush();
@@ -8764,7 +8762,7 @@ function createContextOperations(compressConfig, tokenOps, compressOps, contextS
8764
8762
  try {
8765
8763
  await access.mutate(() => ({ value: void 0 }));
8766
8764
  await touchSession(scope);
8767
- return ok(void 0);
8765
+ return core.ok(void 0);
8768
8766
  } catch (error) {
8769
8767
  return contextFailure(error);
8770
8768
  }
@@ -8792,13 +8790,13 @@ function createContextOperations(compressConfig, tokenOps, compressOps, contextS
8792
8790
  producer.stop();
8793
8791
  }
8794
8792
  }
8795
- return ok(void 0);
8793
+ return core.ok(void 0);
8796
8794
  } catch (error) {
8797
8795
  return contextFailure(error);
8798
8796
  }
8799
8797
  },
8800
8798
  getTurns() {
8801
- return ok(structuredClone(state.turns));
8799
+ return core.ok(structuredClone(state.turns));
8802
8800
  },
8803
8801
  async markTurnSpeaking(turnId) {
8804
8802
  try {
@@ -8817,7 +8815,7 @@ function createContextOperations(compressConfig, tokenOps, compressOps, contextS
8817
8815
  notAfter: active.phase === "generating" ? active.expiresAt : void 0
8818
8816
  };
8819
8817
  });
8820
- return ok(void 0);
8818
+ return core.ok(void 0);
8821
8819
  } catch (error) {
8822
8820
  return contextFailure(error);
8823
8821
  }
@@ -8830,7 +8828,7 @@ function createContextOperations(compressConfig, tokenOps, compressOps, contextS
8830
8828
  },
8831
8829
  async consolidate(consolidateOpts) {
8832
8830
  if (!deps?.summary || !deps?.memory) {
8833
- return err(HaiAIError.MEMORY_PROMOTE_FAILED, aiM("ai_memoryPromoteFailed", {
8831
+ return core.err(HaiAIError.MEMORY_PROMOTE_FAILED, aiM("ai_memoryPromoteFailed", {
8834
8832
  params: { error: "summary/memory deps unavailable" }
8835
8833
  }));
8836
8834
  }
@@ -8848,7 +8846,7 @@ function createContextOperations(compressConfig, tokenOps, compressOps, contextS
8848
8846
  return summaryResult;
8849
8847
  const summaryText = summaryResult.data;
8850
8848
  if (!summaryText.trim()) {
8851
- return ok({ summary: summaryText, memories: [] });
8849
+ return core.ok({ summary: summaryText, memories: [] });
8852
8850
  }
8853
8851
  const durableScope = consolidateOpts?.scope ?? options.memory?.scope;
8854
8852
  const extracted = await deps.memory.extract(
@@ -8865,10 +8863,10 @@ function createContextOperations(compressConfig, tokenOps, compressOps, contextS
8865
8863
  );
8866
8864
  if (!extracted.success)
8867
8865
  return extracted;
8868
- return ok({ summary: summaryText, memories: extracted.data });
8866
+ return core.ok({ summary: summaryText, memories: extracted.data });
8869
8867
  } catch (error) {
8870
8868
  logger13.error("Context consolidate failed", { error });
8871
- return err(HaiAIError.MEMORY_PROMOTE_FAILED, aiM("ai_memoryPromoteFailed", {
8869
+ return core.err(HaiAIError.MEMORY_PROMOTE_FAILED, aiM("ai_memoryPromoteFailed", {
8872
8870
  params: {
8873
8871
  error: String(error)
8874
8872
  }
@@ -8884,9 +8882,9 @@ function createContextOperations(compressConfig, tokenOps, compressOps, contextS
8884
8882
  await Promise.allSettled([...pendingMemoryTasks]);
8885
8883
  const failed = failedMemoryTasks;
8886
8884
  failedMemoryTasks = 0;
8887
- return failed > 0 ? err(HaiAIError.MEMORY_EXTRACT_FAILED, aiM("ai_contextMemoryTasksFailed", {
8885
+ return failed > 0 ? core.err(HaiAIError.MEMORY_EXTRACT_FAILED, aiM("ai_contextMemoryTasksFailed", {
8888
8886
  params: { count: failed }
8889
- })) : ok(void 0);
8887
+ })) : core.ok(void 0);
8890
8888
  })().finally(() => {
8891
8889
  memoryFlush = void 0;
8892
8890
  });
@@ -8895,7 +8893,7 @@ function createContextOperations(compressConfig, tokenOps, compressOps, contextS
8895
8893
  // ─── chat/chatStream 编排 ───
8896
8894
  async chat(message, chatOpts) {
8897
8895
  if (!deps?.llm) {
8898
- return err(HaiAIError.NOT_INITIALIZED, aiM("ai_notInitialized"));
8896
+ return core.err(HaiAIError.NOT_INITIALIZED, aiM("ai_notInitialized"));
8899
8897
  }
8900
8898
  const acq = await acquireGeneration(message, chatOpts?.signal, false);
8901
8899
  if (!acq.success)
@@ -8928,7 +8926,7 @@ function createContextOperations(compressConfig, tokenOps, compressOps, contextS
8928
8926
  if (ragResult.success) {
8929
8927
  const reply = ragResult.data.answer;
8930
8928
  turnId = await finalizeAssistantReply(generation, reply);
8931
- return ok({
8929
+ return core.ok({
8932
8930
  reply,
8933
8931
  model: ragResult.data.model,
8934
8932
  turnId,
@@ -8952,7 +8950,7 @@ function createContextOperations(compressConfig, tokenOps, compressOps, contextS
8952
8950
  if (reasonResult.success) {
8953
8951
  const reply = reasonResult.data.answer;
8954
8952
  turnId = await finalizeAssistantReply(generation, reply);
8955
- return ok({
8953
+ return core.ok({
8956
8954
  reply,
8957
8955
  model: chatOpts?.model ?? options.model ?? "",
8958
8956
  turnId,
@@ -9008,7 +9006,7 @@ function createContextOperations(compressConfig, tokenOps, compressOps, contextS
9008
9006
  }
9009
9007
  const reply = typeof assistantMessage.content === "string" ? assistantMessage.content : "";
9010
9008
  turnId = await finalizeAssistantReply(generation, reply);
9011
- return ok({
9009
+ return core.ok({
9012
9010
  reply,
9013
9011
  model: lastModel,
9014
9012
  turnId,
@@ -9018,7 +9016,7 @@ function createContextOperations(compressConfig, tokenOps, compressOps, contextS
9018
9016
  const lastAssistantMsg = messages.filter((m) => m.role === "assistant").pop();
9019
9017
  const fallbackReply = lastAssistantMsg && "content" in lastAssistantMsg && typeof lastAssistantMsg.content === "string" ? lastAssistantMsg.content : "";
9020
9018
  turnId = await finalizeAssistantReply(generation, fallbackReply);
9021
- return ok({
9019
+ return core.ok({
9022
9020
  reply: fallbackReply,
9023
9021
  model: lastModel,
9024
9022
  turnId,
@@ -9274,7 +9272,7 @@ function createContextOperations(compressConfig, tokenOps, compressOps, contextS
9274
9272
  producers.get(turnId)?.stop();
9275
9273
  if (extracted?.reply)
9276
9274
  enqueueMemoryExtract(extracted.user, extracted.reply);
9277
- return ok(void 0);
9275
+ return core.ok(void 0);
9278
9276
  } catch (error) {
9279
9277
  return contextFailure(error);
9280
9278
  }
@@ -9297,8 +9295,8 @@ function createContextOperations(compressConfig, tokenOps, compressOps, contextS
9297
9295
  createManager(options) {
9298
9296
  try {
9299
9297
  if (!validScope(options?.scope))
9300
- return err(HaiAIError.CONFIGURATION_ERROR, aiM("ai_contextScopeRequired"));
9301
- return ok(buildManager(options));
9298
+ return core.err(HaiAIError.CONFIGURATION_ERROR, aiM("ai_contextScopeRequired"));
9299
+ return core.ok(buildManager(options));
9302
9300
  } catch (error) {
9303
9301
  return contextFailure(error);
9304
9302
  }
@@ -9306,18 +9304,18 @@ function createContextOperations(compressConfig, tokenOps, compressOps, contextS
9306
9304
  async restoreManager(scope, options) {
9307
9305
  try {
9308
9306
  if (!validScope(scope))
9309
- return err(HaiAIError.CONFIGURATION_ERROR, aiM("ai_contextScopeRequired"));
9307
+ return core.err(HaiAIError.CONFIGURATION_ERROR, aiM("ai_contextScopeRequired"));
9310
9308
  const persisted = await contextStore.readVersioned(sessionStoreKey(scope));
9311
9309
  if (persisted?.data.deleted)
9312
9310
  throw new ContextStateError(HaiAIError.SESSION_FAILED, "Context has been deleted");
9313
- return ok(buildManager({ ...options, scope }, persisted?.data));
9311
+ return core.ok(buildManager({ ...options, scope }, persisted?.data));
9314
9312
  } catch (error) {
9315
9313
  return contextFailure(error);
9316
9314
  }
9317
9315
  },
9318
9316
  async listSessions(objectId) {
9319
9317
  if (!sessionStore)
9320
- return ok([]);
9318
+ return core.ok([]);
9321
9319
  try {
9322
9320
  const sessions = await sessionStore.query({
9323
9321
  objectId,
@@ -9325,14 +9323,14 @@ function createContextOperations(compressConfig, tokenOps, compressOps, contextS
9325
9323
  });
9326
9324
  const contexts = await contextStore.query({ objectId });
9327
9325
  const deleted = new Set(contexts.filter((item2) => item2.deleted).map((item2) => sessionStoreKey(item2.scope)));
9328
- return ok(sessions.filter((item2) => !item2.deleted && !deleted.has(sessionStoreKey(item2))));
9326
+ return core.ok(sessions.filter((item2) => !item2.deleted && !deleted.has(sessionStoreKey(item2))));
9329
9327
  } catch (error) {
9330
9328
  return contextFailure(error);
9331
9329
  }
9332
9330
  },
9333
9331
  async renameSession(scope, title) {
9334
9332
  if (!sessionStore)
9335
- return ok(void 0);
9333
+ return core.ok(void 0);
9336
9334
  try {
9337
9335
  const context = await contextStore.readVersioned(sessionStoreKey(scope));
9338
9336
  if (context?.data.deleted)
@@ -9342,7 +9340,7 @@ function createContextOperations(compressConfig, tokenOps, compressOps, contextS
9342
9340
  throw new ContextStateError(HaiAIError.SESSION_FAILED, "Session not found");
9343
9341
  return { ...existing, title, updatedAt: now };
9344
9342
  });
9345
- return ok(void 0);
9343
+ return core.ok(void 0);
9346
9344
  } catch (error) {
9347
9345
  return contextFailure(error);
9348
9346
  }
@@ -9377,7 +9375,7 @@ function createContextOperations(compressConfig, tokenOps, compressOps, contextS
9377
9375
  deleted: true
9378
9376
  }));
9379
9377
  }
9380
- return ok(void 0);
9378
+ return core.ok(void 0);
9381
9379
  } catch (error) {
9382
9380
  return contextFailure(error);
9383
9381
  }
@@ -9412,7 +9410,7 @@ function createEmbeddingOperations(config, loadModels = () => config.llm) {
9412
9410
  params.dimensions = request2.dimensions ?? embeddingConfig.dimensions;
9413
9411
  }
9414
9412
  const response = await client2.embeddings.create(params);
9415
- return ok({
9413
+ return core.ok({
9416
9414
  model: response.model,
9417
9415
  data: response.data.map((item2) => ({
9418
9416
  index: item2.index,
@@ -9425,7 +9423,7 @@ function createEmbeddingOperations(config, loadModels = () => config.llm) {
9425
9423
  });
9426
9424
  } catch (error) {
9427
9425
  logger14.error("Embedding API call failed", { error });
9428
- return err(HaiAIError.EMBEDDING_API_ERROR, aiM("ai_internalError", {
9426
+ return core.err(HaiAIError.EMBEDDING_API_ERROR, aiM("ai_internalError", {
9429
9427
  params: {
9430
9428
  error: String(error)
9431
9429
  }
@@ -9464,7 +9462,7 @@ function createEmbeddingOperations(config, loadModels = () => config.llm) {
9464
9462
  });
9465
9463
  }
9466
9464
  }
9467
- return ok({
9465
+ return core.ok({
9468
9466
  model: resultModel,
9469
9467
  data: allData,
9470
9468
  usage: { prompt_tokens: totalPromptTokens, total_tokens: totalTokens }
@@ -9480,29 +9478,31 @@ function createEmbeddingOperations(config, loadModels = () => config.llm) {
9480
9478
  return result;
9481
9479
  const first = result.data.data.find((item2) => item2.index === 0);
9482
9480
  if (!first) {
9483
- return err(HaiAIError.EMBEDDING_API_ERROR, aiM("ai_internalError", {
9481
+ return core.err(HaiAIError.EMBEDDING_API_ERROR, aiM("ai_internalError", {
9484
9482
  params: { error: "Embedding result is empty" }
9485
9483
  }));
9486
9484
  }
9487
- return ok(first.embedding);
9485
+ return core.ok(first.embedding);
9488
9486
  },
9489
9487
  async embedBatch(texts) {
9490
9488
  const result = await embedRequest({ input: texts });
9491
9489
  if (!result.success)
9492
9490
  return result;
9493
9491
  const sorted = [...result.data.data].sort((a, b) => a.index - b.index);
9494
- return ok(sorted.map((item2) => item2.embedding));
9492
+ return core.ok(sorted.map((item2) => item2.embedding));
9495
9493
  }
9496
9494
  };
9497
9495
  }
9496
+ var parserWorkerUrl = new URL(import.meta.url.endsWith(".ts") ? "../../dist/ai-file-worker.js" : "./ai-file-worker.js", import.meta.url);
9498
9497
  var filePool = core.worker.createPool(
9499
- new URL(import.meta.url.endsWith(".ts") ? "../../dist/ai-file-worker.js" : "./ai-file-worker.js", import.meta.url),
9498
+ parserWorkerUrl,
9500
9499
  { maxWorkers: 2, maxQueuedJobs: 4, idleTimeoutMs: 15e3 }
9501
9500
  );
9501
+ var activeLocalParsers = 0;
9502
9502
  async function parseInWorker(job) {
9503
9503
  const result = await filePool.run(job);
9504
9504
  if (!result.success) {
9505
- return err(HaiAIError.FILE_PARSE_FAILED, aiM("ai_fileParseFailed", {
9505
+ return core.err(HaiAIError.FILE_PARSE_FAILED, aiM("ai_fileParseFailed", {
9506
9506
  params: { error: result.error.message }
9507
9507
  }), result.error);
9508
9508
  }
@@ -9596,6 +9596,118 @@ function parseTextContent(content) {
9596
9596
  return content;
9597
9597
  return content.toString("utf-8");
9598
9598
  }
9599
+ function asBufferOrText(content) {
9600
+ return typeof content === "string" || Buffer.isBuffer(content) ? content : Buffer.from(content.buffer, content.byteOffset, content.byteLength);
9601
+ }
9602
+ async function parseBoundedLocalFile(request2) {
9603
+ const { filename, signal, options = {} } = request2;
9604
+ const {
9605
+ maxInputBytes: maxInputBytes2 = 4 * 1024 * 1024,
9606
+ maxPages = 100,
9607
+ maxTextLength = 12e3,
9608
+ maxZipEntries = 512,
9609
+ maxExpandedBytes = 24 * 1024 * 1024,
9610
+ timeoutMs = 2e4,
9611
+ outputFormat = "text"
9612
+ } = options;
9613
+ const content = asBufferOrText(request2.content);
9614
+ const inputBytes = typeof content === "string" ? Buffer.byteLength(content) : content.byteLength;
9615
+ if (options.useOcr || timeoutMs > 2147483647 || [
9616
+ maxInputBytes2,
9617
+ maxPages,
9618
+ maxTextLength,
9619
+ maxZipEntries,
9620
+ maxExpandedBytes,
9621
+ timeoutMs
9622
+ ].some((limit) => !Number.isSafeInteger(limit) || limit < 1) || !inputBytes || inputBytes > maxInputBytes2) {
9623
+ return core.err(HaiAIError.FILE_INVALID_CONTENT, aiM("ai_fileLocalInvalid"));
9624
+ }
9625
+ if (signal?.aborted)
9626
+ return core.err(HaiAIError.FILE_LOCAL_CANCELLED, aiM("ai_fileLocalCancelled"));
9627
+ const mimeType = detectMimeType(content, filename, options.mimeType);
9628
+ const parameters = {
9629
+ format: outputFormat,
9630
+ locale: core.i18n.getGlobalLocale(),
9631
+ limits: { maxTextLength, maxZipEntries, maxExpandedBytes }
9632
+ };
9633
+ const payload = typeof content === "string" ? content : Uint8Array.from(content);
9634
+ let job;
9635
+ if (TEXT_MIME_TYPES.has(mimeType)) {
9636
+ job = { ...parameters, type: "text", content: payload };
9637
+ } else if (mimeType === "text/html") {
9638
+ job = { ...parameters, type: "html", content: payload };
9639
+ } else if (typeof payload !== "string" && mimeType === "application/pdf") {
9640
+ job = {
9641
+ ...parameters,
9642
+ type: "pdf",
9643
+ content: payload,
9644
+ maxPages
9645
+ };
9646
+ } else if (typeof payload !== "string" && mimeType === "application/vnd.openxmlformats-officedocument.wordprocessingml.document") {
9647
+ job = { ...parameters, type: "docx", content: payload };
9648
+ } else {
9649
+ return core.err(HaiAIError.FILE_UNSUPPORTED_FORMAT, aiM("ai_fileUnsupportedFormat", {
9650
+ params: { mimeType }
9651
+ }));
9652
+ }
9653
+ if (activeLocalParsers >= 3)
9654
+ return core.err(HaiAIError.FILE_LOCAL_BUSY, aiM("ai_fileLocalBusy"));
9655
+ activeLocalParsers++;
9656
+ let worker;
9657
+ const deadline = AbortSignal.timeout(timeoutMs);
9658
+ const operation = signal ? AbortSignal.any([signal, deadline]) : deadline;
9659
+ try {
9660
+ const thread = new Worker(parserWorkerUrl, {
9661
+ resourceLimits: { maxOldGenerationSizeMb: 160 }
9662
+ });
9663
+ worker = thread;
9664
+ const parsed = await new Promise((resolve3) => {
9665
+ const stop = () => finish(void 0);
9666
+ function finish(result) {
9667
+ operation.removeEventListener("abort", stop);
9668
+ resolve3(result);
9669
+ }
9670
+ operation.addEventListener("abort", stop, { once: true });
9671
+ thread.once("error", stop);
9672
+ thread.once("exit", stop);
9673
+ thread.once("message", (result) => finish(result));
9674
+ if (operation.aborted) {
9675
+ stop();
9676
+ } else {
9677
+ thread.postMessage(job, typeof payload === "string" ? [] : [payload.buffer]);
9678
+ }
9679
+ });
9680
+ if (signal?.aborted)
9681
+ return core.err(HaiAIError.FILE_LOCAL_CANCELLED, aiM("ai_fileLocalCancelled"));
9682
+ if (deadline.aborted)
9683
+ return core.err(HaiAIError.FILE_LOCAL_TIMEOUT, aiM("ai_fileLocalTimeout"));
9684
+ if (!parsed)
9685
+ return core.err(HaiAIError.FILE_PARSE_FAILED, aiM("ai_fileLocalFailed"));
9686
+ if (!parsed.success)
9687
+ return parsed;
9688
+ const { text, pageCount, truncated } = parsed.data;
9689
+ return core.ok({
9690
+ text,
9691
+ method: job.type,
9692
+ ...pageCount !== void 0 && { pageCount },
9693
+ metadata: {
9694
+ filename,
9695
+ mimeType,
9696
+ charCount: text.length,
9697
+ ...truncated && { truncated }
9698
+ }
9699
+ });
9700
+ } catch {
9701
+ return core.err(HaiAIError.FILE_PARSE_FAILED, aiM("ai_fileLocalFailed"));
9702
+ } finally {
9703
+ try {
9704
+ await worker?.terminate();
9705
+ } catch {
9706
+ logger15.warn("Local file parser worker termination failed");
9707
+ }
9708
+ activeLocalParsers--;
9709
+ }
9710
+ }
9599
9711
  async function parseImageWithOcr(content, mimeType, llmOps, model, outputFormat = "text", customPrompt) {
9600
9712
  const base64 = content.toString("base64");
9601
9713
  const dataUrl = `data:${mimeType};base64,${base64}`;
@@ -9621,11 +9733,11 @@ async function parseImageWithOcr(content, mimeType, llmOps, model, outputFormat
9621
9733
  ]
9622
9734
  });
9623
9735
  if (!result.success) {
9624
- return err(HaiAIError.FILE_OCR_FAILED, aiM("ai_fileOcrFailed", {
9736
+ return core.err(HaiAIError.FILE_OCR_FAILED, aiM("ai_fileOcrFailed", {
9625
9737
  params: { error: result.error.message }
9626
9738
  }), result.error);
9627
9739
  }
9628
- return ok(result.data.choices[0]?.message?.content ?? "");
9740
+ return core.ok(result.data.choices[0]?.message?.content ?? "");
9629
9741
  }
9630
9742
  function createFileOperations(config, llmOps) {
9631
9743
  async function runOcr(content, mimeType, filename, model, outputFormat, systemPrompt) {
@@ -9646,14 +9758,17 @@ function createFileOperations(config, llmOps) {
9646
9758
  );
9647
9759
  if (!ocrResult.success)
9648
9760
  return ocrResult;
9649
- return ok({
9761
+ return core.ok({
9650
9762
  text: ocrResult.data,
9651
9763
  method: "ocr",
9652
9764
  metadata: { filename, mimeType, charCount: ocrResult.data.length }
9653
9765
  });
9654
9766
  }
9655
9767
  async function doParse(request2) {
9656
- const { content, filename, options = {} } = request2;
9768
+ if (request2.options?.mode === "local")
9769
+ return parseBoundedLocalFile(request2);
9770
+ const { filename, options = {} } = request2;
9771
+ const content = asBufferOrText(request2.content);
9657
9772
  const mimeType = detectMimeType(content, filename, options.mimeType);
9658
9773
  const outputFormat = options.outputFormat ?? "text";
9659
9774
  logger15.trace("Parsing file", {
@@ -9664,7 +9779,7 @@ function createFileOperations(config, llmOps) {
9664
9779
  });
9665
9780
  if (options.useOcr) {
9666
9781
  if (!Buffer.isBuffer(content)) {
9667
- return err(HaiAIError.FILE_INVALID_CONTENT, aiM("ai_fileInvalidContent", {
9782
+ return core.err(HaiAIError.FILE_INVALID_CONTENT, aiM("ai_fileInvalidContent", {
9668
9783
  params: { reason: "OCR requires Buffer content" }
9669
9784
  }));
9670
9785
  }
@@ -9672,7 +9787,7 @@ function createFileOperations(config, llmOps) {
9672
9787
  }
9673
9788
  if (TEXT_MIME_TYPES.has(mimeType)) {
9674
9789
  const text = parseTextContent(content);
9675
- return ok({
9790
+ return core.ok({
9676
9791
  text,
9677
9792
  method: "text",
9678
9793
  metadata: { filename, mimeType, charCount: text.length }
@@ -9695,7 +9810,7 @@ function createFileOperations(config, llmOps) {
9695
9810
  } else {
9696
9811
  text = parseHtmlFile(parseTextContent(content), outputFormat);
9697
9812
  }
9698
- return ok({
9813
+ return core.ok({
9699
9814
  text,
9700
9815
  method: "html",
9701
9816
  metadata: { filename, mimeType, charCount: text.length }
@@ -9704,7 +9819,7 @@ function createFileOperations(config, llmOps) {
9704
9819
  const isPdf = mimeType === "application/pdf";
9705
9820
  if (isPdf || mimeType === "application/vnd.openxmlformats-officedocument.wordprocessingml.document" || mimeType === "application/msword" || mimeType === "application/zip") {
9706
9821
  if (!Buffer.isBuffer(content)) {
9707
- return err(HaiAIError.FILE_INVALID_CONTENT, aiM("ai_fileInvalidContent", {
9822
+ return core.err(HaiAIError.FILE_INVALID_CONTENT, aiM("ai_fileInvalidContent", {
9708
9823
  params: {
9709
9824
  reason: isPdf ? "PDF parsing requires Buffer content" : "DOCX parsing requires Buffer content"
9710
9825
  }
@@ -9721,7 +9836,7 @@ function createFileOperations(config, llmOps) {
9721
9836
  return result;
9722
9837
  if (result.data.success) {
9723
9838
  const { text, pageCount } = result.data.data;
9724
- return ok({
9839
+ return core.ok({
9725
9840
  text,
9726
9841
  method: isPdf ? "pdf" : "docx",
9727
9842
  ...isPdf ? { pageCount } : {},
@@ -9733,13 +9848,13 @@ function createFileOperations(config, llmOps) {
9733
9848
  }
9734
9849
  if (IMAGE_MIME_TYPES.has(mimeType)) {
9735
9850
  if (!Buffer.isBuffer(content)) {
9736
- return err(HaiAIError.FILE_INVALID_CONTENT, aiM("ai_fileInvalidContent", {
9851
+ return core.err(HaiAIError.FILE_INVALID_CONTENT, aiM("ai_fileInvalidContent", {
9737
9852
  params: { reason: "Image OCR requires Buffer content" }
9738
9853
  }));
9739
9854
  }
9740
9855
  return runOcr(content, mimeType, filename, options.model, outputFormat, options.systemPrompt);
9741
9856
  }
9742
- return err(HaiAIError.FILE_UNSUPPORTED_FORMAT, aiM("ai_fileUnsupportedFormat", {
9857
+ return core.err(HaiAIError.FILE_UNSUPPORTED_FORMAT, aiM("ai_fileUnsupportedFormat", {
9743
9858
  params: { mimeType }
9744
9859
  }));
9745
9860
  }
@@ -9749,7 +9864,7 @@ function createFileOperations(config, llmOps) {
9749
9864
  return await doParse(request2);
9750
9865
  } catch (error) {
9751
9866
  logger15.error("File parse failed unexpectedly", { filename: request2.filename, error });
9752
- return err(HaiAIError.FILE_PARSE_FAILED, aiM("ai_fileParseFailed", {
9867
+ return core.err(HaiAIError.FILE_PARSE_FAILED, aiM("ai_fileParseFailed", {
9753
9868
  params: {
9754
9869
  error: String(error)
9755
9870
  }
@@ -9760,7 +9875,7 @@ function createFileOperations(config, llmOps) {
9760
9875
  const result = await this.parse({ content, filename });
9761
9876
  if (!result.success)
9762
9877
  return result;
9763
- return ok(result.data.text);
9878
+ return core.ok(result.data.text);
9764
9879
  }
9765
9880
  };
9766
9881
  }
@@ -9864,12 +9979,12 @@ async function readImageBody(response, maxBytes, signal) {
9864
9979
  }
9865
9980
  function validateImageOutput(image, maxBytes) {
9866
9981
  if (image.data.byteLength > maxBytes)
9867
- return err(HaiAIError.IMAGE_TOO_LARGE, aiM("ai_imageTooLarge"));
9982
+ return core.err(HaiAIError.IMAGE_TOO_LARGE, aiM("ai_imageTooLarge"));
9868
9983
  const bytes = image.data;
9869
9984
  const mime = image.mimeType.toLowerCase() === "image/jpg" ? "image/jpeg" : image.mimeType.toLowerCase();
9870
9985
  const prefix = (value) => value.every((byte, index) => bytes[index] === byte);
9871
9986
  const valid = mime === "image/png" ? prefix([137, 80, 78, 71, 13, 10, 26, 10]) : mime === "image/jpeg" ? prefix([255, 216, 255]) : mime === "image/gif" ? ["GIF87a", "GIF89a"].includes(Buffer.from(bytes.subarray(0, 6)).toString("ascii")) : mime === "image/webp" && Buffer.from(bytes.subarray(0, 4)).toString("ascii") === "RIFF" && Buffer.from(bytes.subarray(8, 12)).toString("ascii") === "WEBP";
9872
- return valid ? ok({ ...image, mimeType: mime }) : imageProtocolError();
9987
+ return valid ? core.ok({ ...image, mimeType: mime }) : imageProtocolError();
9873
9988
  }
9874
9989
  function imageFromBase64(data, mimeType, options) {
9875
9990
  if (Buffer.byteLength(data, "base64") > options.maxImageBytes)
@@ -9898,11 +10013,11 @@ async function readJson(response, request2) {
9898
10013
  if (!response.ok)
9899
10014
  return imageUpstreamError(response, request2.signal);
9900
10015
  try {
9901
- return ok(JSON.parse(new TextDecoder().decode(await readImageBody(response, Math.max(64 * 1024, request2.maxImageBytes * 2), request2.signal))));
10016
+ return core.ok(JSON.parse(new TextDecoder().decode(await readImageBody(response, Math.max(64 * 1024, request2.maxImageBytes * 2), request2.signal))));
9902
10017
  } catch (error) {
9903
10018
  if (error instanceof RangeError || request2.signal?.aborted)
9904
10019
  return imageProviderFailure(error);
9905
- return err(HaiAIError.IMAGE_PROTOCOL_ERROR, aiM("ai_imageProtocolError"), error);
10020
+ return core.err(HaiAIError.IMAGE_PROTOCOL_ERROR, aiM("ai_imageProtocolError"), error);
9906
10021
  }
9907
10022
  }
9908
10023
  async function downloadImage(url, request2) {
@@ -9930,7 +10045,7 @@ async function downloadImage(url, request2) {
9930
10045
  }
9931
10046
  async function downloadImages(urls, request2) {
9932
10047
  if (urls.length > request2.maxImages)
9933
- return err(HaiAIError.IMAGE_TOO_LARGE, aiM("ai_imageTooLarge"));
10048
+ return core.err(HaiAIError.IMAGE_TOO_LARGE, aiM("ai_imageTooLarge"));
9934
10049
  const images = [];
9935
10050
  for (const url of urls) {
9936
10051
  const downloaded = await downloadImage(url, request2);
@@ -9938,7 +10053,7 @@ async function downloadImages(urls, request2) {
9938
10053
  return downloaded;
9939
10054
  images.push(downloaded.data);
9940
10055
  }
9941
- return ok(images);
10056
+ return core.ok(images);
9942
10057
  }
9943
10058
  async function readImageResponse(response, request2) {
9944
10059
  if (!response.ok)
@@ -9965,18 +10080,18 @@ function imageProviderFailure(error) {
9965
10080
  let cause = error;
9966
10081
  for (let depth = 0; depth < 4 && cause instanceof Error; depth++, cause = cause.cause) {
9967
10082
  if (cause instanceof ImageDownloadBlockedError)
9968
- return err(HaiAIError.IMAGE_DOWNLOAD_BLOCKED, aiM("ai_imageDownloadBlocked"));
10083
+ return core.err(HaiAIError.IMAGE_DOWNLOAD_BLOCKED, aiM("ai_imageDownloadBlocked"));
9969
10084
  }
9970
10085
  if (error instanceof RangeError)
9971
- return err(HaiAIError.IMAGE_TOO_LARGE, aiM("ai_imageTooLarge"));
10086
+ return core.err(HaiAIError.IMAGE_TOO_LARGE, aiM("ai_imageTooLarge"));
9972
10087
  if (error instanceof DOMException && error.name === "TimeoutError")
9973
- return err(HaiAIError.IMAGE_TIMEOUT, aiM("ai_imageTimeout"));
10088
+ return core.err(HaiAIError.IMAGE_TIMEOUT, aiM("ai_imageTimeout"));
9974
10089
  if (error instanceof DOMException && error.name === "AbortError")
9975
- return err(HaiAIError.IMAGE_CANCELLED, aiM("ai_imageCancelled"), error);
9976
- return err(HaiAIError.IMAGE_UPSTREAM_ERROR, aiM("ai_imageRequestFailed"), error);
10090
+ return core.err(HaiAIError.IMAGE_CANCELLED, aiM("ai_imageCancelled"), error);
10091
+ return core.err(HaiAIError.IMAGE_UPSTREAM_ERROR, aiM("ai_imageRequestFailed"), error);
9977
10092
  }
9978
10093
  function imageProtocolError() {
9979
- return err(HaiAIError.IMAGE_PROTOCOL_ERROR, aiM("ai_imageProtocolError"));
10094
+ return core.err(HaiAIError.IMAGE_PROTOCOL_ERROR, aiM("ai_imageProtocolError"));
9980
10095
  }
9981
10096
  async function imageUpstreamError(response, signal) {
9982
10097
  const details = {
@@ -10000,7 +10115,7 @@ async function imageUpstreamError(response, signal) {
10000
10115
  const message = response.status === 401 ? aiM("ai_imageAuthenticationFailed") : response.status === 402 ? aiM("ai_imagePaymentRequired") : response.status === 403 ? aiM("ai_imageAccessDenied") : aiM("ai_imageUpstreamError", {
10001
10116
  params: { status: response.status }
10002
10117
  });
10003
- return err(HaiAIError.IMAGE_UPSTREAM_ERROR, message, details);
10118
+ return core.err(HaiAIError.IMAGE_UPSTREAM_ERROR, message, details);
10004
10119
  }
10005
10120
 
10006
10121
  // src/image/providers/ai-image-provider-google.ts
@@ -10317,15 +10432,15 @@ function createImageOperations(config) {
10317
10432
  return {
10318
10433
  async generate(request2) {
10319
10434
  if (!request2.prompt?.trim())
10320
- return err(HaiAIError.IMAGE_INVALID_REQUEST, aiM("ai_imageInvalidRequest"));
10435
+ return core.err(HaiAIError.IMAGE_INVALID_REQUEST, aiM("ai_imageInvalidRequest"));
10321
10436
  if (request2.size && (!Number.isInteger(request2.size.width) || !Number.isInteger(request2.size.height) || request2.size.width <= 0 || request2.size.height <= 0))
10322
- return err(HaiAIError.IMAGE_INVALID_REQUEST, aiM("ai_imageInvalidSize"));
10437
+ return core.err(HaiAIError.IMAGE_INVALID_REQUEST, aiM("ai_imageInvalidSize"));
10323
10438
  if (request2.referenceImages?.some((image) => image.data.byteLength === 0 || !image.mimeType.toLowerCase().startsWith("image/")))
10324
- return err(HaiAIError.IMAGE_INVALID_REQUEST, aiM("ai_imageInvalidReferenceImage"));
10439
+ return core.err(HaiAIError.IMAGE_INVALID_REQUEST, aiM("ai_imageInvalidReferenceImage"));
10325
10440
  if ((request2.referenceImages?.length ?? 0) > imageConfig.maxImages || request2.referenceImages?.some((image) => image.data.byteLength > imageConfig.maxImageBytes))
10326
- return err(HaiAIError.IMAGE_TOO_LARGE, aiM("ai_imageTooLarge"));
10441
+ return core.err(HaiAIError.IMAGE_TOO_LARGE, aiM("ai_imageTooLarge"));
10327
10442
  if (request2.signal?.aborted)
10328
- return err(HaiAIError.IMAGE_CANCELLED, aiM("ai_imageCancelled"));
10443
+ return core.err(HaiAIError.IMAGE_CANCELLED, aiM("ai_imageCancelled"));
10329
10444
  const resolved = resolveImageModel(imageConfig, request2.model);
10330
10445
  if (!resolved.success) {
10331
10446
  logger16.warn("Image model resolution failed", {
@@ -10364,9 +10479,9 @@ function createImageOperations(config) {
10364
10479
  clearTimeout(timer);
10365
10480
  }
10366
10481
  if (request2.signal?.aborted)
10367
- return err(HaiAIError.IMAGE_CANCELLED, aiM("ai_imageCancelled"));
10482
+ return core.err(HaiAIError.IMAGE_CANCELLED, aiM("ai_imageCancelled"));
10368
10483
  if (deadline.signal.aborted)
10369
- return err(HaiAIError.IMAGE_TIMEOUT, aiM("ai_imageTimeout"));
10484
+ return core.err(HaiAIError.IMAGE_TIMEOUT, aiM("ai_imageTimeout"));
10370
10485
  if (!generated.success) {
10371
10486
  logger16.warn("Image generation failed", {
10372
10487
  ...logContext,
@@ -10378,7 +10493,7 @@ function createImageOperations(config) {
10378
10493
  return generated;
10379
10494
  }
10380
10495
  if (generated.data.length > imageConfig.maxImages)
10381
- return err(HaiAIError.IMAGE_TOO_LARGE, aiM("ai_imageTooLarge"));
10496
+ return core.err(HaiAIError.IMAGE_TOO_LARGE, aiM("ai_imageTooLarge"));
10382
10497
  const images = [];
10383
10498
  for (const image of generated.data) {
10384
10499
  const validated = validateImageOutput(image, imageConfig.maxImageBytes);
@@ -10446,7 +10561,7 @@ Rules:
10446
10561
  }
10447
10562
  async function extractEntities(llm, text, model, entityTypes, systemPrompt) {
10448
10563
  if (!text.trim()) {
10449
- return ok([]);
10564
+ return core.ok([]);
10450
10565
  }
10451
10566
  const resolvedTypes = entityTypes ?? DEFAULT_ENTITY_TYPES;
10452
10567
  const resolvedPrompt = systemPrompt ?? buildEntityExtractionPrompt(resolvedTypes);
@@ -10462,7 +10577,7 @@ async function extractEntities(llm, text, model, entityTypes, systemPrompt) {
10462
10577
  });
10463
10578
  if (!chatResult.success) {
10464
10579
  logger17.warn("Entity extraction LLM call failed", { error: chatResult.error });
10465
- return err(HaiAIError.KNOWLEDGE_ENTITY_EXTRACT_FAILED, aiM("ai_knowledgeEntityExtractFailed", {
10580
+ return core.err(HaiAIError.KNOWLEDGE_ENTITY_EXTRACT_FAILED, aiM("ai_knowledgeEntityExtractFailed", {
10466
10581
  params: {
10467
10582
  error: String(chatResult.error.message)
10468
10583
  }
@@ -10472,10 +10587,10 @@ async function extractEntities(llm, text, model, entityTypes, systemPrompt) {
10472
10587
  const validTypes = new Set(resolvedTypes);
10473
10588
  const entities = parseEntityResponse(content, validTypes);
10474
10589
  logger17.trace("Entity extraction completed", { textLength: text.length, entityCount: entities.length });
10475
- return ok(entities);
10590
+ return core.ok(entities);
10476
10591
  } catch (error) {
10477
10592
  logger17.error("Entity extraction failed", { error });
10478
- return err(HaiAIError.KNOWLEDGE_ENTITY_EXTRACT_FAILED, aiM("ai_knowledgeEntityExtractFailed", {
10593
+ return core.err(HaiAIError.KNOWLEDGE_ENTITY_EXTRACT_FAILED, aiM("ai_knowledgeEntityExtractFailed", {
10479
10594
  params: {
10480
10595
  error: String(error)
10481
10596
  }
@@ -10562,7 +10677,7 @@ async function extractEntitiesBatch(llm, chunks, model, entityTypes, systemPromp
10562
10677
  });
10563
10678
  }
10564
10679
  }
10565
- return ok(Array.from(entityMap.values()));
10680
+ return core.ok(Array.from(entityMap.values()));
10566
10681
  }
10567
10682
 
10568
10683
  // src/knowledge/ai-knowledge-functions.ts
@@ -10594,7 +10709,7 @@ function createKnowledgeOperations(config, llm, embedding, datapipe2, store) {
10594
10709
  */
10595
10710
  async setup(options) {
10596
10711
  if (!store) {
10597
- return err(HaiAIError.KNOWLEDGE_SETUP_FAILED, aiM("ai_knowledgeSetupFailed", {
10712
+ return core.err(HaiAIError.KNOWLEDGE_SETUP_FAILED, aiM("ai_knowledgeSetupFailed", {
10598
10713
  params: { error: "KnowledgeStore not available. Provider may not support knowledge operations." }
10599
10714
  }));
10600
10715
  }
@@ -10606,10 +10721,10 @@ function createKnowledgeOperations(config, llm, embedding, datapipe2, store) {
10606
10721
  await store.registerCollection(collection, dimension);
10607
10722
  await store.repair(collection);
10608
10723
  logger18.debug("Knowledge base setup completed", { collection });
10609
- return ok(void 0);
10724
+ return core.ok(void 0);
10610
10725
  } catch (error) {
10611
10726
  logger18.error("Knowledge base setup failed", { error });
10612
- return err(HaiAIError.KNOWLEDGE_SETUP_FAILED, aiM("ai_knowledgeSetupFailed", {
10727
+ return core.err(HaiAIError.KNOWLEDGE_SETUP_FAILED, aiM("ai_knowledgeSetupFailed", {
10613
10728
  params: {
10614
10729
  error: String(error)
10615
10730
  }
@@ -10621,6 +10736,7 @@ function createKnowledgeOperations(config, llm, embedding, datapipe2, store) {
10621
10736
  * 导入文档到知识库
10622
10737
  *
10623
10738
  * 流程:清洗 → 分块 → Embedding/完整实体准备 → 持久暂存 → vecdb → CAS 发布;
10739
+ * 清洗或分块失败时终止导入,避免对未按规则处理的正文生成向量。
10624
10740
  * 实体提取失败不发布新版本,已发布版本与待清理数据分别报告。
10625
10741
  *
10626
10742
  * @param input - 导入输入(documentId、content、可选 cleanOptions / chunkOptions / metadata 等)
@@ -10641,7 +10757,9 @@ function createKnowledgeOperations(config, llm, embedding, datapipe2, store) {
10641
10757
  const enableEntityExtraction = input.enableEntityExtraction ?? config.enableEntityExtraction;
10642
10758
  const cleanOptions = {
10643
10759
  ...config.cleanOptions,
10644
- ...input.cleanOptions
10760
+ ...input.cleanOptions,
10761
+ normalizeWhitespace: input.cleanOptions?.normalizeWhitespace ?? config.cleanOptions.normalizeWhitespace,
10762
+ trim: input.cleanOptions?.trim ?? config.cleanOptions.trim
10645
10763
  };
10646
10764
  const chunkOptions = {
10647
10765
  ...config.chunkOptions,
@@ -10650,12 +10768,10 @@ function createKnowledgeOperations(config, llm, embedding, datapipe2, store) {
10650
10768
  logger18.trace("Ingesting document", { documentId: input.documentId, collection, contentLength: input.content.length });
10651
10769
  try {
10652
10770
  if (!await isCollectionReady(collection))
10653
- return err(HaiAIError.KNOWLEDGE_NOT_SETUP, aiM("ai_knowledgeNotSetup"));
10654
- let chunkResult = await datapipe2.pipeline().clean(cleanOptions).chunk(chunkOptions).run(input.content);
10655
- if (!chunkResult.success && (chunkResult.error.code === HaiDatapipeError.CLEAN_FAILED.code || chunkResult.error.code === HaiDatapipeError.CONFIG_ERROR.code))
10656
- chunkResult = await datapipe2.pipeline().chunk(chunkOptions).run(input.content);
10771
+ return core.err(HaiAIError.KNOWLEDGE_NOT_SETUP, aiM("ai_knowledgeNotSetup"));
10772
+ const chunkResult = await datapipe2.pipeline().clean(cleanOptions).chunk(chunkOptions).run(input.content);
10657
10773
  if (!chunkResult.success) {
10658
- return err(HaiAIError.KNOWLEDGE_INGEST_FAILED, aiM("ai_knowledgeIngestFailed", {
10774
+ return core.err(HaiAIError.KNOWLEDGE_INGEST_FAILED, aiM("ai_knowledgeIngestFailed", {
10659
10775
  params: { error: chunkResult.error.message }
10660
10776
  }), chunkResult.error);
10661
10777
  }
@@ -10663,7 +10779,7 @@ function createKnowledgeOperations(config, llm, embedding, datapipe2, store) {
10663
10779
  const texts = chunks.map((c) => c.content);
10664
10780
  const embedResult = await embedding.embedBatch(texts);
10665
10781
  if (!embedResult.success) {
10666
- return err(HaiAIError.KNOWLEDGE_INGEST_FAILED, aiM("ai_knowledgeIngestFailed", {
10782
+ return core.err(HaiAIError.KNOWLEDGE_INGEST_FAILED, aiM("ai_knowledgeIngestFailed", {
10667
10783
  params: { error: "Embedding failed" }
10668
10784
  }), embedResult.error);
10669
10785
  }
@@ -10715,7 +10831,7 @@ function createKnowledgeOperations(config, llm, embedding, datapipe2, store) {
10715
10831
  });
10716
10832
  }
10717
10833
  } else {
10718
- return err(HaiAIError.KNOWLEDGE_INGEST_FAILED, aiM("ai_knowledgeIngestFailed", {
10834
+ return core.err(HaiAIError.KNOWLEDGE_INGEST_FAILED, aiM("ai_knowledgeIngestFailed", {
10719
10835
  params: { error: entityResult.error.message }
10720
10836
  }), entityResult.error);
10721
10837
  }
@@ -10739,7 +10855,7 @@ function createKnowledgeOperations(config, llm, embedding, datapipe2, store) {
10739
10855
  entityCount: extractedEntities.length,
10740
10856
  duration
10741
10857
  });
10742
- return ok({
10858
+ return core.ok({
10743
10859
  documentId: input.documentId,
10744
10860
  revision,
10745
10861
  cleanupPending: published.cleanupPending,
@@ -10749,7 +10865,7 @@ function createKnowledgeOperations(config, llm, embedding, datapipe2, store) {
10749
10865
  });
10750
10866
  } catch (error) {
10751
10867
  logger18.error("Document ingestion failed", { documentId: input.documentId, error });
10752
- return err(HaiAIError.KNOWLEDGE_INGEST_FAILED, aiM("ai_knowledgeIngestFailed", {
10868
+ return core.err(HaiAIError.KNOWLEDGE_INGEST_FAILED, aiM("ai_knowledgeIngestFailed", {
10753
10869
  params: {
10754
10870
  error: String(error)
10755
10871
  }
@@ -10779,10 +10895,10 @@ function createKnowledgeOperations(config, llm, embedding, datapipe2, store) {
10779
10895
  });
10780
10896
  try {
10781
10897
  if (!await isCollectionReady(collection))
10782
- return err(HaiAIError.KNOWLEDGE_NOT_SETUP, aiM("ai_knowledgeNotSetup"));
10898
+ return core.err(HaiAIError.KNOWLEDGE_NOT_SETUP, aiM("ai_knowledgeNotSetup"));
10783
10899
  const embedResult = await embedding.embedText(query);
10784
10900
  if (!embedResult.success) {
10785
- return err(HaiAIError.KNOWLEDGE_RETRIEVE_FAILED, aiM("ai_knowledgeRetrieveFailed", {
10901
+ return core.err(HaiAIError.KNOWLEDGE_RETRIEVE_FAILED, aiM("ai_knowledgeRetrieveFailed", {
10786
10902
  params: { error: "Query embedding failed" }
10787
10903
  }), embedResult.error);
10788
10904
  }
@@ -10858,7 +10974,7 @@ function createKnowledgeOperations(config, llm, embedding, datapipe2, store) {
10858
10974
  }
10859
10975
  const duration = Date.now() - startTime;
10860
10976
  logger18.trace("Knowledge retrieval completed", { resultCount: items.length, duration });
10861
- return ok({
10977
+ return core.ok({
10862
10978
  items,
10863
10979
  citations: Array.from(citationMap.values()),
10864
10980
  query,
@@ -10866,7 +10982,7 @@ function createKnowledgeOperations(config, llm, embedding, datapipe2, store) {
10866
10982
  });
10867
10983
  } catch (error) {
10868
10984
  logger18.error("Knowledge retrieval failed", { error });
10869
- return err(HaiAIError.KNOWLEDGE_RETRIEVE_FAILED, aiM("ai_knowledgeRetrieveFailed", {
10985
+ return core.err(HaiAIError.KNOWLEDGE_RETRIEVE_FAILED, aiM("ai_knowledgeRetrieveFailed", {
10870
10986
  params: {
10871
10987
  error: String(error)
10872
10988
  }
@@ -10886,7 +11002,7 @@ function createKnowledgeOperations(config, llm, embedding, datapipe2, store) {
10886
11002
  async ask(query, options) {
10887
11003
  const retrieveResult = await this.retrieve(query, options);
10888
11004
  if (!retrieveResult.success) {
10889
- return err(HaiAIError.RAG_FAILED, aiM("ai_ragFailed", {
11005
+ return core.err(HaiAIError.RAG_FAILED, aiM("ai_ragFailed", {
10890
11006
  params: { error: retrieveResult.error.message }
10891
11007
  }), retrieveResult.error);
10892
11008
  }
@@ -10915,7 +11031,7 @@ ${contextText}
10915
11031
  temperature: options?.temperature
10916
11032
  });
10917
11033
  if (!chatResult.success) {
10918
- return err(HaiAIError.RAG_FAILED, aiM("ai_ragFailed", {
11034
+ return core.err(HaiAIError.RAG_FAILED, aiM("ai_ragFailed", {
10919
11035
  params: { error: chatResult.error.message }
10920
11036
  }), chatResult.error);
10921
11037
  }
@@ -10925,7 +11041,7 @@ ${contextText}
10925
11041
  contextCount: items.length,
10926
11042
  model: chatResult.data.model
10927
11043
  });
10928
- return ok({
11044
+ return core.ok({
10929
11045
  answer,
10930
11046
  context: items,
10931
11047
  citations,
@@ -10942,16 +11058,16 @@ ${contextText}
10942
11058
  async findByEntity(entityName, options) {
10943
11059
  const collection = options?.collection ?? config.collection;
10944
11060
  if (!store) {
10945
- return err(HaiAIError.KNOWLEDGE_NOT_SETUP, aiM("ai_knowledgeNotSetup"));
11061
+ return core.err(HaiAIError.KNOWLEDGE_NOT_SETUP, aiM("ai_knowledgeNotSetup"));
10946
11062
  }
10947
11063
  try {
10948
11064
  if (!await isCollectionReady(collection))
10949
- return err(HaiAIError.KNOWLEDGE_NOT_SETUP, aiM("ai_knowledgeNotSetup"));
11065
+ return core.err(HaiAIError.KNOWLEDGE_NOT_SETUP, aiM("ai_knowledgeNotSetup"));
10950
11066
  const results = await store.findByEntityName(entityName, {
10951
11067
  collection,
10952
11068
  type: options?.type
10953
11069
  });
10954
- return ok(results.map((item2) => ({
11070
+ return core.ok(results.map((item2) => ({
10955
11071
  entity: {
10956
11072
  id: item2.entity.id,
10957
11073
  name: item2.entity.name,
@@ -10968,7 +11084,7 @@ ${contextText}
10968
11084
  }))
10969
11085
  })));
10970
11086
  } catch (error) {
10971
- return err(HaiAIError.KNOWLEDGE_RETRIEVE_FAILED, aiM("ai_knowledgeRetrieveFailed", {
11087
+ return core.err(HaiAIError.KNOWLEDGE_RETRIEVE_FAILED, aiM("ai_knowledgeRetrieveFailed", {
10972
11088
  params: {
10973
11089
  error: String(error)
10974
11090
  }
@@ -10978,7 +11094,7 @@ ${contextText}
10978
11094
  // ─── listEntities ───
10979
11095
  async listEntities(options) {
10980
11096
  if (!store) {
10981
- return err(HaiAIError.KNOWLEDGE_NOT_SETUP, aiM("ai_knowledgeNotSetup"));
11097
+ return core.err(HaiAIError.KNOWLEDGE_NOT_SETUP, aiM("ai_knowledgeNotSetup"));
10982
11098
  }
10983
11099
  try {
10984
11100
  const rows = await store.listEntities({
@@ -10987,7 +11103,7 @@ ${contextText}
10987
11103
  keyword: options?.keyword,
10988
11104
  limit: options?.limit
10989
11105
  });
10990
- return ok(rows.map((row) => ({
11106
+ return core.ok(rows.map((row) => ({
10991
11107
  id: row.id,
10992
11108
  name: row.name,
10993
11109
  type: row.type,
@@ -10997,7 +11113,7 @@ ${contextText}
10997
11113
  updatedAt: row.updatedAt ?? void 0
10998
11114
  })));
10999
11115
  } catch (error) {
11000
- return err(HaiAIError.KNOWLEDGE_RETRIEVE_FAILED, aiM("ai_knowledgeRetrieveFailed", {
11116
+ return core.err(HaiAIError.KNOWLEDGE_RETRIEVE_FAILED, aiM("ai_knowledgeRetrieveFailed", {
11001
11117
  params: {
11002
11118
  error: String(error)
11003
11119
  }
@@ -11008,11 +11124,11 @@ ${contextText}
11008
11124
  async listDocuments(options) {
11009
11125
  const collection = options?.collection ?? config.collection;
11010
11126
  if (!store) {
11011
- return err(HaiAIError.KNOWLEDGE_NOT_SETUP, aiM("ai_knowledgeNotSetup"));
11127
+ return core.err(HaiAIError.KNOWLEDGE_NOT_SETUP, aiM("ai_knowledgeNotSetup"));
11012
11128
  }
11013
11129
  try {
11014
11130
  if (!await isCollectionReady(collection))
11015
- return err(HaiAIError.KNOWLEDGE_NOT_SETUP, aiM("ai_knowledgeNotSetup"));
11131
+ return core.err(HaiAIError.KNOWLEDGE_NOT_SETUP, aiM("ai_knowledgeNotSetup"));
11016
11132
  const docs = await store.listDocuments(collection, {
11017
11133
  offset: options?.offset,
11018
11134
  limit: options?.limit
@@ -11026,9 +11142,9 @@ ${contextText}
11026
11142
  entityCount: d.entityCount,
11027
11143
  createdAt: d.createdAt
11028
11144
  }));
11029
- return ok(result);
11145
+ return core.ok(result);
11030
11146
  } catch (error) {
11031
- return err(HaiAIError.KNOWLEDGE_RETRIEVE_FAILED, aiM("ai_knowledgeRetrieveFailed", {
11147
+ return core.err(HaiAIError.KNOWLEDGE_RETRIEVE_FAILED, aiM("ai_knowledgeRetrieveFailed", {
11032
11148
  params: {
11033
11149
  error: String(error)
11034
11150
  }
@@ -11039,16 +11155,16 @@ ${contextText}
11039
11155
  async removeDocument(documentId, options) {
11040
11156
  const collection = options?.collection ?? config.collection;
11041
11157
  if (!store) {
11042
- return err(HaiAIError.KNOWLEDGE_NOT_SETUP, aiM("ai_knowledgeNotSetup"));
11158
+ return core.err(HaiAIError.KNOWLEDGE_NOT_SETUP, aiM("ai_knowledgeNotSetup"));
11043
11159
  }
11044
11160
  try {
11045
11161
  if (!await isCollectionReady(collection))
11046
- return err(HaiAIError.KNOWLEDGE_NOT_SETUP, aiM("ai_knowledgeNotSetup"));
11162
+ return core.err(HaiAIError.KNOWLEDGE_NOT_SETUP, aiM("ai_knowledgeNotSetup"));
11047
11163
  await store.removeDocument(documentId, collection);
11048
11164
  logger18.debug("Document removed", { documentId, collection });
11049
- return ok(void 0);
11165
+ return core.ok(void 0);
11050
11166
  } catch (error) {
11051
- return err(HaiAIError.KNOWLEDGE_INGEST_FAILED, aiM("ai_knowledgeIngestFailed", {
11167
+ return core.err(HaiAIError.KNOWLEDGE_INGEST_FAILED, aiM("ai_knowledgeIngestFailed", {
11052
11168
  params: {
11053
11169
  error: String(error)
11054
11170
  }
@@ -11060,16 +11176,16 @@ ${contextText}
11060
11176
  */
11061
11177
  async repair(options) {
11062
11178
  if (!store)
11063
- return err(HaiAIError.KNOWLEDGE_NOT_SETUP, aiM("ai_knowledgeNotSetup"));
11179
+ return core.err(HaiAIError.KNOWLEDGE_NOT_SETUP, aiM("ai_knowledgeNotSetup"));
11064
11180
  if (!Number.isSafeInteger(options?.offset ?? 0) || (options?.offset ?? 0) < 0 || !Number.isSafeInteger(options?.limit ?? 100) || (options?.limit ?? 100) < 1 || (options?.limit ?? 100) > 1e3) {
11065
- return err(HaiAIError.KNOWLEDGE_INGEST_FAILED, aiM("ai_knowledgeIngestFailed", {
11181
+ return core.err(HaiAIError.KNOWLEDGE_INGEST_FAILED, aiM("ai_knowledgeIngestFailed", {
11066
11182
  params: { error: "Repair offset must be nonnegative and limit must be between 1 and 1000" }
11067
11183
  }));
11068
11184
  }
11069
11185
  try {
11070
- return ok(await store.repair(options?.collection ?? config.collection, options));
11186
+ return core.ok(await store.repair(options?.collection ?? config.collection, options));
11071
11187
  } catch (error) {
11072
- return err(HaiAIError.KNOWLEDGE_INGEST_FAILED, aiM("ai_knowledgeIngestFailed", {
11188
+ return core.err(HaiAIError.KNOWLEDGE_INGEST_FAILED, aiM("ai_knowledgeIngestFailed", {
11073
11189
  params: {
11074
11190
  error: String(error)
11075
11191
  }
@@ -11098,7 +11214,7 @@ ${contextText}
11098
11214
  chunkOptions: input.chunkOptions
11099
11215
  });
11100
11216
  } catch (error) {
11101
- return err(HaiAIError.KNOWLEDGE_INGEST_FAILED, aiM("ai_knowledgeIngestFailed", {
11217
+ return core.err(HaiAIError.KNOWLEDGE_INGEST_FAILED, aiM("ai_knowledgeIngestFailed", {
11102
11218
  params: {
11103
11219
  error: String(error)
11104
11220
  }
@@ -11137,7 +11253,7 @@ ${contextText}
11137
11253
  });
11138
11254
  }
11139
11255
  }
11140
- return ok({
11256
+ return core.ok({
11141
11257
  successCount,
11142
11258
  failureCount,
11143
11259
  results,
@@ -11147,7 +11263,7 @@ ${contextText}
11147
11263
  // ─── deleteCollection ───
11148
11264
  async deleteCollection(collection) {
11149
11265
  if (!store) {
11150
- return err(HaiAIError.KNOWLEDGE_SETUP_FAILED, aiM("ai_knowledgeSetupFailed", {
11266
+ return core.err(HaiAIError.KNOWLEDGE_SETUP_FAILED, aiM("ai_knowledgeSetupFailed", {
11151
11267
  params: { error: "KnowledgeStore not available. Provider may not support knowledge operations." }
11152
11268
  }));
11153
11269
  }
@@ -11156,10 +11272,10 @@ ${contextText}
11156
11272
  try {
11157
11273
  await store.deleteCollection(col);
11158
11274
  logger18.debug("Knowledge collection deleted", { collection: col });
11159
- return ok(void 0);
11275
+ return core.ok(void 0);
11160
11276
  } catch (error) {
11161
11277
  logger18.error("Knowledge collection deletion failed", { collection: col, error });
11162
- return err(HaiAIError.KNOWLEDGE_SETUP_FAILED, aiM("ai_knowledgeSetupFailed", {
11278
+ return core.err(HaiAIError.KNOWLEDGE_SETUP_FAILED, aiM("ai_knowledgeSetupFailed", {
11163
11279
  params: {
11164
11280
  error: String(error)
11165
11281
  }
@@ -11169,6 +11285,138 @@ ${contextText}
11169
11285
  };
11170
11286
  }
11171
11287
 
11288
+ // src/llm/ai-llm-json-preview.ts
11289
+ var escapedCharacters = {
11290
+ '"': '"',
11291
+ "\\": "\\",
11292
+ "/": "/",
11293
+ "b": "\b",
11294
+ "f": "\f",
11295
+ "n": "\n",
11296
+ "r": "\r",
11297
+ "t": " "
11298
+ };
11299
+ function createJsonFieldPreview(field, options = {}) {
11300
+ const { maxLength = 12e3, maxInputLength = 1e6 } = options;
11301
+ if (!field || !Number.isSafeInteger(maxLength) || maxLength < 1 || !Number.isSafeInteger(maxInputLength) || maxInputLength < 1) {
11302
+ throw new RangeError("Invalid JSON preview limits");
11303
+ }
11304
+ let received = 0;
11305
+ let depth = 0;
11306
+ let phase = "root";
11307
+ let inString = false;
11308
+ let capture;
11309
+ let escaping = false;
11310
+ let unicode;
11311
+ let token = "";
11312
+ let matches = false;
11313
+ let preview = "";
11314
+ let published = "";
11315
+ let finished = false;
11316
+ function append(character) {
11317
+ if (capture === "key" && token.length <= field.length)
11318
+ token += character;
11319
+ if (capture === "value" && preview.length < maxLength)
11320
+ preview += character;
11321
+ }
11322
+ function readString(character) {
11323
+ if (unicode !== void 0) {
11324
+ if (!/^[\da-f]$/i.test(character)) {
11325
+ finished = true;
11326
+ return;
11327
+ }
11328
+ unicode += character;
11329
+ if (unicode.length === 4) {
11330
+ append(String.fromCharCode(Number.parseInt(unicode, 16)));
11331
+ unicode = void 0;
11332
+ }
11333
+ return;
11334
+ }
11335
+ if (escaping) {
11336
+ escaping = false;
11337
+ if (character === "u") {
11338
+ unicode = "";
11339
+ } else if (Object.hasOwn(escapedCharacters, character)) {
11340
+ append(escapedCharacters[character]);
11341
+ } else {
11342
+ finished = true;
11343
+ }
11344
+ return;
11345
+ }
11346
+ if (character === "\\") {
11347
+ escaping = true;
11348
+ return;
11349
+ }
11350
+ if (character !== '"') {
11351
+ append(character);
11352
+ return;
11353
+ }
11354
+ inString = false;
11355
+ if (capture === "key") {
11356
+ matches = token === field;
11357
+ phase = "colon";
11358
+ } else if (capture === "value") {
11359
+ finished = true;
11360
+ }
11361
+ capture = void 0;
11362
+ }
11363
+ return {
11364
+ push(fragment) {
11365
+ received += fragment.length;
11366
+ if (received > maxInputLength)
11367
+ throw new RangeError("JSON stream exceeds its input length limit");
11368
+ for (const character of fragment) {
11369
+ if (finished)
11370
+ break;
11371
+ if (inString) {
11372
+ readString(character);
11373
+ continue;
11374
+ }
11375
+ if (/\s/u.test(character))
11376
+ continue;
11377
+ if (phase === "root") {
11378
+ if (character !== "{") {
11379
+ finished = true;
11380
+ break;
11381
+ }
11382
+ depth = 1;
11383
+ phase = "key";
11384
+ continue;
11385
+ }
11386
+ if (character === '"') {
11387
+ inString = true;
11388
+ if (depth === 1 && phase === "key") {
11389
+ capture = "key";
11390
+ token = "";
11391
+ } else if (depth === 1 && phase === "value") {
11392
+ capture = matches ? "value" : void 0;
11393
+ phase = "afterValue";
11394
+ }
11395
+ } else if (character === "{" || character === "[") {
11396
+ if (depth === 1 && phase === "value")
11397
+ phase = "afterValue";
11398
+ depth++;
11399
+ } else if (character === "}" || character === "]") {
11400
+ if (--depth === 0)
11401
+ finished = true;
11402
+ } else if (depth === 1) {
11403
+ if (character === ":" && phase === "colon")
11404
+ phase = "value";
11405
+ else if (character === "," && phase === "afterValue")
11406
+ phase = "key";
11407
+ else if (phase === "value")
11408
+ phase = "afterValue";
11409
+ }
11410
+ }
11411
+ const prefix = preview.slice(0, maxLength).replace(/[\uD800-\uDBFF]$/u, "");
11412
+ if (prefix === published)
11413
+ return void 0;
11414
+ published = prefix;
11415
+ return prefix;
11416
+ }
11417
+ };
11418
+ }
11419
+
11172
11420
  // src/tools/ai-tools-protocol-schema.ts
11173
11421
  var maps = /* @__PURE__ */ new Set([
11174
11422
  "properties",
@@ -11230,12 +11478,12 @@ function projectToolProtocolSchema(schema) {
11230
11478
  var logger19 = core.logger.child({ module: "ai", scope: "tool-protocol" });
11231
11479
  function decodeCall(call) {
11232
11480
  if (call.type !== "function")
11233
- return err(HaiAIError.TOOL_PROTOCOL_ERROR, aiM("ai_toolInvalidCall"));
11481
+ return core.err(HaiAIError.TOOL_PROTOCOL_ERROR, aiM("ai_toolInvalidCall"));
11234
11482
  try {
11235
11483
  const input = JSON.parse(call.function.arguments);
11236
- return ok({ name: call.function.name, input });
11484
+ return core.ok({ name: call.function.name, input });
11237
11485
  } catch (cause) {
11238
- return err(HaiAIError.TOOL_PROTOCOL_ERROR, aiM("ai_toolInvalidJson"), cause);
11486
+ return core.err(HaiAIError.TOOL_PROTOCOL_ERROR, aiM("ai_toolInvalidJson"), cause);
11239
11487
  }
11240
11488
  }
11241
11489
  function encodeResult(call, output) {
@@ -11243,10 +11491,10 @@ function encodeResult(call, output) {
11243
11491
  const content = typeof output === "string" ? output : JSON.stringify(output === void 0 ? null : output);
11244
11492
  if (typeof content !== "string")
11245
11493
  throw new TypeError("Tool output is not JSON serializable");
11246
- return ok({ role: "tool", tool_call_id: call.id, content });
11494
+ return core.ok({ role: "tool", tool_call_id: call.id, content });
11247
11495
  } catch (cause) {
11248
11496
  logger19.error("Tool result encoding failed", { code: HaiAIError.TOOL_RESULT_ERROR.code });
11249
- return err(HaiAIError.TOOL_RESULT_ERROR, aiM("ai_toolInvalidResult"), cause);
11497
+ return core.err(HaiAIError.TOOL_RESULT_ERROR, aiM("ai_toolInvalidResult"), cause);
11250
11498
  }
11251
11499
  }
11252
11500
  function adaptToolRegistry(registry) {
@@ -11286,7 +11534,7 @@ function adaptToolRegistry(registry) {
11286
11534
  return encoded;
11287
11535
  messages.push(encoded.data);
11288
11536
  }
11289
- return ok(messages);
11537
+ return core.ok(messages);
11290
11538
  }
11291
11539
  };
11292
11540
  }
@@ -11454,13 +11702,13 @@ function createAnthropicProvider(deps) {
11454
11702
  const model = tempModel?.model ?? entry?.model ?? requestModel ?? config.llm.model ?? "claude-3-5-sonnet-latest";
11455
11703
  const apiKey = tempModel?.apiKey ?? entry?.apiKey ?? config.llm.apiKey ?? (process2.env.HAI_AI_LLM_APIKEY?.trim() || process2.env.ANTHROPIC_API_KEY);
11456
11704
  if (!apiKey) {
11457
- return err(HaiAIError.CONFIGURATION_ERROR, aiM("ai_configError", {
11705
+ return core.err(HaiAIError.CONFIGURATION_ERROR, aiM("ai_configError", {
11458
11706
  params: { error: "API Key is required for Anthropic" }
11459
11707
  }));
11460
11708
  }
11461
11709
  const globalBaseUrl = config.llm.protocol === "anthropic" ? config.llm.baseUrl ?? (process2.env.HAI_AI_LLM_BASEURL?.trim() || void 0) : void 0;
11462
11710
  const baseUrl = (tempModel?.baseUrl ?? entry?.baseUrl ?? globalBaseUrl ?? process2.env.ANTHROPIC_BASE_URL ?? DEFAULT_ANTHROPIC_BASE_URL).replace(/\/+$/, "");
11463
- return ok({
11711
+ return core.ok({
11464
11712
  apiKey,
11465
11713
  baseUrl,
11466
11714
  model,
@@ -11518,14 +11766,14 @@ function createAnthropicProvider(deps) {
11518
11766
  if (!res.ok) {
11519
11767
  const detail = await res.text().catch(() => res.statusText);
11520
11768
  const mapped = httpError(res.status, detail.slice(0, 500));
11521
- return err(mapped.def, mapped.message, { status: res.status });
11769
+ return core.err(mapped.def, mapped.message, { status: res.status });
11522
11770
  }
11523
11771
  const data = await res.json();
11524
- return ok(toChatResponse(data, resolved.model));
11772
+ return core.ok(toChatResponse(data, resolved.model));
11525
11773
  } catch (error) {
11526
11774
  if (error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError"))
11527
- return err(HaiAIError.TIMEOUT, aiM("ai_requestTimeout"), { message: error.message });
11528
- return err(HaiAIError.INTERNAL_ERROR, aiM("ai_internalError", {
11775
+ return core.err(HaiAIError.TIMEOUT, aiM("ai_requestTimeout"), { message: error.message });
11776
+ return core.err(HaiAIError.INTERNAL_ERROR, aiM("ai_internalError", {
11529
11777
  params: {
11530
11778
  error: error instanceof Error ? error.message : "Unknown error"
11531
11779
  }
@@ -11588,7 +11836,7 @@ function createAnthropicProvider(deps) {
11588
11836
  if ((entry.protocol ?? config.llm.protocol) === "anthropic")
11589
11837
  models.add(entry.model);
11590
11838
  }
11591
- return ok([...models]);
11839
+ return core.ok([...models]);
11592
11840
  }
11593
11841
  };
11594
11842
  }
@@ -11862,7 +12110,7 @@ function createOpenAIProvider(deps) {
11862
12110
  return resolvedResult;
11863
12111
  const { apiKey, baseUrl, timeout, model, protocol: api } = resolvedResult.data;
11864
12112
  const resolvedApi = api === "responses" ? "responses" : "chat";
11865
- return ok({
12113
+ return core.ok({
11866
12114
  client: getClient(apiKey ?? "", baseUrl ?? "https://api.openai.com/v1", timeout),
11867
12115
  model,
11868
12116
  protocol: resolvedApi
@@ -11871,14 +12119,14 @@ function createOpenAIProvider(deps) {
11871
12119
  function resolveTempClient(tempModel) {
11872
12120
  const apiKey = tempModel.apiKey ?? config.llm.apiKey ?? (process2.env.HAI_AI_LLM_APIKEY?.trim() || process2.env.OPENAI_API_KEY);
11873
12121
  if (!apiKey) {
11874
- return err(HaiAIError.CONFIGURATION_ERROR, aiM("ai_configError", {
12122
+ return core.err(HaiAIError.CONFIGURATION_ERROR, aiM("ai_configError", {
11875
12123
  params: { error: "API Key is required for temp model" }
11876
12124
  }));
11877
12125
  }
11878
12126
  const baseUrl = tempModel.baseUrl ?? config.llm.baseUrl ?? (process2.env.HAI_AI_LLM_BASEURL?.trim() || process2.env.OPENAI_BASE_URL) ?? "https://api.openai.com/v1";
11879
12127
  const timeout = tempModel.timeout ?? config.llm.timeout ?? 6e4;
11880
12128
  const api = (tempModel.protocol ?? config.llm.protocol) === "responses" ? "responses" : "chat";
11881
- return ok({
12129
+ return core.ok({
11882
12130
  client: getTempClient(apiKey, baseUrl, timeout),
11883
12131
  model: tempModel.model,
11884
12132
  protocol: api,
@@ -11892,7 +12140,7 @@ function createOpenAIProvider(deps) {
11892
12140
  if (responseFormat?.type === "json_schema") {
11893
12141
  const { json_schema: jsonSchema } = responseFormat;
11894
12142
  if (!jsonSchema?.schema)
11895
- return err(HaiAIError.INVALID_REQUEST, aiM("ai_llmResponsesSchemaRequired"));
12143
+ return core.err(HaiAIError.INVALID_REQUEST, aiM("ai_llmResponsesSchemaRequired"));
11896
12144
  const { name, schema, description, strict } = jsonSchema;
11897
12145
  format = {
11898
12146
  type: "json_schema",
@@ -11907,7 +12155,7 @@ function createOpenAIProvider(deps) {
11907
12155
  const maxOutput = request2.max_tokens ?? resolved.maxTokens;
11908
12156
  const temperature = request2.temperature ?? resolved.temperature;
11909
12157
  const toolChoice = typeof request2.tool_choice === "string" ? request2.tool_choice : void 0;
11910
- return ok({
12158
+ return core.ok({
11911
12159
  model: resolved.model,
11912
12160
  input: toResponsesInput(request2.messages),
11913
12161
  ...format ? {
@@ -11937,7 +12185,7 @@ function createOpenAIProvider(deps) {
11937
12185
  if (!params2.success)
11938
12186
  return params2;
11939
12187
  const response2 = await client2.responses.create(params2.data, { signal });
11940
- return ok(responsesToChatResponse(response2, model));
12188
+ return core.ok(responsesToChatResponse(response2, model));
11941
12189
  }
11942
12190
  const openaiMessages = request2.messages.map(toOpenAIMessage);
11943
12191
  const params = {
@@ -11949,10 +12197,10 @@ function createOpenAIProvider(deps) {
11949
12197
  stream: false
11950
12198
  };
11951
12199
  const response = signal ? await client2.chat.completions.create(params, { signal }) : await client2.chat.completions.create(params);
11952
- return ok(response);
12200
+ return core.ok(response);
11953
12201
  } catch (error) {
11954
12202
  const mapped = toAIError(error);
11955
- return err(mapped.def, mapped.message, mapped.cause);
12203
+ return core.err(mapped.def, mapped.message, mapped.cause);
11956
12204
  }
11957
12205
  },
11958
12206
  async *chatStream(request2) {
@@ -12002,10 +12250,10 @@ function createOpenAIProvider(deps) {
12002
12250
  try {
12003
12251
  const response = await client2.models.list();
12004
12252
  const models = response.data.map((m) => m.id);
12005
- return ok(models);
12253
+ return core.ok(models);
12006
12254
  } catch (error) {
12007
12255
  const mapped = toAIError(error);
12008
- return err(mapped.def, mapped.message, mapped.cause);
12256
+ return core.err(mapped.def, mapped.message, mapped.cause);
12009
12257
  }
12010
12258
  }
12011
12259
  };
@@ -12097,7 +12345,7 @@ function createAILLMFunctions(config, deps) {
12097
12345
  try {
12098
12346
  result = await (await currentProvider()).chat(request2);
12099
12347
  } catch {
12100
- return err(
12348
+ return core.err(
12101
12349
  HaiAIError.RESOURCE_OPERATION_FAILED,
12102
12350
  aiM("ai_resourceOperationFailed")
12103
12351
  );
@@ -12243,7 +12491,7 @@ function createAILLMFunctions(config, deps) {
12243
12491
  }
12244
12492
  async function getHistory(scope, options) {
12245
12493
  if (!recordStore) {
12246
- return ok([]);
12494
+ return core.ok([]);
12247
12495
  }
12248
12496
  try {
12249
12497
  const records = await recordStore.query({
@@ -12252,9 +12500,9 @@ function createAILLMFunctions(config, deps) {
12252
12500
  orderBy: { field: "createdAt", direction: options?.order ?? "desc" },
12253
12501
  limit: options?.limit
12254
12502
  });
12255
- return ok(records);
12503
+ return core.ok(records);
12256
12504
  } catch (error) {
12257
- return err(
12505
+ return core.err(
12258
12506
  HaiAIError.LLM_HISTORY_FAILED,
12259
12507
  aiM("ai_llmHistoryFailed", {
12260
12508
  params: {
@@ -12267,16 +12515,16 @@ function createAILLMFunctions(config, deps) {
12267
12515
  }
12268
12516
  async function listSessions(objectId) {
12269
12517
  if (!sessionStore) {
12270
- return ok([]);
12518
+ return core.ok([]);
12271
12519
  }
12272
12520
  try {
12273
12521
  const sessions = await sessionStore.query({
12274
12522
  objectId,
12275
12523
  orderBy: { field: "updatedAt", direction: "desc" }
12276
12524
  });
12277
- return ok(sessions.filter((item2) => !item2.deleted));
12525
+ return core.ok(sessions.filter((item2) => !item2.deleted));
12278
12526
  } catch (error) {
12279
- return err(
12527
+ return core.err(
12280
12528
  HaiAIError.LLM_HISTORY_FAILED,
12281
12529
  aiM("ai_llmHistoryFailed", {
12282
12530
  params: {
@@ -12294,7 +12542,7 @@ function createAILLMFunctions(config, deps) {
12294
12542
  try {
12295
12543
  return await (await currentProvider()).listModels();
12296
12544
  } catch {
12297
- return err(
12545
+ return core.err(
12298
12546
  HaiAIError.RESOURCE_OPERATION_FAILED,
12299
12547
  aiM("ai_resourceOperationFailed")
12300
12548
  );
@@ -12320,7 +12568,7 @@ function createAILLMFunctions(config, deps) {
12320
12568
  });
12321
12569
  if (!result.success)
12322
12570
  return result;
12323
- return ok(result.data.choices[0]?.message?.content ?? "");
12571
+ return core.ok(result.data.choices[0]?.message?.content ?? "");
12324
12572
  },
12325
12573
  async *askStream(question, options) {
12326
12574
  const messages = [];
@@ -12348,7 +12596,14 @@ function createAILLMFunctions(config, deps) {
12348
12596
  if (request2.systemPrompt)
12349
12597
  baseMessages.push({ role: "system", content: request2.systemPrompt });
12350
12598
  baseMessages.push(...request2.messages);
12351
- const jsonSchema = z.toJSONSchema(request2.schema);
12599
+ let jsonSchema;
12600
+ try {
12601
+ jsonSchema = z.toJSONSchema(request2.schema);
12602
+ } catch {
12603
+ return core.err(HaiAIError.INVALID_REQUEST, aiM("ai_generateObjectFailed", {
12604
+ params: { error: "schema cannot be represented as JSON Schema" }
12605
+ }));
12606
+ }
12352
12607
  const jsonObject = request2.responseFormat === "json_object";
12353
12608
  if (jsonObject) {
12354
12609
  baseMessages.unshift({
@@ -12373,35 +12628,83 @@ function createAILLMFunctions(config, deps) {
12373
12628
  })
12374
12629
  }
12375
12630
  ];
12376
- const result = await chatWithRecord({
12631
+ const chatRequest = {
12377
12632
  messages,
12378
12633
  model: request2.model,
12379
12634
  temperature: request2.temperature,
12380
12635
  tempModel: request2.tempModel,
12381
12636
  enablePersist: false,
12382
12637
  signal: request2.signal,
12638
+ max_tokens: request2.maxTokens,
12383
12639
  response_format: jsonObject ? { type: "json_object" } : {
12384
12640
  type: "json_schema",
12385
12641
  json_schema: { name: schemaName, schema: jsonSchema, strict: true }
12386
12642
  }
12387
- });
12388
- if (!result.success)
12389
- return result;
12390
- const content = result.data.choices[0]?.message?.content;
12391
- const text = typeof content === "string" ? content : "";
12643
+ };
12644
+ const preview = request2.preview;
12645
+ let text = "";
12646
+ let previewPublished = false;
12647
+ async function clearPreview() {
12648
+ if (!previewPublished)
12649
+ return;
12650
+ try {
12651
+ await preview?.onPrefix("");
12652
+ } catch {
12653
+ logger20.warn("Structured output preview cleanup failed");
12654
+ }
12655
+ }
12656
+ let finishReason = null;
12657
+ if (preview) {
12658
+ try {
12659
+ const parser = createJsonFieldPreview(preview.field, preview);
12660
+ for await (const chunk of chatStreamWithRecord(chatRequest)) {
12661
+ const choice = chunk.choices.find((item2) => item2.index === 0);
12662
+ if (!choice)
12663
+ continue;
12664
+ finishReason = choice.finish_reason ?? finishReason;
12665
+ const fragment = choice.delta.content;
12666
+ if (!fragment)
12667
+ continue;
12668
+ const prefix = parser.push(fragment);
12669
+ text += fragment;
12670
+ if (prefix !== void 0) {
12671
+ previewPublished = true;
12672
+ await preview.onPrefix(prefix);
12673
+ }
12674
+ }
12675
+ } catch {
12676
+ await clearPreview();
12677
+ return core.err(HaiAIError.RESOURCE_OPERATION_FAILED, aiM("ai_resourceOperationFailed"));
12678
+ }
12679
+ if (request2.signal?.aborted || finishReason !== "stop") {
12680
+ await clearPreview();
12681
+ lastError = "structured response did not finish";
12682
+ if (request2.signal?.aborted)
12683
+ break;
12684
+ continue;
12685
+ }
12686
+ } else {
12687
+ const result = await chatWithRecord(chatRequest);
12688
+ if (!result.success)
12689
+ return result;
12690
+ const content = result.data.choices[0]?.message?.content;
12691
+ text = typeof content === "string" ? content : "";
12692
+ }
12392
12693
  let parsed;
12393
12694
  try {
12394
12695
  parsed = JSON.parse(text);
12395
12696
  } catch {
12697
+ await clearPreview();
12396
12698
  lastError = "invalid JSON";
12397
12699
  continue;
12398
12700
  }
12399
12701
  const validated = request2.schema.safeParse(parsed);
12400
12702
  if (validated.success)
12401
- return ok(validated.data);
12703
+ return core.ok(validated.data);
12704
+ await clearPreview();
12402
12705
  lastError = validated.error.message;
12403
12706
  }
12404
- return err(
12707
+ return core.err(
12405
12708
  HaiAIError.INVALID_REQUEST,
12406
12709
  aiM("ai_generateObjectFailed", {
12407
12710
  params: { error: lastError || "unknown" }
@@ -12414,6 +12717,7 @@ function createAILLMFunctions(config, deps) {
12414
12717
  };
12415
12718
  const stream = {
12416
12719
  createProcessor: createStreamProcessor,
12720
+ createJsonFieldPreview,
12417
12721
  collect: collectStream,
12418
12722
  createSSEDecoder,
12419
12723
  encodeSSE
@@ -12431,9 +12735,9 @@ function createAIMCPFunctions() {
12431
12735
  try {
12432
12736
  const validate = validator.getValidator(definition.inputSchema);
12433
12737
  tools4.set(definition.name, { definition, handler, validate });
12434
- return ok(void 0);
12738
+ return core.ok(void 0);
12435
12739
  } catch (error) {
12436
- return err(HaiAIError.MCP_TOOL_ERROR, aiM("ai_mcpInvalidToolSchema", {
12740
+ return core.err(HaiAIError.MCP_TOOL_ERROR, aiM("ai_mcpInvalidToolSchema", {
12437
12741
  params: { name: definition.name }
12438
12742
  }), error);
12439
12743
  }
@@ -12441,12 +12745,12 @@ function createAIMCPFunctions() {
12441
12745
  /** 注册 MCP 资源(同 URI 覆盖) */
12442
12746
  registerResource(resource, handler) {
12443
12747
  resources.set(resource.uri, { resource, handler });
12444
- return ok(void 0);
12748
+ return core.ok(void 0);
12445
12749
  },
12446
12750
  /** 注册 MCP 提示词模板(同名覆盖) */
12447
12751
  registerPrompt(prompt, handler) {
12448
12752
  prompts.set(prompt.name, { prompt, handler });
12449
- return ok(void 0);
12753
+ return core.ok(void 0);
12450
12754
  },
12451
12755
  /**
12452
12756
  * 调用已注册的 MCP 工具
@@ -12460,21 +12764,21 @@ function createAIMCPFunctions() {
12460
12764
  try {
12461
12765
  const registration = tools4.get(name);
12462
12766
  if (!registration) {
12463
- return err(HaiAIError.MCP_TOOL_ERROR, aiM("ai_mcpToolNotFound", {
12767
+ return core.err(HaiAIError.MCP_TOOL_ERROR, aiM("ai_mcpToolNotFound", {
12464
12768
  params: { name }
12465
12769
  }));
12466
12770
  }
12467
12771
  const validation = registration.validate(args);
12468
12772
  if (!validation.valid) {
12469
- return err(HaiAIError.MCP_TOOL_ERROR, aiM("ai_mcpInvalidToolInput", {
12773
+ return core.err(HaiAIError.MCP_TOOL_ERROR, aiM("ai_mcpInvalidToolInput", {
12470
12774
  params: { name }
12471
12775
  }));
12472
12776
  }
12473
12777
  const ctx = { ...context, requestId: context?.requestId ?? crypto.randomUUID() };
12474
12778
  const result = await registration.handler(args, ctx);
12475
- return ok(result);
12779
+ return core.ok(result);
12476
12780
  } catch (error) {
12477
- return err(
12781
+ return core.err(
12478
12782
  HaiAIError.MCP_TOOL_ERROR,
12479
12783
  aiM("ai_mcpToolFailed", {
12480
12784
  params: {
@@ -12496,7 +12800,7 @@ function createAIMCPFunctions() {
12496
12800
  try {
12497
12801
  const registration = resources.get(uri);
12498
12802
  if (!registration) {
12499
- return err(HaiAIError.MCP_RESOURCE_ERROR, aiM("ai_mcpResourceNotFound", {
12803
+ return core.err(HaiAIError.MCP_RESOURCE_ERROR, aiM("ai_mcpResourceNotFound", {
12500
12804
  params: { uri }
12501
12805
  }));
12502
12806
  }
@@ -12504,13 +12808,13 @@ function createAIMCPFunctions() {
12504
12808
  const text = TextResourceContentsSchema.safeParse(content);
12505
12809
  const blob = BlobResourceContentsSchema.safeParse(content);
12506
12810
  if (text.success === blob.success || text.success && Object.hasOwn(content, "blob") || blob.success && Object.hasOwn(content, "text")) {
12507
- return err(HaiAIError.MCP_RESOURCE_ERROR, aiM("ai_mcpInvalidResource", {
12811
+ return core.err(HaiAIError.MCP_RESOURCE_ERROR, aiM("ai_mcpInvalidResource", {
12508
12812
  params: { uri }
12509
12813
  }));
12510
12814
  }
12511
- return ok(content);
12815
+ return core.ok(content);
12512
12816
  } catch (error) {
12513
- return err(
12817
+ return core.err(
12514
12818
  HaiAIError.MCP_RESOURCE_ERROR,
12515
12819
  aiM("ai_mcpResourceFailed", {
12516
12820
  params: {
@@ -12535,31 +12839,31 @@ function createAIMCPFunctions() {
12535
12839
  try {
12536
12840
  const registration = prompts.get(name);
12537
12841
  if (!registration) {
12538
- return err(HaiAIError.MCP_PROTOCOL_ERROR, aiM("ai_mcpPromptNotFound", {
12842
+ return core.err(HaiAIError.MCP_PROTOCOL_ERROR, aiM("ai_mcpPromptNotFound", {
12539
12843
  params: { name }
12540
12844
  }));
12541
12845
  }
12542
12846
  for (const arg of registration.prompt.arguments || []) {
12543
12847
  if (arg.required && !Object.hasOwn(args, arg.name)) {
12544
- return err(HaiAIError.MCP_PROTOCOL_ERROR, aiM("ai_mcpPromptMissingArg", {
12848
+ return core.err(HaiAIError.MCP_PROTOCOL_ERROR, aiM("ai_mcpPromptMissingArg", {
12545
12849
  params: { name, arg: arg.name }
12546
12850
  }));
12547
12851
  }
12548
12852
  if (Object.hasOwn(args, arg.name) && typeof args[arg.name] !== "string") {
12549
- return err(HaiAIError.MCP_PROTOCOL_ERROR, aiM("ai_mcpInvalidPrompt", {
12853
+ return core.err(HaiAIError.MCP_PROTOCOL_ERROR, aiM("ai_mcpInvalidPrompt", {
12550
12854
  params: { name }
12551
12855
  }));
12552
12856
  }
12553
12857
  }
12554
12858
  const messages = await registration.handler(args);
12555
12859
  if (!Array.isArray(messages) || messages.some((message) => !PromptMessageSchema.safeParse(message).success)) {
12556
- return err(HaiAIError.MCP_PROTOCOL_ERROR, aiM("ai_mcpInvalidPrompt", {
12860
+ return core.err(HaiAIError.MCP_PROTOCOL_ERROR, aiM("ai_mcpInvalidPrompt", {
12557
12861
  params: { name }
12558
12862
  }));
12559
12863
  }
12560
- return ok(messages);
12864
+ return core.ok(messages);
12561
12865
  } catch (error) {
12562
- return err(
12866
+ return core.err(
12563
12867
  HaiAIError.MCP_PROTOCOL_ERROR,
12564
12868
  aiM("ai_mcpPromptFailed", {
12565
12869
  params: {
@@ -12599,7 +12903,7 @@ var digest = (token) => createHash("sha256").update(token).digest("hex");
12599
12903
  function createMCPServiceBroker(read, invoke, options, lifecycle, local) {
12600
12904
  const endpoint = URL.parse(options?.url);
12601
12905
  if (!endpoint || !["http:", "https:"].includes(endpoint.protocol) || endpoint.username || endpoint.password || endpoint.hash || endpoint.search || typeof options.authorize !== "function")
12602
- return err(HaiAIError.RESOURCE_INVALID, aiM("ai_resourceInvalid"));
12906
+ return core.err(HaiAIError.RESOURCE_INVALID, aiM("ai_resourceInvalid"));
12603
12907
  const grants = /* @__PURE__ */ new Map();
12604
12908
  let closed = false;
12605
12909
  function createGrant(input, validators, key) {
@@ -12637,13 +12941,13 @@ function createMCPServiceBroker(read, invoke, options, lifecycle, local) {
12637
12941
  const broker = {
12638
12942
  async bind(request2) {
12639
12943
  if (closed || lifecycle.aborted)
12640
- return err(HaiAIError.NOT_INITIALIZED, aiM("ai_notInitialized"));
12944
+ return core.err(HaiAIError.NOT_INITIALIZED, aiM("ai_notInitialized"));
12641
12945
  try {
12642
12946
  const parsed = bindingSchema.safeParse(request2);
12643
12947
  if (!parsed.success || new Set(parsed.data.tools.map((tool) => tool.id)).size !== parsed.data.tools.length)
12644
- return err(HaiAIError.RESOURCE_INVALID, aiM("ai_resourceInvalid"));
12948
+ return core.err(HaiAIError.RESOURCE_INVALID, aiM("ai_resourceInvalid"));
12645
12949
  if (Buffer.byteLength(JSON.stringify(parsed.data.tools)) > maxRequestBytes)
12646
- return err(HaiAIError.RESOURCE_INVALID, aiM("ai_resourceInvalid"));
12950
+ return core.err(HaiAIError.RESOURCE_INVALID, aiM("ai_resourceInvalid"));
12647
12951
  const input = {
12648
12952
  ...parsed.data,
12649
12953
  tools: structuredClone(parsed.data.tools)
@@ -12655,27 +12959,27 @@ function createMCPServiceBroker(read, invoke, options, lifecycle, local) {
12655
12959
  const catalog = await local.catalog(input.principal, input.taskId, input.signal);
12656
12960
  const actual = catalog.success ? catalog.data.find((item2) => item2.name === tool.tool) : void 0;
12657
12961
  if (!actual || actual.description !== tool.description || JSON.stringify(actual.inputSchema) !== JSON.stringify(tool.inputSchema))
12658
- return err(HaiAIError.MCP_TOOL_FORBIDDEN, aiM("ai_mcpServiceForbidden"));
12962
+ return core.err(HaiAIError.MCP_TOOL_FORBIDDEN, aiM("ai_mcpServiceForbidden"));
12659
12963
  } else {
12660
12964
  if (!services.has(tool.serviceId))
12661
12965
  services.set(tool.serviceId, await read(tool.serviceId));
12662
12966
  const service = services.get(tool.serviceId);
12663
12967
  if (!service || !["http", "job"].includes(service.transport) || !service.allowedTools?.includes(tool.tool))
12664
- return err(HaiAIError.MCP_TOOL_FORBIDDEN, aiM("ai_mcpServiceForbidden"));
12968
+ return core.err(HaiAIError.MCP_TOOL_FORBIDDEN, aiM("ai_mcpServiceForbidden"));
12665
12969
  }
12666
12970
  validators.set(tool.id, new AjvJsonSchemaValidator().getValidator(tool.inputSchema));
12667
12971
  }
12668
12972
  if (closed || lifecycle.aborted)
12669
- return err(HaiAIError.NOT_INITIALIZED, aiM("ai_notInitialized"));
12973
+ return core.err(HaiAIError.NOT_INITIALIZED, aiM("ai_notInitialized"));
12670
12974
  if (grants.size >= 1024)
12671
- return err(HaiAIError.RESOURCE_OPERATION_FAILED, aiM("ai_resourceOperationFailed"));
12975
+ return core.err(HaiAIError.RESOURCE_OPERATION_FAILED, aiM("ai_resourceOperationFailed"));
12672
12976
  const token = randomBytes(32).toString("base64url");
12673
12977
  const key = digest(token);
12674
12978
  const grant = createGrant(input, validators, key);
12675
12979
  if (!grant)
12676
- return err(HaiAIError.MCP_TOOL_CANCELLED, aiM("ai_mcpServiceCancelled"));
12980
+ return core.err(HaiAIError.MCP_TOOL_CANCELLED, aiM("ai_mcpServiceCancelled"));
12677
12981
  grants.set(key, grant);
12678
- return ok({
12982
+ return core.ok({
12679
12983
  servers: [
12680
12984
  {
12681
12985
  type: "http",
@@ -12690,7 +12994,7 @@ function createMCPServiceBroker(read, invoke, options, lifecycle, local) {
12690
12994
  signal: grant.signal
12691
12995
  });
12692
12996
  } catch {
12693
- return err(HaiAIError.RESOURCE_INVALID, aiM("ai_resourceInvalid"));
12997
+ return core.err(HaiAIError.RESOURCE_INVALID, aiM("ai_resourceInvalid"));
12694
12998
  }
12695
12999
  },
12696
13000
  async handleRequest(request2, response) {
@@ -12797,7 +13101,7 @@ function createMCPServiceBroker(read, invoke, options, lifecycle, local) {
12797
13101
  grants.clear();
12798
13102
  }
12799
13103
  };
12800
- return ok(broker);
13104
+ return core.ok(broker);
12801
13105
  }
12802
13106
  var kind = "ai-mcp-job";
12803
13107
  var fileName = /^[a-z0-9][\w.-]{0,127}$/i;
@@ -13059,10 +13363,10 @@ function createMCPServiceOperations(read, runner, files, configuredServices = []
13059
13363
  throw new Error("Managed MCP warm pools require a runner and file access policy");
13060
13364
  const jobs = runner && files ? createMCPJobs(read, runner, files, warmServices) : void 0;
13061
13365
  const operations2 = {
13062
- createBroker: (options) => lifecycle.signal.aborted ? err(HaiAIError.NOT_INITIALIZED, aiM("ai_notInitialized")) : createMCPServiceBroker(read, operations2.invoke, options, lifecycle.signal),
13366
+ createBroker: (options) => lifecycle.signal.aborted ? core.err(HaiAIError.NOT_INITIALIZED, aiM("ai_notInitialized")) : createMCPServiceBroker(read, operations2.invoke, options, lifecycle.signal),
13063
13367
  async invoke(request2, authorization) {
13064
13368
  if (lifecycle.signal.aborted)
13065
- return err(HaiAIError.NOT_INITIALIZED, aiM("ai_notInitialized"));
13369
+ return core.err(HaiAIError.NOT_INITIALIZED, aiM("ai_notInitialized"));
13066
13370
  let connected = false;
13067
13371
  let timeout;
13068
13372
  let transport;
@@ -13072,17 +13376,17 @@ function createMCPServiceOperations(read, runner, files, configuredServices = []
13072
13376
  const parsed = requestSchema.safeParse(request2);
13073
13377
  const principal2 = principalSchema.safeParse(authorization?.principal);
13074
13378
  if (!parsed.success || !principal2.success || Buffer.byteLength(JSON.stringify(parsed.data)) > maxInputBytes)
13075
- return err(HaiAIError.RESOURCE_INVALID, aiM("ai_resourceInvalid"));
13379
+ return core.err(HaiAIError.RESOURCE_INVALID, aiM("ai_resourceInvalid"));
13076
13380
  if (authorization.signal?.aborted)
13077
- return err(HaiAIError.MCP_TOOL_CANCELLED, aiM("ai_mcpServiceCancelled"));
13381
+ return core.err(HaiAIError.MCP_TOOL_CANCELLED, aiM("ai_mcpServiceCancelled"));
13078
13382
  const input = parsed.data;
13079
13383
  const service = await read(input.serviceId);
13080
13384
  if (!service?.allowedTools?.includes(input.tool) || typeof authorization.authorize !== "function")
13081
- return err(HaiAIError.MCP_TOOL_FORBIDDEN, aiM("ai_mcpServiceForbidden"));
13385
+ return core.err(HaiAIError.MCP_TOOL_FORBIDDEN, aiM("ai_mcpServiceForbidden"));
13082
13386
  if (service.transport === "job" && !jobs)
13083
- return err(HaiAIError.MCP_CONNECTION_ERROR, aiM("ai_mcpServiceConnectionFailed"));
13387
+ return core.err(HaiAIError.MCP_CONNECTION_ERROR, aiM("ai_mcpServiceConnectionFailed"));
13084
13388
  if (service.transport !== "job" && (service.transport !== "http" || !service.url))
13085
- return err(HaiAIError.MCP_PROTOCOL_ERROR, aiM("ai_mcpServiceConnectionFailed"));
13389
+ return core.err(HaiAIError.MCP_PROTOCOL_ERROR, aiM("ai_mcpServiceConnectionFailed"));
13086
13390
  const timeoutMs = service.timeoutMs ?? 3e4;
13087
13391
  timeout = AbortSignal.timeout(timeoutMs);
13088
13392
  const signal = AbortSignal.any([
@@ -13108,24 +13412,24 @@ function createMCPServiceOperations(read, runner, files, configuredServices = []
13108
13412
  listener?.[Symbol.dispose]();
13109
13413
  }
13110
13414
  if (allowed !== true)
13111
- return err(HaiAIError.MCP_TOOL_FORBIDDEN, aiM("ai_mcpServiceForbidden"));
13415
+ return core.err(HaiAIError.MCP_TOOL_FORBIDDEN, aiM("ai_mcpServiceForbidden"));
13112
13416
  if (JSON.stringify(await read(input.serviceId)) !== JSON.stringify(service))
13113
- return err(HaiAIError.RESOURCE_CONFLICT, aiM("ai_resourceConflict"));
13417
+ return core.err(HaiAIError.RESOURCE_CONFLICT, aiM("ai_resourceConflict"));
13114
13418
  signal.throwIfAborted();
13115
13419
  if (service.transport === "job" && jobs) {
13116
13420
  connected = true;
13117
- return ok(await jobs.invoke(service, input, principal2.data, authorization.taskId, signal));
13421
+ return core.ok(await jobs.invoke(service, input, principal2.data, authorization.taskId, signal));
13118
13422
  }
13119
13423
  if (!service.url)
13120
- return err(HaiAIError.MCP_PROTOCOL_ERROR, aiM("ai_mcpServiceConnectionFailed"));
13424
+ return core.err(HaiAIError.MCP_PROTOCOL_ERROR, aiM("ai_mcpServiceConnectionFailed"));
13121
13425
  const url = new URL(service.url);
13122
13426
  if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.hash)
13123
- return err(HaiAIError.MCP_PROTOCOL_ERROR, aiM("ai_mcpServiceConnectionFailed"));
13427
+ return core.err(HaiAIError.MCP_PROTOCOL_ERROR, aiM("ai_mcpServiceConnectionFailed"));
13124
13428
  const headers = new Headers();
13125
13429
  for (const [key, reference2] of Object.entries(service.headerEnv)) {
13126
13430
  const value = process2.env[reference2];
13127
13431
  if (!value || forbiddenHeaders.test(key))
13128
- return err(HaiAIError.MCP_CONNECTION_ERROR, aiM("ai_mcpServiceConnectionFailed"));
13432
+ return core.err(HaiAIError.MCP_CONNECTION_ERROR, aiM("ai_mcpServiceConnectionFailed"));
13129
13433
  headers.set(key, value);
13130
13434
  }
13131
13435
  let received = 0;
@@ -13166,16 +13470,16 @@ function createMCPServiceOperations(read, runner, files, configuredServices = []
13166
13470
  await client2.connect(transport, { signal, timeout: timeoutMs });
13167
13471
  connected = true;
13168
13472
  if (JSON.stringify(await read(input.serviceId)) !== JSON.stringify(service))
13169
- return err(HaiAIError.RESOURCE_CONFLICT, aiM("ai_resourceConflict"));
13473
+ return core.err(HaiAIError.RESOURCE_CONFLICT, aiM("ai_resourceConflict"));
13170
13474
  signal.throwIfAborted();
13171
13475
  const result = CallToolResultSchema.parse(await client2.callTool({ name: input.tool, arguments: input.arguments }, CallToolResultSchema, { signal, timeout: timeoutMs }));
13172
- return result.isError ? err(HaiAIError.MCP_TOOL_ERROR, aiM("ai_mcpServiceCallFailed")) : ok(result);
13476
+ return result.isError ? core.err(HaiAIError.MCP_TOOL_ERROR, aiM("ai_mcpServiceCallFailed")) : core.ok(result);
13173
13477
  } catch {
13174
13478
  if (timeout?.aborted)
13175
- return err(HaiAIError.TIMEOUT, aiM("ai_requestTimeout"));
13479
+ return core.err(HaiAIError.TIMEOUT, aiM("ai_requestTimeout"));
13176
13480
  if (lifecycle.signal.aborted || authorization?.signal?.aborted)
13177
- return err(HaiAIError.MCP_TOOL_CANCELLED, aiM("ai_mcpServiceCancelled"));
13178
- return connected ? err(HaiAIError.MCP_TOOL_ERROR, aiM("ai_mcpServiceCallFailed")) : err(HaiAIError.MCP_CONNECTION_ERROR, aiM("ai_mcpServiceConnectionFailed"));
13481
+ return core.err(HaiAIError.MCP_TOOL_CANCELLED, aiM("ai_mcpServiceCancelled"));
13482
+ return connected ? core.err(HaiAIError.MCP_TOOL_ERROR, aiM("ai_mcpServiceCallFailed")) : core.err(HaiAIError.MCP_CONNECTION_ERROR, aiM("ai_mcpServiceConnectionFailed"));
13179
13483
  } finally {
13180
13484
  fetchSignal = AbortSignal.timeout(1e3);
13181
13485
  await transport?.terminateSession().catch(() => void 0);
@@ -13191,27 +13495,27 @@ function createMCPServiceOperations(read, runner, files, configuredServices = []
13191
13495
  }
13192
13496
  };
13193
13497
  }
13194
- function createScopedMemory(core39, binding) {
13498
+ function createScopedMemory(memoryCore, binding) {
13195
13499
  if (typeof binding.objectId !== "string" || !binding.objectId.trim())
13196
13500
  throw new TypeError(aiM("ai_memoryScopeInvalid"));
13197
13501
  const { objectId, scope } = binding;
13198
13502
  const accessScope = { objectId, scope };
13199
13503
  return {
13200
- extract: (messages, options) => core39.extract(messages, { ...options, objectId, scope }),
13201
- recall: (query, options) => core39.recall(query, { ...options, objectId, scope }),
13202
- injectMemories: (messages, options) => core39.injectMemories(messages, { ...options, objectId, scope }),
13203
- add: (entry) => core39.add({ ...entry, objectId, scope }),
13204
- update: (memoryId, updates) => core39.update(memoryId, updates, accessScope),
13205
- get: (memoryId) => core39.get(memoryId, accessScope),
13206
- remove: (memoryId) => core39.remove(memoryId, accessScope),
13207
- list: (options) => core39.list({ ...options, objectId, scope }),
13208
- listPage: (options) => core39.listPage({ ...options, objectId, scope }),
13209
- clear: (options) => core39.clear({ ...options, objectId, scope })
13504
+ extract: (messages, options) => memoryCore.extract(messages, { ...options, objectId, scope }),
13505
+ recall: (query, options) => memoryCore.recall(query, { ...options, objectId, scope }),
13506
+ injectMemories: (messages, options) => memoryCore.injectMemories(messages, { ...options, objectId, scope }),
13507
+ add: (entry) => memoryCore.add({ ...entry, objectId, scope }),
13508
+ update: (memoryId, updates) => memoryCore.update(memoryId, updates, accessScope),
13509
+ get: (memoryId) => memoryCore.get(memoryId, accessScope),
13510
+ remove: (memoryId) => memoryCore.remove(memoryId, accessScope),
13511
+ list: (options) => memoryCore.list({ ...options, objectId, scope }),
13512
+ listPage: (options) => memoryCore.listPage({ ...options, objectId, scope }),
13513
+ clear: (options) => memoryCore.clear({ ...options, objectId, scope })
13210
13514
  };
13211
13515
  }
13212
- function createMemoryOperations(core39) {
13516
+ function createMemoryOperations(memoryCore) {
13213
13517
  return {
13214
- ...core39,
13518
+ ...memoryCore,
13215
13519
  /**
13216
13520
  * 清空记忆(空过滤保护)。
13217
13521
  *
@@ -13220,20 +13524,20 @@ function createMemoryOperations(core39) {
13220
13524
  */
13221
13525
  async clear(options) {
13222
13526
  if (options?.objectId !== void 0 && (typeof options.objectId !== "string" || !options.objectId.trim()))
13223
- return err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryScopeInvalid"));
13527
+ return core.err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryScopeInvalid"));
13224
13528
  const hasFilter = Boolean(options?.objectId?.trim()) || Boolean(options?.types?.length) || Boolean(options?.scope && Object.keys(options.scope).length);
13225
13529
  if (!hasFilter) {
13226
- return err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryClearRequiresFilter"));
13530
+ return core.err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryClearRequiresFilter"));
13227
13531
  }
13228
- return core39.clear(options);
13532
+ return memoryCore.clear(options);
13229
13533
  },
13230
- scoped: (binding) => createScopedMemory(core39, binding),
13534
+ scoped: (binding) => createScopedMemory(memoryCore, binding),
13231
13535
  admin: {
13232
13536
  async clearAll(options) {
13233
13537
  if (options?.confirm !== true) {
13234
- return err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryClearAllUnconfirmed"));
13538
+ return core.err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryClearAllUnconfirmed"));
13235
13539
  }
13236
- return core39.clear();
13540
+ return memoryCore.clear();
13237
13541
  }
13238
13542
  }
13239
13543
  };
@@ -13393,7 +13697,7 @@ function formatMessages(messages) {
13393
13697
  async function extractMemories(llm, messages, options) {
13394
13698
  const conversationText = formatMessages(messages);
13395
13699
  if (!conversationText.trim()) {
13396
- return ok([]);
13700
+ return core.ok([]);
13397
13701
  }
13398
13702
  try {
13399
13703
  let userPrompt = conversationText;
@@ -13414,7 +13718,7 @@ Only extract memories of these types: ${options.types.join(", ")}`;
13414
13718
  });
13415
13719
  if (!chatResult.success) {
13416
13720
  logger22.warn("Memory extraction LLM call failed", { error: chatResult.error });
13417
- return err(HaiAIError.MEMORY_EXTRACT_FAILED, aiM("ai_memoryExtractFailed", {
13721
+ return core.err(HaiAIError.MEMORY_EXTRACT_FAILED, aiM("ai_memoryExtractFailed", {
13418
13722
  params: {
13419
13723
  error: String(chatResult.error.message)
13420
13724
  }
@@ -13433,10 +13737,10 @@ Only extract memories of these types: ${options.types.join(", ")}`;
13433
13737
  entries = entries.map((e) => ({ ...e, objectId: options.objectId }));
13434
13738
  }
13435
13739
  logger22.trace("Memory extraction completed", { messageCount: messages.length, extractedCount: entries.length });
13436
- return ok(entries);
13740
+ return core.ok(entries);
13437
13741
  } catch (error) {
13438
13742
  logger22.error("Memory extraction failed", { error });
13439
- return err(HaiAIError.MEMORY_EXTRACT_FAILED, aiM("ai_memoryExtractFailed", {
13743
+ return core.err(HaiAIError.MEMORY_EXTRACT_FAILED, aiM("ai_memoryExtractFailed", {
13440
13744
  params: {
13441
13745
  error: String(error)
13442
13746
  }
@@ -13521,7 +13825,7 @@ async function injectRelevantMemories(messages, options, recall) {
13521
13825
  try {
13522
13826
  const query = extractQueryFromMessages(messages);
13523
13827
  if (!query)
13524
- return ok([...messages]);
13828
+ return core.ok([...messages]);
13525
13829
  const recallResult = await recall(query, {
13526
13830
  topK,
13527
13831
  candidateMultiplier: options?.candidateMultiplier,
@@ -13531,12 +13835,12 @@ async function injectRelevantMemories(messages, options, recall) {
13531
13835
  minImportance: options?.minImportance
13532
13836
  });
13533
13837
  if (!recallResult.success) {
13534
- return err(HaiAIError.MEMORY_ENRICH_FAILED, aiM("ai_memoryEnrichFailed", {
13838
+ return core.err(HaiAIError.MEMORY_ENRICH_FAILED, aiM("ai_memoryEnrichFailed", {
13535
13839
  params: { error: recallResult.error.message }
13536
13840
  }), recallResult.error);
13537
13841
  }
13538
13842
  if (recallResult.data.length === 0)
13539
- return ok([...messages]);
13843
+ return core.ok([...messages]);
13540
13844
  let memoryText = recallResult.data.map((memory, index) => `[${index + 1}] (${memory.type}) ${memory.content}`).join("\n");
13541
13845
  if (options?.maxTokens && options.maxTokens > 0) {
13542
13846
  const estimatedTokens = memoryText.length * 0.25;
@@ -13581,10 +13885,10 @@ ${memoryText}
13581
13885
  }
13582
13886
  }
13583
13887
  logger23.trace("Memories enriched", { count: recallResult.data.length, position });
13584
- return ok(result);
13888
+ return core.ok(result);
13585
13889
  } catch (error) {
13586
13890
  logger23.error("Memory enrichment failed", { error });
13587
- return err(HaiAIError.MEMORY_ENRICH_FAILED, aiM("ai_memoryEnrichFailed", {
13891
+ return core.err(HaiAIError.MEMORY_ENRICH_FAILED, aiM("ai_memoryEnrichFailed", {
13588
13892
  params: {
13589
13893
  error: String(error)
13590
13894
  }
@@ -13914,7 +14218,7 @@ var MEMORY_TYPES = /* @__PURE__ */ new Set([
13914
14218
  var Mem0ListIncompleteError = class extends Error {
13915
14219
  };
13916
14220
  function memoryWriteFailure(definition, message, memoryIds) {
13917
- const failure = err(definition, message);
14221
+ const failure = core.err(definition, message);
13918
14222
  if (!failure.success) {
13919
14223
  failure.error.ext = {
13920
14224
  requiresEffectReconciliation: true,
@@ -13995,20 +14299,20 @@ function buildVectorStoreConfig(deps) {
13995
14299
  } catch {
13996
14300
  }
13997
14301
  if (!validConnection) {
13998
- return err(HaiAIError.CONFIGURATION_ERROR, aiM("ai_memoryBackendConnectionRequired", {
14302
+ return core.err(HaiAIError.CONFIGURATION_ERROR, aiM("ai_memoryBackendConnectionRequired", {
13999
14303
  params: { backend: backend.type }
14000
14304
  }));
14001
14305
  }
14002
- return ok({
14306
+ return core.ok({
14003
14307
  provider: "qdrant",
14004
14308
  persistent: true,
14005
14309
  backend: { url: backend.url, apiKey: backend.apiKey }
14006
14310
  });
14007
14311
  }
14008
14312
  if (backend?.type === "pgvector")
14009
- return err(HaiAIError.CONFIGURATION_ERROR, aiM("ai_memoryBackendUnsupported"));
14313
+ return core.err(HaiAIError.CONFIGURATION_ERROR, aiM("ai_memoryBackendUnsupported"));
14010
14314
  if (backend && !deps.config.allowEphemeralFallback) {
14011
- return err(
14315
+ return core.err(
14012
14316
  HaiAIError.CONFIGURATION_ERROR,
14013
14317
  aiM("ai_memoryEphemeralFallbackDenied", {
14014
14318
  params: { backend: backend.type }
@@ -14017,7 +14321,7 @@ function buildVectorStoreConfig(deps) {
14017
14321
  }
14018
14322
  if (backend)
14019
14323
  logger24.warn("Mem0 format falls back to in-memory vector store (allowEphemeralFallback=true); data will not survive restart", { backend: backend.type });
14020
- return ok({
14324
+ return core.ok({
14021
14325
  provider: "memory",
14022
14326
  persistent: false
14023
14327
  });
@@ -14037,7 +14341,7 @@ async function extractMemories2(context, messages, options) {
14037
14341
  if (!extracted.success)
14038
14342
  return extracted;
14039
14343
  if (extracted.data.length === 0)
14040
- return ok([]);
14344
+ return core.ok([]);
14041
14345
  try {
14042
14346
  const stored = await Promise.allSettled(extracted.data.map(async (entry) => {
14043
14347
  const id3 = await context.memory.add(entry.content, objectId, buildMetadata({
@@ -14055,7 +14359,7 @@ async function extractMemories2(context, messages, options) {
14055
14359
  const failed = stored.find((result) => result.status === "rejected");
14056
14360
  if (failed?.status === "rejected")
14057
14361
  throw failed.reason;
14058
- return ok(stored.flatMap((result) => result.status === "fulfilled" ? [result.value] : []));
14362
+ return core.ok(stored.flatMap((result) => result.status === "fulfilled" ? [result.value] : []));
14059
14363
  } catch (error) {
14060
14364
  logger24.error("Mem0 format extract failed", {
14061
14365
  error: core.sanitize.sanitizeSensitiveFields(error)
@@ -14082,12 +14386,12 @@ async function recallMemories(context, query, options) {
14082
14386
  return { entry, score: relevance * (1 - recencyWeight) + recency * recencyWeight };
14083
14387
  }).sort((a, b) => b.score - a.score).map((ranked) => ranked.entry);
14084
14388
  }
14085
- return ok(entries.slice(0, topK));
14389
+ return core.ok(entries.slice(0, topK));
14086
14390
  } catch (error) {
14087
14391
  logger24.error("Mem0 format recall failed", {
14088
14392
  error: core.sanitize.sanitizeSensitiveFields(error)
14089
14393
  });
14090
- return err(HaiAIError.MEMORY_RECALL_FAILED, aiM("ai_memoryOperationFailed"));
14394
+ return core.err(HaiAIError.MEMORY_RECALL_FAILED, aiM("ai_memoryOperationFailed"));
14091
14395
  }
14092
14396
  }
14093
14397
  async function addMemory(context, entry) {
@@ -14099,7 +14403,7 @@ async function addMemory(context, entry) {
14099
14403
  const persisted = await context.memory.get(id3);
14100
14404
  if (!persisted)
14101
14405
  throw new Error("Mem0 format stored memory could not be read back");
14102
- return ok(toMemoryEntry(persisted, objectId));
14406
+ return core.ok(toMemoryEntry(persisted, objectId));
14103
14407
  } catch (error) {
14104
14408
  logger24.error("Mem0 format add failed", {
14105
14409
  error: core.sanitize.sanitizeSensitiveFields(error)
@@ -14111,13 +14415,13 @@ async function updateMemory(context, memoryId, updates, accessScope) {
14111
14415
  try {
14112
14416
  const item2 = await context.memory.get(memoryId);
14113
14417
  if (!item2) {
14114
- return err(HaiAIError.MEMORY_NOT_FOUND, aiM("ai_memoryNotFound", {
14418
+ return core.err(HaiAIError.MEMORY_NOT_FOUND, aiM("ai_memoryNotFound", {
14115
14419
  params: { id: memoryId }
14116
14420
  }));
14117
14421
  }
14118
14422
  const existing = toMemoryEntry(item2, context.defaultObjectId);
14119
14423
  if (isMemoryAccessDenied(existing, accessScope)) {
14120
- return err(HaiAIError.MEMORY_NOT_FOUND, aiM("ai_memoryNotFound", {
14424
+ return core.err(HaiAIError.MEMORY_NOT_FOUND, aiM("ai_memoryNotFound", {
14121
14425
  params: { id: memoryId }
14122
14426
  }));
14123
14427
  }
@@ -14133,11 +14437,11 @@ async function updateMemory(context, memoryId, updates, accessScope) {
14133
14437
  await context.memory.update(memoryId, updates.content, buildMetadata(merged, objectId), objectId);
14134
14438
  const refreshed = await context.memory.get(memoryId);
14135
14439
  if (!refreshed) {
14136
- return err(HaiAIError.MEMORY_NOT_FOUND, aiM("ai_memoryNotFound", {
14440
+ return core.err(HaiAIError.MEMORY_NOT_FOUND, aiM("ai_memoryNotFound", {
14137
14441
  params: { id: memoryId }
14138
14442
  }));
14139
14443
  }
14140
- return ok(toMemoryEntry(refreshed, objectId));
14444
+ return core.ok(toMemoryEntry(refreshed, objectId));
14141
14445
  } catch (error) {
14142
14446
  logger24.error("Mem0 format update failed", {
14143
14447
  id: memoryId,
@@ -14150,22 +14454,22 @@ async function getMemory(context, memoryId, accessScope) {
14150
14454
  try {
14151
14455
  const item2 = await context.memory.get(memoryId);
14152
14456
  if (!item2) {
14153
- return err(HaiAIError.MEMORY_NOT_FOUND, aiM("ai_memoryNotFound", {
14457
+ return core.err(HaiAIError.MEMORY_NOT_FOUND, aiM("ai_memoryNotFound", {
14154
14458
  params: { id: memoryId }
14155
14459
  }));
14156
14460
  }
14157
14461
  const entry = toMemoryEntry(item2, context.defaultObjectId);
14158
14462
  if (isMemoryAccessDenied(entry, accessScope)) {
14159
- return err(HaiAIError.MEMORY_NOT_FOUND, aiM("ai_memoryNotFound", {
14463
+ return core.err(HaiAIError.MEMORY_NOT_FOUND, aiM("ai_memoryNotFound", {
14160
14464
  params: { id: memoryId }
14161
14465
  }));
14162
14466
  }
14163
- return ok(entry);
14467
+ return core.ok(entry);
14164
14468
  } catch (error) {
14165
14469
  logger24.error("Mem0 format read failed", {
14166
14470
  error: core.sanitize.sanitizeSensitiveFields(error)
14167
14471
  });
14168
- return err(HaiAIError.MEMORY_RECALL_FAILED, aiM("ai_memoryOperationFailed"));
14472
+ return core.err(HaiAIError.MEMORY_RECALL_FAILED, aiM("ai_memoryOperationFailed"));
14169
14473
  }
14170
14474
  }
14171
14475
  async function removeMemory(context, memoryId, accessScope) {
@@ -14173,18 +14477,18 @@ async function removeMemory(context, memoryId, accessScope) {
14173
14477
  if (accessScope) {
14174
14478
  const item2 = await context.memory.get(memoryId);
14175
14479
  if (!item2 || isMemoryAccessDenied(toMemoryEntry(item2, context.defaultObjectId), accessScope)) {
14176
- return err(HaiAIError.MEMORY_NOT_FOUND, aiM("ai_memoryNotFound", {
14480
+ return core.err(HaiAIError.MEMORY_NOT_FOUND, aiM("ai_memoryNotFound", {
14177
14481
  params: { id: memoryId }
14178
14482
  }));
14179
14483
  }
14180
14484
  }
14181
14485
  await context.memory.remove(memoryId);
14182
- return ok(void 0);
14486
+ return core.ok(void 0);
14183
14487
  } catch (error) {
14184
14488
  logger24.error("Mem0 format delete failed", {
14185
14489
  error: core.sanitize.sanitizeSensitiveFields(error)
14186
14490
  });
14187
- return err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryOperationFailed"));
14491
+ return core.err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryOperationFailed"));
14188
14492
  }
14189
14493
  }
14190
14494
  function isExpiredMemory(item2, today) {
@@ -14217,7 +14521,7 @@ async function createMem0MemoryOperations(deps) {
14217
14521
  if (!configResult.success)
14218
14522
  throw configResult.error;
14219
14523
  if (core.module.requiresSharedState(process2.env) && !configResult.data.persistent) {
14220
- const failure = err(HaiAIError.CONFIGURATION_ERROR, aiM("ai_memorySharedBackendRequired"));
14524
+ const failure = core.err(HaiAIError.CONFIGURATION_ERROR, aiM("ai_memorySharedBackendRequired"));
14221
14525
  if (!failure.success)
14222
14526
  throw failure.error;
14223
14527
  }
@@ -14233,7 +14537,7 @@ async function createMem0MemoryOperations(deps) {
14233
14537
  logger24.error("Mem0 data storage initialization failed", {
14234
14538
  error: core.sanitize.sanitizeSensitiveFields(error)
14235
14539
  });
14236
- const failure = err(HaiAIError.CONFIGURATION_ERROR, aiM("ai_memoryOperationFailed"));
14540
+ const failure = core.err(HaiAIError.CONFIGURATION_ERROR, aiM("ai_memoryOperationFailed"));
14237
14541
  if (!failure.success)
14238
14542
  throw failure.error;
14239
14543
  throw new Error("Unreachable memory initialization state");
@@ -14269,7 +14573,7 @@ async function createMem0MemoryOperations(deps) {
14269
14573
  remove: (memoryId, accessScope) => removeMemory(context, memoryId, accessScope),
14270
14574
  async list(options) {
14271
14575
  try {
14272
- return ok(await listMemories(context, options));
14576
+ return core.ok(await listMemories(context, options));
14273
14577
  } catch (error) {
14274
14578
  logger24.error("Mem0 data list failed", {
14275
14579
  operation: "list",
@@ -14277,8 +14581,8 @@ async function createMem0MemoryOperations(deps) {
14277
14581
  error: core.sanitize.sanitizeSensitiveFields(error)
14278
14582
  });
14279
14583
  if (error instanceof Mem0ListIncompleteError)
14280
- return err(HaiAIError.MEMORY_LIST_INCOMPLETE, error.message);
14281
- return err(HaiAIError.MEMORY_RECALL_FAILED, aiM("ai_memoryOperationFailed"));
14584
+ return core.err(HaiAIError.MEMORY_LIST_INCOMPLETE, error.message);
14585
+ return core.err(HaiAIError.MEMORY_RECALL_FAILED, aiM("ai_memoryOperationFailed"));
14282
14586
  }
14283
14587
  },
14284
14588
  async listPage(options) {
@@ -14286,7 +14590,7 @@ async function createMem0MemoryOperations(deps) {
14286
14590
  const offset = options?.offset ?? 0;
14287
14591
  const limit = options?.limit ?? 20;
14288
14592
  const all = await listMemories(context, { objectId: options?.objectId, types: options?.types, scope: options?.scope });
14289
- return ok({
14593
+ return core.ok({
14290
14594
  items: all.slice(offset, offset + limit),
14291
14595
  total: all.length
14292
14596
  });
@@ -14297,8 +14601,8 @@ async function createMem0MemoryOperations(deps) {
14297
14601
  error: core.sanitize.sanitizeSensitiveFields(error)
14298
14602
  });
14299
14603
  if (error instanceof Mem0ListIncompleteError)
14300
- return err(HaiAIError.MEMORY_LIST_INCOMPLETE, error.message);
14301
- return err(HaiAIError.MEMORY_RECALL_FAILED, aiM("ai_memoryOperationFailed"));
14604
+ return core.err(HaiAIError.MEMORY_LIST_INCOMPLETE, error.message);
14605
+ return core.err(HaiAIError.MEMORY_RECALL_FAILED, aiM("ai_memoryOperationFailed"));
14302
14606
  }
14303
14607
  },
14304
14608
  /**
@@ -14313,11 +14617,11 @@ async function createMem0MemoryOperations(deps) {
14313
14617
  const hasTypeOrScope = Boolean(options?.types?.length) || Boolean(options?.scope);
14314
14618
  if (!options?.objectId && !hasTypeOrScope) {
14315
14619
  await context.memory.clear();
14316
- return ok(void 0);
14620
+ return core.ok(void 0);
14317
14621
  }
14318
14622
  if (options?.objectId && !hasTypeOrScope) {
14319
14623
  await context.memory.removeObject(options.objectId);
14320
- return ok(void 0);
14624
+ return core.ok(void 0);
14321
14625
  }
14322
14626
  const matched = await listMemories(context, { objectId: options?.objectId, types: options?.types, scope: options?.scope });
14323
14627
  for (const entry of matched)
@@ -14328,7 +14632,7 @@ async function createMem0MemoryOperations(deps) {
14328
14632
  types: options?.types,
14329
14633
  scoped: Boolean(options?.scope)
14330
14634
  });
14331
- return ok(void 0);
14635
+ return core.ok(void 0);
14332
14636
  } catch (error) {
14333
14637
  logger24.error("Mem0 data clear failed", {
14334
14638
  operation: "clear",
@@ -14336,8 +14640,8 @@ async function createMem0MemoryOperations(deps) {
14336
14640
  error: core.sanitize.sanitizeSensitiveFields(error)
14337
14641
  });
14338
14642
  if (error instanceof Mem0ListIncompleteError)
14339
- return err(HaiAIError.MEMORY_LIST_INCOMPLETE, error.message);
14340
- return err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryOperationFailed"));
14643
+ return core.err(HaiAIError.MEMORY_LIST_INCOMPLETE, error.message);
14644
+ return core.err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryOperationFailed"));
14341
14645
  }
14342
14646
  }
14343
14647
  };
@@ -14402,7 +14706,7 @@ async function collectRelated(deps, candidates, options) {
14402
14706
  for (const entry of result.data)
14403
14707
  related.set(entry.id, entry);
14404
14708
  }
14405
- return ok([
14709
+ return core.ok([
14406
14710
  ...related.values()
14407
14711
  ]);
14408
14712
  }
@@ -14500,7 +14804,7 @@ async function applyConsolidationOps(deps, ops, options) {
14500
14804
  return addResult;
14501
14805
  entries.push(addResult.data);
14502
14806
  }
14503
- return ok(entries);
14807
+ return core.ok(entries);
14504
14808
  }
14505
14809
  async function extractAndConsolidate(deps, messages, options) {
14506
14810
  logger25.trace("Consolidation extract", { messageCount: messages.length });
@@ -14517,7 +14821,7 @@ async function extractAndConsolidate(deps, messages, options) {
14517
14821
  return extractResult;
14518
14822
  const candidates = extractResult.data;
14519
14823
  if (candidates.length === 0)
14520
- return ok([]);
14824
+ return core.ok([]);
14521
14825
  const relatedResult = await collectRelated(deps, candidates, options);
14522
14826
  if (!relatedResult.success)
14523
14827
  return relatedResult;
@@ -14549,7 +14853,7 @@ async function extractAndConsolidate(deps, messages, options) {
14549
14853
  signal: options?.signal
14550
14854
  });
14551
14855
  if (!consolidationResult.success) {
14552
- return err(HaiAIError.MEMORY_EXTRACT_FAILED, aiM("ai_memoryExtractFailed", {
14856
+ return core.err(HaiAIError.MEMORY_EXTRACT_FAILED, aiM("ai_memoryExtractFailed", {
14553
14857
  params: {
14554
14858
  error: String(consolidationResult.error.message)
14555
14859
  }
@@ -14580,7 +14884,7 @@ async function extractAndConsolidate(deps, messages, options) {
14580
14884
  ops: ops.length,
14581
14885
  written: applyResult.data.length
14582
14886
  });
14583
- return ok(applyResult.data);
14887
+ return core.ok(applyResult.data);
14584
14888
  }
14585
14889
  var logger26 = core.logger.child({ module: "ai", scope: "memory-vector-scan" });
14586
14890
  var checkpointId = "scan";
@@ -14921,7 +15225,7 @@ function assembleNativeMemory(config, llm, embedding, store, vectorStore, vector
14921
15225
  logger28.error("Memory storage operation failed", {
14922
15226
  error: core.sanitize.sanitizeSensitiveFields(error)
14923
15227
  });
14924
- return err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryOperationFailed"));
15228
+ return core.err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryOperationFailed"));
14925
15229
  }
14926
15230
  }
14927
15231
  async function touchEntry(memoryId, accessScope) {
@@ -15039,7 +15343,7 @@ function assembleNativeMemory(config, llm, embedding, store, vectorStore, vector
15039
15343
  try {
15040
15344
  const before = await store.get(memoryId);
15041
15345
  if (!before || isMemoryAccessDenied(before, accessScope)) {
15042
- return err(HaiAIError.MEMORY_NOT_FOUND, aiM("ai_memoryNotFound", {
15346
+ return core.err(HaiAIError.MEMORY_NOT_FOUND, aiM("ai_memoryNotFound", {
15043
15347
  params: { id: memoryId }
15044
15348
  }));
15045
15349
  }
@@ -15083,18 +15387,18 @@ function assembleNativeMemory(config, llm, embedding, store, vectorStore, vector
15083
15387
  return publicEntry(changed);
15084
15388
  });
15085
15389
  if (!existing) {
15086
- return err(HaiAIError.MEMORY_NOT_FOUND, aiM("ai_memoryNotFound", {
15390
+ return core.err(HaiAIError.MEMORY_NOT_FOUND, aiM("ai_memoryNotFound", {
15087
15391
  params: { id: memoryId }
15088
15392
  }));
15089
15393
  }
15090
15394
  logger28.trace("Memory updated", { id: memoryId });
15091
- return ok(existing);
15395
+ return core.ok(existing);
15092
15396
  } catch (error) {
15093
15397
  logger28.error("Memory update failed", {
15094
15398
  id: memoryId,
15095
15399
  error: core.sanitize.sanitizeSensitiveFields(error)
15096
15400
  });
15097
- return err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryOperationFailed"));
15401
+ return core.err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryOperationFailed"));
15098
15402
  }
15099
15403
  }
15100
15404
  async function recallEntries(query, options, updateAccessStats = true) {
@@ -15124,7 +15428,7 @@ function assembleNativeMemory(config, llm, embedding, store, vectorStore, vector
15124
15428
  });
15125
15429
  const candidates = options?.scope ? allCandidates.filter((e) => matchScope2(e, options.scope)) : allCandidates;
15126
15430
  if (candidates.length === 0) {
15127
- return ok([]);
15431
+ return core.ok([]);
15128
15432
  }
15129
15433
  let queryVector;
15130
15434
  if (config.embeddingEnabled && embedding) {
@@ -15180,12 +15484,12 @@ function assembleNativeMemory(config, llm, embedding, store, vectorStore, vector
15180
15484
  resultCount: results.length,
15181
15485
  updateAccessStats
15182
15486
  });
15183
- return ok(results);
15487
+ return core.ok(results);
15184
15488
  } catch (error) {
15185
15489
  logger28.error("Memory recall failed", {
15186
15490
  error: core.sanitize.sanitizeSensitiveFields(error)
15187
15491
  });
15188
- return err(HaiAIError.MEMORY_RECALL_FAILED, aiM("ai_memoryOperationFailed"));
15492
+ return core.err(HaiAIError.MEMORY_RECALL_FAILED, aiM("ai_memoryOperationFailed"));
15189
15493
  }
15190
15494
  }
15191
15495
  const operations2 = {
@@ -15233,14 +15537,14 @@ function assembleNativeMemory(config, llm, embedding, store, vectorStore, vector
15233
15537
  const vector = await computeVector(entry.content);
15234
15538
  const stored = await saveEntry(entry, vector);
15235
15539
  if (!stored)
15236
- return err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryOperationFailed"));
15540
+ return core.err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryOperationFailed"));
15237
15541
  logger28.trace("Memory added", { id: stored.id, type: stored.type });
15238
- return ok(stored);
15542
+ return core.ok(stored);
15239
15543
  } catch (error) {
15240
15544
  logger28.error("Memory add failed", {
15241
15545
  error: core.sanitize.sanitizeSensitiveFields(error)
15242
15546
  });
15243
- return err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryOperationFailed"));
15547
+ return core.err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryOperationFailed"));
15244
15548
  }
15245
15549
  },
15246
15550
  /**
@@ -15259,11 +15563,11 @@ function assembleNativeMemory(config, llm, embedding, store, vectorStore, vector
15259
15563
  async get(memoryId, accessScope) {
15260
15564
  const entry = await touchEntry(memoryId, accessScope);
15261
15565
  if (!entry) {
15262
- return err(HaiAIError.MEMORY_NOT_FOUND, aiM("ai_memoryNotFound", {
15566
+ return core.err(HaiAIError.MEMORY_NOT_FOUND, aiM("ai_memoryNotFound", {
15263
15567
  params: { id: memoryId }
15264
15568
  }));
15265
15569
  }
15266
- return ok(publicEntry(entry));
15570
+ return core.ok(publicEntry(entry));
15267
15571
  },
15268
15572
  /**
15269
15573
  * 根据 ID 删除一条记忆(同时清理关系存储与向量库)
@@ -15280,12 +15584,12 @@ function assembleNativeMemory(config, llm, embedding, store, vectorStore, vector
15280
15584
  return deleteEntry(active, existing, pending);
15281
15585
  });
15282
15586
  if (!removed2) {
15283
- return err(HaiAIError.MEMORY_NOT_FOUND, aiM("ai_memoryNotFound", {
15587
+ return core.err(HaiAIError.MEMORY_NOT_FOUND, aiM("ai_memoryNotFound", {
15284
15588
  params: { id: memoryId }
15285
15589
  }));
15286
15590
  }
15287
15591
  logger28.trace("Memory removed", { id: memoryId });
15288
- return ok(void 0);
15592
+ return core.ok(void 0);
15289
15593
  },
15290
15594
  /**
15291
15595
  * 列出记忆条目(不分页)
@@ -15310,9 +15614,9 @@ function assembleNativeMemory(config, llm, embedding, store, vectorStore, vector
15310
15614
  limit: options?.scope ? void 0 : options?.limit
15311
15615
  });
15312
15616
  if (!options?.scope)
15313
- return ok(results.map(publicEntry));
15617
+ return core.ok(results.map(publicEntry));
15314
15618
  const filtered = results.filter((e) => matchScope2(e, options.scope));
15315
- return ok((options.limit ? filtered.slice(0, options.limit) : filtered).map(publicEntry));
15619
+ return core.ok((options.limit ? filtered.slice(0, options.limit) : filtered).map(publicEntry));
15316
15620
  },
15317
15621
  /**
15318
15622
  * 分页列出记忆条目
@@ -15340,7 +15644,7 @@ function assembleNativeMemory(config, llm, embedding, store, vectorStore, vector
15340
15644
  },
15341
15645
  { offset, limit }
15342
15646
  );
15343
- return ok({
15647
+ return core.ok({
15344
15648
  ...page,
15345
15649
  items: page.items.map(publicEntry)
15346
15650
  });
@@ -15352,7 +15656,7 @@ function assembleNativeMemory(config, llm, embedding, store, vectorStore, vector
15352
15656
  orderBy: { field: "createdAt", direction: "desc" }
15353
15657
  });
15354
15658
  const filtered = all.filter((e) => matchScope2(e, options.scope));
15355
- return ok({
15659
+ return core.ok({
15356
15660
  items: filtered.slice(offset, offset + limit).map(publicEntry),
15357
15661
  total: filtered.length
15358
15662
  });
@@ -15371,7 +15675,7 @@ function assembleNativeMemory(config, llm, embedding, store, vectorStore, vector
15371
15675
  await vectorStore.clear();
15372
15676
  await store.clear();
15373
15677
  logger28.debug("All memories cleared");
15374
- return ok(void 0);
15678
+ return core.ok(void 0);
15375
15679
  }
15376
15680
  const where = {};
15377
15681
  if (options?.types && options.types.length === 1)
@@ -15407,7 +15711,7 @@ function assembleNativeMemory(config, llm, embedding, store, vectorStore, vector
15407
15711
  types: options?.types,
15408
15712
  scoped: Boolean(scope)
15409
15713
  });
15410
- return ok(void 0);
15714
+ return core.ok(void 0);
15411
15715
  }
15412
15716
  };
15413
15717
  return {
@@ -15444,7 +15748,7 @@ function createPersonaOperations(store) {
15444
15748
  logger29.error("Persona storage operation failed", {
15445
15749
  error: core.sanitize.sanitizeSensitiveFields(error)
15446
15750
  });
15447
- return err(HaiAIError.PERSONA_SAVE_FAILED, aiM("ai_personaOperationFailed"));
15751
+ return core.err(HaiAIError.PERSONA_SAVE_FAILED, aiM("ai_personaOperationFailed"));
15448
15752
  }
15449
15753
  }
15450
15754
  const operations2 = {
@@ -15466,30 +15770,30 @@ function createPersonaOperations(store) {
15466
15770
  };
15467
15771
  await store.save(key, profile, { objectId });
15468
15772
  logger29.trace("Persona saved", { id: profile.id, objectId });
15469
- return ok(profile);
15773
+ return core.ok(profile);
15470
15774
  } catch (error) {
15471
15775
  logger29.error("Persona save failed", {
15472
15776
  error: core.sanitize.sanitizeSensitiveFields(error)
15473
15777
  });
15474
- return err(HaiAIError.PERSONA_SAVE_FAILED, aiM("ai_personaOperationFailed"));
15778
+ return core.err(HaiAIError.PERSONA_SAVE_FAILED, aiM("ai_personaOperationFailed"));
15475
15779
  }
15476
15780
  },
15477
15781
  async get(id3, options) {
15478
15782
  const objectId = options?.objectId ?? DEFAULT_OBJECT_ID2;
15479
15783
  const profile = await store.get(personaKey(objectId, id3));
15480
15784
  if (!profile) {
15481
- return err(HaiAIError.PERSONA_NOT_FOUND, aiM("ai_personaNotFound", {
15785
+ return core.err(HaiAIError.PERSONA_NOT_FOUND, aiM("ai_personaNotFound", {
15482
15786
  params: { id: id3 }
15483
15787
  }));
15484
15788
  }
15485
- return ok(profile);
15789
+ return core.ok(profile);
15486
15790
  },
15487
15791
  async update(id3, updates, options) {
15488
15792
  const objectId = options?.objectId ?? DEFAULT_OBJECT_ID2;
15489
15793
  const key = personaKey(objectId, id3);
15490
15794
  const existing = await store.get(key);
15491
15795
  if (!existing) {
15492
- return err(HaiAIError.PERSONA_NOT_FOUND, aiM("ai_personaNotFound", {
15796
+ return core.err(HaiAIError.PERSONA_NOT_FOUND, aiM("ai_personaNotFound", {
15493
15797
  params: { id: id3 }
15494
15798
  }));
15495
15799
  }
@@ -15503,18 +15807,18 @@ function createPersonaOperations(store) {
15503
15807
  updatedAt: Date.now()
15504
15808
  };
15505
15809
  await store.save(key, profile, { objectId });
15506
- return ok(profile);
15810
+ return core.ok(profile);
15507
15811
  } catch (error) {
15508
15812
  logger29.error("Persona update failed", {
15509
15813
  error: core.sanitize.sanitizeSensitiveFields(error)
15510
15814
  });
15511
- return err(HaiAIError.PERSONA_SAVE_FAILED, aiM("ai_personaOperationFailed"));
15815
+ return core.err(HaiAIError.PERSONA_SAVE_FAILED, aiM("ai_personaOperationFailed"));
15512
15816
  }
15513
15817
  },
15514
15818
  async remove(id3, options) {
15515
15819
  const objectId = options?.objectId ?? DEFAULT_OBJECT_ID2;
15516
15820
  await store.remove(personaKey(objectId, id3));
15517
- return ok(void 0);
15821
+ return core.ok(void 0);
15518
15822
  },
15519
15823
  async list(options) {
15520
15824
  const objectId = options?.objectId ?? DEFAULT_OBJECT_ID2;
@@ -15522,17 +15826,17 @@ function createPersonaOperations(store) {
15522
15826
  objectId,
15523
15827
  orderBy: { field: "createdAt", direction: "asc" }
15524
15828
  });
15525
- return ok(profiles);
15829
+ return core.ok(profiles);
15526
15830
  },
15527
15831
  async compose(id3, options) {
15528
15832
  const objectId = options?.objectId ?? DEFAULT_OBJECT_ID2;
15529
15833
  const profile = await store.get(personaKey(objectId, id3));
15530
15834
  if (!profile) {
15531
- return err(HaiAIError.PERSONA_NOT_FOUND, aiM("ai_personaNotFound", {
15835
+ return core.err(HaiAIError.PERSONA_NOT_FOUND, aiM("ai_personaNotFound", {
15532
15836
  params: { id: id3 }
15533
15837
  }));
15534
15838
  }
15535
- return ok(composeSystemPrompt(profile));
15839
+ return core.ok(composeSystemPrompt(profile));
15536
15840
  }
15537
15841
  };
15538
15842
  return {
@@ -15586,7 +15890,7 @@ function createRagOperations(llm, retrieval) {
15586
15890
  rerankModel: options?.rerankModel
15587
15891
  });
15588
15892
  if (!retrieveResult.success) {
15589
- return err(HaiAIError.RAG_CONTEXT_BUILD_FAILED, aiM("ai_internalError", {
15893
+ return core.err(HaiAIError.RAG_CONTEXT_BUILD_FAILED, aiM("ai_internalError", {
15590
15894
  params: { error: "Failed to retrieve context" }
15591
15895
  }), retrieveResult.error);
15592
15896
  }
@@ -15622,7 +15926,7 @@ ${contextText}
15622
15926
  signal: options?.signal
15623
15927
  });
15624
15928
  if (!chatResult.success) {
15625
- return err(HaiAIError.RAG_FAILED, aiM("ai_internalError", {
15929
+ return core.err(HaiAIError.RAG_FAILED, aiM("ai_internalError", {
15626
15930
  params: { error: "LLM generation failed" }
15627
15931
  }), chatResult.error);
15628
15932
  }
@@ -15642,7 +15946,7 @@ ${contextText}
15642
15946
  }
15643
15947
  }
15644
15948
  const citations = Array.from(citationMap.values());
15645
- return ok({
15949
+ return core.ok({
15646
15950
  answer,
15647
15951
  context: contextItems,
15648
15952
  citations,
@@ -15656,7 +15960,7 @@ ${contextText}
15656
15960
  });
15657
15961
  } catch (error) {
15658
15962
  logger30.error("RAG query failed", { code: HaiAIError.RAG_FAILED.code, queryLength: query.length });
15659
- return err(HaiAIError.RAG_FAILED, aiM("ai_internalError", {
15963
+ return core.err(HaiAIError.RAG_FAILED, aiM("ai_internalError", {
15660
15964
  params: {
15661
15965
  error: String(error)
15662
15966
  }
@@ -15801,7 +16105,7 @@ function createReasoningOperations(config, llm) {
15801
16105
  return chatResult;
15802
16106
  const choice = chatResult.data.choices[0];
15803
16107
  if (!choice) {
15804
- return err(HaiAIError.REASONING_FAILED, aiM("ai_internalError", {
16108
+ return core.err(HaiAIError.REASONING_FAILED, aiM("ai_internalError", {
15805
16109
  params: { error: "No response from LLM" }
15806
16110
  }));
15807
16111
  }
@@ -15846,7 +16150,7 @@ function createReasoningOperations(config, llm) {
15846
16150
  if (choice.finish_reason === "stop") {
15847
16151
  const answer = typeof assistantMessage.content === "string" ? assistantMessage.content : "";
15848
16152
  steps.push({ type: "answer", content: answer, index: stepIndex });
15849
- return ok({
16153
+ return core.ok({
15850
16154
  answer,
15851
16155
  steps,
15852
16156
  strategy: "react",
@@ -15855,7 +16159,7 @@ function createReasoningOperations(config, llm) {
15855
16159
  });
15856
16160
  }
15857
16161
  }
15858
- return err(HaiAIError.REASONING_MAX_ROUNDS, aiM("ai_internalError", {
16162
+ return core.err(HaiAIError.REASONING_MAX_ROUNDS, aiM("ai_internalError", {
15859
16163
  params: { error: `Max rounds (${maxRounds}) reached` }
15860
16164
  }));
15861
16165
  }
@@ -15897,7 +16201,7 @@ Please think step by step.` }
15897
16201
  });
15898
16202
  }
15899
16203
  messages.push({ role: "assistant", content: answer });
15900
- return ok({
16204
+ return core.ok({
15901
16205
  answer,
15902
16206
  steps,
15903
16207
  strategy: "cot",
@@ -15985,7 +16289,7 @@ ${query}` }
15985
16289
  if (choice.finish_reason === "stop") {
15986
16290
  const answer = typeof msg.content === "string" ? msg.content : "";
15987
16291
  steps.push({ type: "answer", content: answer, index: stepIndex });
15988
- return ok({
16292
+ return core.ok({
15989
16293
  answer,
15990
16294
  steps,
15991
16295
  strategy: "plan-execute",
@@ -15994,7 +16298,7 @@ ${query}` }
15994
16298
  });
15995
16299
  }
15996
16300
  }
15997
- return err(HaiAIError.REASONING_MAX_ROUNDS, aiM("ai_internalError", {
16301
+ return core.err(HaiAIError.REASONING_MAX_ROUNDS, aiM("ai_internalError", {
15998
16302
  params: { error: `Max rounds (${maxRounds}) reached` }
15999
16303
  }));
16000
16304
  }
@@ -16011,13 +16315,13 @@ ${query}` }
16011
16315
  case "plan-execute":
16012
16316
  return await runPlanExecute(query, options ?? {});
16013
16317
  default:
16014
- return err(HaiAIError.REASONING_STRATEGY_NOT_FOUND, aiM("ai_internalError", {
16318
+ return core.err(HaiAIError.REASONING_STRATEGY_NOT_FOUND, aiM("ai_internalError", {
16015
16319
  params: { error: `Unknown strategy: ${strategy}` }
16016
16320
  }));
16017
16321
  }
16018
16322
  } catch (error) {
16019
16323
  logger31.error("Reasoning failed", { error });
16020
- return err(HaiAIError.REASONING_FAILED, aiM("ai_internalError", {
16324
+ return core.err(HaiAIError.REASONING_FAILED, aiM("ai_internalError", {
16021
16325
  params: {
16022
16326
  error: String(error)
16023
16327
  }
@@ -16078,7 +16382,7 @@ function createRerankOperations(config, loadModels = () => config.llm) {
16078
16382
  const resolved = resolvedResult.data;
16079
16383
  const { texts, ids } = normalizeDocuments(request2.documents);
16080
16384
  if (texts.length === 0) {
16081
- return err(HaiAIError.RERANK_INVALID_REQUEST, aiM("ai_rerankInvalidRequest", {
16385
+ return core.err(HaiAIError.RERANK_INVALID_REQUEST, aiM("ai_rerankInvalidRequest", {
16082
16386
  params: { reason: "documents cannot be empty" }
16083
16387
  }));
16084
16388
  }
@@ -16112,7 +16416,7 @@ function createRerankOperations(config, loadModels = () => config.llm) {
16112
16416
  status: response.status,
16113
16417
  providerRequestId: requestId && /^[\w.:-]{1,128}$/.test(requestId) ? requestId : void 0
16114
16418
  });
16115
- return err(HaiAIError.RERANK_API_ERROR, aiM("ai_rerankApiFailed", {
16419
+ return core.err(HaiAIError.RERANK_API_ERROR, aiM("ai_rerankApiFailed", {
16116
16420
  params: { error: `HTTP ${response.status}` }
16117
16421
  }));
16118
16422
  }
@@ -16124,11 +16428,11 @@ function createRerankOperations(config, loadModels = () => config.llm) {
16124
16428
  document: item2.document?.text
16125
16429
  }));
16126
16430
  logger32.trace("Rerank completed", { resultCount: results.length });
16127
- return ok({ model: resolved.model, results });
16431
+ return core.ok({ model: resolved.model, results });
16128
16432
  } catch (error) {
16129
16433
  const causeName = error instanceof Error ? error.name : void 0;
16130
16434
  logger32.error("Rerank API call failed", { causeName });
16131
- return err(HaiAIError.RERANK_API_ERROR, aiM("ai_rerankApiFailed", {
16435
+ return core.err(HaiAIError.RERANK_API_ERROR, aiM("ai_rerankApiFailed", {
16132
16436
  params: {
16133
16437
  error: causeName ?? core.i18n.coreM("core_errorInternal")
16134
16438
  }
@@ -16159,7 +16463,7 @@ function createRerankOperations(config, loadModels = () => config.llm) {
16159
16463
  const result = await callRerankAPI({ query, documents: texts, topN });
16160
16464
  if (!result.success)
16161
16465
  return result;
16162
- return ok(result.data.results);
16466
+ return core.ok(result.data.results);
16163
16467
  }
16164
16468
  };
16165
16469
  }
@@ -16187,17 +16491,17 @@ function createRetrievalOperations(embeddingOps, storeProvider, sourceStore, rer
16187
16491
  async addSource(source) {
16188
16492
  if (registry) {
16189
16493
  const result = await registry.operations.register(source);
16190
- return result.success ? ok(void 0) : result;
16494
+ return result.success ? core.ok(void 0) : result;
16191
16495
  }
16192
16496
  const existing = await sourceStore.get(source.id);
16193
16497
  if (existing) {
16194
- return err(HaiAIError.RETRIEVAL_FAILED, aiM("ai_internalError", {
16498
+ return core.err(HaiAIError.RETRIEVAL_FAILED, aiM("ai_internalError", {
16195
16499
  params: { error: `Source '${source.id}' already exists` }
16196
16500
  }));
16197
16501
  }
16198
16502
  await sourceStore.save(source.id, source);
16199
16503
  logger33.debug("Retrieval source added", { sourceId: source.id, collection: source.collection });
16200
- return ok(void 0);
16504
+ return core.ok(void 0);
16201
16505
  },
16202
16506
  /**
16203
16507
  * 取消注册检索源
@@ -16212,13 +16516,13 @@ function createRetrievalOperations(embeddingOps, storeProvider, sourceStore, rer
16212
16516
  return registry.operations.remove(sourceId);
16213
16517
  const existing = await sourceStore.get(sourceId);
16214
16518
  if (!existing) {
16215
- return err(HaiAIError.RETRIEVAL_SOURCE_NOT_FOUND, aiM("ai_internalError", {
16519
+ return core.err(HaiAIError.RETRIEVAL_SOURCE_NOT_FOUND, aiM("ai_internalError", {
16216
16520
  params: { error: `Source '${sourceId}' not found` }
16217
16521
  }));
16218
16522
  }
16219
16523
  await sourceStore.remove(sourceId);
16220
16524
  logger33.debug("Retrieval source removed", { sourceId });
16221
- return ok(void 0);
16525
+ return core.ok(void 0);
16222
16526
  },
16223
16527
  /**
16224
16528
  * 列出所有已注册的检索源
@@ -16250,13 +16554,13 @@ function createRetrievalOperations(embeddingOps, storeProvider, sourceStore, rer
16250
16554
  } : {}
16251
16555
  );
16252
16556
  if (targetSources.length === 0) {
16253
- return err(HaiAIError.RETRIEVAL_SOURCE_NOT_FOUND, aiM("ai_internalError", {
16557
+ return core.err(HaiAIError.RETRIEVAL_SOURCE_NOT_FOUND, aiM("ai_internalError", {
16254
16558
  params: { error: "No retrieval sources configured" }
16255
16559
  }));
16256
16560
  }
16257
16561
  const embedResult = await embeddingOps.embedText(request2.query);
16258
16562
  if (!embedResult.success) {
16259
- return err(HaiAIError.RETRIEVAL_FAILED, aiM("ai_internalError", {
16563
+ return core.err(HaiAIError.RETRIEVAL_FAILED, aiM("ai_internalError", {
16260
16564
  params: { error: "Failed to embed query" }
16261
16565
  }), embedResult.error);
16262
16566
  }
@@ -16312,14 +16616,14 @@ function createRetrievalOperations(embeddingOps, storeProvider, sourceStore, rer
16312
16616
  const limitedItems = allItems.slice(0, topK);
16313
16617
  const duration = Date.now() - startTime;
16314
16618
  logger33.trace("Retrieval completed", { queryLength: request2.query.length, resultCount: limitedItems.length, duration });
16315
- return ok({
16619
+ return core.ok({
16316
16620
  items: limitedItems,
16317
16621
  query: request2.query,
16318
16622
  duration
16319
16623
  });
16320
16624
  } catch (error) {
16321
16625
  logger33.error("Retrieval failed", { error });
16322
- return err(HaiAIError.RETRIEVAL_FAILED, aiM("ai_internalError", {
16626
+ return core.err(HaiAIError.RETRIEVAL_FAILED, aiM("ai_internalError", {
16323
16627
  params: {
16324
16628
  error: String(error)
16325
16629
  }
@@ -16377,13 +16681,13 @@ ${INCREMENTAL_SUMMARIZE_SUFFIX.replace("{previousSummary}", options.previousSumm
16377
16681
  enablePersist: false
16378
16682
  });
16379
16683
  if (!chatResult.success) {
16380
- return err(HaiAIError.CONTEXT_SUMMARIZE_FAILED, aiM("ai_contextSummarizeFailed", {
16684
+ return core.err(HaiAIError.CONTEXT_SUMMARIZE_FAILED, aiM("ai_contextSummarizeFailed", {
16381
16685
  params: {
16382
16686
  error: String(chatResult.error.message)
16383
16687
  }
16384
16688
  }), chatResult.error);
16385
16689
  }
16386
- return ok(chatResult.data.choices[0]?.message?.content ?? "");
16690
+ return core.ok(chatResult.data.choices[0]?.message?.content ?? "");
16387
16691
  }
16388
16692
  async function summarize(messages, options) {
16389
16693
  logger34.trace("Summarizing messages", { messageCount: messages.length });
@@ -16392,14 +16696,14 @@ ${INCREMENTAL_SUMMARIZE_SUFFIX.replace("{previousSummary}", options.previousSumm
16392
16696
  if (!result.success)
16393
16697
  return result;
16394
16698
  const summary = result.data;
16395
- return ok({
16699
+ return core.ok({
16396
16700
  summary,
16397
16701
  tokenCount: token.estimateText(summary),
16398
16702
  coveredMessages: messages.filter((m) => m.role !== "system").length
16399
16703
  });
16400
16704
  } catch (error) {
16401
16705
  logger34.error("Context summarization failed", { error });
16402
- return err(HaiAIError.CONTEXT_SUMMARIZE_FAILED, aiM("ai_contextSummarizeFailed", {
16706
+ return core.err(HaiAIError.CONTEXT_SUMMARIZE_FAILED, aiM("ai_contextSummarizeFailed", {
16403
16707
  params: {
16404
16708
  error: String(error)
16405
16709
  }
@@ -16603,7 +16907,7 @@ async function createAISubsystems(config, deps) {
16603
16907
  try {
16604
16908
  return await operation();
16605
16909
  } catch {
16606
- return err(
16910
+ return core.err(
16607
16911
  HaiAIError.RESOURCE_OPERATION_FAILED,
16608
16912
  aiM("ai_resourceOperationFailed")
16609
16913
  );
@@ -16747,8 +17051,8 @@ async function createAISubsystems(config, deps) {
16747
17051
  );
16748
17052
  const managedMCPServers = {
16749
17053
  ...mcpServers.operations,
16750
- register: (input) => input?.pool?.maxTotal === void 0 ? mcpServers.operations.register(input) : Promise.resolve(err(HaiAIError.RESOURCE_INVALID, aiM("ai_resourceInvalid"))),
16751
- update: (input, version) => input?.pool?.maxTotal === void 0 ? mcpServers.operations.update(input, version) : Promise.resolve(err(HaiAIError.RESOURCE_INVALID, aiM("ai_resourceInvalid")))
17054
+ register: (input) => input?.pool?.maxTotal === void 0 ? mcpServers.operations.register(input) : Promise.resolve(core.err(HaiAIError.RESOURCE_INVALID, aiM("ai_resourceInvalid"))),
17055
+ update: (input, version) => input?.pool?.maxTotal === void 0 ? mcpServers.operations.update(input, version) : Promise.resolve(core.err(HaiAIError.RESOURCE_INVALID, aiM("ai_resourceInvalid")))
16752
17056
  };
16753
17057
  const mcp = Object.assign(createAIMCPFunctions(), {
16754
17058
  servers: managedMCPServers,
@@ -18198,7 +18502,7 @@ function createMemoryStoreProvider() {
18198
18502
  function createBuiltinToolBroker(options) {
18199
18503
  const lifecycle = new AbortController();
18200
18504
  const serviceId = "hai-local-tools";
18201
- const forbidden = () => err(HaiAIError.MCP_TOOL_FORBIDDEN, aiM("ai_mcpServiceForbidden"));
18505
+ const forbidden = () => core.err(HaiAIError.MCP_TOOL_FORBIDDEN, aiM("ai_mcpServiceForbidden"));
18202
18506
  const created = createMCPServiceBroker(async () => void 0, async () => forbidden(), {
18203
18507
  url: options.url,
18204
18508
  authorize: () => true
@@ -18206,15 +18510,15 @@ function createBuiltinToolBroker(options) {
18206
18510
  id: serviceId,
18207
18511
  async catalog(scope, sessionId, signal) {
18208
18512
  const result = await options.service.catalog({ scope, sessionId, signal });
18209
- return result.success ? ok(result.data.tools) : result;
18513
+ return result.success ? core.ok(result.data.tools) : result;
18210
18514
  },
18211
18515
  async invoke(request2, authorization, idempotencyKey) {
18212
18516
  if (!authorization.taskId)
18213
18517
  return forbidden();
18214
18518
  const result = await options.service.invoke({ name: request2.tool, input: request2.arguments ?? {}, idempotencyKey }, { scope: authorization.principal, sessionId: authorization.taskId, signal: authorization.signal });
18215
18519
  if (!result.success)
18216
- return err(core.error.toPublic(result.error));
18217
- return ok({
18520
+ return core.err(core.error.toPublic(result.error));
18521
+ return core.ok({
18218
18522
  content: [
18219
18523
  {
18220
18524
  type: "text",
@@ -18228,7 +18532,7 @@ function createBuiltinToolBroker(options) {
18228
18532
  if (!created.success)
18229
18533
  return created;
18230
18534
  const broker = created.data;
18231
- return ok({
18535
+ return core.ok({
18232
18536
  async bind(input) {
18233
18537
  const catalog = await options.service.catalog({ scope: input.scope, sessionId: input.sessionId, signal: input.signal });
18234
18538
  if (!catalog.success)
@@ -18358,7 +18662,7 @@ function parameterSchema() {
18358
18662
  }).refine((input) => input.width % 2 === 0 && input.height % 2 === 0 && input.width * input.height <= 1920 * 1080 && (input.width === input.height || input.width * 9 === input.height * 16 || input.width * 16 === input.height * 9));
18359
18663
  }
18360
18664
  function invalid(cause) {
18361
- return err(HaiAIError.INVALID_REQUEST, aiM("ai_toolVideoInvalid"), cause);
18665
+ return core.err(HaiAIError.INVALID_REQUEST, aiM("ai_toolVideoInvalid"), cause);
18362
18666
  }
18363
18667
  function readScreenshots(names, files) {
18364
18668
  let pixels = 0;
@@ -18485,7 +18789,7 @@ function createWebsiteVideoTool(options, dependencies) {
18485
18789
  };
18486
18790
  const stage = async (phase, progress) => {
18487
18791
  if (!context.execution)
18488
- return ok(void 0);
18792
+ return core.ok(void 0);
18489
18793
  return context.execution.emit({ type: "phase", phase, progress });
18490
18794
  };
18491
18795
  const captureStage = await stage("capture", 0.05);
@@ -18533,7 +18837,7 @@ function createWebsiteVideoTool(options, dependencies) {
18533
18837
  const palette = capture.colors.map(color).filter((value) => !!value);
18534
18838
  const accent = input.brandColor ?? palette.find((value) => !/^#(?:000000|ffffff)$/i.test(value)) ?? palette[0];
18535
18839
  if (!accent)
18536
- return err(HaiAIError.INVALID_REQUEST, aiM("ai_toolVideoMissingBrand"));
18840
+ return core.err(HaiAIError.INVALID_REQUEST, aiM("ai_toolVideoMissingBrand"));
18537
18841
  const scriptStage = await stage("script", 0.2);
18538
18842
  if (!scriptStage.success)
18539
18843
  return scriptStage;
@@ -18656,7 +18960,7 @@ Do not execute website scripts, insert remote media, invent claims, or clip narr
18656
18960
  if (!playable.success)
18657
18961
  return playable;
18658
18962
  if (playable.data.format !== "wav")
18659
- return err(HaiAIError.AUDIO_INVALID_REQUEST, aiM("ai_toolVideoWavRequired"));
18963
+ return core.err(HaiAIError.AUDIO_INVALID_REQUEST, aiM("ai_toolVideoWavRequired"));
18660
18964
  bytes = Buffer.from(playable.data.audioBase64, "base64");
18661
18965
  }
18662
18966
  let voiceMs;
@@ -18683,7 +18987,7 @@ Do not execute website scripts, insert remote media, invent claims, or clip narr
18683
18987
  }
18684
18988
  const voiceTotal = narrated.reduce((sum, scene) => sum + scene.voiceMs, 0);
18685
18989
  if (voiceTotal + narrated.length * 100 > input.durationSeconds * 1e3)
18686
- return err(HaiAIError.AUDIO_INVALID_REQUEST, aiM("ai_toolVideoNarrationTooLong"));
18990
+ return core.err(HaiAIError.AUDIO_INVALID_REQUEST, aiM("ai_toolVideoNarrationTooLong"));
18687
18991
  const padding = (input.durationSeconds * 1e3 - voiceTotal) / narrated.length;
18688
18992
  let startMs = 0;
18689
18993
  const scenes = narrated.map((scene) => {
@@ -18773,7 +19077,7 @@ ${scene.narration.replaceAll("-->", "\u2192")}
18773
19077
  const done = await stage("complete", 1);
18774
19078
  if (!done.success)
18775
19079
  return done;
18776
- return ok({ ...manifest, artifacts });
19080
+ return core.ok({ ...manifest, artifacts });
18777
19081
  }
18778
19082
  });
18779
19083
  }
@@ -18820,7 +19124,7 @@ function createBuiltinTools(options, dependencies) {
18820
19124
  if (!read.success)
18821
19125
  return read;
18822
19126
  if (!read.data.mediaType.startsWith("image/"))
18823
- return err(HaiAIError.IMAGE_INVALID_REQUEST, aiM("ai_toolInvalidMedia"));
19127
+ return core.err(HaiAIError.IMAGE_INVALID_REQUEST, aiM("ai_toolInvalidMedia"));
18824
19128
  referenceImages.push({ data: read.data.data, mimeType: read.data.mediaType });
18825
19129
  }
18826
19130
  const generated = await dependencies.image().generate({
@@ -18837,7 +19141,7 @@ function createBuiltinTools(options, dependencies) {
18837
19141
  execution.signal.throwIfAborted();
18838
19142
  const extension = imageExtensions[image2.mimeType];
18839
19143
  if (!extension)
18840
- return err(HaiAIError.IMAGE_INVALID_REQUEST, aiM("ai_toolInvalidMedia"));
19144
+ return core.err(HaiAIError.IMAGE_INVALID_REQUEST, aiM("ai_toolInvalidMedia"));
18841
19145
  const published = await options.files.publish(context, {
18842
19146
  name: `generated-${index + 1}.${extension}`,
18843
19147
  kind: "image",
@@ -18848,7 +19152,7 @@ function createBuiltinTools(options, dependencies) {
18848
19152
  return published;
18849
19153
  artifacts.push(published.data);
18850
19154
  }
18851
- return ok({ artifacts });
19155
+ return core.ok({ artifacts });
18852
19156
  }
18853
19157
  });
18854
19158
  const synthesize = tools.define({
@@ -18890,7 +19194,7 @@ function createBuiltinTools(options, dependencies) {
18890
19194
  });
18891
19195
  if (!published.success)
18892
19196
  return published;
18893
- return ok({
19197
+ return core.ok({
18894
19198
  artifacts: [published.data],
18895
19199
  ...result.data.durationMs === void 0 ? {} : { durationMs: result.data.durationMs }
18896
19200
  });
@@ -18914,7 +19218,7 @@ function createBuiltinTools(options, dependencies) {
18914
19218
  return read;
18915
19219
  const format = audioFormat(read.data.name, read.data.mediaType);
18916
19220
  if (!format)
18917
- return err(HaiAIError.AUDIO_UNSUPPORTED_INPUT, aiM("ai_toolInvalidMedia"));
19221
+ return core.err(HaiAIError.AUDIO_UNSUPPORTED_INPUT, aiM("ai_toolInvalidMedia"));
18918
19222
  const transcribed = await dependencies.audio().transcribe({
18919
19223
  audio: { data: read.data.data, format },
18920
19224
  model: input.model,
@@ -18932,7 +19236,7 @@ function createBuiltinTools(options, dependencies) {
18932
19236
  });
18933
19237
  if (!published.success)
18934
19238
  return published;
18935
- return ok({
19239
+ return core.ok({
18936
19240
  text: transcribed.data.text,
18937
19241
  ...transcribed.data.language ? { language: transcribed.data.language } : {},
18938
19242
  ...transcribed.data.segments ? { segments: transcribed.data.segments } : {},
@@ -18959,18 +19263,18 @@ function createBuiltinTools(options, dependencies) {
18959
19263
  return read;
18960
19264
  const baseVersion = input.baseVersion ?? read.data.version;
18961
19265
  if (baseVersion === void 0 || read.data.version !== baseVersion)
18962
- return err(HaiAIError.RESOURCE_CONFLICT, aiM("ai_toolRewriteConflict"));
19266
+ return core.err(HaiAIError.RESOURCE_CONFLICT, aiM("ai_toolRewriteConflict"));
18963
19267
  if (!["text/markdown", "text/plain"].includes(read.data.mediaType))
18964
- return err(HaiAIError.INVALID_REQUEST, aiM("ai_toolInvalidMedia"));
19268
+ return core.err(HaiAIError.INVALID_REQUEST, aiM("ai_toolInvalidMedia"));
18965
19269
  let draft;
18966
19270
  try {
18967
19271
  draft = input.content ?? new TextDecoder("utf-8", { fatal: true }).decode(read.data.data);
18968
19272
  } catch {
18969
- return err(HaiAIError.INVALID_REQUEST, aiM("ai_toolInvalidMedia"));
19273
+ return core.err(HaiAIError.INVALID_REQUEST, aiM("ai_toolInvalidMedia"));
18970
19274
  }
18971
19275
  const start = input.selectedText === void 0 ? 0 : draft.indexOf(input.selectedText);
18972
19276
  if (start < 0 || input.selectedText !== void 0 && draft.lastIndexOf(input.selectedText) !== start)
18973
- return err(HaiAIError.INVALID_REQUEST, aiM("ai_toolRewriteSelection"));
19277
+ return core.err(HaiAIError.INVALID_REQUEST, aiM("ai_toolRewriteSelection"));
18974
19278
  const target = input.selectedText ?? draft;
18975
19279
  const result = await dependencies.llm().chat({
18976
19280
  model: input.model,
@@ -18988,9 +19292,9 @@ function createBuiltinTools(options, dependencies) {
18988
19292
  return result;
18989
19293
  const replacement = result.data.choices[0]?.message.content;
18990
19294
  if (typeof replacement !== "string" || !replacement.trim())
18991
- return err(HaiAIError.TOOL_RESULT_ERROR, aiM("ai_toolInvalidResult"));
19295
+ return core.err(HaiAIError.TOOL_RESULT_ERROR, aiM("ai_toolInvalidResult"));
18992
19296
  const content = input.selectedText === void 0 ? replacement : `${draft.slice(0, start)}${replacement}${draft.slice(start + target.length)}`;
18993
- return ok({
19297
+ return core.ok({
18994
19298
  id: input.id,
18995
19299
  content,
18996
19300
  baseVersion,
@@ -19048,7 +19352,7 @@ function createMcpTools(options, services) {
19048
19352
  resultHandler: async (input, { signal }) => {
19049
19353
  const args = z.record(z.string(), z.unknown()).safeParse(input);
19050
19354
  if (!args.success)
19051
- return err(HaiAIError.RESOURCE_INVALID, aiM("ai_resourceInvalid"));
19355
+ return core.err(HaiAIError.RESOURCE_INVALID, aiM("ai_resourceInvalid"));
19052
19356
  const result = await services().invoke({ serviceId: definition.serviceId, tool: definition.tool, arguments: args.data }, {
19053
19357
  principal: options.context.scope,
19054
19358
  taskId: options.context.sessionId,
@@ -19058,12 +19362,12 @@ function createMcpTools(options, services) {
19058
19362
  if (!result.success)
19059
19363
  return result;
19060
19364
  if (result.data.isError)
19061
- return err(HaiAIError.MCP_TOOL_ERROR, aiM("ai_mcpServiceCallFailed"));
19062
- return ok(result.data);
19365
+ return core.err(HaiAIError.MCP_TOOL_ERROR, aiM("ai_mcpServiceCallFailed"));
19366
+ return core.ok(result.data);
19063
19367
  }
19064
19368
  });
19065
19369
  });
19066
- return ok({
19370
+ return core.ok({
19067
19371
  tools: definitions,
19068
19372
  groups: [
19069
19373
  {
@@ -19074,7 +19378,7 @@ function createMcpTools(options, services) {
19074
19378
  ]
19075
19379
  });
19076
19380
  } catch (cause) {
19077
- return err(HaiAIError.RESOURCE_INVALID, aiM("ai_resourceInvalid"), cause);
19381
+ return core.err(HaiAIError.RESOURCE_INVALID, aiM("ai_resourceInvalid"), cause);
19078
19382
  }
19079
19383
  }
19080
19384
 
@@ -19198,7 +19502,10 @@ var notInitializedContext = {
19198
19502
  removeSession: () => Promise.resolve(notInitialized.result())
19199
19503
  };
19200
19504
  var notInitializedRerank = notInitialized.proxy();
19201
- var notInitializedFile = notInitialized.proxy();
19505
+ var notInitializedFile = {
19506
+ parse: (request2) => request2.options?.mode === "local" ? parseBoundedLocalFile(request2) : Promise.resolve(notInitialized.result()),
19507
+ parseText: () => Promise.resolve(notInitialized.result())
19508
+ };
19202
19509
  var notInitializedAudio = {
19203
19510
  models: notInitialized.proxy(),
19204
19511
  transcribe: () => Promise.resolve(notInitialized.result()),
@@ -19274,15 +19581,36 @@ var toolsOperations = {
19274
19581
  };
19275
19582
  var streamOperations = {
19276
19583
  createProcessor: createStreamProcessor,
19584
+ createJsonFieldPreview,
19277
19585
  collect: collectStream,
19278
19586
  createSSEDecoder,
19279
19587
  encodeSSE
19280
19588
  };
19281
19589
  var ai = {
19590
+ AgentEvent,
19591
+ Message,
19592
+ Part,
19593
+ SendMessageRequest,
19594
+ Task,
19595
+ TaskArtifactUpdateEvent,
19596
+ TaskStatus,
19597
+ TaskStatusUpdateEvent,
19598
+ McpServer: McpServer,
19599
+ SSEServerTransport,
19600
+ StdioServerTransport,
19601
+ StreamableHTTPServerTransport,
19602
+ // 独立工具保持原有调用契约,不依赖模块初始化状态。
19603
+ createMcpServer,
19604
+ ensureAudioCredential,
19605
+ resolveAudioModel,
19606
+ resolveImageModel,
19607
+ resolveModelApi,
19608
+ resolveModelEntry,
19609
+ serializePlayableAudio,
19282
19610
  async init(config, options) {
19283
19611
  if (initInProgress || closingPromise) {
19284
19612
  logger36.warn("AI init already in progress, skipping concurrent call");
19285
- return err(HaiAIError.INIT_IN_PROGRESS, aiM("ai_initInProgress"));
19613
+ return core.err(HaiAIError.INIT_IN_PROGRESS, aiM("ai_initInProgress"));
19286
19614
  }
19287
19615
  initInProgress = true;
19288
19616
  let resolveInit;
@@ -19301,7 +19629,7 @@ var ai = {
19301
19629
  const parseResult = AIConfigSchema.safeParse(config ?? {});
19302
19630
  if (!parseResult.success) {
19303
19631
  logger36.error("AI config validation failed", { error: parseResult.error.message });
19304
- return err(
19632
+ return core.err(
19305
19633
  HaiAIError.CONFIGURATION_ERROR,
19306
19634
  aiM("ai_configError", {
19307
19635
  params: { error: parseResult.error.message }
@@ -19320,7 +19648,7 @@ var ai = {
19320
19648
  logger36.warn("AI is using the ephemeral in-memory store; initialize reldb and vecdb before ai.init() for persistent data");
19321
19649
  }
19322
19650
  if (core.module.requiresSharedState(process2.env) && storeProvider.stateScope !== "shared")
19323
- return err(HaiAIError.CONFIGURATION_ERROR, aiM("ai_sharedBackendRequired"));
19651
+ return core.err(HaiAIError.CONFIGURATION_ERROR, aiM("ai_sharedBackendRequired"));
19324
19652
  currentStoreProvider = storeProvider;
19325
19653
  const subs = await createAISubsystems(parsed, {
19326
19654
  storeProvider,
@@ -19354,7 +19682,7 @@ var ai = {
19354
19682
  currentA2AStores = subs.a2aStores;
19355
19683
  currentConfig = parsed;
19356
19684
  logger36.info("AI module initialized", { model: parsed.llm?.model });
19357
- return ok(void 0);
19685
+ return core.ok(void 0);
19358
19686
  } catch (error) {
19359
19687
  if (!closingPrevious) {
19360
19688
  try {
@@ -19364,7 +19692,7 @@ var ai = {
19364
19692
  }
19365
19693
  }
19366
19694
  logger36.error("AI module initialization failed", { error });
19367
- return err(
19695
+ return core.err(
19368
19696
  HaiAIError.CONFIGURATION_ERROR,
19369
19697
  aiM("ai_initFailed", {
19370
19698
  params: {
@@ -19464,6 +19792,6 @@ var ai = {
19464
19792
  }
19465
19793
  };
19466
19794
 
19467
- export { ai, createMcpServer };
19795
+ export { ai };
19468
19796
  //# sourceMappingURL=index.js.map
19469
19797
  //# sourceMappingURL=index.js.map